diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/test/java/org/blitzem/test/integ/BlitzemIntegTest.java b/src/test/java/org/blitzem/test/integ/BlitzemIntegTest.java index b824588..29bf07d 100644 --- a/src/test/java/org/blitzem/test/integ/BlitzemIntegTest.java +++ b/src/test/java/org/blitzem/test/integ/BlitzemIntegTest.java @@ -1,93 +1,93 @@ package org.blitzem.test.integ; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Files; @RunWith(Parameterized.class) public class BlitzemIntegTest extends ShellIntegTestBase { private static final String HOME = System.getProperty("user.home"); static final Logger LOGGER = LoggerFactory.getLogger(BlitzemIntegTest.class); private final String configPath; @Parameters public static Collection<Object[]> config() { Object[][] config = new Object[][] { { HOME + "/.blitzem/rackspace-uk.properties" }, { HOME + "/.blitzem/aws.properties" }}; return Arrays.asList(config); } public BlitzemIntegTest(String configPath) { this.configPath = configPath; } @Before public void unpackAssembly() throws Exception { // Extract blitzem tempDir = Files.createTempDir(); exec("cp target/*.zip {}/ && cd {} && unzip *.zip", tempDir.getCanonicalPath(), tempDir.getCanonicalPath()); } @Before public void selectConfiguration() throws IOException { LOGGER.info("Selecting configuration {}", configPath); // Put the right configuration file in place File cloudConfigFile = new File(HOME + "/.blitzem/config.properties"); cloudConfigFile.delete(); Files.copy(new File(this.configPath), cloudConfigFile); } @Test public void testSimpleEndToEnd() throws Exception { execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy down"); String stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); assertTrue(stdout.contains("Applying command StatusCommand to whole environment")); assertTrue(stdout.contains("Fetching status of nodes and load balancers")); execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy up"); stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); - Matcher matcher = Pattern.compile(".*web-lb1\\s+UP\\s+\\[([\\w\\d\\.]+).*", Pattern.MULTILINE + Pattern.DOTALL).matcher(stdout); + Matcher matcher = Pattern.compile(".*web-lb1\\s+UP\\s+\\[([\\w\\-\\d\\.]+).*", Pattern.MULTILINE + Pattern.DOTALL).matcher(stdout); assertTrue(matcher.matches()); String loadBalancerIpAddress = matcher.group(1); URL loadBalancerUrl = new URL("http", loadBalancerIpAddress, 80, ""); System.out.println(loadBalancerUrl); Set<String> contentSeen = Sets.newHashSet(); while (contentSeen.size()<4) { String content = new String(ByteStreams.toByteArray((java.io.InputStream) loadBalancerUrl.openStream())); contentSeen.add(content); Thread.sleep(100L); } System.out.println(contentSeen); } @After public void tearDown() throws Exception { execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy down"); } }
true
true
public void testSimpleEndToEnd() throws Exception { execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy down"); String stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); assertTrue(stdout.contains("Applying command StatusCommand to whole environment")); assertTrue(stdout.contains("Fetching status of nodes and load balancers")); execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy up"); stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); Matcher matcher = Pattern.compile(".*web-lb1\\s+UP\\s+\\[([\\w\\d\\.]+).*", Pattern.MULTILINE + Pattern.DOTALL).matcher(stdout); assertTrue(matcher.matches()); String loadBalancerIpAddress = matcher.group(1); URL loadBalancerUrl = new URL("http", loadBalancerIpAddress, 80, ""); System.out.println(loadBalancerUrl); Set<String> contentSeen = Sets.newHashSet(); while (contentSeen.size()<4) { String content = new String(ByteStreams.toByteArray((java.io.InputStream) loadBalancerUrl.openStream())); contentSeen.add(content); Thread.sleep(100L); } System.out.println(contentSeen); }
public void testSimpleEndToEnd() throws Exception { execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy down"); String stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); assertTrue(stdout.contains("Applying command StatusCommand to whole environment")); assertTrue(stdout.contains("Fetching status of nodes and load balancers")); execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy up"); stdout = execInDir("bin/blitzem --source=examples/load_balanced/environment.groovy status"); Matcher matcher = Pattern.compile(".*web-lb1\\s+UP\\s+\\[([\\w\\-\\d\\.]+).*", Pattern.MULTILINE + Pattern.DOTALL).matcher(stdout); assertTrue(matcher.matches()); String loadBalancerIpAddress = matcher.group(1); URL loadBalancerUrl = new URL("http", loadBalancerIpAddress, 80, ""); System.out.println(loadBalancerUrl); Set<String> contentSeen = Sets.newHashSet(); while (contentSeen.size()<4) { String content = new String(ByteStreams.toByteArray((java.io.InputStream) loadBalancerUrl.openStream())); contentSeen.add(content); Thread.sleep(100L); } System.out.println(contentSeen); }
diff --git a/src/main/java/sword/java/class_analyzer/MemberModifierMask.java b/src/main/java/sword/java/class_analyzer/MemberModifierMask.java index a54e720..abd250f 100644 --- a/src/main/java/sword/java/class_analyzer/MemberModifierMask.java +++ b/src/main/java/sword/java/class_analyzer/MemberModifierMask.java @@ -1,62 +1,67 @@ package sword.java.class_analyzer; public class MemberModifierMask extends ModifierMask { public MemberModifierMask(int mask) { super(mask); } public boolean isSynchronized() { return (mMask & 0x20) != 0; } public boolean isVolatile() { return (mMask & 0x40) != 0; } public boolean isTransient() { return (mMask & 0x80) != 0; } public boolean isNative() { return (mMask & 0x100) != 0; } @Override public String getModifiersString() { String result = getVisibilityString(); if (result.length() != 0) { result = result + ' '; } if (isStatic()) { result = result + "static "; } if (isFinal()) { result = result + "final "; } if (isSynchronized()) { result = result + "synchronized "; } if (isVolatile()) { result = result + "volatile "; } if (isTransient()) { result = result + "transient "; } if (isNative()) { result = result + "native "; } if (isAbstract()) { result = result + "abstract "; } - return result.substring(0, result.length() - 1); + if (result.length() == 0) { + return result; + } + else { + return result.substring(0, result.length() - 1); + } } }
true
true
public String getModifiersString() { String result = getVisibilityString(); if (result.length() != 0) { result = result + ' '; } if (isStatic()) { result = result + "static "; } if (isFinal()) { result = result + "final "; } if (isSynchronized()) { result = result + "synchronized "; } if (isVolatile()) { result = result + "volatile "; } if (isTransient()) { result = result + "transient "; } if (isNative()) { result = result + "native "; } if (isAbstract()) { result = result + "abstract "; } return result.substring(0, result.length() - 1); }
public String getModifiersString() { String result = getVisibilityString(); if (result.length() != 0) { result = result + ' '; } if (isStatic()) { result = result + "static "; } if (isFinal()) { result = result + "final "; } if (isSynchronized()) { result = result + "synchronized "; } if (isVolatile()) { result = result + "volatile "; } if (isTransient()) { result = result + "transient "; } if (isNative()) { result = result + "native "; } if (isAbstract()) { result = result + "abstract "; } if (result.length() == 0) { return result; } else { return result.substring(0, result.length() - 1); } }
diff --git a/src/com/android/calendar/selectcalendars/SelectVisibleCalendarsFragment.java b/src/com/android/calendar/selectcalendars/SelectVisibleCalendarsFragment.java index 65a9c36b..5f6c6b5e 100644 --- a/src/com/android/calendar/selectcalendars/SelectVisibleCalendarsFragment.java +++ b/src/com/android/calendar/selectcalendars/SelectVisibleCalendarsFragment.java @@ -1,182 +1,184 @@ /* * 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.calendar.selectcalendars; import com.android.calendar.AsyncQueryService; import com.android.calendar.CalendarController.EventInfo; import com.android.calendar.CalendarController.EventType; import com.android.calendar.R; import com.android.calendar.CalendarController; import com.android.calendar.Utils; import android.app.Activity; import android.app.Fragment; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; public class SelectVisibleCalendarsFragment extends Fragment implements AdapterView.OnItemClickListener, CalendarController.EventHandler { private static final String TAG = "Calendar"; private static final String IS_PRIMARY = "\"primary\""; private static final String SELECTION = Calendars.SYNC_EVENTS + "=?"; private static final String[] SELECTION_ARGS = new String[] {"1"}; private static final String[] PROJECTION = new String[] { Calendars._ID, Calendars.ACCOUNT_NAME, Calendars.OWNER_ACCOUNT, Calendars.CALENDAR_DISPLAY_NAME, Calendars.CALENDAR_COLOR, Calendars.VISIBLE, Calendars.SYNC_EVENTS, "(" + Calendars.ACCOUNT_NAME + "=" + Calendars.OWNER_ACCOUNT + ") AS " + IS_PRIMARY, }; private static int mUpdateToken; private static int mQueryToken; private static int mCalendarItemLayout = R.layout.mini_calendar_item; private View mView = null; private ListView mList; private SelectCalendarsSimpleAdapter mAdapter; private Activity mContext; private AsyncQueryService mService; private Cursor mCursor; public SelectVisibleCalendarsFragment() { } public SelectVisibleCalendarsFragment(int itemLayout) { mCalendarItemLayout = itemLayout; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = activity; mService = new AsyncQueryService(activity) { @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { mAdapter.changeCursor(cursor); mCursor = cursor; } }; } @Override public void onDetach() { super.onDetach(); if (mCursor != null) { mAdapter.changeCursor(null); mCursor.close(); mCursor = null; } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mView = inflater.inflate(R.layout.select_calendars_fragment, null); mList = (ListView)mView.findViewById(R.id.list); // Hide the Calendars to Sync button on tablets for now. // Long terms stick it in the list of calendars if (Utils.isMultiPaneConfiguration(getActivity())) { + // Don't show dividers on tablets + mList.setDivider(null); View v = mView.findViewById(R.id.manage_sync_set); if (v != null) { v.setVisibility(View.GONE); } } return mView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mAdapter = new SelectCalendarsSimpleAdapter(mContext, mCalendarItemLayout, null); mList.setAdapter(mAdapter); mList.setOnItemClickListener(this); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mAdapter == null || mAdapter.getCount() <= position) { return; } toggleVisibility(position); } @Override public void onResume() { super.onResume(); mQueryToken = mService.getNextToken(); mService.startQuery(mQueryToken, null, Calendars.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, Calendars.ACCOUNT_NAME); } /* * Write back the changes that have been made. */ public void toggleVisibility(int position) { Log.d(TAG, "Toggling calendar at " + position); mUpdateToken = mService.getNextToken(); Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, mAdapter.getItemId(position)); ContentValues values = new ContentValues(); // Toggle the current setting int visibility = mAdapter.getVisible(position)^1; values.put(Calendars.VISIBLE, visibility); mService.startUpdate(mUpdateToken, null, uri, values, null, null, 0); mAdapter.setVisible(position, visibility); } @Override public void eventsChanged() { if (mService != null) { mService.cancelOperation(mQueryToken); mQueryToken = mService.getNextToken(); mService.startQuery(mQueryToken, null, Calendars.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, Calendars.ACCOUNT_NAME); } } @Override public long getSupportedEventTypes() { return EventType.EVENTS_CHANGED; } @Override public void handleEvent(EventInfo event) { if (event.eventType == EventType.EVENTS_CHANGED) { eventsChanged(); } } }
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mView = inflater.inflate(R.layout.select_calendars_fragment, null); mList = (ListView)mView.findViewById(R.id.list); // Hide the Calendars to Sync button on tablets for now. // Long terms stick it in the list of calendars if (Utils.isMultiPaneConfiguration(getActivity())) { View v = mView.findViewById(R.id.manage_sync_set); if (v != null) { v.setVisibility(View.GONE); } } return mView; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mView = inflater.inflate(R.layout.select_calendars_fragment, null); mList = (ListView)mView.findViewById(R.id.list); // Hide the Calendars to Sync button on tablets for now. // Long terms stick it in the list of calendars if (Utils.isMultiPaneConfiguration(getActivity())) { // Don't show dividers on tablets mList.setDivider(null); View v = mView.findViewById(R.id.manage_sync_set); if (v != null) { v.setVisibility(View.GONE); } } return mView; }
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java index 0edc7e02..76ce49e0 100644 --- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java +++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java @@ -1,38 +1,35 @@ package pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.activities; import module.workflow.activities.ActivityInformation; import module.workflow.activities.WorkflowActivity; import myorg.applicationTier.Authenticate.UserView; import myorg.domain.User; import myorg.util.BundleUtil; import pt.ist.expenditureTrackingSystem.domain.acquisitions.RegularAcquisitionProcess; import pt.ist.expenditureTrackingSystem.domain.organization.Person; public class ConfirmInvoice extends WorkflowActivity<RegularAcquisitionProcess, ActivityInformation<RegularAcquisitionProcess>> { @Override public boolean isActive(RegularAcquisitionProcess process, User user) { Person person = user.getExpenditurePerson(); - return isUserProcessOwner(process, user) - && person != null - && !process.isInvoiceReceived() - && !process.getUnconfirmedInvoices(person).isEmpty() - && process.isResponsibleForUnit(person); + return isUserProcessOwner(process, user) && person != null && process.isActive() && !process.isInvoiceReceived() + && !process.getUnconfirmedInvoices(person).isEmpty() && process.isResponsibleForUnit(person); } @Override protected void process(ActivityInformation<RegularAcquisitionProcess> activityInformation) { activityInformation.getProcess().confirmInvoiceBy(UserView.getCurrentUser().getExpenditurePerson()); } @Override public String getLocalizedName() { return BundleUtil.getStringFromResourceBundle(getUsedBundle(), "label." + getClass().getName()); } @Override public String getUsedBundle() { return "resources/AcquisitionResources"; } }
true
true
public boolean isActive(RegularAcquisitionProcess process, User user) { Person person = user.getExpenditurePerson(); return isUserProcessOwner(process, user) && person != null && !process.isInvoiceReceived() && !process.getUnconfirmedInvoices(person).isEmpty() && process.isResponsibleForUnit(person); }
public boolean isActive(RegularAcquisitionProcess process, User user) { Person person = user.getExpenditurePerson(); return isUserProcessOwner(process, user) && person != null && process.isActive() && !process.isInvoiceReceived() && !process.getUnconfirmedInvoices(person).isEmpty() && process.isResponsibleForUnit(person); }
diff --git a/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/generator/ScalableGenerator.java b/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/generator/ScalableGenerator.java index db51a0d..e625515 100644 --- a/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/generator/ScalableGenerator.java +++ b/ldbc_socialnet_dbgen/src/main/java/ldbc/socialnet/dbgen/generator/ScalableGenerator.java @@ -1,1979 +1,1979 @@ /* * Copyright (c) 2013 LDBC * Linked Data Benchmark Council (http://ldbc.eu) * * This file is part of ldbc_socialnet_dbgen. * * ldbc_socialnet_dbgen 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. * * ldbc_socialnet_dbgen 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 ldbc_socialnet_dbgen. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2011 OpenLink Software <[email protected]> * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; only Version 2 of the License dated * June 1991. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ldbc.socialnet.dbgen.generator; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Writer; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Random; import java.util.Vector; import ldbc.socialnet.dbgen.dictionary.BrowserDictionary; import ldbc.socialnet.dbgen.dictionary.CompanyDictionary; import ldbc.socialnet.dbgen.dictionary.EmailDictionary; import ldbc.socialnet.dbgen.dictionary.IPAddressDictionary; import ldbc.socialnet.dbgen.dictionary.InterestDictionary; import ldbc.socialnet.dbgen.dictionary.LanguageDictionary; import ldbc.socialnet.dbgen.dictionary.LocationDictionary; import ldbc.socialnet.dbgen.dictionary.NamesDictionary; import ldbc.socialnet.dbgen.dictionary.OrganizationsDictionary; import ldbc.socialnet.dbgen.dictionary.PopularPlacesDictionary; import ldbc.socialnet.dbgen.dictionary.TagDictionary; import ldbc.socialnet.dbgen.dictionary.TagMatrix; import ldbc.socialnet.dbgen.dictionary.UserAgentDictionary; import ldbc.socialnet.dbgen.objects.Comment; import ldbc.socialnet.dbgen.objects.Friend; import ldbc.socialnet.dbgen.objects.Group; import ldbc.socialnet.dbgen.objects.GroupMemberShip; import ldbc.socialnet.dbgen.objects.Photo; import ldbc.socialnet.dbgen.objects.PhotoAlbum; import ldbc.socialnet.dbgen.objects.Post; import ldbc.socialnet.dbgen.objects.ReducedUserProfile; import ldbc.socialnet.dbgen.objects.RelationshipStatus; import ldbc.socialnet.dbgen.objects.UserExtraInfo; import ldbc.socialnet.dbgen.objects.UserProfile; import ldbc.socialnet.dbgen.serializer.CSV; import ldbc.socialnet.dbgen.serializer.Serializer; import ldbc.socialnet.dbgen.serializer.Turtle; import ldbc.socialnet.dbgen.storage.MFStoreManager; import ldbc.socialnet.dbgen.storage.StorageManager; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Mapper.Context; import org.apache.hadoop.mapreduce.Reducer; public class ScalableGenerator{ public static long postId = -1; // For sliding window int cellSize = 1; // Number of user in one cell int numberOfCellPerWindow = 200; int numtotalUser = 10000; int windowSize; int lastCellPos; int lastCell; int lastMapCellPos; int lastMapCell; int startMapUserIdx; int machineId; ReducedUserProfile reducedUserProfiles[]; ReducedUserProfile reducedUserProfilesCell[]; // Store new cell of user profiles ReducedUserProfile removedUserProfiles[]; // For (de-)serialization FileOutputStream ofUserProfiles; ObjectOutputStream oosUserProfile; FileInputStream ifUserProfile; ObjectInputStream oisUserProfile; // For multiple files boolean isMultipleFile = true; int numFiles = 10; int numCellPerfile; int numCellInLastFile; int numCellRead = 0; Random randomFileSelect; Random randomIdxInWindow; HashSet<Integer> selectedFileIdx; // For friendship generation int friendshipNo = 0; int minNoFriends = 5; int maxNoFriends = 50; double friendRejectRatio = 0.02; double friendReApproveRatio = 0.5; int numCorrDimensions = 3; // Run 3 passes for friendship generation StorageManager storeManager[]; StorageManager groupStoreManager; MRWriter mrWriter; double friendsRatioPerPass[] = { 0.45, 0.45, 0.1 }; // Indicate how many // friends will be created for each pass // e.g., 30% in the first pass with // location information Random randFriendReject; Random randFriendReapprov; Random randInitiator; double alpha = 0.4; // Alpha value for power-law distribution double baseProbLocationCorrelated = 0.8; // Higher probability, faster // sliding along this pass double baseProbCorrelated = 0.9; // Probability that two user having the same // atrributes value become friends; double limitProCorrelated = 0.2; // For each user int maxNoInterestsPerUser = 10; int maxNoTagsPerUser = 10; int maxNumLocationPostPerMonth = 30; int maxNumInterestPostPerMonth = 50; int maxNumComments = 20; // Random values generators PowerDistGenerator randPowerlaw; //Random seedRandom = new Random(53223436L); Long[] seeds; Random randUniform; Random randNumInterest; Random randNumTags; Random randomFriendIdx; // For third pass Random randNumberPost; Random randNumberComments; // Generate number of comments per post Random randNumberPhotoAlbum; Random randNumberPhotos; Random randNumberGroup; Random randNumberUserPerGroup; Random randGender; Random randUserRandomIdx; // For generating the // random dimension int maxUserRandomIdx = 100; //SHOULE BE IMPORTANT PARAM DateGenerator dateTimeGenerator; int startYear; int endYear; private static final int startMonth = 1; private static final int startDate = 1; private static final int endMonth = 1; private static final int endDate = 1; // Dictionaries private static final String countryDicFile = "dicLocation.txt"; private static final String languageDicFile = "languagesByCountry.txt"; private static final String cityDicFile = "institutesCityByCountry.txt"; private static final String interestDicFile = "locationInterestDist.txt"; private static final String tagNamesFile = "dicTopic.txt"; private static final String mainTagDicFile = "dicCelebritiesByCountry.txt"; private static final String topicTagDicFile = "topicMatrixId.txt"; private static final String interestNamesFile = "singerNames.txt"; private static final String musicGenreFile = "singerGenres.txt"; private static final String givennamesDicFile = "givennameByCountryBirthPlace.txt.freq.full"; private static final String surnamesDicFile = "surnameByCountryBirthPlace.txt.freq.sort"; private static final String organizationsDicFile = "institutesCityByCountry.txt"; private static final String companiesDicFile = "companiesByCountry.txt"; private static final String popularPlacesDicFile = "popularPlacesByCountry.txt"; private static final String regionalArticleFile = "articlesLocation.txt"; private static final String interestArticleFile = "articlesInterest.txt"; private static final String stopWordFileName = "googleStopwords.txt"; private static final String agentFile = "smartPhonesProviders.txt"; private static final String emailDicFile = "email.txt"; private static final String browserDicFile = "browsersDic.txt"; private static final String countryAbbrMappingFile = "countryAbbrMapping.txt"; LocationDictionary locationDic; LanguageDictionary languageDic; TagDictionary mainTagDic; double tagCountryCorrProb; TagMatrix topicTagDic; InterestDictionary interestDic; NamesDictionary namesDictionary; double geometricProb = 0.2; OrganizationsDictionary organizationsDictionary; double probUnCorrelatedOrganization = 0.005; double probTopUniv = 0.9; // 90% users go to top university CompanyDictionary companiesDictionary; double probUnCorrelatedCompany = 0.05; UserAgentDictionary userAgentDic; EmailDictionary emailDic; BrowserDictionary browserDic; PopularPlacesDictionary popularDictionary; int maxNumPopularPlaces; Random randNumPopularPlaces; double probPopularPlaces; //probability of taking a photo at popular place IPAddressDictionary ipAddDictionary; int locationIdx = 0; //Which is current index of the location in dictionary // For generating texts of posts and comments RandomTextGenerator textGenerator; int maxNumLikes = 10; GroupPostGenerator groupPostGenerator; int maxEmails = 5; int maxCompanies = 3; double probEnglish = 0.6; double probSecondLang = 0.2; int numArticles = 3606; // May be set -1 if do not know int minTextSize = 20; int maxTextSize = 200; int minCommentSize = 20; int maxCommentSize = 60; double ratioReduceText = 0.8; // 80% text has size less than 1/2 max size // For photo generator PhotoGenerator photoGenerator; int maxNumUserTags = 10; int maxNumPhotoAlbums = 5; // This is number of photo album per month int maxNumPhotoPerAlbums = 100; // For generating groups GroupGenerator groupGenerator; int maxNumGroupCreatedPerUser = 4; int maxNumMemberGroup = 100; double groupModeratorProb = 0.05; double levelProbs[] = { 0.5, 0.8, 1.0 }; // Cumulative 'join' probability // for friends of level 1, 2 and 3 // of a user double joinProbs[] = { 0.7, 0.4, 0.1 }; Random randFriendLevelSelect; // For select an level of moderator's // friendship Random randMembership; // For deciding whether or not a user is joined Random randMemberIdxSelector; Random randGroupMemStep; Random randGroupModerator; // Decide whether a user can be moderator // of groups or not // For group posts int maxNumGroupPostPerMonth = 20; Random randNumberGroupPost; // For serialize to RDF format private String rdfOutputFileName = "ldbc_socialnet_dbg"; Serializer serializer; String serializerType = "ttl"; String outUserProfileName = "userProf.ser"; String outUserProfile; int numRdfOutputFile = 1; boolean forwardChaining = false; int mapreduceFileIdx; String sibOutputDir; String sibHomeDir; String sibDicDataDir = "/dictionaries/"; String ipZoneDir = "/ipaddrByCountries"; // For user's extra info String gender[] = { "male", "female" }; Random randomExtraInfo; Random randomExactLongLat; double missingRatio = 0.2; Random randomHaveStatus; Random randomStatusSingle; Random randomStatus; double missingStatusRatio = 0.5; double probSingleStatus = 0.8; // Status "Single" has more probability than // others' double probAnotherBrowser; double probHavingSmartPhone = 0.5; Random randUserAgent; double probSentFromAgent = 0.2; Random randIsFrequent; double probUnFrequent = 0.01; // Whether or not a user frequently changes // The probability that normal user posts from different location double probDiffIPinTravelSeason = 0.1; // in travel season double probDiffIPnotTravelSeason = 0.02; // not in travel season // The probability that travellers post from different location double probDiffIPforTraveller = 0.3; // For loading parameters; String paramFileName = "params.ini"; static String shellArgs[]; // For MapReduce public static int numMaps = -1; MFStoreManager mfStore; // Writing data for test driver OutputDataWriter outputDataWriter; int thresholdPopularUser = 40; int numPopularUser = 0; public ScalableGenerator(int _mapreduceFileIdx, String _sibOutputDir, String _sibHomeDir){ mapreduceFileIdx = _mapreduceFileIdx; System.out.println("Map Reduce File Idx is: " + mapreduceFileIdx); if (mapreduceFileIdx != -1){ outUserProfile = "mr" + mapreduceFileIdx + "_" + outUserProfileName; } sibOutputDir = _sibOutputDir; sibHomeDir = _sibHomeDir; System.out.println("Current directory in ScaleGenerator is " + _sibHomeDir); } public void initAllParams(String args[], int _numMaps, int mapIdx){ this.machineId = mapIdx; loadParamsFromFile(); numFiles = _numMaps; rdfOutputFileName = "mr" + mapreduceFileIdx + "_" + rdfOutputFileName; init(mapIdx, true); System.out.println("Number of files " + numFiles); System.out.println("Number of cells per file " + numCellPerfile); System.out.println("Number of cells in last file " + numCellInLastFile); mrWriter = new MRWriter(cellSize, windowSize, sibOutputDir); } public void mapreduceTask(String inputFile, int numberCell){ startWritingUserData(); long startPostGeneration = System.currentTimeMillis(); generatePostandPhoto(inputFile, numberCell); long endPostGeneration = System.currentTimeMillis(); System.out.println("Post generation takes " + getDuration(startPostGeneration, endPostGeneration)); finishWritingUserData(); long startGroupGeneration = System.currentTimeMillis(); generateGroupAll(inputFile, numberCell); long endGroupGeneration = System.currentTimeMillis(); System.out.println("Group generation takes " + getDuration(startGroupGeneration, endGroupGeneration)); if (mapreduceFileIdx != -1) serializer.serialize(); System.out.println("Number of generated triples " + serializer.triplesGenerated()); // Write data for testdrivers System.out.println("Writing the data for test driver "); System.out.println("Number of popular users " + numPopularUser); } public void loadParamsFromFile() { try { //First read the internal params.ini BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(getClass( ).getResourceAsStream("/"+paramFileName), "UTF-8")); String line; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("cellSize")) { cellSize = Short.parseShort(infos[1].trim()); continue; } else if (infos[0].startsWith("numberOfCellPerWindow")) { numberOfCellPerWindow = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minNoFriends")) { minNoFriends = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoFriends")) { maxNoFriends = Integer.parseInt(infos[1].trim()); thresholdPopularUser = (int) (maxNoFriends * 0.9); continue; } else if (infos[0].startsWith("friendRejectRatio")) { friendRejectRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("friendReApproveRatio")) { friendReApproveRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoInterestsPerUser")) { maxNoInterestsPerUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoTagsPerUser")) { maxNoTagsPerUser= Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumLocationPostPerMonth")) { maxNumLocationPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumInterestPostPerMonth")) { maxNumInterestPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumComments")) { maxNumComments = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("limitProCorrelated")) { limitProCorrelated = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("baseProbCorrelated")) { baseProbCorrelated = Double .parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxEmails")) { maxEmails = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCompanies")) { maxCompanies = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probEnglish")) { probEnglish = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSecondLang")) { probSecondLang = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probAnotherBrowser")) { probAnotherBrowser = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("minTextSize")) { minTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxTextSize")) { maxTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minCommentSize")) { minCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCommentSize")) { maxCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("ratioReduceText")) { ratioReduceText = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumUserTags")) { maxNumUserTags = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoAlbums")) { maxNumPhotoAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoPerAlbums")) { maxNumPhotoPerAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupCreatedPerUser")) { maxNumGroupCreatedPerUser = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumMemberGroup")) { maxNumMemberGroup = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("groupModeratorProb")) { groupModeratorProb = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupPostPerMonth")) { maxNumGroupPostPerMonth = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; }else if (infos[0].startsWith("missingRatio")) { missingRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("missingStatusRatio")) { missingStatusRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSingleStatus")) { probSingleStatus = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probHavingSmartPhone")) { probHavingSmartPhone = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSentFromAgent")) { probSentFromAgent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnFrequent")) { probUnFrequent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probDiffIPinTravelSeason")) { probDiffIPinTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPnotTravelSeason")) { probDiffIPnotTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPforTraveller")) { probDiffIPforTraveller = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedCompany")) { probUnCorrelatedCompany = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedOrganization")) { probUnCorrelatedOrganization = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probTopUniv")) { probTopUniv = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPopularPlaces")) { maxNumPopularPlaces = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probPopularPlaces")) { probPopularPlaces = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("tagCountryCorrProb")) { tagCountryCorrProb = Double.parseDouble(infos[1].trim()); continue; } } paramFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { //read the user param file BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(new FileInputStream(sibHomeDir + paramFileName), "UTF-8")); String line; numtotalUser = -1; int numYears = -1; startYear = -1; serializerType = ""; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("numtotalUser")) { numtotalUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("startYear")) { startYear = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("numYears")) { numYears = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; } else { System.out.println("This param " + line + " does not match any option"); } } paramFile.close(); if (numtotalUser == -1) { throw new Exception("No numtotalUser parameter provided"); } if (startYear == -1) { throw new Exception("No startYears parameter provided"); } if (numYears == -1) { throw new Exception("No numYears parameter provided"); } if (!serializerType.equals("ttl") && !serializerType.equals("nt") && - serializerType.equals("csv")) { + !serializerType.equals("csv")) { throw new Exception("serializerType must be ttl, nt or csv"); } endYear = startYear + numYears; } catch (Exception e) { System.out.println("Using default configuration"); // If the user params file wasn't found use the default configuration. } } // Init the data for the first window of cells public void init(int mapId, boolean isFullLoad) { seedGenerate(mapId); windowSize = (int) cellSize * numberOfCellPerWindow; randPowerlaw = new PowerDistGenerator(minNoFriends, maxNoFriends, alpha, seeds[2]); randUniform = new Random(seeds[3]); randGender = new Random(seeds[3]); randNumInterest = new Random(seeds[4]); randNumTags = new Random(seeds[4]); randomFriendIdx = new Random(seeds[6]); randomFileSelect = new Random(seeds[7]); randomIdxInWindow = new Random(seeds[8]); randNumberPost = new Random(seeds[9]); randNumberComments = new Random(seeds[10]); randNumberPhotoAlbum = new Random(seeds[11]); randNumberPhotos = new Random(seeds[12]); randNumberGroup = new Random(seeds[13]); randNumberUserPerGroup = new Random(seeds[14]); randMemberIdxSelector = new Random(seeds[18]); randGroupMemStep = new Random(seeds[19]); randFriendLevelSelect = new Random(seeds[20]); randMembership = new Random(seeds[21]); randGroupModerator = new Random(seeds[22]); randomExtraInfo = new Random(seeds[27]); randomExactLongLat = new Random(seeds[27]); randUserAgent = new Random(seeds[29]); randIsFrequent = new Random(seeds[34]); randNumberGroupPost = new Random(seeds[36]); randFriendReject = new Random(seeds[37]); randFriendReapprov = new Random(seeds[38]); randInitiator = new Random(seeds[39]); randomHaveStatus = new Random(seeds[41]); randomStatusSingle = new Random(seeds[42]); randomStatus = new Random(seeds[43]); randNumPopularPlaces = new Random(seeds[47]); randUserRandomIdx = new Random(seeds[48]); //userProfiles = new UserProfile[windowSize]; // Collect of user reducedUserProfiles = new ReducedUserProfile[windowSize]; //// Collect of reduced user profile cellReducedUserProfiles = new ReducedUserProfile[cellSize]; // Number of users should be a multiple of the cellsize if (numtotalUser % cellSize != 0) { System.out .println("Number of users should be a multiple of the cellsize "); System.exit(-1); } dateTimeGenerator = new DateGenerator(new GregorianCalendar(startYear, startMonth, startDate), new GregorianCalendar(endYear, endMonth, endDate), seeds[0], seeds[1], alpha); lastCellPos = (int) (numtotalUser - windowSize) / cellSize; lastCell = (int) numtotalUser / cellSize - 1; // The last cell of the // sliding process lastMapCellPos = (int)(numtotalUser/numMaps - windowSize) / cellSize; lastMapCell = (int)numtotalUser/(numMaps * cellSize) - 1; startMapUserIdx = (numtotalUser/numMaps) * mapId; // For multiple output files numCellPerfile = (lastCell + 1) / numFiles; numCellInLastFile = (lastCell + 1) - numCellPerfile * (numFiles - 1); if (numCellPerfile < numberOfCellPerWindow) { System.out .println("The number of Cell per file should be greater than that of a window "); System.exit(-1); } if (isFullLoad){ // Init all dictionaries System.out .println("Building interests dictionary & locations/interests distribution "); interestDic = new InterestDictionary(sibDicDataDir + interestDicFile, sibDicDataDir + interestNamesFile, seeds[5], sibDicDataDir + musicGenreFile); interestDic.init(); System.out.println("Building locations dictionary "); locationDic = new LocationDictionary(numtotalUser, seeds[7] ,sibDicDataDir + countryDicFile, sibDicDataDir + cityDicFile); locationDic.init(); languageDic = new LanguageDictionary(sibDicDataDir + languageDicFile, locationDic.getLocationNameMapping(), probEnglish, probSecondLang, seeds[11]); languageDic.init(); System.out.println("Building Tags dictionary "); mainTagDic = new TagDictionary(sibDicDataDir + tagNamesFile, sibDicDataDir + mainTagDicFile, locationDic.getLocationNameMapping().size(), seeds[5], tagCountryCorrProb); mainTagDic.extractTags(); System.out.println("Building Tag Matrix dictionary "); topicTagDic = new TagMatrix(sibDicDataDir + topicTagDicFile, mainTagDic.getNumCelebrity() , seeds[5]); topicTagDic.initMatrix(); ipAddDictionary = new IPAddressDictionary(sibDicDataDir + countryAbbrMappingFile, ipZoneDir, locationDic.getVecLocations(), seeds[33], probDiffIPinTravelSeason, probDiffIPnotTravelSeason, probDiffIPforTraveller); ipAddDictionary.init(); System.out.println("Building dictionary of articles "); textGenerator = new RandomTextGenerator(sibDicDataDir + regionalArticleFile, sibDicDataDir + interestArticleFile, sibDicDataDir + stopWordFileName, seeds[15], seeds[16], numArticles, locationDic.getLocationNameMapping(), interestDic.getInterestNames(), dateTimeGenerator, minTextSize, maxTextSize, minCommentSize, maxCommentSize, ratioReduceText, seeds[31]); groupGenerator = new GroupGenerator(dateTimeGenerator, locationDic, mainTagDic, numtotalUser, seeds[35]); namesDictionary = new NamesDictionary(sibDicDataDir + surnamesDicFile, sibDicDataDir + givennamesDicFile, locationDic.getLocationNameMapping(), seeds[23], geometricProb); namesDictionary.init(); emailDic = new EmailDictionary(sibDicDataDir + emailDicFile, seeds[32]); emailDic.init(); browserDic = new BrowserDictionary(sibDicDataDir + browserDicFile, seeds[44], probAnotherBrowser); browserDic.init(); organizationsDictionary = new OrganizationsDictionary( sibDicDataDir + organizationsDicFile, locationDic.getLocationNameMapping(), seeds[24], probUnCorrelatedOrganization, seeds[45], probTopUniv, locationDic); organizationsDictionary.init(); companiesDictionary = new CompanyDictionary(sibDicDataDir + companiesDicFile, locationDic.getLocationNameMapping(), seeds[40], probUnCorrelatedCompany); companiesDictionary.init(); popularDictionary = new PopularPlacesDictionary(sibDicDataDir + popularPlacesDicFile, locationDic.getLocationNameMapping(), seeds[46]); popularDictionary.init(); photoGenerator = new PhotoGenerator(dateTimeGenerator, locationDic.getVecLocations(), seeds[17], maxNumUserTags, popularDictionary, probPopularPlaces); System.out.println("Building user agents dictionary"); userAgentDic = new UserAgentDictionary(sibDicDataDir + agentFile, seeds[28], seeds[30], probSentFromAgent); userAgentDic.init(); textGenerator.setSupportDictionaries(userAgentDic, ipAddDictionary, browserDic); outputDataWriter = new OutputDataWriter(); serializer = getSerializer(serializerType, rdfOutputFileName); } } public void generateGroupAll(String inputFile, int numberOfCell){ // Fifth pass: Group & group posts generator groupStoreManager = new StorageManager(cellSize, windowSize, outUserProfile, sibOutputDir); groupStoreManager.initDeserialization(inputFile); generateGroups(); int curCellPost = 0; while (curCellPost < (numberOfCell - numberOfCellPerWindow)){ curCellPost++; generateGroups(4, curCellPost, numberOfCell); } System.out.println("Done generating user groups and groups' posts"); groupStoreManager.endDeserialization(); System.out.println("Number of deserialized objects for group is " + groupStoreManager.getNumberDeSerializedObject()); } public int numUserProfilesRead = 0; public int numUserForNewCell = 0; public int mrCurCellPost = 0; public ReducedUserProfile[] cellReducedUserProfiles; public int exactOutput = 0; public void pushUserProfile(ReducedUserProfile reduceUser, int pass, Reducer<IntWritable, ReducedUserProfile,IntWritable, ReducedUserProfile>.Context context, boolean isContext, ObjectOutputStream oos){ numUserProfilesRead++; ReducedUserProfile userObject = new ReducedUserProfile(); userObject.copyFields(reduceUser); if (numUserProfilesRead < windowSize){ if (reducedUserProfiles[numUserProfilesRead-1] != null){ reducedUserProfiles[numUserProfilesRead-1].clear(); reducedUserProfiles[numUserProfilesRead-1] = null; } reducedUserProfiles[numUserProfilesRead-1] = userObject; } else if (numUserProfilesRead == windowSize){ if (reducedUserProfiles[numUserProfilesRead-1] != null){ reducedUserProfiles[numUserProfilesRead-1].clear(); reducedUserProfiles[numUserProfilesRead-1] = null; } reducedUserProfiles[numUserProfilesRead-1] = userObject; mr2InitFriendShipWindow(pass, context, isContext, oos); } else{ numUserForNewCell++; if (cellReducedUserProfiles[numUserForNewCell-1] != null){ cellReducedUserProfiles[numUserForNewCell-1] = null; } cellReducedUserProfiles[numUserForNewCell-1] = userObject; if (numUserForNewCell == cellSize){ mrCurCellPost++; mr2SlideFriendShipWindow(pass,mrCurCellPost, context, cellReducedUserProfiles, isContext, oos); numUserForNewCell = 0; } } if (reduceUser != null){ reduceUser = null; } } public void pushAllRemainingUser(int pass, Reducer<IntWritable, ReducedUserProfile,IntWritable, ReducedUserProfile>.Context context, boolean isContext, ObjectOutputStream oos){ int numLeftCell = numberOfCellPerWindow - 1; while (numLeftCell > 0){ mrCurCellPost++; mr2SlideLastCellsFriendShip(pass, mrCurCellPost, numLeftCell, context, isContext, oos); numLeftCell--; } } public void mrGenerateUserInfo(int pass, Context context, int mapIdx){ int numToGenerateUser; if (numMaps == mapIdx){ numToGenerateUser = numCellInLastFile * cellSize; } else numToGenerateUser = numCellPerfile * cellSize; System.out.println("numToGenerateUser in Machine " + mapIdx + " = " + numToGenerateUser); int numZeroPopularPlace = 0; for (int i = 0; i < numToGenerateUser; i++) { UserProfile user = generateGeneralInformation(i + startMapUserIdx); ReducedUserProfile reduceUserProf = new ReducedUserProfile(user, numCorrDimensions); if (reduceUserProf.getNumPopularPlace() == 0) numZeroPopularPlace++; user = null; try { context.write(new IntWritable(reduceUserProf.getDicElementId(pass)), reduceUserProf); //System.out.println("[Debug] mrGenerateUserInfo - Number of popular places " + reduceUserProf.getNumPopularPlace()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Number of Zero popular places: " + numZeroPopularPlace); } public void initBasicParams(String args[], int _numMaps, String _mrInputFile, int mapIdx){ loadParamsFromFile(); numFiles = _numMaps; rdfOutputFileName = "mr" + mapreduceFileIdx + "_" + rdfOutputFileName; rdfOutputFileName = rdfOutputFileName + numtotalUser; init(mapIdx, false); System.out.println("Number of files " + numFiles); System.out.println("Number of cells per file " + numCellPerfile); System.out.println("Number of cells in last file " + numCellInLastFile); mrWriter = new MRWriter(cellSize, windowSize, sibOutputDir); } public void generateCellOfUsers2(int newStartIndex, ReducedUserProfile[] _cellReduceUserProfiles){ int curIdxInWindow; for (int i = 0; i < cellSize; i++) { curIdxInWindow = newStartIndex + i; if (reducedUserProfiles[curIdxInWindow] != null){ reducedUserProfiles[curIdxInWindow].clear(); reducedUserProfiles[curIdxInWindow] = null; } reducedUserProfiles[curIdxInWindow] = _cellReduceUserProfiles[i]; } } public void mr2InitFriendShipWindow(int pass, Reducer.Context context, boolean isContext, ObjectOutputStream oos){ //Generate the friendship in the first window // Create the friend based on the location info //Runtime.getRuntime().gc(); double randProb; for (int i = 0; i < cellSize; i++) { // From this user, check all the user in the window to create friendship for (int j = i + 1; j < windowSize - 1; j++) { if (reducedUserProfiles[i].getNumFriendsAdded() == reducedUserProfiles[i].getNumFriends(pass)) break; if (reducedUserProfiles[j].getNumFriendsAdded() == reducedUserProfiles[j].getNumFriends(pass)) continue; if (reducedUserProfiles[i].isExistFriend( reducedUserProfiles[j].getAccountId())) continue; // Generate a random value randProb = randUniform.nextDouble(); double prob = getFriendCreatePro(i, j, pass); if ((randProb < prob) || (randProb < limitProCorrelated)) { // add a friendship createFriendShip(reducedUserProfiles[i], reducedUserProfiles[j], (byte) pass); } } } updateLastPassFriendAdded(0, cellSize, pass); mrWriter.writeReducedUserProfiles(0, cellSize, pass, reducedUserProfiles, context, isContext, oos); exactOutput = exactOutput + cellSize; } public void mr2SlideFriendShipWindow(int pass, int cellPos, Reducer.Context context, ReducedUserProfile[] _cellReduceUserProfiles, boolean isContext, ObjectOutputStream oos){ // In window, position of new cell = the position of last removed cell = // cellPos - 1 int newCellPosInWindow = (cellPos - 1) % numberOfCellPerWindow; int newStartIndex = newCellPosInWindow * cellSize; int curIdxInWindow; // Init the number of friends for each user in the new cell generateCellOfUsers2(newStartIndex, _cellReduceUserProfiles); // Create the friendships // Start from each user in the first cell of the window --> at the // cellPos, not from the new cell newStartIndex = (cellPos % numberOfCellPerWindow) * cellSize; for (int i = 0; i < cellSize; i++) { curIdxInWindow = newStartIndex + i; // Generate set of friends list // Here assume that all the users in the window including the new // cell have the number of friends // and also the number of friends to add double randProb; if (reducedUserProfiles[curIdxInWindow].getNumFriendsAdded() == reducedUserProfiles[curIdxInWindow].getNumFriends(pass)) continue; // From this user, check all the user in the window to create // friendship for (int j = i + 1; (j < windowSize - 1) && reducedUserProfiles[curIdxInWindow].getNumFriendsAdded() < reducedUserProfiles[curIdxInWindow].getNumFriends(pass); j++) { int checkFriendIdx = (curIdxInWindow + j) % windowSize; if (reducedUserProfiles[checkFriendIdx].getNumFriendsAdded() == reducedUserProfiles[checkFriendIdx].getNumFriends(pass)) continue; if (reducedUserProfiles[curIdxInWindow].isExistFriend( reducedUserProfiles[checkFriendIdx].getAccountId())) continue; // Generate a random value randProb = randUniform.nextDouble(); double prob = getFriendCreatePro(curIdxInWindow, checkFriendIdx, pass); if ((randProb < prob) || (randProb < limitProCorrelated)) { // add a friendship createFriendShip(reducedUserProfiles[curIdxInWindow], reducedUserProfiles[checkFriendIdx], (byte) pass); } } } updateLastPassFriendAdded(newStartIndex, newStartIndex + cellSize, pass); mrWriter.writeReducedUserProfiles(newStartIndex, newStartIndex + cellSize, pass, reducedUserProfiles, context, isContext, oos); exactOutput = exactOutput + cellSize; } public void mr2SlideLastCellsFriendShip(int pass, int cellPos, int numleftCell, Reducer.Context context, boolean isContext, ObjectOutputStream oos) { int newStartIndex; int curIdxInWindow; newStartIndex = (cellPos % numberOfCellPerWindow) * cellSize; //System.out.println("LastCell: Slide at start index " + newStartIndex); for (int i = 0; i < cellSize; i++) { curIdxInWindow = newStartIndex + i; // Generate set of friends list // Here assume that all the users in the window including the new // cell have the number of friends // and also the number of friends to add double randProb; if (reducedUserProfiles[curIdxInWindow].getNumFriendsAdded() == reducedUserProfiles[curIdxInWindow].getNumFriends(pass)) continue; // From this user, check all the user in the window to create // friendship for (int j = i + 1; (j < numleftCell * cellSize - 1) && reducedUserProfiles[curIdxInWindow].getNumFriendsAdded() < reducedUserProfiles[curIdxInWindow].getNumFriends(pass); j++) { int checkFriendIdx = (curIdxInWindow + j) % windowSize; if (reducedUserProfiles[checkFriendIdx].getNumFriendsAdded() == reducedUserProfiles[checkFriendIdx].getNumFriends(pass)) continue; if (reducedUserProfiles[curIdxInWindow].isExistFriend( reducedUserProfiles[checkFriendIdx].getAccountId())) continue; // Generate a random value randProb = randUniform.nextDouble(); double prob = getFriendCreatePro(curIdxInWindow, checkFriendIdx, pass); if ((randProb < prob) || (randProb < limitProCorrelated)) { // add a friendship createFriendShip(reducedUserProfiles[curIdxInWindow], reducedUserProfiles[checkFriendIdx], (byte) pass); } } } updateLastPassFriendAdded(newStartIndex, newStartIndex + cellSize, pass); mrWriter.writeReducedUserProfiles(newStartIndex, newStartIndex + cellSize, pass, reducedUserProfiles, context, isContext, oos); exactOutput = exactOutput + cellSize; } // inputFile for this step is the file that public void generatePostandPhoto(String inputFile, int numOfCells) { // Init neccessary objects StorageManager storeManager = new StorageManager(cellSize, windowSize, outUserProfile, sibOutputDir); storeManager.initDeserialization(inputFile); reducedUserProfilesCell = new ReducedUserProfile[cellSize]; System.out.println("Generating the posts & comments "); // Processing for each cell in the file System.out.println("Number of cells in file : " + numOfCells); for (int j = 0; j < numOfCells; j++) { storeManager.deserializeOneCellUserProfile(reducedUserProfilesCell); for (int k = 0; k < cellSize; k++) { // Generate extra info such as names, organization before // writing out UserExtraInfo extraInfo = new UserExtraInfo(); setInfoFromUserProfile(reducedUserProfilesCell[k], extraInfo); // serializer.gatherData(userProfilesCell[k]); serializer.gatherData(reducedUserProfilesCell[k], extraInfo); generateLocationPost(reducedUserProfilesCell[k], extraInfo); generateInterestPost(reducedUserProfilesCell[k], extraInfo); generatePhoto(reducedUserProfilesCell[k], extraInfo); } } storeManager.endDeserialization(); System.out.println("Done generating the posts and photos...."); System.out.println("Number of deserialized objects is " + storeManager.getNumberDeSerializedObject()); } public void generateLocationPost(ReducedUserProfile user, UserExtraInfo extraInfo){ // Generate location-related posts int numRegionalPost = getNumOfRegionalPost(user); for (int m = 0; m < numRegionalPost; m++) { Post post = textGenerator.getRandomRegionalPost(user, maxNumLikes); Integer languageIndex = randUniform.nextInt(extraInfo.getLanguages().size()); post.setLanguage(extraInfo.getLanguages().get(languageIndex)); // Set user agent userAgentDic.setPostUserAgent(user, post); ipAddDictionary.setPostIPAdress(user.isFrequentChange(), user.getIpAddress(), post); // set browser idx post.setBrowserIdx(browserDic.getPostBrowserId(user.getBrowserIdx())); serializer.gatherData(post); // Generate comments int numComment = randNumberComments.nextInt(maxNumComments); long lastCommentCreateDate = post.getCreatedDate(); long lastCommentId = -1; long startCommentId = RandomTextGenerator.commentId; for (int l = 0; l < numComment; l++) { Comment comment = textGenerator.getRandomRegionalComment(post, user, lastCommentCreateDate, startCommentId, lastCommentId); if (comment.getAuthorId() != -1) { serializer.gatherData(comment); lastCommentCreateDate = comment.getCreateDate(); lastCommentId = comment.getCommentId(); } } } } public void generateInterestPost(ReducedUserProfile user, UserExtraInfo extraInfo){ // Generate interest-related posts int numInterstPost = getNumOfInterestPost(user); for (int m = 0; m < numInterstPost; m++) { Post post = textGenerator.getRandomInterestPost( user, maxNumLikes); Integer languageIndex = randUniform.nextInt(extraInfo.getLanguages().size()); post.setLanguage(extraInfo.getLanguages().get(languageIndex)); userAgentDic.setPostUserAgent(user, post); ipAddDictionary.setPostIPAdress(user.isFrequentChange(), user.getIpAddress(), post); // set browser idx post.setBrowserIdx(browserDic.getPostBrowserId(user.getBrowserIdx())); serializer.gatherData(post); // Generate comment for interest-related post int numComment = randNumberComments .nextInt(maxNumComments); long lastCommentCreateDate = post.getCreatedDate(); long lastCommentId = -1; long startCommentId = RandomTextGenerator.commentId; for (int l = 0; l < numComment; l++) { Comment comment = textGenerator.getRandomInterestComment(post, user,lastCommentCreateDate, startCommentId, lastCommentId); // In case the comment is not created because of the friendship's createddate if (comment.getAuthorId() != -1) { serializer.gatherData(comment); lastCommentCreateDate = comment.getCreateDate(); lastCommentId = comment.getCommentId(); } } } } public void generatePhoto(ReducedUserProfile user, UserExtraInfo extraInfo){ // Generate photo Album and photos int numOfmonths = (int) dateTimeGenerator.numberOfMonths(user); int numPhotoAlbums; if (numOfmonths == 0){ numPhotoAlbums = randNumberPhotoAlbum .nextInt(maxNumPhotoAlbums); } else numPhotoAlbums = numOfmonths * randNumberPhotoAlbum .nextInt(maxNumPhotoAlbums); for (int m = 0; m < numPhotoAlbums; m++) { PhotoAlbum album = photoGenerator.generateAlbum(user); serializer.gatherData(album); // Generate photos for this album int numPhotos = randNumberPhotos.nextInt(maxNumPhotoPerAlbums); for (int l = 0; l < numPhotos; l++) { Photo photo = photoGenerator.generatePhoto(user, album, l, maxNumLikes); // Set user agent userAgentDic.setPhotoUserAgent(user, photo); // set browser idx photo.setBrowserIdx(browserDic.getPostBrowserId(user.getBrowserIdx())); ipAddDictionary.setPhotoIPAdress(user.isFrequentChange(), user.getIpAddress(), photo); serializer.gatherData(photo); } } } // The group only created from users and their friends in the current // sliding window. // We do that, because we need the user's created date information for // generating the // group's joining datetime and group's post created date. // For one user, a number of groups are created. For each group, the number // of members is first // generated. // To select a member for joining the group // First, select which level of friends that we are considering // Second, randomSelect one user in that level // Decide whether that user can be a member of the group by their joinProb public void generateGroups() { System.out.println("Generating user groups "); //deserializeWindowlUserProfile(3); groupStoreManager.deserializeWindowlUserProfile(reducedUserProfiles); // Init a window of removed users, now it is empty removedUserProfiles = new ReducedUserProfile[windowSize]; double moderatorProb; for (int i = 0; i < cellSize; i++) { moderatorProb = randGroupModerator.nextDouble(); if (moderatorProb > groupModeratorProb) continue; Friend firstLevelFriends[]; Vector<Friend> secondLevelFriends = new Vector<Friend>(); // Get the set of first and second level friends firstLevelFriends = reducedUserProfiles[i].getFriendList(); for (int j = 0; j < reducedUserProfiles[i].getNumFriendsAdded(); j++) { int friendId = firstLevelFriends[j].getFriendAcc(); int friendIdxInWindow = getIdxInWindow(0, 0, friendId); if (friendIdxInWindow != -1) { Friend friendOfFriends[] = reducedUserProfiles[friendIdxInWindow] .getFriendList(); for (int k = 0; k < friendOfFriends.length; k++) { if (friendOfFriends[k] != null) secondLevelFriends.add(friendOfFriends[k]); else break; } } } // Create a group whose the moderator is the current user int numGroup = randNumberGroup.nextInt(maxNumGroupCreatedPerUser); for (int j = 0; j < numGroup; j++) { createGroupForUser(reducedUserProfiles[i], firstLevelFriends, secondLevelFriends); } } } public void generateGroups(int pass, int cellPos, int numberCellInFile) { int newCellPosInWindow = (cellPos - 1) % numberOfCellPerWindow; int newIdxInWindow = newCellPosInWindow * cellSize; ; // Store the to-be-removed cell to the window storeCellToRemovedWindow(newIdxInWindow, cellSize, pass); // Deserialize the cell from file //deserializeOneCellUserProfile(newIdxInWindow, cellSize, pass); groupStoreManager.deserializeOneCellUserProfile(newIdxInWindow, cellSize, reducedUserProfiles); int newStartIndex = (cellPos % numberOfCellPerWindow) * cellSize; int curIdxInWindow; double moderatorProb; for (int i = 0; i < cellSize; i++) { moderatorProb = randGroupModerator.nextDouble(); if (moderatorProb > groupModeratorProb) continue; curIdxInWindow = newStartIndex + i; Friend firstLevelFriends[]; Vector<Friend> secondLevelFriends = new Vector<Friend>(); // Get the set of first and second level friends firstLevelFriends = reducedUserProfiles[curIdxInWindow].getFriendList(); // Create a group whose the moderator is the current user int numGroup = randNumberGroup.nextInt(maxNumGroupCreatedPerUser); for (int j = 0; j < numGroup; j++) { //System.out.println(" createGroupForUser for userId " + reducedUserProfiles[curIdxInWindow].getAccountId()); createGroupForUser(reducedUserProfiles[curIdxInWindow], firstLevelFriends, secondLevelFriends); } } } public int getIdxInWindow(int startIndex, int startUserId, int userAccId) { // (cellPos % numberOfCellPerWindow) * cellSize; if (((startUserId + windowSize) <= userAccId) || (startUserId > userAccId)) { return -1; } else return (startIndex + (userAccId - startUserId)) % windowSize; } public int getIdxInRemovedWindow(int startIndex, int startUserId, int userAccId) { if (userAccId >= startUserId || ((userAccId + windowSize) < startUserId)) { return -1; } else return (startIndex + (userAccId + windowSize - startUserId)) % windowSize; } public void createGroupForUser(ReducedUserProfile user, Friend firstLevelFriends[], Vector<Friend> secondLevelFriends) { double randLevelProb; double randMemberProb; Group group = groupGenerator.createGroup(user); HashSet<Integer> memberIds = new HashSet<Integer>(); int numGroupMember = randNumberUserPerGroup.nextInt(maxNumMemberGroup); group.initAllMemberships(numGroupMember); //System.out.println("numGroupMember = " + numGroupMember); int numLoop = 0; //int maxLoop = windowSize * 2; while ((group.getNumMemberAdded() < numGroupMember) && (numLoop < windowSize)) { numLoop++; randLevelProb = randFriendLevelSelect.nextDouble(); // Select the appropriate friend level if (randLevelProb < levelProbs[0]) { // ==> level 1 // Find a friendIdx int friendIdx = randMemberIdxSelector.nextInt(user .getNumFriendsAdded()); // Note: Use user.getNumFriendsAdded(), do not use // firstLevelFriends.length // because we allocate a array for friendLists, but do not // guarantee that // all the element in this array contain values int potentialMemberAcc = firstLevelFriends[friendIdx].getFriendAcc(); randMemberProb = randMembership.nextDouble(); if (randMemberProb < joinProbs[0]) { // Check whether this user has been added and then add to // the group if (!memberIds.contains(potentialMemberAcc)) { memberIds.add(potentialMemberAcc); // Assume the earliest membership date is the friendship // created date GroupMemberShip memberShip = groupGenerator .createGroupMember(potentialMemberAcc, group .getCreatedDate(), firstLevelFriends[friendIdx] .getCreatedTime()); group.addMember(memberShip); } } } else if (randLevelProb < levelProbs[1]) { // ==> level 2 // if (secondLevelFriends.size() == 0) continue; int friendIdx = randMemberIdxSelector .nextInt(secondLevelFriends.size()); int potentialMemberAcc = secondLevelFriends.get(friendIdx) .getFriendAcc(); randMemberProb = randMembership.nextDouble(); if (randMemberProb < joinProbs[1]) { // Check whether this user has been added and then add to // the group if (!memberIds.contains(potentialMemberAcc)) { memberIds.add(potentialMemberAcc); // Assume the earliest membership date is the friendship // created date GroupMemberShip memberShip = groupGenerator .createGroupMember(potentialMemberAcc, group .getCreatedDate(), secondLevelFriends .get(friendIdx).getCreatedTime()); group.addMember(memberShip); } } } else { // ==> random users // Select a user from window int friendIdx = randMemberIdxSelector.nextInt(windowSize); int potentialMemberAcc = reducedUserProfiles[friendIdx].getAccountId(); randMemberProb = randMembership.nextDouble(); if (randMemberProb < joinProbs[2]) { // Check whether this user has been added and then add to // the group if (!memberIds.contains(potentialMemberAcc)) { memberIds.add(potentialMemberAcc); GroupMemberShip memberShip = groupGenerator .createGroupMember(potentialMemberAcc, group .getCreatedDate(), reducedUserProfiles[friendIdx] .getCreatedDate()); group.addMember(memberShip); } } } } serializer.gatherData(group); // Generate posts and comments for this groups generatePostForGroup(group); } public void generatePostForGroup(Group group) { int numberGroupPost = getNumOfGroupPost(group); // System.out.println("Group post number for group " + // group.getGroupId() + " : " + numberGroupPost); for (int i = 0; i < numberGroupPost; i++) { Post groupPost = textGenerator.getRandomGroupPost(group, maxNumLikes); groupPost.setUserAgent(""); groupPost.setBrowserIdx((byte) -1); // groupPost.setIpAddress(new // IP((short)-1,(short)-1,(short)-1,(short)-1)); serializer.gatherData(groupPost); int numComment = randNumberComments.nextInt(maxNumComments); long lastCommentCreateDate = groupPost.getCreatedDate(); long lastCommentId = -1; long startCommentId = RandomTextGenerator.commentId; for (int j = 0; j < numComment; j++) { Comment comment = textGenerator.getRandomGroupComment( groupPost, group, lastCommentCreateDate, startCommentId, lastCommentId); if (comment.getAuthorId() != -1) { // In case the comment is not // created because of // the friendship's createddate comment.setUserAgent(""); comment.setBrowserIdx((byte) -1); serializer.gatherData(comment); lastCommentCreateDate = comment.getCreateDate(); lastCommentId = comment.getCommentId(); } } } } // User has more friends will have more posts // Thus, the number of post is calculated according // to the number of friends and createdDate of a user public int getNumOfRegionalPost(ReducedUserProfile user) { int numOfmonths = (int) dateTimeGenerator.numberOfMonths(user); int numberPost; if (numOfmonths == 0) { numberPost = randNumberPost.nextInt(maxNumLocationPostPerMonth); } else numberPost = randNumberPost.nextInt(maxNumLocationPostPerMonth * numOfmonths); numberPost = (numberPost * user.getNumFriendsAdded()) / maxNoFriends; return numberPost; } public int getNumOfInterestPost(ReducedUserProfile user) { int numOfmonths = (int) dateTimeGenerator.numberOfMonths(user); int numberPost; if (numOfmonths == 0) { numberPost = randNumberPost.nextInt(maxNumInterestPostPerMonth); } else numberPost = randNumberPost.nextInt(maxNumInterestPostPerMonth * numOfmonths); numberPost = (numberPost * user.getNumFriendsAdded()) / maxNoFriends; return numberPost; } public int getNumOfGroupPost(Group group) { int numOfmonths = (int) dateTimeGenerator.numberOfMonths(group .getCreatedDate()); // System.out.println("Number of month " + numOfmonths); int numberPost; if (numOfmonths == 0) numberPost = randNumberGroupPost.nextInt(maxNumGroupPostPerMonth); else numberPost = randNumberGroupPost.nextInt(maxNumGroupPostPerMonth * numOfmonths); // System.out.println("Number of post before divided " + numberPost); numberPost = (numberPost * group.getNumMemberAdded()) / maxNumMemberGroup; return numberPost; } public void seedGenerate(int mapIdx) { seeds = new Long[50]; Random seedRandom = new Random(53223436L + 1234567*mapIdx); for (int i = 0; i < 50; i++) { seeds[i] = seedRandom.nextLong(); } } public UserProfile generateGeneralInformation(int accountId) { UserProfile userProf = new UserProfile(); userProf.resetUser(); userProf.setAccountId(accountId); // Create date userProf.setCreatedDate(dateTimeGenerator.randomDateInMillis()); userProf.setNumFriends((short) randPowerlaw.getValue()); userProf.allocateFriendListMemory(numCorrDimensions); short totalFriendSet = 0; for (int i = 0; i < numCorrDimensions-1; i++){ short numPassFriend = (short) Math.floor(friendsRatioPerPass[0] * userProf.getNumFriends()); totalFriendSet = (short) (totalFriendSet + numPassFriend); //userProf.setNumPassFriends(numPassFriend,i); userProf.setNumPassFriends(totalFriendSet,i); } // Prevent the case that the number of friends added exceeds the total number of friends userProf.setNumPassFriends(userProf.getNumFriends(),numCorrDimensions-1); userProf.setNumFriendsAdded((short) 0); userProf.setLocationIdx(locationDic.getLocation(accountId)); userProf.setCityIdx(locationDic.getRandomCity(userProf.getLocationIdx())); userProf.setLocationZId(locationDic.getZorderID(userProf.getLocationIdx())); //Set Main Tag //System.out.println("Main tag for this user. Location " + userProf.getLocationIdx() + // " === Tag: " + mainTagDic.getaTagByCountry(userProf.getLocationIdx()) ); int userMainTag = mainTagDic.getaTagByCountry(userProf.getLocationIdx()); userProf.setMainTagId(userMainTag); userProf.setNumTags((short) (randNumTags.nextInt(maxNoTagsPerUser) + 1)); userProf.setSetOfTags(topicTagDic.getSetofTags(userMainTag, userProf.getNumTags())); // University userProf.setLocationOrganizationId(organizationsDictionary.getRandomOrganization(userProf.getLocationIdx())); // date of birth userProf.setBirthDay(dateTimeGenerator.getBirthDay(userProf.getCreatedDate())); // Gender if (randGender.nextDouble() > 0.5){ userProf.setGender((byte)1); } else { userProf.setGender((byte)0); } userProf.setForumWallId(accountId * 2); // Each user has an wall userProf.setForumStatusId(accountId * 2 + 1); userProf.setNumInterests((short) (randNumInterest .nextInt(maxNoInterestsPerUser) + 1)); // +1 in order to remove the case that the user does not have any // interest // User's Agent if (randUserAgent.nextDouble() > probHavingSmartPhone) { userProf.setHaveSmartPhone(true); userProf.setAgentIdx(userAgentDic.getRandomUserAgentIdx()); } else { userProf.setHaveSmartPhone(false); } // User's browser userProf.setBrowserIdx(browserDic.getRandomBrowserId()); // source IP userProf.setIpAddress(ipAddDictionary .getRandomIPAddressFromLocation(userProf.getLocationIdx())); // Popular places byte numPopularPlaces = (byte) randNumPopularPlaces.nextInt(maxNumPopularPlaces + 1); userProf.setNumPopularPlace(numPopularPlaces); short popularPlaces[] = new short[numPopularPlaces]; for (int i = 0; i < numPopularPlaces; i++){ popularPlaces[i] = popularDictionary.getPopularPlace(userProf.getLocationIdx()); if (popularPlaces[i] == -1){ // no popular place here //System.out.println("[DEBUG] There is a location "+ userProf.getLocationIdx() +" without any popular place"); userProf.setNumPopularPlace((byte)0); break; } } userProf.setPopularPlaceIds(popularPlaces); // Get set of interests userProf.setSetOfInterests(interestDic.getInterests(userProf.getLocationIdx(), userProf.getNumInterests())); userProf.setIntZValue(interestDic.getZValue(userProf.getSetOfInterests())); // Get random Idx userProf.setRandomIdx(randUserRandomIdx.nextInt(maxUserRandomIdx)); return userProf; } public void setInfoFromUserProfile(ReducedUserProfile user, UserExtraInfo userExtraInfo) { // The country will be always present, but the city can be missing if that data is // not available on the dictionary int locationId = (user.getCityIdx() != -1) ? user.getCityIdx() : user.getLocationIdx(); userExtraInfo.setLocationId(locationId); if (user.getCityIdx() != -1) { userExtraInfo.setLocation(locationDic.getCityName(user.getCityIdx())); } else { userExtraInfo.setLocation(locationDic.getLocationName(user.getLocationIdx())); } // We consider that the distance from where user is living and double distance = randomExactLongLat.nextDouble() * 2; userExtraInfo.setLatt(locationDic.getLatt(user.getLocationIdx()) + distance); userExtraInfo.setLongt(locationDic.getLongt(user.getLocationIdx()) + distance); userExtraInfo.setOrganization( organizationsDictionary.getOrganizationName(user.getLocationOrganizationIdx())); // Relationship status if (randomHaveStatus.nextDouble() > missingStatusRatio) { if (randomStatusSingle.nextDouble() < probSingleStatus) { userExtraInfo.setStatus(RelationshipStatus.SINGLE); userExtraInfo.setSpecialFriendIdx(-1); } else { // The two first status, "NO_STATUS" and "SINGLE", are not included int statusIdx = randomStatus.nextInt(RelationshipStatus.values().length - 2) + 2; userExtraInfo.setStatus(RelationshipStatus.values()[statusIdx]); // Select a special friend Friend friends[] = user.getFriendList(); if (user.getNumFriendsAdded() > 0) { int specialFriendId = 0; int numFriendCheck = 0; do { specialFriendId = randomHaveStatus.nextInt(user .getNumFriendsAdded()); numFriendCheck++; } while (friends[specialFriendId].getCreatedTime() == -1 && numFriendCheck < friends.length); if (friends[specialFriendId].getCreatedTime() == -1) {// In case do not find any friendId userExtraInfo.setSpecialFriendIdx(-1); } else { userExtraInfo .setSpecialFriendIdx(friends[specialFriendId] .getFriendAcc()); } } else { userExtraInfo.setSpecialFriendIdx(-1); } } } else { userExtraInfo.setStatus(RelationshipStatus.NOSTATUS); } boolean isMale; if (user.getGender() == 1) { isMale = true; userExtraInfo.setGender(gender[0]); // male } else { isMale = false; userExtraInfo.setGender(gender[1]); // female } userExtraInfo.setFirstName(namesDictionary.getRandomGivenName( user.getLocationIdx(),isMale, dateTimeGenerator.getBirthYear(user.getBirthDay()))); userExtraInfo.setLastName(namesDictionary.getRandomSurName(user .getLocationIdx())); // email is created by using the user's first name + userId int numEmails = randomExtraInfo.nextInt(maxEmails) + 1; double prob = randomExtraInfo.nextDouble(); if (prob >= missingRatio) { String base = userExtraInfo.getFirstName().replaceAll(" ", "."); for (int i = 0; i < numEmails; i++) { String email = base + "" + user.getAccountId() + "@" + emailDic.getRandomEmail(); userExtraInfo.addEmail(email); } } // Set class year prob = randomExtraInfo.nextDouble(); if ((prob < missingRatio) || userExtraInfo.getOrganization().equals("")) { userExtraInfo.setClassYear(-1); } else { userExtraInfo.setClassYear(dateTimeGenerator.getClassYear( user.getCreatedDate(), user.getBirthDay())); } // Set company and workFrom int numCompanies = randomExtraInfo.nextInt(maxCompanies) + 1; prob = randomExtraInfo.nextDouble(); if (prob >= missingRatio) { for (int i = 0; i < numCompanies; i++) { if (userExtraInfo.getClassYear() != -1) { long workFrom = dateTimeGenerator.getWorkFromYear(user.getCreatedDate(), user.getBirthDay()); userExtraInfo.addCompany(companiesDictionary.getRandomCompany(user.getLocationIdx()), workFrom); } else { long workFrom = dateTimeGenerator.getWorkFromYear(userExtraInfo.getClassYear()); userExtraInfo.addCompany(companiesDictionary.getRandomCompany(user.getLocationIdx()), workFrom); } } } Vector<Integer> userLanguages = languageDic.getLanguages(user.getLocationIdx()); int nativeLanguage = randomExtraInfo.nextInt(userLanguages.size()); userExtraInfo.setNativeLanguage(userLanguages.get(nativeLanguage)); int internationalLang = languageDic.getInternationlLanguage(); if (internationalLang != -1 && userLanguages.indexOf(internationalLang) == -1) { userLanguages.add(internationalLang); } userExtraInfo.setLanguages(userLanguages); // write user data for test driver if (user.getNumFriendsAdded() > thresholdPopularUser) { outputDataWriter.writeUserData(user.getAccountId(), user.getNumFriendsAdded()); numPopularUser++; } } public void storeCellToRemovedWindow(int startIdex, int cellSize, int pass) { for (int i = 0; i < cellSize; i++) removedUserProfiles[startIdex + i] = reducedUserProfiles[startIdex + i]; } public double getFriendCreatePro(int i, int j, int pass){ double prob; //prob = baseProbCorrelated * Math.pow(baseExponentialRate, //Math.abs(reducedUserProfiles[i].getDicElementId(pass)- reducedUserProfiles[j].getDicElementId(pass))); if (j > i){ prob = Math.pow(baseProbCorrelated, (j- i)); } else{ prob = Math.pow(baseProbCorrelated, (j + windowSize - i)); } return prob; } public void createFriendShip(ReducedUserProfile user1, ReducedUserProfile user2, byte pass) { long requestedTime = dateTimeGenerator.randomFriendRequestedDate(user1, user2); byte initiator = (byte) randInitiator.nextInt(2); long createdTime = -1; long declinedTime = -1; if (randFriendReject.nextDouble() > friendRejectRatio) { createdTime = dateTimeGenerator .randomFriendApprovedDate(requestedTime); } else { declinedTime = dateTimeGenerator .randomFriendDeclinedDate(requestedTime); if (randFriendReapprov.nextDouble() < friendReApproveRatio) { createdTime = dateTimeGenerator .randomFriendReapprovedDate(declinedTime); } } user2.addNewFriend(new Friend(user1, requestedTime, declinedTime, createdTime, pass, initiator)); user1.addNewFriend(new Friend(user2, requestedTime, declinedTime, createdTime, pass, initiator)); friendshipNo++; } public void updateLastPassFriendAdded(int from, int to, int pass) { if (to > windowSize) { for (int i = from; i < windowSize; i++) { reducedUserProfiles[i].setPassFriendsAdded(pass, reducedUserProfiles[i].getNumFriendsAdded()); } for (int i = 0; i < to - windowSize; i++) { reducedUserProfiles[i].setPassFriendsAdded(pass, reducedUserProfiles[i].getNumFriendsAdded()); } } else { for (int i = from; i < to; i++) { reducedUserProfiles[i].setPassFriendsAdded(pass, reducedUserProfiles[i].getNumFriendsAdded()); } } } // private static Serializer getSerializer(String type) { private Serializer getSerializer(String type, String outputFileName) { String t = type.toLowerCase(); if (t.equals("ttl")) { return new Turtle(sibOutputDir + outputFileName, forwardChaining, numRdfOutputFile, true, mainTagDic.getTagsNamesMapping(), browserDic.getvBrowser(), companiesDictionary.getCompanyCountryMap(), organizationsDictionary.GetOrganizationLocationMap(), ipAddDictionary, locationDic, languageDic); } else if (t.equals("nt")) { return new Turtle(sibOutputDir + outputFileName, forwardChaining, numRdfOutputFile, false, mainTagDic.getTagsNamesMapping(), browserDic.getvBrowser(), companiesDictionary.getCompanyCountryMap(), organizationsDictionary.GetOrganizationLocationMap(), ipAddDictionary, locationDic, languageDic); } else if (t.equals("csv")) { return new CSV(sibOutputDir /*+ outputFileName*/, forwardChaining, numRdfOutputFile, mainTagDic.getTagsNamesMapping(), browserDic.getvBrowser(), companiesDictionary.getCompanyCountryMap(), ipAddDictionary,locationDic, languageDic); } else { return null; } } private void startWritingUserData() { outputDataWriter.initWritingUserData(); } private void finishWritingUserData() { outputDataWriter.finishWritingUserData(); } public void writeToOutputFile(String filenames[], String outputfile){ Writer output = null; File file = new File(outputfile); try { output = new BufferedWriter(new FileWriter(file)); for (int i = 0; i < (filenames.length - 1); i++) output.write(filenames[i] + " " + numCellPerfile + "\n"); output.write(filenames[filenames.length - 1] + " " + numCellInLastFile + "\n"); output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getDuration(long startTime, long endTime){ String duration = (endTime - startTime) / 60000 + " minutes and " + ((endTime - startTime) % 60000) / 1000 + " seconds"; return duration; } public void printHeapSize(){ long heapSize = Runtime.getRuntime().totalMemory(); long heapMaxSize = Runtime.getRuntime().maxMemory(); long heapFreeSize = Runtime.getRuntime().freeMemory(); System.out.println(" ---------------------- "); System.out.println(" Current Heap Size: " + heapSize/(1024*1024)); System.out.println(" Max Heap Size: " + heapMaxSize/(1024*1024)); System.out.println(" Free Heap Size: " + heapFreeSize/(1024*1024)); System.out.println(" ---------------------- "); } public int getCellSize() { return cellSize; } public int getMapId() { return machineId; } public void setMapId(int mapId) { this.machineId = mapId; } }
true
true
public void loadParamsFromFile() { try { //First read the internal params.ini BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(getClass( ).getResourceAsStream("/"+paramFileName), "UTF-8")); String line; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("cellSize")) { cellSize = Short.parseShort(infos[1].trim()); continue; } else if (infos[0].startsWith("numberOfCellPerWindow")) { numberOfCellPerWindow = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minNoFriends")) { minNoFriends = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoFriends")) { maxNoFriends = Integer.parseInt(infos[1].trim()); thresholdPopularUser = (int) (maxNoFriends * 0.9); continue; } else if (infos[0].startsWith("friendRejectRatio")) { friendRejectRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("friendReApproveRatio")) { friendReApproveRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoInterestsPerUser")) { maxNoInterestsPerUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoTagsPerUser")) { maxNoTagsPerUser= Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumLocationPostPerMonth")) { maxNumLocationPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumInterestPostPerMonth")) { maxNumInterestPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumComments")) { maxNumComments = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("limitProCorrelated")) { limitProCorrelated = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("baseProbCorrelated")) { baseProbCorrelated = Double .parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxEmails")) { maxEmails = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCompanies")) { maxCompanies = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probEnglish")) { probEnglish = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSecondLang")) { probSecondLang = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probAnotherBrowser")) { probAnotherBrowser = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("minTextSize")) { minTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxTextSize")) { maxTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minCommentSize")) { minCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCommentSize")) { maxCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("ratioReduceText")) { ratioReduceText = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumUserTags")) { maxNumUserTags = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoAlbums")) { maxNumPhotoAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoPerAlbums")) { maxNumPhotoPerAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupCreatedPerUser")) { maxNumGroupCreatedPerUser = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumMemberGroup")) { maxNumMemberGroup = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("groupModeratorProb")) { groupModeratorProb = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupPostPerMonth")) { maxNumGroupPostPerMonth = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; }else if (infos[0].startsWith("missingRatio")) { missingRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("missingStatusRatio")) { missingStatusRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSingleStatus")) { probSingleStatus = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probHavingSmartPhone")) { probHavingSmartPhone = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSentFromAgent")) { probSentFromAgent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnFrequent")) { probUnFrequent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probDiffIPinTravelSeason")) { probDiffIPinTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPnotTravelSeason")) { probDiffIPnotTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPforTraveller")) { probDiffIPforTraveller = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedCompany")) { probUnCorrelatedCompany = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedOrganization")) { probUnCorrelatedOrganization = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probTopUniv")) { probTopUniv = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPopularPlaces")) { maxNumPopularPlaces = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probPopularPlaces")) { probPopularPlaces = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("tagCountryCorrProb")) { tagCountryCorrProb = Double.parseDouble(infos[1].trim()); continue; } } paramFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { //read the user param file BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(new FileInputStream(sibHomeDir + paramFileName), "UTF-8")); String line; numtotalUser = -1; int numYears = -1; startYear = -1; serializerType = ""; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("numtotalUser")) { numtotalUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("startYear")) { startYear = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("numYears")) { numYears = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; } else { System.out.println("This param " + line + " does not match any option"); } } paramFile.close(); if (numtotalUser == -1) { throw new Exception("No numtotalUser parameter provided"); } if (startYear == -1) { throw new Exception("No startYears parameter provided"); } if (numYears == -1) { throw new Exception("No numYears parameter provided"); } if (!serializerType.equals("ttl") && !serializerType.equals("nt") && serializerType.equals("csv")) { throw new Exception("serializerType must be ttl, nt or csv"); } endYear = startYear + numYears; } catch (Exception e) { System.out.println("Using default configuration"); // If the user params file wasn't found use the default configuration. } }
public void loadParamsFromFile() { try { //First read the internal params.ini BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(getClass( ).getResourceAsStream("/"+paramFileName), "UTF-8")); String line; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("cellSize")) { cellSize = Short.parseShort(infos[1].trim()); continue; } else if (infos[0].startsWith("numberOfCellPerWindow")) { numberOfCellPerWindow = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minNoFriends")) { minNoFriends = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoFriends")) { maxNoFriends = Integer.parseInt(infos[1].trim()); thresholdPopularUser = (int) (maxNoFriends * 0.9); continue; } else if (infos[0].startsWith("friendRejectRatio")) { friendRejectRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("friendReApproveRatio")) { friendReApproveRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoInterestsPerUser")) { maxNoInterestsPerUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNoTagsPerUser")) { maxNoTagsPerUser= Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumLocationPostPerMonth")) { maxNumLocationPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumInterestPostPerMonth")) { maxNumInterestPostPerMonth = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumComments")) { maxNumComments = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("limitProCorrelated")) { limitProCorrelated = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("baseProbCorrelated")) { baseProbCorrelated = Double .parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxEmails")) { maxEmails = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCompanies")) { maxCompanies = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probEnglish")) { probEnglish = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSecondLang")) { probSecondLang = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probAnotherBrowser")) { probAnotherBrowser = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("minTextSize")) { minTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxTextSize")) { maxTextSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("minCommentSize")) { minCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxCommentSize")) { maxCommentSize = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("ratioReduceText")) { ratioReduceText = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumUserTags")) { maxNumUserTags = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoAlbums")) { maxNumPhotoAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPhotoPerAlbums")) { maxNumPhotoPerAlbums = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupCreatedPerUser")) { maxNumGroupCreatedPerUser = Integer.parseInt(infos[1] .trim()); continue; } else if (infos[0].startsWith("maxNumMemberGroup")) { maxNumMemberGroup = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("groupModeratorProb")) { groupModeratorProb = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumGroupPostPerMonth")) { maxNumGroupPostPerMonth = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; }else if (infos[0].startsWith("missingRatio")) { missingRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("missingStatusRatio")) { missingStatusRatio = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSingleStatus")) { probSingleStatus = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probHavingSmartPhone")) { probHavingSmartPhone = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probSentFromAgent")) { probSentFromAgent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnFrequent")) { probUnFrequent = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probDiffIPinTravelSeason")) { probDiffIPinTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPnotTravelSeason")) { probDiffIPnotTravelSeason = Double.parseDouble(infos[1] .trim()); continue; } else if (infos[0].startsWith("probDiffIPforTraveller")) { probDiffIPforTraveller = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedCompany")) { probUnCorrelatedCompany = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probUnCorrelatedOrganization")) { probUnCorrelatedOrganization = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("probTopUniv")) { probTopUniv = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("maxNumPopularPlaces")) { maxNumPopularPlaces = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("probPopularPlaces")) { probPopularPlaces = Double.parseDouble(infos[1].trim()); continue; } else if (infos[0].startsWith("tagCountryCorrProb")) { tagCountryCorrProb = Double.parseDouble(infos[1].trim()); continue; } } paramFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { //read the user param file BufferedReader paramFile; paramFile = new BufferedReader(new InputStreamReader(new FileInputStream(sibHomeDir + paramFileName), "UTF-8")); String line; numtotalUser = -1; int numYears = -1; startYear = -1; serializerType = ""; while ((line = paramFile.readLine()) != null) { String infos[] = line.split(": "); if (infos[0].startsWith("numtotalUser")) { numtotalUser = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("startYear")) { startYear = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("numYears")) { numYears = Integer.parseInt(infos[1].trim()); continue; } else if (infos[0].startsWith("serializerType")) { serializerType = infos[1].trim(); continue; } else { System.out.println("This param " + line + " does not match any option"); } } paramFile.close(); if (numtotalUser == -1) { throw new Exception("No numtotalUser parameter provided"); } if (startYear == -1) { throw new Exception("No startYears parameter provided"); } if (numYears == -1) { throw new Exception("No numYears parameter provided"); } if (!serializerType.equals("ttl") && !serializerType.equals("nt") && !serializerType.equals("csv")) { throw new Exception("serializerType must be ttl, nt or csv"); } endYear = startYear + numYears; } catch (Exception e) { System.out.println("Using default configuration"); // If the user params file wasn't found use the default configuration. } }
diff --git a/org.springframework.context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java b/org.springframework.context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java index 8566f543b..94e3f6907 100644 --- a/org.springframework.context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java +++ b/org.springframework.context/src/test/java/org/springframework/context/conversionservice/ConversionServiceContextConfigTests.java @@ -1,21 +1,21 @@ package org.springframework.context.conversionservice; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ConversionServiceContextConfigTests { @Test public void testConfigOk() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/springframework/context/conversionservice/conversionservice.xml"); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/springframework/context/conversionservice/conversionService.xml"); TestClient client = context.getBean("testClient", TestClient.class); assertEquals(2, client.getBars().size()); assertEquals("value1", client.getBars().get(0).getValue()); assertEquals("value2", client.getBars().get(1).getValue()); assertTrue(client.isBool()); } }
true
true
public void testConfigOk() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/springframework/context/conversionservice/conversionservice.xml"); TestClient client = context.getBean("testClient", TestClient.class); assertEquals(2, client.getBars().size()); assertEquals("value1", client.getBars().get(0).getValue()); assertEquals("value2", client.getBars().get(1).getValue()); assertTrue(client.isBool()); }
public void testConfigOk() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/springframework/context/conversionservice/conversionService.xml"); TestClient client = context.getBean("testClient", TestClient.class); assertEquals(2, client.getBars().size()); assertEquals("value1", client.getBars().get(0).getValue()); assertEquals("value2", client.getBars().get(1).getValue()); assertTrue(client.isBool()); }
diff --git a/Radar.java b/Radar.java index 4fc84e1..f74e582 100644 --- a/Radar.java +++ b/Radar.java @@ -1,128 +1,128 @@ import java.util.Arrays; /** * The radar to show what has been discovered of the enemy * The default size is 10x10 which represents the 1:10 and A:J * and leaves column zero and row zero blank * * X represents a hit on a ship * O represents a miss * * represents an unused space */ public class Radar { private char[][] radar; private int radarWidth; private int radarHeight; public Radar() { this(10, 10); } /* If we want a 10x10 board we create an 11x11 array so that we can omit * row and column zero and just use 1:n and 1:m indicies */ public Radar(int radarHeight, int radarWidth) { this.radarWidth = radarHeight+1; this.radarHeight = radarWidth+1; this.radar = new char[this.radarHeight][this.radarWidth]; radarInit(); } /* This assumes a blank (no ships) NxM board (i.e. rows are equal lengths) */ public Radar(char[][] radar) { this.radarWidth = radar.length; this.radarHeight = radar[0].length; this.radar = radar; radarInit(); } private void radarInit() { /* clear the zero'th row and column */ for(int i = 0; i < this.radarHeight; i++) this.radar[i][0] = ' '; for(int i = 0; i < this.radarWidth; i++) this.radar[0][i] = ' '; for(int i = 1; i < this.radarHeight; i++) { for(int j = 1; j < this.radarWidth; j++) { this.radar[i][j] = '*'; } } } /** * Marks a given shot on the radar * @param row Row to mark * @param col Column to mark. * @param hitOrMiss 'h' or 'H' indicates a hit. 'm' or 'M' indicates a miss. * @return Returns true if the spot is successfully marked. False otherwise * with a printed error message */ public boolean markRadar(int row, int col, char hitOrMiss) { if(!checkShotParams(row, col, hitOrMiss)) return false; if(hitOrMiss == 'h' || hitOrMiss == 'H') { this.radar[row][col] = 'X'; return true; } else { // no need to check for 'm' or 'M' since we passed the check params this.radar[row][col] = 'O'; return true; } } /* returns true if it is a valid location, false otherwise */ private boolean checkLocation(int row, int col) { /* check if the coordinates are in the playable range */ - if(row < 1 || row > this.radarHeight) { + if(row < 1 || row > this.radarHeight-1) { System.err.println(String.format("Error: The row must be between 1 and %d", this.radarHeight-1)); return false; } - else if(col < 1 || col > this.radarWidth) { + else if(col < 1 || col > this.radarWidth-1) { System.err.println(String.format("Error: The column must be between 1 and %d", this.radarWidth-1)); return false; } // Looks ok return true; } /* returns true if the parameters are valid, false otherwise */ private boolean checkShotParams(int row, int col, char hitOrMiss) { if(!checkLocation(row, col)) return false; /* is the hitOrMiss one we know? */ else if(hitOrMiss != 'h' && hitOrMiss != 'H' && hitOrMiss != 'm' && hitOrMiss != 'M') { System.err.println(String.format("Error: Unrecognized his or miss value '%c'", hitOrMiss)); return false; } /* Everything looks good! */ return true; } /** * Returns the value stored in the radar at a given location * @param row The row to check. * @param col The column to check. * @return Will return the character stored at that location if it is a * valid spot, or the null character for any invalid locations. */ public char getLocation(int row, int col) { if(!checkLocation(row, col)) return '\0'; return this.radar[row][col]; } public String toString() { StringBuilder s = new StringBuilder(); for(int i = 0; i < this.radarHeight; i++) { s.append(Arrays.toString(this.radar[i])); s.append("\n"); } return s.toString(); } }
false
true
private boolean checkLocation(int row, int col) { /* check if the coordinates are in the playable range */ if(row < 1 || row > this.radarHeight) { System.err.println(String.format("Error: The row must be between 1 and %d", this.radarHeight-1)); return false; } else if(col < 1 || col > this.radarWidth) { System.err.println(String.format("Error: The column must be between 1 and %d", this.radarWidth-1)); return false; } // Looks ok return true; }
private boolean checkLocation(int row, int col) { /* check if the coordinates are in the playable range */ if(row < 1 || row > this.radarHeight-1) { System.err.println(String.format("Error: The row must be between 1 and %d", this.radarHeight-1)); return false; } else if(col < 1 || col > this.radarWidth-1) { System.err.println(String.format("Error: The column must be between 1 and %d", this.radarWidth-1)); return false; } // Looks ok return true; }
diff --git a/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java b/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java index f25887a9..a9b43fe5 100644 --- a/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java +++ b/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java @@ -1,206 +1,206 @@ /* The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is "PropertyInputPanel.java". Description: "Swing Input panel to be used to enter in the value for a ConfigParam @author Shu" The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU Public License license (the GPL License), in which case the provisions of GPL License are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL License. */ package ca.nengo.ui.configurable; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import ca.nengo.ui.lib.Style.NengoStyle; /** * Swing Input panel to be used to enter in the value for a ConfigParam * * @author Shu */ public abstract class PropertyInputPanel { private final JPanel innerPanel; private final JPanel outerPanel; private Property propDescriptor; private JLabel statusMessage; /** * @param property * A description of the Configuration parameter to be configured */ public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); - JButton help=new JButton("<html><u>?</u></html>"); + final JButton help=new JButton("<html><u>?</u></html>"); help.setFocusable(false); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - JOptionPane.showMessageDialog(null,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); + JOptionPane.showMessageDialog(help,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); } /** * @param comp * Component to be added to the input panel */ protected void add(Component comp) { innerPanel.add(comp); } /** * @return */ protected JDialog getDialogParent() { /* * get the JDialog parent */ Container parent = outerPanel.getParent(); while (parent != null) { if (parent instanceof JDialog) { return (JDialog) parent; } parent = parent.getParent(); } throw new RuntimeException("Input panel does not have a dialog parent"); } /** * @param comp * Component to be removed from the input panel */ protected void removeFromPanel(Component comp) { innerPanel.remove(comp); } /** * @param msg */ protected void setStatusMsg(String msg) { statusMessage.setText(msg); } /** * @return Descriptor of the configuration parameter */ public Property getDescriptor() { return propDescriptor; } /** * @return TODO */ public JPanel getJPanel() { return outerPanel; } /** * @return TODO */ public String getName() { return outerPanel.getName(); } /** * @return Value of the parameter */ public abstract Object getValue(); /** * @return TODO */ public boolean isEnabled() { return innerPanel.isEnabled(); } /** * @return True if configuration parameter is set */ public abstract boolean isValueSet(); /** * @param enabled TODO */ public void setEnabled(boolean enabled) { innerPanel.setEnabled(enabled); } /** * @param value * Sets the configuration parameter */ public abstract void setValue(Object value); }
false
true
public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); JButton help=new JButton("<html><u>?</u></html>"); help.setFocusable(false); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); }
public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); final JButton help=new JButton("<html><u>?</u></html>"); help.setFocusable(false); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(help,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); }
diff --git a/source/net/sourceforge/texlipse/texparser/LatexParser.java b/source/net/sourceforge/texlipse/texparser/LatexParser.java index 1a61186..dda00f7 100644 --- a/source/net/sourceforge/texlipse/texparser/LatexParser.java +++ b/source/net/sourceforge/texlipse/texparser/LatexParser.java @@ -1,901 +1,904 @@ /* * $Id$ * * Copyright (c) 2004-2005 by the TeXlapse Team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package net.sourceforge.texlipse.texparser; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Pattern; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.model.DocumentReference; import net.sourceforge.texlipse.model.OutlineNode; import net.sourceforge.texlipse.model.ParseErrorMessage; import net.sourceforge.texlipse.model.ReferenceEntry; import net.sourceforge.texlipse.model.TexCommandEntry; import net.sourceforge.texlipse.texparser.lexer.LexerException; import net.sourceforge.texlipse.texparser.node.*; import org.eclipse.core.resources.IMarker; /** * Simple parser for LaTeX: does very basic structure checking and * extracts useful data. * * @author Oskar Ojala * @author Boris von Loesch */ public class LatexParser { // These should be allocated between 1000-2000 public static final int TYPE_LABEL = 1000; private static final Pattern PART_RE = Pattern.compile("\\\\part(?:[^a-zA-Z]|$)"); private static final Pattern CHAPTER_RE = Pattern.compile("\\\\chapter(?:[^a-zA-Z]|$)"); private static final Pattern SECTION_RE = Pattern.compile("\\\\section(?:[^a-zA-Z]|$)"); private static final Pattern SSECTION_RE = Pattern.compile("\\\\subsection(?:[^a-zA-Z]|$)"); private static final Pattern SSSECTION_RE = Pattern.compile("\\\\subsubsection(?:[^a-zA-Z]|$)"); private static final Pattern PARAGRAPH_RE = Pattern.compile("\\\\paragraph(?:[^a-zA-Z]|$)"); private static final Pattern LABEL_RE = Pattern.compile("\\\\label(?:[^a-zA-Z]|$)"); /** * Defines a new stack implementation, which is unsynchronized and * tuned for the needs of the parser, making it much faster than * java.util.Stack * * @author Oskar Ojala */ private final static class StackUnsynch<E> { private static final int INITIAL_SIZE = 10; private static final int GROWTH_FACTOR = 2; private int capacity; private int size; private Object[] stack; /** * Creates a new stack. */ public StackUnsynch() { stack = new Object[INITIAL_SIZE]; size = 0; capacity = INITIAL_SIZE; } /** * @return True if the stack is empty, false if it contains items */ public boolean empty() { return (size == 0); } /** * @return The item at the top of the stack */ @SuppressWarnings("unchecked") public E peek() { return (E)(stack[size-1]); } /** * Removes the item at the stop of the stack. * * @return The item at the top of the stack */ @SuppressWarnings("unchecked") public E pop() { size--; E top = (E) stack[size]; stack[size] = null; return top; } /** * Pushes an item to the top of the stack. * * @param item The item to push on the stack */ public void push(final E item) { // what if size would be where to put the next item? if (size >= capacity) { capacity *= GROWTH_FACTOR; Object[] newStack = new Object[capacity]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[size] = item; size++; } /** * Clears the stack; removes all entries. */ public void clear() { for (size--; size >= 0; size--) { stack[size] = null; } size = 0; } } private List<ReferenceEntry> labels; private List<DocumentReference> cites; private List<DocumentReference> refs; private ArrayList<TexCommandEntry> commands; private List<ParseErrorMessage> tasks; private String[] bibs; private String bibstyle; private List<OutlineNode> inputs; private ArrayList<OutlineNode> outlineTree; private List<ParseErrorMessage> errors; private OutlineNode documentEnv; private boolean index; private boolean fatalErrors; /** * Initializes the internal datastructures that are exported after parsing. */ private void initializeDatastructs() { this.labels = new ArrayList<ReferenceEntry>(); this.cites = new ArrayList<DocumentReference>(); this.refs = new ArrayList<DocumentReference>(); this.commands = new ArrayList<TexCommandEntry>(); this.tasks = new ArrayList<ParseErrorMessage>(); this.inputs = new ArrayList<OutlineNode>(2); this.outlineTree = new ArrayList<OutlineNode>(); this.errors = new ArrayList<ParseErrorMessage>(); this.bibs = null; this.index = false; this.fatalErrors = false; } /** * Parses a LaTeX document. Uses the given lexer's <code>next()</code> * method to receive tokens that are processed. * * @param lex The lexer to use for extracting the document tokens * @param definedLabels Labels that are defined, used to check for references to * nonexistant labels * @param definedBibs Defined bibliography entries, used to check for references to * nonexistant bibliography entries * @throws LexerException If the given lexer cannot tokenize the document * @throws IOException If the document is unreadable */ public void parse(LatexLexer lex, boolean checkForMissingSections) throws LexerException, IOException { parse(lex, null, checkForMissingSections); } /** * Parses a LaTeX document. Uses the given lexer's <code>next()</code> * method to receive tokens that are processed. * * @param lexer The lexer to use for extracting the document tokens * @param definedLabels Labels that are defined, used to check for references to * nonexistant labels * @param definedBibs Defined bibliography entries, used to check for references to * nonexistant bibliography entries * @param preamble An <code>OutlineNode</code> containing the preamble, null if there is no preamble * @param checkForMissingSections * @throws LexerException If the given lexer cannot tokenize the document * @throws IOException If the document is unreadable */ public void parse(final LatexLexer lexer, final OutlineNode preamble, final boolean checkForMissingSections) throws LexerException, IOException { initializeDatastructs(); StackUnsynch<OutlineNode> blocks = new StackUnsynch<OutlineNode>(); StackUnsynch<Token> braces = new StackUnsynch<Token>(); boolean expectArg = false; boolean expectArg2 = false; Token prevToken = null; TexCommandEntry currentCommand = null; int argCount = 0; int nodeType; HashMap<String, Integer> sectioning = new HashMap<String, Integer>(); if (preamble != null) { outlineTree.add(preamble); blocks.push(preamble); } // newcommand would need to check for the valid format // duplicate labels? // change order of ifs to optimize performance? int accumulatedLength = 0; Token t = lexer.next(); for (; !(t instanceof EOF); t = lexer.next()) { if (expectArg) { if (t instanceof TArgument) { if (prevToken instanceof TClabel) { //this.labels.add(new ReferenceEntry(t.getText())); ReferenceEntry l = new ReferenceEntry(t.getText()); l.setPosition(t.getPos(), t.getText().length()); l.startLine = t.getLine(); this.labels.add(l); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_LABEL, t.getLine(), t.getPos(), t.getText().length()); on.setEndLine(t.getLine()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } else if (prevToken instanceof TCref) { this.refs.add(new DocumentReference(t.getText(), t.getLine(), t.getPos(), t.getText().length())); } else if (prevToken instanceof TCcite) { if (!"*".equals(t.getText())) { - String[] cs = t.getText().replaceAll("\\s", "").split(","); + String[] cs = t.getText().split(","); for (String c : cs) { //just add all citation and check for errors later, after updating the citation index - this.cites.add(new DocumentReference(c, + this.cites.add(new DocumentReference(c.trim(), t.getLine(), t.getPos(), t.getText().length())); } } } else if (prevToken instanceof TCbegin) { // \begin{...} OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length()); if ("document".equals(t.getText())) { if (preamble != null) preamble.setEndLine(t.getLine()); blocks.clear(); documentEnv = on; } else { if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } blocks.push(on); } } else if (prevToken instanceof TCend) { // \end{...} int endLine = t.getLine(); OutlineNode prev = null; // check if the document ends if ("document".equals(t.getText())) { documentEnv.setEndLine(endLine + 1); // terminate open blocks here; check for errors while (!blocks.empty()) { prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{document} found; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); fatalErrors = true; } } } else { // the "normal" case boolean traversing = true; if (!blocks.empty()) { while (traversing && !blocks.empty()) { prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.setEndLine(endLine + 1); traversing = false; } else { prev.setEndLine(endLine); } } } if (blocks.empty() && traversing) { fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + t.getText() + "} found with no preceding \\begin", IMarker.SEVERITY_ERROR)); } else if (!prev.getName().equals(t.getText())) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), prev.getOffsetOnLine(), prev.getDeclarationLength(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } else if (prevToken instanceof TCpart) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PART, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.addChild(on); on.setParent(prev); traversing = false; } else { prev.setEndLine(startLine); blocks.pop(); } } } if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCchapter) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_CHAPTER, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCsection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SECTION, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) { outlineTree.add(on); } blocks.push(on); } else if (prevToken instanceof TCssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSECTION, startLine, null); boolean foundSection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SECTION: foundSection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsection " + prevToken.getText() + " has no preceding section", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCsssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSUBSECTION, prevToken.getLine(), null); boolean foundSsection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSECTION: foundSsection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSsection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsubsection " + prevToken.getText() + " has no preceding subsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCparagraph) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PARAGRAPH, prevToken.getLine(), null); boolean foundSssection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSUBSECTION: foundSssection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: case OutlineNode.TYPE_SUBSECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSssection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Paragraph " + prevToken.getText() + " has no preceding subsubsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCbib) { bibs = t.getText().split(","); + for (int i = 0; i < bibs.length; i++) { + bibs[i] = bibs[i].trim(); + } int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCbibstyle) { this.bibstyle = t.getText(); int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCinput || prevToken instanceof TCinclude) { //inputs.add(t.getText()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), prev); on.setEndLine(t.getLine()); prev.addChild(on); inputs.add(on); } else { OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), null); on.setEndLine(t.getLine()); outlineTree.add(on); inputs.add(on); } } else if (prevToken instanceof TCnew) { //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; } // reset state to normal scanning accumulatedLength = 0; prevToken = null; expectArg = false; } else if ((t instanceof TCword) && (prevToken instanceof TCnew)) { // this handles the \newcommand\comx{...} -format //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; accumulatedLength = 0; prevToken = null; expectArg = false; } else if (!(t instanceof TOptargument) && !(t instanceof TWhitespace) && !(t instanceof TStar) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... //fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "No argument following " + prevToken.getText(), IMarker.SEVERITY_WARNING)); accumulatedLength = 0; prevToken = null; expectArg = false; } else { accumulatedLength += t.getText().length(); } } else if (expectArg2) { // we are capturing the second argument of a command with two arguments // the only one of those that interests us is newcommand if (t instanceof TArgument) { currentCommand.info = t.getText(); commands.add(currentCommand); if (PART_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PART); //else if (currentCommand.info.indexOf("\\chapter") != -1) else if (CHAPTER_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_CHAPTER); //else if (currentCommand.info.indexOf("\\section") != -1) else if (SECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SECTION); //else if (currentCommand.info.indexOf("\\subsection") != -1) else if (SSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSECTION); //else if (currentCommand.info.indexOf("\\subsubsection") != -1) else if (SSSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSUBSECTION); //else if (currentCommand.info.indexOf("\\paragraph") != -1) else if (PARAGRAPH_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PARAGRAPH); //else if (currentCommand.info.indexOf("\\label") != -1) else if (LABEL_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, LatexParser.TYPE_LABEL); argCount = 0; expectArg2 = false; } else if (t instanceof TOptargument) { if (argCount == 0) { try { currentCommand.arguments = Integer.parseInt(t.getText()); } catch (NumberFormatException nfe) { errors.add(new ParseErrorMessage(prevToken.getLine(), t.getPos(), t.getText().length(), "The first optional argument of newcommand must only contain the number of arguments", IMarker.SEVERITY_ERROR)); expectArg2 = false; } } argCount++; } else if (!(t instanceof TWhitespace) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... errors.add(new ParseErrorMessage(t.getLine(), t.getPos(), t.getText().length(), "No 2nd argument following newcommand", IMarker.SEVERITY_WARNING)); argCount = 0; expectArg2 = false; } } else { if (t instanceof TClabel || t instanceof TCref || t instanceof TCcite || t instanceof TCbib || t instanceof TCbibstyle || t instanceof TCbegin || t instanceof TCend || t instanceof TCinput || t instanceof TCinclude || t instanceof TCpart || t instanceof TCchapter || t instanceof TCsection || t instanceof TCssection || t instanceof TCsssection || t instanceof TCparagraph || t instanceof TCnew) { prevToken = t; expectArg = true; } else if (t instanceof TCword) { // macros (\newcommand) show up as TCword when used, so we need // to check (for each word!) whether it happens to be a command if (sectioning.containsKey(t.getText())) { nodeType = sectioning.get(t.getText()); switch (nodeType) { case OutlineNode.TYPE_PART: prevToken = new TCpart(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_CHAPTER: prevToken = new TCchapter(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SECTION: prevToken = new TCsection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSECTION: prevToken = new TCssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSUBSECTION: prevToken = new TCsssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_PARAGRAPH: prevToken = new TCparagraph(t.getLine(), t.getPos()); break; case LatexParser.TYPE_LABEL: prevToken = new TClabel(t.getLine(), t.getPos()); break; default: break; } expectArg = true; } } else if (t instanceof TCpindex) { this.index = true; } else if (t instanceof TTaskcomment) { int severity = IMarker.PRIORITY_HIGH; int start = t.getText().indexOf("FIXME"); if (start == -1) { severity = IMarker.PRIORITY_NORMAL; start = t.getText().indexOf("TODO"); if (start == -1) { start = t.getText().indexOf("XXX"); } } String taskText = t.getText().substring(start).trim(); tasks.add(new ParseErrorMessage(t.getLine(), t.getPos(), taskText.length(), taskText, severity)); } else if (t instanceof TVtext) { // Fold OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), t.getPos(), t.getText().length()); // TODO uses memory, but doesn't require much code... String[] lines = t.getText().split("\\r\\n|\\n|\\r"); on.setEndLine(t.getLine() + lines.length); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } } if (t instanceof TLBrace) { braces.push(t); } else if (t instanceof TRBrace) { if (braces.empty()) { //There is an opening brace missing errors.add(new ParseErrorMessage(t.getLine(), t.getPos()-1, 1, TexlipsePlugin.getResourceString("parseErrorMissingLBrace"), IMarker.SEVERITY_ERROR)); } else { braces.pop(); } } } //Check for missing closing braces while (!braces.empty()) { Token mt = (Token) braces.pop(); errors.add(new ParseErrorMessage(mt.getLine(), mt.getPos() - 1, 1, TexlipsePlugin.getResourceString("parseErrorMissingRBrace"), IMarker.SEVERITY_ERROR)); } int endLine = t.getLine() + 1; //endline is exclusive while (!blocks.empty()) { OutlineNode prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), 0, prev.getName().length(), "\\begin{" + prev.getName() + "} does not have matching end; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } /** * @return The labels defined in this document */ public List<ReferenceEntry> getLabels() { return this.labels; } /** * @return The BibTeX citations */ public List<DocumentReference> getCites() { return this.cites; } /** * @return The refencing commands */ public List<DocumentReference> getRefs() { return this.refs; } /** * @return The bibliography files to use. */ public String[] getBibs() { return this.bibs; } /** * @return The bibliography style. */ public String getBibstyle() { return bibstyle; } /** * @return The input commands in this document */ public List<OutlineNode> getInputs() { return this.inputs; } /** * @return The outline tree of the document (OutlineNode objects). */ public ArrayList<OutlineNode> getOutlineTree() { return this.outlineTree; } /** * @return The list of errors (ParseErrorMessage objects) in the document */ public List<ParseErrorMessage> getErrors() { return this.errors; } /** * @return Returns whether makeindex is to be used or not */ public boolean isIndex() { return index; } /** * @return Returns the documentEnv. */ public OutlineNode getDocumentEnv() { return documentEnv; } /** * @return Returns whether there are fatal errors in the document */ public boolean isFatalErrors() { return fatalErrors; } /** * @return Returns the commands. */ public ArrayList<TexCommandEntry> getCommands() { return commands; } /** * @return Returns the tasks. */ public List<ParseErrorMessage> getTasks() { return tasks; } }
false
true
public void parse(final LatexLexer lexer, final OutlineNode preamble, final boolean checkForMissingSections) throws LexerException, IOException { initializeDatastructs(); StackUnsynch<OutlineNode> blocks = new StackUnsynch<OutlineNode>(); StackUnsynch<Token> braces = new StackUnsynch<Token>(); boolean expectArg = false; boolean expectArg2 = false; Token prevToken = null; TexCommandEntry currentCommand = null; int argCount = 0; int nodeType; HashMap<String, Integer> sectioning = new HashMap<String, Integer>(); if (preamble != null) { outlineTree.add(preamble); blocks.push(preamble); } // newcommand would need to check for the valid format // duplicate labels? // change order of ifs to optimize performance? int accumulatedLength = 0; Token t = lexer.next(); for (; !(t instanceof EOF); t = lexer.next()) { if (expectArg) { if (t instanceof TArgument) { if (prevToken instanceof TClabel) { //this.labels.add(new ReferenceEntry(t.getText())); ReferenceEntry l = new ReferenceEntry(t.getText()); l.setPosition(t.getPos(), t.getText().length()); l.startLine = t.getLine(); this.labels.add(l); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_LABEL, t.getLine(), t.getPos(), t.getText().length()); on.setEndLine(t.getLine()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } else if (prevToken instanceof TCref) { this.refs.add(new DocumentReference(t.getText(), t.getLine(), t.getPos(), t.getText().length())); } else if (prevToken instanceof TCcite) { if (!"*".equals(t.getText())) { String[] cs = t.getText().replaceAll("\\s", "").split(","); for (String c : cs) { //just add all citation and check for errors later, after updating the citation index this.cites.add(new DocumentReference(c, t.getLine(), t.getPos(), t.getText().length())); } } } else if (prevToken instanceof TCbegin) { // \begin{...} OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length()); if ("document".equals(t.getText())) { if (preamble != null) preamble.setEndLine(t.getLine()); blocks.clear(); documentEnv = on; } else { if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } blocks.push(on); } } else if (prevToken instanceof TCend) { // \end{...} int endLine = t.getLine(); OutlineNode prev = null; // check if the document ends if ("document".equals(t.getText())) { documentEnv.setEndLine(endLine + 1); // terminate open blocks here; check for errors while (!blocks.empty()) { prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{document} found; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); fatalErrors = true; } } } else { // the "normal" case boolean traversing = true; if (!blocks.empty()) { while (traversing && !blocks.empty()) { prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.setEndLine(endLine + 1); traversing = false; } else { prev.setEndLine(endLine); } } } if (blocks.empty() && traversing) { fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + t.getText() + "} found with no preceding \\begin", IMarker.SEVERITY_ERROR)); } else if (!prev.getName().equals(t.getText())) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), prev.getOffsetOnLine(), prev.getDeclarationLength(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } else if (prevToken instanceof TCpart) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PART, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.addChild(on); on.setParent(prev); traversing = false; } else { prev.setEndLine(startLine); blocks.pop(); } } } if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCchapter) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_CHAPTER, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCsection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SECTION, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) { outlineTree.add(on); } blocks.push(on); } else if (prevToken instanceof TCssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSECTION, startLine, null); boolean foundSection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SECTION: foundSection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsection " + prevToken.getText() + " has no preceding section", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCsssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSUBSECTION, prevToken.getLine(), null); boolean foundSsection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSECTION: foundSsection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSsection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsubsection " + prevToken.getText() + " has no preceding subsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCparagraph) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PARAGRAPH, prevToken.getLine(), null); boolean foundSssection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSUBSECTION: foundSssection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: case OutlineNode.TYPE_SUBSECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSssection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Paragraph " + prevToken.getText() + " has no preceding subsubsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCbib) { bibs = t.getText().split(","); int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCbibstyle) { this.bibstyle = t.getText(); int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCinput || prevToken instanceof TCinclude) { //inputs.add(t.getText()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), prev); on.setEndLine(t.getLine()); prev.addChild(on); inputs.add(on); } else { OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), null); on.setEndLine(t.getLine()); outlineTree.add(on); inputs.add(on); } } else if (prevToken instanceof TCnew) { //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; } // reset state to normal scanning accumulatedLength = 0; prevToken = null; expectArg = false; } else if ((t instanceof TCword) && (prevToken instanceof TCnew)) { // this handles the \newcommand\comx{...} -format //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; accumulatedLength = 0; prevToken = null; expectArg = false; } else if (!(t instanceof TOptargument) && !(t instanceof TWhitespace) && !(t instanceof TStar) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... //fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "No argument following " + prevToken.getText(), IMarker.SEVERITY_WARNING)); accumulatedLength = 0; prevToken = null; expectArg = false; } else { accumulatedLength += t.getText().length(); } } else if (expectArg2) { // we are capturing the second argument of a command with two arguments // the only one of those that interests us is newcommand if (t instanceof TArgument) { currentCommand.info = t.getText(); commands.add(currentCommand); if (PART_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PART); //else if (currentCommand.info.indexOf("\\chapter") != -1) else if (CHAPTER_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_CHAPTER); //else if (currentCommand.info.indexOf("\\section") != -1) else if (SECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SECTION); //else if (currentCommand.info.indexOf("\\subsection") != -1) else if (SSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSECTION); //else if (currentCommand.info.indexOf("\\subsubsection") != -1) else if (SSSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSUBSECTION); //else if (currentCommand.info.indexOf("\\paragraph") != -1) else if (PARAGRAPH_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PARAGRAPH); //else if (currentCommand.info.indexOf("\\label") != -1) else if (LABEL_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, LatexParser.TYPE_LABEL); argCount = 0; expectArg2 = false; } else if (t instanceof TOptargument) { if (argCount == 0) { try { currentCommand.arguments = Integer.parseInt(t.getText()); } catch (NumberFormatException nfe) { errors.add(new ParseErrorMessage(prevToken.getLine(), t.getPos(), t.getText().length(), "The first optional argument of newcommand must only contain the number of arguments", IMarker.SEVERITY_ERROR)); expectArg2 = false; } } argCount++; } else if (!(t instanceof TWhitespace) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... errors.add(new ParseErrorMessage(t.getLine(), t.getPos(), t.getText().length(), "No 2nd argument following newcommand", IMarker.SEVERITY_WARNING)); argCount = 0; expectArg2 = false; } } else { if (t instanceof TClabel || t instanceof TCref || t instanceof TCcite || t instanceof TCbib || t instanceof TCbibstyle || t instanceof TCbegin || t instanceof TCend || t instanceof TCinput || t instanceof TCinclude || t instanceof TCpart || t instanceof TCchapter || t instanceof TCsection || t instanceof TCssection || t instanceof TCsssection || t instanceof TCparagraph || t instanceof TCnew) { prevToken = t; expectArg = true; } else if (t instanceof TCword) { // macros (\newcommand) show up as TCword when used, so we need // to check (for each word!) whether it happens to be a command if (sectioning.containsKey(t.getText())) { nodeType = sectioning.get(t.getText()); switch (nodeType) { case OutlineNode.TYPE_PART: prevToken = new TCpart(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_CHAPTER: prevToken = new TCchapter(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SECTION: prevToken = new TCsection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSECTION: prevToken = new TCssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSUBSECTION: prevToken = new TCsssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_PARAGRAPH: prevToken = new TCparagraph(t.getLine(), t.getPos()); break; case LatexParser.TYPE_LABEL: prevToken = new TClabel(t.getLine(), t.getPos()); break; default: break; } expectArg = true; } } else if (t instanceof TCpindex) { this.index = true; } else if (t instanceof TTaskcomment) { int severity = IMarker.PRIORITY_HIGH; int start = t.getText().indexOf("FIXME"); if (start == -1) { severity = IMarker.PRIORITY_NORMAL; start = t.getText().indexOf("TODO"); if (start == -1) { start = t.getText().indexOf("XXX"); } } String taskText = t.getText().substring(start).trim(); tasks.add(new ParseErrorMessage(t.getLine(), t.getPos(), taskText.length(), taskText, severity)); } else if (t instanceof TVtext) { // Fold OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), t.getPos(), t.getText().length()); // TODO uses memory, but doesn't require much code... String[] lines = t.getText().split("\\r\\n|\\n|\\r"); on.setEndLine(t.getLine() + lines.length); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } } if (t instanceof TLBrace) { braces.push(t); } else if (t instanceof TRBrace) { if (braces.empty()) { //There is an opening brace missing errors.add(new ParseErrorMessage(t.getLine(), t.getPos()-1, 1, TexlipsePlugin.getResourceString("parseErrorMissingLBrace"), IMarker.SEVERITY_ERROR)); } else { braces.pop(); } } } //Check for missing closing braces while (!braces.empty()) { Token mt = (Token) braces.pop(); errors.add(new ParseErrorMessage(mt.getLine(), mt.getPos() - 1, 1, TexlipsePlugin.getResourceString("parseErrorMissingRBrace"), IMarker.SEVERITY_ERROR)); } int endLine = t.getLine() + 1; //endline is exclusive while (!blocks.empty()) { OutlineNode prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), 0, prev.getName().length(), "\\begin{" + prev.getName() + "} does not have matching end; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } }
public void parse(final LatexLexer lexer, final OutlineNode preamble, final boolean checkForMissingSections) throws LexerException, IOException { initializeDatastructs(); StackUnsynch<OutlineNode> blocks = new StackUnsynch<OutlineNode>(); StackUnsynch<Token> braces = new StackUnsynch<Token>(); boolean expectArg = false; boolean expectArg2 = false; Token prevToken = null; TexCommandEntry currentCommand = null; int argCount = 0; int nodeType; HashMap<String, Integer> sectioning = new HashMap<String, Integer>(); if (preamble != null) { outlineTree.add(preamble); blocks.push(preamble); } // newcommand would need to check for the valid format // duplicate labels? // change order of ifs to optimize performance? int accumulatedLength = 0; Token t = lexer.next(); for (; !(t instanceof EOF); t = lexer.next()) { if (expectArg) { if (t instanceof TArgument) { if (prevToken instanceof TClabel) { //this.labels.add(new ReferenceEntry(t.getText())); ReferenceEntry l = new ReferenceEntry(t.getText()); l.setPosition(t.getPos(), t.getText().length()); l.startLine = t.getLine(); this.labels.add(l); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_LABEL, t.getLine(), t.getPos(), t.getText().length()); on.setEndLine(t.getLine()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } else if (prevToken instanceof TCref) { this.refs.add(new DocumentReference(t.getText(), t.getLine(), t.getPos(), t.getText().length())); } else if (prevToken instanceof TCcite) { if (!"*".equals(t.getText())) { String[] cs = t.getText().split(","); for (String c : cs) { //just add all citation and check for errors later, after updating the citation index this.cites.add(new DocumentReference(c.trim(), t.getLine(), t.getPos(), t.getText().length())); } } } else if (prevToken instanceof TCbegin) { // \begin{...} OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length()); if ("document".equals(t.getText())) { if (preamble != null) preamble.setEndLine(t.getLine()); blocks.clear(); documentEnv = on; } else { if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } blocks.push(on); } } else if (prevToken instanceof TCend) { // \end{...} int endLine = t.getLine(); OutlineNode prev = null; // check if the document ends if ("document".equals(t.getText())) { documentEnv.setEndLine(endLine + 1); // terminate open blocks here; check for errors while (!blocks.empty()) { prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{document} found; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); fatalErrors = true; } } } else { // the "normal" case boolean traversing = true; if (!blocks.empty()) { while (traversing && !blocks.empty()) { prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.setEndLine(endLine + 1); traversing = false; } else { prev.setEndLine(endLine); } } } if (blocks.empty() && traversing) { fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + t.getText() + "} found with no preceding \\begin", IMarker.SEVERITY_ERROR)); } else if (!prev.getName().equals(t.getText())) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), prev.getOffsetOnLine(), prev.getDeclarationLength(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "\\end{" + prev.getName() + "} expected, but \\end{" + t.getText() + "} found; unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } } else if (prevToken instanceof TCpart) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PART, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { prev.addChild(on); on.setParent(prev); traversing = false; } else { prev.setEndLine(startLine); blocks.pop(); } } } if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCchapter) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_CHAPTER, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); blocks.push(on); } else if (prevToken instanceof TCsection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SECTION, startLine, null); if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_ENVIRONMENT: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) { outlineTree.add(on); } blocks.push(on); } else if (prevToken instanceof TCssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSECTION, startLine, null); boolean foundSection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SECTION: foundSection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsection " + prevToken.getText() + " has no preceding section", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCsssection) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_SUBSUBSECTION, prevToken.getLine(), null); boolean foundSsection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSECTION: foundSsection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSsection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Subsubsection " + prevToken.getText() + " has no preceding subsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCparagraph) { int startLine = prevToken.getLine(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_PARAGRAPH, prevToken.getLine(), null); boolean foundSssection = false; if (!blocks.empty()) { boolean traversing = true; while (traversing && !blocks.empty()) { OutlineNode prev = blocks.peek(); switch (prev.getType()) { case OutlineNode.TYPE_ENVIRONMENT: case OutlineNode.TYPE_SUBSUBSECTION: foundSssection = true; case OutlineNode.TYPE_PART: case OutlineNode.TYPE_CHAPTER: case OutlineNode.TYPE_SECTION: case OutlineNode.TYPE_SUBSECTION: prev.addChild(on); on.setParent(prev); traversing = false; break; default: prev.setEndLine(startLine); blocks.pop(); break; } } } // add directly to tree if no parent was found if (blocks.empty()) outlineTree.add(on); if (!foundSssection && checkForMissingSections) { errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "Paragraph " + prevToken.getText() + " has no preceding subsubsection", IMarker.SEVERITY_WARNING)); } blocks.push(on); } else if (prevToken instanceof TCbib) { bibs = t.getText().split(","); for (int i = 0; i < bibs.length; i++) { bibs[i] = bibs[i].trim(); } int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCbibstyle) { this.bibstyle = t.getText(); int startLine = prevToken.getLine(); while (!blocks.empty()) { OutlineNode prev = blocks.pop(); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { // this is an error... blocks.push(prev); break; } prev.setEndLine(startLine); } } else if (prevToken instanceof TCinput || prevToken instanceof TCinclude) { //inputs.add(t.getText()); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), prev); on.setEndLine(t.getLine()); prev.addChild(on); inputs.add(on); } else { OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_INPUT, t.getLine(), null); on.setEndLine(t.getLine()); outlineTree.add(on); inputs.add(on); } } else if (prevToken instanceof TCnew) { //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; } // reset state to normal scanning accumulatedLength = 0; prevToken = null; expectArg = false; } else if ((t instanceof TCword) && (prevToken instanceof TCnew)) { // this handles the \newcommand\comx{...} -format //currentCommand = new CommandEntry(t.getText().substring(1)); currentCommand = new TexCommandEntry(t.getText().substring(1), "", 0); currentCommand.startLine = t.getLine(); lexer.registerCommand(currentCommand.key); expectArg2 = true; accumulatedLength = 0; prevToken = null; expectArg = false; } else if (!(t instanceof TOptargument) && !(t instanceof TWhitespace) && !(t instanceof TStar) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... //fatalErrors = true; errors.add(new ParseErrorMessage(prevToken.getLine(), prevToken.getPos(), prevToken.getText().length() + accumulatedLength + t.getText().length(), "No argument following " + prevToken.getText(), IMarker.SEVERITY_WARNING)); accumulatedLength = 0; prevToken = null; expectArg = false; } else { accumulatedLength += t.getText().length(); } } else if (expectArg2) { // we are capturing the second argument of a command with two arguments // the only one of those that interests us is newcommand if (t instanceof TArgument) { currentCommand.info = t.getText(); commands.add(currentCommand); if (PART_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PART); //else if (currentCommand.info.indexOf("\\chapter") != -1) else if (CHAPTER_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_CHAPTER); //else if (currentCommand.info.indexOf("\\section") != -1) else if (SECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SECTION); //else if (currentCommand.info.indexOf("\\subsection") != -1) else if (SSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSECTION); //else if (currentCommand.info.indexOf("\\subsubsection") != -1) else if (SSSECTION_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_SUBSUBSECTION); //else if (currentCommand.info.indexOf("\\paragraph") != -1) else if (PARAGRAPH_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, OutlineNode.TYPE_PARAGRAPH); //else if (currentCommand.info.indexOf("\\label") != -1) else if (LABEL_RE.matcher(currentCommand.info).find()) sectioning.put("\\" + currentCommand.key, LatexParser.TYPE_LABEL); argCount = 0; expectArg2 = false; } else if (t instanceof TOptargument) { if (argCount == 0) { try { currentCommand.arguments = Integer.parseInt(t.getText()); } catch (NumberFormatException nfe) { errors.add(new ParseErrorMessage(prevToken.getLine(), t.getPos(), t.getText().length(), "The first optional argument of newcommand must only contain the number of arguments", IMarker.SEVERITY_ERROR)); expectArg2 = false; } } argCount++; } else if (!(t instanceof TWhitespace) && !(t instanceof TCommentline) && !(t instanceof TTaskcomment)) { // if we didn't get the mandatory argument we were expecting... errors.add(new ParseErrorMessage(t.getLine(), t.getPos(), t.getText().length(), "No 2nd argument following newcommand", IMarker.SEVERITY_WARNING)); argCount = 0; expectArg2 = false; } } else { if (t instanceof TClabel || t instanceof TCref || t instanceof TCcite || t instanceof TCbib || t instanceof TCbibstyle || t instanceof TCbegin || t instanceof TCend || t instanceof TCinput || t instanceof TCinclude || t instanceof TCpart || t instanceof TCchapter || t instanceof TCsection || t instanceof TCssection || t instanceof TCsssection || t instanceof TCparagraph || t instanceof TCnew) { prevToken = t; expectArg = true; } else if (t instanceof TCword) { // macros (\newcommand) show up as TCword when used, so we need // to check (for each word!) whether it happens to be a command if (sectioning.containsKey(t.getText())) { nodeType = sectioning.get(t.getText()); switch (nodeType) { case OutlineNode.TYPE_PART: prevToken = new TCpart(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_CHAPTER: prevToken = new TCchapter(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SECTION: prevToken = new TCsection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSECTION: prevToken = new TCssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_SUBSUBSECTION: prevToken = new TCsssection(t.getLine(), t.getPos()); break; case OutlineNode.TYPE_PARAGRAPH: prevToken = new TCparagraph(t.getLine(), t.getPos()); break; case LatexParser.TYPE_LABEL: prevToken = new TClabel(t.getLine(), t.getPos()); break; default: break; } expectArg = true; } } else if (t instanceof TCpindex) { this.index = true; } else if (t instanceof TTaskcomment) { int severity = IMarker.PRIORITY_HIGH; int start = t.getText().indexOf("FIXME"); if (start == -1) { severity = IMarker.PRIORITY_NORMAL; start = t.getText().indexOf("TODO"); if (start == -1) { start = t.getText().indexOf("XXX"); } } String taskText = t.getText().substring(start).trim(); tasks.add(new ParseErrorMessage(t.getLine(), t.getPos(), taskText.length(), taskText, severity)); } else if (t instanceof TVtext) { // Fold OutlineNode on = new OutlineNode(t.getText(), OutlineNode.TYPE_ENVIRONMENT, t.getLine(), t.getPos(), t.getText().length()); // TODO uses memory, but doesn't require much code... String[] lines = t.getText().split("\\r\\n|\\n|\\r"); on.setEndLine(t.getLine() + lines.length); if (!blocks.empty()) { OutlineNode prev = blocks.peek(); prev.addChild(on); on.setParent(prev); } else { outlineTree.add(on); } } } if (t instanceof TLBrace) { braces.push(t); } else if (t instanceof TRBrace) { if (braces.empty()) { //There is an opening brace missing errors.add(new ParseErrorMessage(t.getLine(), t.getPos()-1, 1, TexlipsePlugin.getResourceString("parseErrorMissingLBrace"), IMarker.SEVERITY_ERROR)); } else { braces.pop(); } } } //Check for missing closing braces while (!braces.empty()) { Token mt = (Token) braces.pop(); errors.add(new ParseErrorMessage(mt.getLine(), mt.getPos() - 1, 1, TexlipsePlugin.getResourceString("parseErrorMissingRBrace"), IMarker.SEVERITY_ERROR)); } int endLine = t.getLine() + 1; //endline is exclusive while (!blocks.empty()) { OutlineNode prev = blocks.pop(); prev.setEndLine(endLine); if (prev.getType() == OutlineNode.TYPE_ENVIRONMENT) { fatalErrors = true; errors.add(new ParseErrorMessage(prev.getBeginLine(), 0, prev.getName().length(), "\\begin{" + prev.getName() + "} does not have matching end; at least one unbalanced begin-end", IMarker.SEVERITY_ERROR)); } } }
diff --git a/com.palantir.typescript/src/com/palantir/typescript/services/language/LanguageService.java b/com.palantir.typescript/src/com/palantir/typescript/services/language/LanguageService.java index 4529c93..fe3d03b 100644 --- a/com.palantir.typescript/src/com/palantir/typescript/services/language/LanguageService.java +++ b/com.palantir.typescript/src/com/palantir/typescript/services/language/LanguageService.java @@ -1,293 +1,293 @@ /* * Copyright 2013 Palantir Technologies, 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.palantir.typescript.services.language; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.IScopeContext; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.MapType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.io.Resources; import com.palantir.typescript.IPreferenceConstants; import com.palantir.typescript.ResourceVisitors; import com.palantir.typescript.TypeScriptPlugin; import com.palantir.typescript.services.Bridge; import com.palantir.typescript.services.Request; /** * The language service. * <p> * This service provides code completion, formatting, compiling, etc... * * @author tyleradams */ public final class LanguageService { private static final String SERVICE = "language"; private final Bridge bridge; private final MyPropertyChangeListener preferencesListener; private final IProject project; public LanguageService(String fileName) { this(null, ImmutableList.of(fileName)); } public LanguageService(IProject project) { this(project, ResourceVisitors.getTypeScriptFileNames(project)); } private LanguageService(IProject project, List<String> fileNames) { checkNotNull(fileNames); this.bridge = new Bridge(); this.preferencesListener = new MyPropertyChangeListener(); this.project = project; this.addDefaultLibrary(); this.addFiles(fileNames); this.updateCompilationSettings(); TypeScriptPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this.preferencesListener); } public void dispose() { TypeScriptPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this.preferencesListener); this.bridge.dispose(); } public void editFile(String fileName, int offset, int length, String replacementText) { checkNotNull(fileName); checkArgument(offset >= 0); checkArgument(length >= 0); checkNotNull(replacementText); Request request = new Request(SERVICE, "editFile", fileName, offset, length, replacementText); this.bridge.call(request, Void.class); } public List<Reference> findReferences(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "findReferences", fileName, position); CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class, Reference.class); return this.bridge.call(request, returnType); } public Map<String, List<Diagnostic>> getAllDiagnostics() { Request request = new Request(SERVICE, "getAllDiagnostics"); JavaType stringType = TypeFactory.defaultInstance().uncheckedSimpleType(String.class); CollectionType diagnosticListType = TypeFactory.defaultInstance().constructCollectionType(List.class, Diagnostic.class); MapType returnType = TypeFactory.defaultInstance().constructMapType(Map.class, stringType, diagnosticListType); return LanguageService.this.bridge.call(request, returnType); } public CompletionInfo getCompletionsAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getCompletionsAtPosition", fileName, position); return this.bridge.call(request, CompletionInfo.class); } public List<DefinitionInfo> getDefinitionAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getDefinitionAtPosition", fileName, position); CollectionType resultType = TypeFactory.defaultInstance().constructCollectionType(List.class, DefinitionInfo.class); return this.bridge.call(request, resultType); } public List<Diagnostic> getDiagnostics(String fileName) { checkNotNull(fileName); Request request = new Request(SERVICE, "getDiagnostics", fileName); CollectionType resultType = TypeFactory.defaultInstance().constructCollectionType(List.class, Diagnostic.class); return this.bridge.call(request, resultType); } public List<String> getEmitOutput(String fileName) { checkNotNull(fileName); Request request = new Request(SERVICE, "getEmitOutput", fileName); CollectionType resultType = TypeFactory.defaultInstance().constructCollectionType(List.class, String.class); return this.bridge.call(request, resultType); } public List<TextEdit> getFormattingEditsForRange(String fileName, int minChar, int limChar, FormatCodeOptions options) { checkNotNull(fileName); checkArgument(minChar >= 0); checkArgument(limChar >= 0); checkNotNull(options); Request request = new Request(SERVICE, "getFormattingEditsForRange", fileName, minChar, limChar, options); CollectionType resultType = TypeFactory.defaultInstance().constructCollectionType(List.class, TextEdit.class); return this.bridge.call(request, resultType); } public SpanInfo getNameOrDottedNameSpan(String fileName, int startPos, int endPos) { checkNotNull(fileName); checkArgument(startPos >= 0); checkArgument(endPos >= 0); Request request = new Request(SERVICE, "getNameOrDottedNameSpan", fileName, startPos, endPos); return this.bridge.call(request, SpanInfo.class); } public List<ReferenceEntry> getOccurrencesAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getOccurrencesAtPosition", fileName, position); CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class, ReferenceEntry.class); return this.bridge.call(request, returnType); } public List<ReferenceEntry> getReferencesAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getReferencesAtPosition", fileName, position); CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class, ReferenceEntry.class); return this.bridge.call(request, returnType); } public List<NavigateToItem> getScriptLexicalStructure(String fileName) { checkNotNull(fileName); Request request = new Request(SERVICE, "getScriptLexicalStructure", fileName); CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class, NavigateToItem.class); return this.bridge.call(request, returnType); } public SignatureInfo getSignatureAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getSignatureAtPosition", fileName, position); return this.bridge.call(request, SignatureInfo.class); } public TypeInfo getTypeAtPosition(String fileName, int position) { checkNotNull(fileName); checkArgument(position >= 0); Request request = new Request(SERVICE, "getTypeAtPosition", fileName, position); return this.bridge.call(request, TypeInfo.class); } public void setFileOpen(String fileName, boolean open) { checkNotNull(fileName); Request request = new Request(SERVICE, "setFileOpen", fileName, open); this.bridge.call(request, Void.class); } public void updateFiles(List<FileDelta> fileDeltas) { checkNotNull(fileDeltas); if (!fileDeltas.isEmpty()) { Request request = new Request(SERVICE, "updateFiles", fileDeltas); LanguageService.this.bridge.call(request, Void.class); } } private void addDefaultLibrary() { String libraryContents; try { libraryContents = Resources.toString(LanguageService.class.getResource("lib.d.ts"), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } Request request = new Request(SERVICE, "addDefaultLibrary", libraryContents); this.bridge.call(request, Void.class); } private void addFiles(List<String> fileNames) { Request request = new Request(SERVICE, "addFiles", fileNames); this.bridge.call(request, Void.class); } private static String getProjectPreference(IProject project, String key) { IScopeContext projectScope = new ProjectScope(project); IEclipsePreferences projectPreferences = projectScope.getNode(TypeScriptPlugin.ID); return projectPreferences.get(key, ""); } private void updateCompilationSettings() { IPreferenceStore preferenceStore = TypeScriptPlugin.getDefault().getPreferenceStore(); // create the compilation settings from the preferences CompilationSettings compilationSettings = new CompilationSettings(); compilationSettings.setCodeGenTarget(LanguageVersion.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_CODE_GEN_TARGET))); compilationSettings.setMapSourceFiles(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_MAP_SOURCE_FILES)); compilationSettings.setModuleGenTarget(ModuleGenTarget.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_MODULE_GEN_TARGET))); compilationSettings.setNoLib(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_NO_LIB)); compilationSettings.setRemoveComments(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_REMOVE_COMMENTS)); // set the output directory if it was specified if (this.project != null) { String relativePath = getProjectPreference(this.project, IPreferenceConstants.COMPILER_OUTPUT_DIR_OPTION); if (!Strings.isNullOrEmpty(relativePath)) { - IFolder sourceFolder = this.project.getFolder(relativePath); - String outDir = sourceFolder.getRawLocation().toOSString() + "/"; + IFolder outputFolder = this.project.getFolder(relativePath); + String outDir = outputFolder.getRawLocation().toOSString() + "/"; compilationSettings.setOutDirOption(outDir); } } Request request = new Request(SERVICE, "setCompilationSettings", compilationSettings); this.bridge.call(request, Void.class); } private final class MyPropertyChangeListener implements IPropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent event) { String property = event.getProperty(); if (IPreferenceConstants.COMPILER_PREFERENCES.contains(property)) { updateCompilationSettings(); } } } }
true
true
private void updateCompilationSettings() { IPreferenceStore preferenceStore = TypeScriptPlugin.getDefault().getPreferenceStore(); // create the compilation settings from the preferences CompilationSettings compilationSettings = new CompilationSettings(); compilationSettings.setCodeGenTarget(LanguageVersion.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_CODE_GEN_TARGET))); compilationSettings.setMapSourceFiles(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_MAP_SOURCE_FILES)); compilationSettings.setModuleGenTarget(ModuleGenTarget.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_MODULE_GEN_TARGET))); compilationSettings.setNoLib(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_NO_LIB)); compilationSettings.setRemoveComments(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_REMOVE_COMMENTS)); // set the output directory if it was specified if (this.project != null) { String relativePath = getProjectPreference(this.project, IPreferenceConstants.COMPILER_OUTPUT_DIR_OPTION); if (!Strings.isNullOrEmpty(relativePath)) { IFolder sourceFolder = this.project.getFolder(relativePath); String outDir = sourceFolder.getRawLocation().toOSString() + "/"; compilationSettings.setOutDirOption(outDir); } } Request request = new Request(SERVICE, "setCompilationSettings", compilationSettings); this.bridge.call(request, Void.class); }
private void updateCompilationSettings() { IPreferenceStore preferenceStore = TypeScriptPlugin.getDefault().getPreferenceStore(); // create the compilation settings from the preferences CompilationSettings compilationSettings = new CompilationSettings(); compilationSettings.setCodeGenTarget(LanguageVersion.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_CODE_GEN_TARGET))); compilationSettings.setMapSourceFiles(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_MAP_SOURCE_FILES)); compilationSettings.setModuleGenTarget(ModuleGenTarget.valueOf(preferenceStore .getString(IPreferenceConstants.COMPILER_MODULE_GEN_TARGET))); compilationSettings.setNoLib(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_NO_LIB)); compilationSettings.setRemoveComments(preferenceStore.getBoolean(IPreferenceConstants.COMPILER_REMOVE_COMMENTS)); // set the output directory if it was specified if (this.project != null) { String relativePath = getProjectPreference(this.project, IPreferenceConstants.COMPILER_OUTPUT_DIR_OPTION); if (!Strings.isNullOrEmpty(relativePath)) { IFolder outputFolder = this.project.getFolder(relativePath); String outDir = outputFolder.getRawLocation().toOSString() + "/"; compilationSettings.setOutDirOption(outDir); } } Request request = new Request(SERVICE, "setCompilationSettings", compilationSettings); this.bridge.call(request, Void.class); }
diff --git a/java/src/main/java/sandbox/Sleep.java b/java/src/main/java/sandbox/Sleep.java index b17a592..8fd888d 100644 --- a/java/src/main/java/sandbox/Sleep.java +++ b/java/src/main/java/sandbox/Sleep.java @@ -1,13 +1,13 @@ package sandbox; public class Sleep { public static void main(String[] args) throws Exception { - long sec = Long.MAX_VALUE; + long msec = Long.MAX_VALUE; if (args.length != 0) { try { - sec = Long.parseLong(args[0]); + msec = Long.parseLong(args[0]); } catch (Exception ignore) { } } - Thread.sleep(sec); + Thread.sleep(msec); } }
false
true
public static void main(String[] args) throws Exception { long sec = Long.MAX_VALUE; if (args.length != 0) { try { sec = Long.parseLong(args[0]); } catch (Exception ignore) { } } Thread.sleep(sec); }
public static void main(String[] args) throws Exception { long msec = Long.MAX_VALUE; if (args.length != 0) { try { msec = Long.parseLong(args[0]); } catch (Exception ignore) { } } Thread.sleep(msec); }
diff --git a/xstream/src/java/com/thoughtworks/xstream/core/util/Cloneables.java b/xstream/src/java/com/thoughtworks/xstream/core/util/Cloneables.java index 7d98e7e2..e44a49b3 100644 --- a/xstream/src/java/com/thoughtworks/xstream/core/util/Cloneables.java +++ b/xstream/src/java/com/thoughtworks/xstream/core/util/Cloneables.java @@ -1,46 +1,46 @@ /* * Copyright (C) 2009 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 29. August 2009 by Joerg Schaible */ package com.thoughtworks.xstream.core.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.thoughtworks.xstream.converters.reflection.ObjectAccessException; /** * Utility functions for {@link Cloneable} objects. * * @author J&ouml;rg Schaible * @since upcoming */ public class Cloneables { public static Object clone(Object o) { if (o instanceof Cloneable) { try { Method clone = o.getClass().getMethod("clone", (Class[])null); return clone.invoke(o, (Object[])null); } catch (NoSuchMethodException e) { - new ObjectAccessException("Cloneable type has no clone method", e); + throw new ObjectAccessException("Cloneable type has no clone method", e); } catch (IllegalAccessException e) { - new ObjectAccessException("Cannot clone Cloneable type", e); + throw new ObjectAccessException("Cannot clone Cloneable type", e); } catch (InvocationTargetException e) { - new ObjectAccessException("Exception cloning Cloneable type", e.getCause()); + throw new ObjectAccessException("Exception cloning Cloneable type", e.getCause()); } } return null; } public static Object cloneIfPossible(Object o) { Object clone = clone(o); return clone == null ? o : clone; } }
false
true
public static Object clone(Object o) { if (o instanceof Cloneable) { try { Method clone = o.getClass().getMethod("clone", (Class[])null); return clone.invoke(o, (Object[])null); } catch (NoSuchMethodException e) { new ObjectAccessException("Cloneable type has no clone method", e); } catch (IllegalAccessException e) { new ObjectAccessException("Cannot clone Cloneable type", e); } catch (InvocationTargetException e) { new ObjectAccessException("Exception cloning Cloneable type", e.getCause()); } } return null; }
public static Object clone(Object o) { if (o instanceof Cloneable) { try { Method clone = o.getClass().getMethod("clone", (Class[])null); return clone.invoke(o, (Object[])null); } catch (NoSuchMethodException e) { throw new ObjectAccessException("Cloneable type has no clone method", e); } catch (IllegalAccessException e) { throw new ObjectAccessException("Cannot clone Cloneable type", e); } catch (InvocationTargetException e) { throw new ObjectAccessException("Exception cloning Cloneable type", e.getCause()); } } return null; }
diff --git a/java/src/org/vinodkd/jnv/Notes.java b/java/src/org/vinodkd/jnv/Notes.java index 3448322..fa7ad93 100644 --- a/java/src/org/vinodkd/jnv/Notes.java +++ b/java/src/org/vinodkd/jnv/Notes.java @@ -1,72 +1,72 @@ package org.vinodkd.jnv; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.ArrayList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.io.IOException; public class Notes implements Model{ private HashMap<String,Note> notes = new HashMap<String,Note>(); private final String ABOUTNOTE_lOC = "res/about.txt"; public Notes() {} public void add(Note n){ notes.put(n.getTitle(),n); } public void set(String title, String contents) { Note n = new Note(title,contents); notes.put(title,n); } public Note get(String title) { return notes.get(title);} public void load(){ // read from file here } public void store(){ // write to file here } public Object getInitialValue(){ load(); Note aboutNote = new Note("About", getAboutText()); add(aboutNote); return notes; } private String getAboutText(){ InputStream is = getClass().getClassLoader().getResourceAsStream(ABOUTNOTE_lOC); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer aboutText = new StringBuffer(""); String line; try{ while((line=br.readLine())!=null){ - aboutText.append(line); + aboutText.append(line);aboutText.append("\n"); } }catch(IOException ioe){ // TODO: PUT IN DEFAULT TEXT IF THIS FAILS } return aboutText.toString(); } public Object getCurrentValue(){ return notes; } public List<String> search(String searchText){ ArrayList<String> searchResult = new ArrayList<String>(); Set<String> titles = notes.keySet(); for(String title: titles){ if(title.contains(searchText)){ searchResult.add(title); } } return searchResult; } }
true
true
private String getAboutText(){ InputStream is = getClass().getClassLoader().getResourceAsStream(ABOUTNOTE_lOC); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer aboutText = new StringBuffer(""); String line; try{ while((line=br.readLine())!=null){ aboutText.append(line); } }catch(IOException ioe){ // TODO: PUT IN DEFAULT TEXT IF THIS FAILS } return aboutText.toString(); }
private String getAboutText(){ InputStream is = getClass().getClassLoader().getResourceAsStream(ABOUTNOTE_lOC); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer aboutText = new StringBuffer(""); String line; try{ while((line=br.readLine())!=null){ aboutText.append(line);aboutText.append("\n"); } }catch(IOException ioe){ // TODO: PUT IN DEFAULT TEXT IF THIS FAILS } return aboutText.toString(); }
diff --git a/core/src/visad/trunk/FunctionType.java b/core/src/visad/trunk/FunctionType.java index 7649b351a..720ba1831 100644 --- a/core/src/visad/trunk/FunctionType.java +++ b/core/src/visad/trunk/FunctionType.java @@ -1,325 +1,326 @@ // // FunctionType.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.rmi.*; import java.util.Vector; /** FunctionType is the VisAD data type for functions.<P> A Function domain type may be either a RealType (for a function with domain = R) or a RealTupleType (for a function with domain = R^n for n > 0).<P> */ public class FunctionType extends MathType { private RealTupleType Domain; private MathType Range; private RealTupleType FlatRange; private boolean Real; // true if range is RealType or RealTupleType private boolean Flat; // true if Real or if range is Flat TupleType /** this is an array of RealType-s that are RealType components of Range or RealType components of RealTupleType components of Range; a non_realType and non-TupleType Range is marked by null; components of a TupleType Range that are neither RealType nor RealTupleType are ignored */ private RealType[] realComponents; /** array of TextType Range components */ private TextType[] textComponents; /** array of component indices of TextType Range components */ private int[] textIndices; public final static FunctionType REAL_1TO1_FUNCTION = new FunctionType(RealType.Generic, RealType.Generic, true); private static RealType[] real3 = {RealType.Generic, RealType.Generic, RealType.Generic}; public final static FunctionType REAL_1TO3_FUNCTION = new FunctionType(RealType.Generic, new RealTupleType(real3, true), true); private static RealType[] real4 = {RealType.Generic, RealType.Generic, RealType.Generic, RealType.Generic}; public final static FunctionType REAL_1TO4_FUNCTION = new FunctionType(RealType.Generic, new RealTupleType(real4, true), true); /** domain must be a RealType or a RealTupleType; range may be any MathType */ public FunctionType(MathType domain, MathType range) throws VisADException { super(); if (!(domain instanceof RealTupleType || domain instanceof RealType)) { throw new TypeException("FunctionType: domain must be RealTupleType" + " or RealType"); } Domain = makeFlat(domain); Real = range instanceof RealType || range instanceof RealTupleType; Flat = Real || (range instanceof TupleType && ((TupleType) range).getFlat()); Range = range; FlatRange = Flat ? makeFlat(range) : null; realComponents = getComponents(Range); makeTextComponents(); } /** trusted constructor for initializers */ FunctionType(MathType domain, MathType range, boolean b) { super(b); Domain = makeFlatTrusted(domain); Real = range instanceof RealType || range instanceof RealTupleType; Flat = Real || (range instanceof TupleType && ((TupleType) range).getFlat()); Range = range; FlatRange = Flat ? makeFlatTrusted(range) : null; realComponents = getComponents(Range); makeTextComponents(); } private void makeTextComponents() { int n = 0; textComponents = null; textIndices = null; if (Range instanceof TextType) { textComponents = new TextType[] {(TextType) Range}; textIndices = new int[] {0}; n = 1; } else if (Range instanceof TupleType) { try { for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) n++; } if (n == 0) return; textComponents = new TextType[n]; textIndices = new int[n]; int j = 0; for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) { textComponents[j] = (TextType) ((TupleType) Range).getComponent(i); textIndices[j] = i; + j++; } } } catch (VisADException e) { textComponents = null; textIndices = null; } } } public TextType[] getTextComponents() { return textComponents; } public int[] getTextIndices() { return textIndices; } private static RealType[] getComponents(MathType type) { RealType[] reals; if (type instanceof RealType) { RealType[] r = {(RealType) type}; return r; } else if (type instanceof TupleType) { return ((TupleType) type).getRealComponents(); } else { return null; } } private static RealTupleType makeFlat(MathType type) throws VisADException { if (type instanceof RealTupleType) { return (RealTupleType) type; } else if (type instanceof RealType) { RealType[] types = {(RealType) type}; return new RealTupleType(types, null, ((RealType) type).getDefaultSet()); } else if (type instanceof TupleType && ((TupleType) type).getFlat()) { return new RealTupleType(((TupleType) type).getRealComponents()); } else { throw new TypeException("FunctionType: illegal input to makeFlat"); } } private static RealTupleType makeFlatTrusted(MathType type) { if (type instanceof RealTupleType) { return (RealTupleType) type; } else if (type instanceof RealType) { RealType[] types = {(RealType) type}; return new RealTupleType(types, true); } else if (type instanceof TupleType && ((TupleType) type).getFlat()) { return new RealTupleType(((TupleType) type).getRealComponents(), true); } else { return null; } } /** if the domain passed to constructor was a RealType, getDomain returns a RealTupleType with that RealType as its single component */ public RealTupleType getDomain() { return Domain; } public MathType getRange() { return Range; } public boolean getFlat() { return Flat; } public boolean getReal() { return Real; } public RealTupleType getFlatRange() { return FlatRange; } public RealType[] getRealComponents() { return realComponents; } public boolean equals(Object type) { if (!(type instanceof FunctionType)) return false; return (Domain.equals(((FunctionType) type).getDomain()) && Range.equals(((FunctionType) type).getRange())); } /** * Returns the hash code of this instance. If {@link #equals(Object type)}, * then <code>{@link #hashCode()} == type.hashCode()</code>. * * @return The hash code of this instance. */ public int hashCode() { return Domain.hashCode() ^ Range.hashCode(); } public boolean equalsExceptName(MathType type) { if (!(type instanceof FunctionType)) return false; return (Domain.equalsExceptName(((FunctionType) type).getDomain()) && Range.equalsExceptName(((FunctionType) type).getRange())); } /*- TDR May 1998 */ public boolean equalsExceptNameButUnits(MathType type) throws VisADException { if (!(type instanceof FunctionType)) return false; return (Domain.equalsExceptNameButUnits(((FunctionType) type).getDomain()) && Range.equalsExceptNameButUnits(((FunctionType) type).getRange())); } /*- TDR June 1998 */ public MathType cloneDerivative( RealType d_partial ) throws VisADException { return (MathType) new FunctionType( Domain, Range.cloneDerivative(d_partial)); } /*- TDR July 1998 */ public MathType binary( MathType type, int op, Vector names ) throws VisADException { if (type == null) { throw new TypeException("FunctionType.binary: type may not be null" ); } if (equalsExceptName(type)) { return new FunctionType(Domain, Range.binary(((FunctionType)type).getRange(), op, names)); } else if (type instanceof RealType || getRange().equalsExceptName(type)) { return new FunctionType(Domain, Range.binary(type, op, names)); } else if (type instanceof FunctionType && ((FunctionType) type).getRange().equalsExceptName(this)) { return new FunctionType(((FunctionType) type).getDomain(), ((FunctionType) type).getRange().binary(this, DataImpl.invertOp(op), names)); } else { throw new TypeException("FunctionType.binary: types don't match"); } /* WLH 10 Sept 98 MathType m_type = (type instanceof FunctionType) ? ((FunctionType)type).getRange() : type; return (MathType) new FunctionType( Domain, Range.binary( m_type, op, names )); */ } /*- TDR July 1998 */ public MathType unary( int op, Vector names ) throws VisADException { return (MathType) new FunctionType( Domain, Range.unary( op, names )); } /* WLH 5 Jan 2000 public String toString() { String t = Real ? " (Real): " : Flat ? " (Flat): " : ": "; return "FunctionType" + t + Domain.toString() + " -> " + Range.toString(); } */ public String prettyString(int indent) { String ds = "(" + Domain.prettyString(indent) + " -> "; int n = ds.length(); String rs = Range.prettyString(indent + n) + ")"; return ds + rs; } public Data missingData() throws VisADException, RemoteException { int n = Domain.getDimension(); double[] values = new double[n]; for (int i=0; i<n; i++) values[i] = 0.0; RealTuple tuple = new RealTuple(Domain, values); Set domainSet = new SingletonSet(tuple); return getFlat() ? new FlatField(this, domainSet) : new FieldImpl(this, domainSet); } public ShadowType buildShadowType(DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return (ShadowType) link.getRenderer().makeShadowFunctionType(this, link, parent); } }
true
true
private void makeTextComponents() { int n = 0; textComponents = null; textIndices = null; if (Range instanceof TextType) { textComponents = new TextType[] {(TextType) Range}; textIndices = new int[] {0}; n = 1; } else if (Range instanceof TupleType) { try { for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) n++; } if (n == 0) return; textComponents = new TextType[n]; textIndices = new int[n]; int j = 0; for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) { textComponents[j] = (TextType) ((TupleType) Range).getComponent(i); textIndices[j] = i; } } } catch (VisADException e) { textComponents = null; textIndices = null; } } }
private void makeTextComponents() { int n = 0; textComponents = null; textIndices = null; if (Range instanceof TextType) { textComponents = new TextType[] {(TextType) Range}; textIndices = new int[] {0}; n = 1; } else if (Range instanceof TupleType) { try { for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) n++; } if (n == 0) return; textComponents = new TextType[n]; textIndices = new int[n]; int j = 0; for (int i=0; i<((TupleType) Range).getDimension(); i++) { if (((TupleType) Range).getComponent(i) instanceof TextType) { textComponents[j] = (TextType) ((TupleType) Range).getComponent(i); textIndices[j] = i; j++; } } } catch (VisADException e) { textComponents = null; textIndices = null; } } }
diff --git a/src/com/pong/Assets.java b/src/com/pong/Assets.java index d9226a7..2488f14 100644 --- a/src/com/pong/Assets.java +++ b/src/com/pong/Assets.java @@ -1,49 +1,49 @@ package com.pong; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class Assets { public static Texture textureatlas; public static Texture paddles_n_ball; public static TextureRegion gameScreenBackgroundRegion; public static TextureRegion mainMenuScreenRegion; public static TextureRegion paddle; public static TextureRegion ball; public static BitmapFont font; public static Music music; public static Sound bounceSound; public static Texture loadTexture(String file){ return new Texture(Gdx.files.internal(file)); } public static void load(){ textureatlas = loadTexture("data/screen_atlas.png"); paddles_n_ball = loadTexture("data/paddles.png"); gameScreenBackgroundRegion = new TextureRegion(textureatlas, 0,0,480,320); //0,0,480,320 mainMenuScreenRegion = new TextureRegion(textureatlas, 0,320,480,320); //0,320,480,320 paddle = new TextureRegion(paddles_n_ball, 0,0,10,64); ball = new TextureRegion(paddles_n_ball, 53,53,10,10); font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); - music = Gdx.audio.newMusic(Gdx.files.internal("data/Legend_of_zelda_Nullification_OC_ReMix.mp3")); + music = Gdx.audio.newMusic(Gdx.files.internal("data/loz-oc-remix.mp3")); music.setLooping(true); music.setVolume(0.5f); music.play(); bounceSound = Gdx.audio.newSound(Gdx.files.internal("data/ball_bump.wav")); } public static void playSound(Sound sound){ sound.play(1); } }
true
true
public static void load(){ textureatlas = loadTexture("data/screen_atlas.png"); paddles_n_ball = loadTexture("data/paddles.png"); gameScreenBackgroundRegion = new TextureRegion(textureatlas, 0,0,480,320); //0,0,480,320 mainMenuScreenRegion = new TextureRegion(textureatlas, 0,320,480,320); //0,320,480,320 paddle = new TextureRegion(paddles_n_ball, 0,0,10,64); ball = new TextureRegion(paddles_n_ball, 53,53,10,10); font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); music = Gdx.audio.newMusic(Gdx.files.internal("data/Legend_of_zelda_Nullification_OC_ReMix.mp3")); music.setLooping(true); music.setVolume(0.5f); music.play(); bounceSound = Gdx.audio.newSound(Gdx.files.internal("data/ball_bump.wav")); }
public static void load(){ textureatlas = loadTexture("data/screen_atlas.png"); paddles_n_ball = loadTexture("data/paddles.png"); gameScreenBackgroundRegion = new TextureRegion(textureatlas, 0,0,480,320); //0,0,480,320 mainMenuScreenRegion = new TextureRegion(textureatlas, 0,320,480,320); //0,320,480,320 paddle = new TextureRegion(paddles_n_ball, 0,0,10,64); ball = new TextureRegion(paddles_n_ball, 53,53,10,10); font = new BitmapFont(Gdx.files.internal("data/font.fnt"), Gdx.files.internal("data/font.png"), false); music = Gdx.audio.newMusic(Gdx.files.internal("data/loz-oc-remix.mp3")); music.setLooping(true); music.setVolume(0.5f); music.play(); bounceSound = Gdx.audio.newSound(Gdx.files.internal("data/ball_bump.wav")); }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java b/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java index 066286b72..b7a8ed408 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/util/SVNSSLUtil.java @@ -1,144 +1,146 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.util; import java.security.MessageDigest; import java.security.cert.CertificateException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Date; import java.util.Iterator; /** * @version 1.0 * @author TMate Software Ltd. */ public class SVNSSLUtil { public static StringBuffer getServerCertificatePrompt(X509Certificate cert, String realm, String hostName) { int failures = getServerCertificateFailures(cert, hostName); StringBuffer prompt = new StringBuffer(); prompt.append("Error validating server certificate for '"); prompt.append(realm); prompt.append("':\n"); if ((failures & 8) != 0) { prompt.append(" - The certificate is not issued by a trusted authority. Use the\n" + " fingerprint to validate the certificate manually!\n"); } if ((failures & 4) != 0) { prompt.append(" - The certificate hostname does not match.\n"); } if ((failures & 2) != 0) { prompt.append(" - The certificate has expired.\n"); } if ((failures & 1) != 0) { prompt.append(" - The certificate is not yet valid.\n"); } getServerCertificateInfo(cert, prompt); return prompt; } private static String getFingerprint(X509Certificate cert) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cert.getEncoded()); byte[] digest = md.digest(); for (int i= 0; i < digest.length; i++) { if (i != 0) { s.append(':'); } int b = digest[i] & 0xFF; String hex = Integer.toHexString(b); if (hex.length() == 1) { s.append('0'); } s.append(hex.toLowerCase()); } } catch (Exception e) { } return s.toString(); } private static void getServerCertificateInfo(X509Certificate cert, StringBuffer info) { info.append("Certificate information:"); info.append('\n'); info.append(" - Subject: "); info.append(cert.getSubjectDN().getName()); info.append('\n'); info.append(" - Valid: "); info.append("from " + cert.getNotBefore() + " until " + cert.getNotAfter()); info.append('\n'); info.append(" - Issuer: "); info.append(cert.getIssuerDN().getName()); info.append('\n'); info.append(" - Fingerprint: "); info.append(getFingerprint(cert)); } public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); int index = certHostName.indexOf("CN=") + 3; if (index >= 0) { certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); - for (Iterator names = altNames.iterator(); names.hasNext();) { - Object nameList = names.next(); - if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { - Object[] name = ((Collection) nameList).toArray(); - Object type = name[0]; - Object host = name[1]; - if (type instanceof Integer && host instanceof String) { - if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { - return mask; + if(altNames != null) { + for (Iterator names = altNames.iterator(); names.hasNext();) { + Object nameList = names.next(); + if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { + Object[] name = ((Collection) nameList).toArray(); + Object type = name[0]; + Object host = name[1]; + if (type instanceof Integer && host instanceof String) { + if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { + return mask; + } } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; } public static class CertificateNotTrustedException extends CertificateException { public CertificateNotTrustedException() { super(); } public CertificateNotTrustedException(String msg) { super(msg); } } }
true
true
public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); int index = certHostName.indexOf("CN=") + 3; if (index >= 0) { certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); for (Iterator names = altNames.iterator(); names.hasNext();) { Object nameList = names.next(); if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { Object[] name = ((Collection) nameList).toArray(); Object type = name[0]; Object host = name[1]; if (type instanceof Integer && host instanceof String) { if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { return mask; } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; }
public static int getServerCertificateFailures(X509Certificate cert, String realHostName) { int mask = 8; Date time = new Date(System.currentTimeMillis()); if (time.before(cert.getNotBefore())) { mask |= 1; } if (time.after(cert.getNotAfter())) { mask |= 2; } String certHostName = cert.getSubjectDN().getName(); int index = certHostName.indexOf("CN=") + 3; if (index >= 0) { certHostName = certHostName.substring(index); if (certHostName.indexOf(' ') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(' ')); } if (certHostName.indexOf(',') >= 0) { certHostName = certHostName.substring(0, certHostName.indexOf(',')); } } if (!realHostName.equals(certHostName)) { try { Collection altNames = cert.getSubjectAlternativeNames(); if(altNames != null) { for (Iterator names = altNames.iterator(); names.hasNext();) { Object nameList = names.next(); if (nameList instanceof Collection && ((Collection) nameList).size() >= 2) { Object[] name = ((Collection) nameList).toArray(); Object type = name[0]; Object host = name[1]; if (type instanceof Integer && host instanceof String) { if (((Integer) type).intValue() == 2 && host.equals(realHostName)) { return mask; } } } } } } catch (CertificateParsingException e) { } mask |= 4; } return mask; }
diff --git a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java index 0bcfd0b..b179b85 100644 --- a/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java +++ b/v7/mediarouter/src/android/support/v7/media/RegisteredMediaRouteProvider.java @@ -1,669 +1,669 @@ /* * Copyright (C) 2013 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 android.support.v7.media; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.DeadObjectException; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.IBinder.DeathRecipient; import android.os.Message; import android.os.Messenger; import android.support.v7.media.MediaRouter.ControlRequestCallback; import android.util.Log; import android.util.SparseArray; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; /** * Maintains a connection to a particular media route provider service. */ final class RegisteredMediaRouteProvider extends MediaRouteProvider implements ServiceConnection { private static final String TAG = "MediaRouteProviderProxy"; // max. 23 chars private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); private final ComponentName mComponentName; private final PrivateHandler mPrivateHandler; private final ArrayList<Controller> mControllers = new ArrayList<Controller>(); private boolean mStarted; private boolean mBound; private Connection mActiveConnection; private boolean mConnectionReady; public RegisteredMediaRouteProvider(Context context, ComponentName componentName) { super(context, new ProviderMetadata(componentName.getPackageName())); mComponentName = componentName; mPrivateHandler = new PrivateHandler(); } @Override public RouteController onCreateRouteController(String routeId) { MediaRouteProviderDescriptor descriptor = getDescriptor(); if (descriptor != null) { List<MediaRouteDescriptor> routes = descriptor.getRoutes(); final int count = routes.size(); for (int i = 0; i < count; i++) { final MediaRouteDescriptor route = routes.get(i); if (route.getId().equals(routeId)) { Controller controller = new Controller(routeId); mControllers.add(controller); if (mConnectionReady) { controller.attachConnection(mActiveConnection); } updateBinding(); return controller; } } } return null; } @Override public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) { if (mConnectionReady) { mActiveConnection.setDiscoveryRequest(request); } updateBinding(); } public boolean hasComponentName(String packageName, String className) { return mComponentName.getPackageName().equals(packageName) && mComponentName.getClassName().equals(className); } public void start() { if (!mStarted) { if (DEBUG) { Log.d(TAG, this + ": Starting"); } mStarted = true; updateBinding(); } } public void stop() { if (mStarted) { if (DEBUG) { Log.d(TAG, this + ": Stopping"); } mStarted = false; updateBinding(); } } public void rebindIfDisconnected() { if (mActiveConnection == null && shouldBind()) { unbind(); bind(); } } private void updateBinding() { if (shouldBind()) { bind(); } else { unbind(); } } private boolean shouldBind() { if (mStarted) { // Bind whenever there is a discovery request. if (getDiscoveryRequest() != null) { return true; } // Bind whenever the application has an active route controller. // This means that one of this provider's routes is selected. if (!mControllers.isEmpty()) { return true; } } return false; } private void bind() { if (!mBound) { if (DEBUG) { Log.d(TAG, this + ": Binding"); } Intent service = new Intent(MediaRouteProviderService.SERVICE_INTERFACE); service.setComponent(mComponentName); try { mBound = getContext().bindService(service, this, Context.BIND_AUTO_CREATE); if (!mBound && DEBUG) { Log.d(TAG, this + ": Bind failed"); } } catch (SecurityException ex) { if (DEBUG) { Log.d(TAG, this + ": Bind failed", ex); } } } } private void unbind() { if (mBound) { if (DEBUG) { Log.d(TAG, this + ": Unbinding"); } mBound = false; disconnect(); getContext().unbindService(this); } } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (DEBUG) { Log.d(TAG, this + ": Connected"); } if (mBound) { disconnect(); Messenger messenger = (service != null ? new Messenger(service) : null); if (MediaRouteProviderService.isValidRemoteMessenger(messenger)) { Connection connection = new Connection(messenger); if (connection.register()) { mActiveConnection = connection; } else { if (DEBUG) { Log.d(TAG, this + ": Registration failed"); } } } else { Log.e(TAG, this + ": Service returned invalid messenger binder"); } } } @Override public void onServiceDisconnected(ComponentName name) { if (DEBUG) { Log.d(TAG, this + ": Service disconnected"); } disconnect(); } private void onConnectionReady(Connection connection) { if (mActiveConnection == connection) { mConnectionReady = true; attachControllersToConnection(); MediaRouteDiscoveryRequest request = getDiscoveryRequest(); if (request != null) { mActiveConnection.setDiscoveryRequest(request); } } } private void onConnectionDied(Connection connection) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Service connection died"); } disconnect(); } } private void onConnectionError(Connection connection, String error) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Service connection error - " + error); } unbind(); } } private void onConnectionDescriptorChanged(Connection connection, MediaRouteProviderDescriptor descriptor) { if (mActiveConnection == connection) { if (DEBUG) { Log.d(TAG, this + ": Descriptor changed, descriptor=" + descriptor); } setDescriptor(descriptor); } } private void disconnect() { if (mActiveConnection != null) { setDescriptor(null); mConnectionReady = false; detachControllersFromConnection(); mActiveConnection.dispose(); mActiveConnection = null; } } private void onControllerReleased(Controller controller) { mControllers.remove(controller); controller.detachConnection(); updateBinding(); } private void attachControllersToConnection() { int count = mControllers.size(); for (int i = 0; i < count; i++) { mControllers.get(i).attachConnection(mActiveConnection); } } private void detachControllersFromConnection() { int count = mControllers.size(); for (int i = 0; i < count; i++) { mControllers.get(i).detachConnection(); } } @Override public String toString() { return "Service connection " + mComponentName.flattenToShortString(); } private final class Controller extends RouteController { private final String mRouteId; private boolean mSelected; private int mPendingSetVolume = -1; private int mPendingUpdateVolumeDelta; private Connection mConnection; private int mControllerId; public Controller(String routeId) { mRouteId = routeId; } public void attachConnection(Connection connection) { mConnection = connection; mControllerId = connection.createRouteController(mRouteId); if (mSelected) { connection.selectRoute(mControllerId); if (mPendingSetVolume >= 0) { connection.setVolume(mControllerId, mPendingSetVolume); mPendingSetVolume = -1; } if (mPendingUpdateVolumeDelta != 0) { connection.updateVolume(mControllerId, mPendingUpdateVolumeDelta); mPendingUpdateVolumeDelta = 0; } } } public void detachConnection() { if (mConnection != null) { mConnection.releaseRouteController(mControllerId); mConnection = null; mControllerId = 0; } } @Override public void onRelease() { onControllerReleased(this); } @Override public void onSelect() { mSelected = true; if (mConnection != null) { mConnection.selectRoute(mControllerId); } } @Override public void onUnselect() { mSelected = false; if (mConnection != null) { mConnection.unselectRoute(mControllerId); } } @Override public void onSetVolume(int volume) { if (mConnection != null) { mConnection.setVolume(mControllerId, volume); } else { mPendingSetVolume = volume; mPendingUpdateVolumeDelta = 0; } } @Override public void onUpdateVolume(int delta) { if (mConnection != null) { mConnection.updateVolume(mControllerId, delta); } else { mPendingUpdateVolumeDelta += delta; } } @Override public boolean onControlRequest(Intent intent, ControlRequestCallback callback) { if (mConnection != null) { return mConnection.sendControlRequest(mControllerId, intent, callback); } return false; } } private final class Connection implements DeathRecipient { private final Messenger mServiceMessenger; private final ReceiveHandler mReceiveHandler; private final Messenger mReceiveMessenger; private int mNextRequestId = 1; private int mNextControllerId = 1; private int mServiceVersion; // non-zero when registration complete private int mPendingRegisterRequestId; private final SparseArray<ControlRequestCallback> mPendingCallbacks = new SparseArray<ControlRequestCallback>(); public Connection(Messenger serviceMessenger) { mServiceMessenger = serviceMessenger; mReceiveHandler = new ReceiveHandler(this); mReceiveMessenger = new Messenger(mReceiveHandler); } public boolean register() { mPendingRegisterRequestId = mNextRequestId++; if (!sendRequest(MediaRouteProviderService.CLIENT_MSG_REGISTER, mPendingRegisterRequestId, MediaRouteProviderService.CLIENT_VERSION_CURRENT, null, null)) { return false; } try { mServiceMessenger.getBinder().linkToDeath(this, 0); return true; } catch (RemoteException ex) { binderDied(); } return false; } public void dispose() { sendRequest(MediaRouteProviderService.CLIENT_MSG_UNREGISTER, 0, 0, null, null); mReceiveHandler.dispose(); mServiceMessenger.getBinder().unlinkToDeath(this, 0); mPrivateHandler.post(new Runnable() { @Override public void run() { failPendingCallbacks(); } }); } private void failPendingCallbacks() { int count = 0; for (int i = 0; i < mPendingCallbacks.size(); i++) { mPendingCallbacks.valueAt(i).onError(null, null); } mPendingCallbacks.clear(); } public boolean onGenericFailure(int requestId) { if (requestId == mPendingRegisterRequestId) { mPendingRegisterRequestId = 0; onConnectionError(this, "Registation failed"); } ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onError(null, null); } return true; } public boolean onGenericSuccess(int requestId) { return true; } public boolean onRegistered(int requestId, int serviceVersion, Bundle descriptorBundle) { if (mServiceVersion == 0 && requestId == mPendingRegisterRequestId && serviceVersion >= MediaRouteProviderService.SERVICE_VERSION_1) { mPendingRegisterRequestId = 0; mServiceVersion = serviceVersion; onConnectionDescriptorChanged(this, MediaRouteProviderDescriptor.fromBundle(descriptorBundle)); onConnectionReady(this); return true; } return false; } public boolean onDescriptorChanged(Bundle descriptorBundle) { if (mServiceVersion != 0) { onConnectionDescriptorChanged(this, MediaRouteProviderDescriptor.fromBundle(descriptorBundle)); return true; } return false; } public boolean onControlRequestSucceeded(int requestId, Bundle data) { ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onResult(data); return true; } return false; } public boolean onControlRequestFailed(int requestId, String error, Bundle data) { ControlRequestCallback callback = mPendingCallbacks.get(requestId); if (callback != null) { mPendingCallbacks.remove(requestId); callback.onError(error, data); return true; } return false; } @Override public void binderDied() { mPrivateHandler.post(new Runnable() { @Override public void run() { onConnectionDied(Connection.this); } }); } public int createRouteController(String routeId) { int controllerId = mNextControllerId++; Bundle data = new Bundle(); data.putString(MediaRouteProviderService.CLIENT_DATA_ROUTE_ID, routeId); sendRequest(MediaRouteProviderService.CLIENT_MSG_CREATE_ROUTE_CONTROLLER, mNextRequestId++, controllerId, null, data); return controllerId; } public void releaseRouteController(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_RELEASE_ROUTE_CONTROLLER, mNextRequestId++, controllerId, null, null); } public void selectRoute(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_SELECT_ROUTE, mNextRequestId++, controllerId, null, null); } public void unselectRoute(int controllerId) { sendRequest(MediaRouteProviderService.CLIENT_MSG_UNSELECT_ROUTE, mNextRequestId++, controllerId, null, null); } public void setVolume(int controllerId, int volume) { Bundle data = new Bundle(); data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, volume); sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_ROUTE_VOLUME, mNextRequestId++, controllerId, null, data); } public void updateVolume(int controllerId, int delta) { Bundle data = new Bundle(); data.putInt(MediaRouteProviderService.CLIENT_DATA_VOLUME, delta); sendRequest(MediaRouteProviderService.CLIENT_MSG_UPDATE_ROUTE_VOLUME, mNextRequestId++, controllerId, null, data); } public boolean sendControlRequest(int controllerId, Intent intent, ControlRequestCallback callback) { int requestId = mNextRequestId++; if (sendRequest(MediaRouteProviderService.CLIENT_MSG_ROUTE_CONTROL_REQUEST, requestId, controllerId, intent, null)) { if (callback != null) { mPendingCallbacks.put(requestId, callback); } return true; } return false; } public void setDiscoveryRequest(MediaRouteDiscoveryRequest request) { sendRequest(MediaRouteProviderService.CLIENT_MSG_SET_DISCOVERY_REQUEST, mNextRequestId++, 0, request != null ? request.asBundle() : null, null); } private boolean sendRequest(int what, int requestId, int arg, Object obj, Bundle data) { Message msg = Message.obtain(); msg.what = what; msg.arg1 = requestId; msg.arg2 = arg; msg.obj = obj; msg.setData(data); msg.replyTo = mReceiveMessenger; try { mServiceMessenger.send(msg); return true; } catch (DeadObjectException ex) { // The service died. } catch (RemoteException ex) { if (what != MediaRouteProviderService.CLIENT_MSG_UNREGISTER) { Log.e(TAG, "Could not send message to service.", ex); } } return false; } } private final class PrivateHandler extends Handler { } /** * Handler that receives messages from the server. * <p> * This inner class is static and only retains a weak reference to the connection * to prevent the client from being leaked in case the service is holding an * active reference to the client's messenger. * </p><p> * This handler should not be used to handle any messages other than those * that come from the service. * </p> */ private static final class ReceiveHandler extends Handler { private final WeakReference<Connection> mConnectionRef; public ReceiveHandler(Connection connection) { mConnectionRef = new WeakReference<Connection>(connection); } public void dispose() { mConnectionRef.clear(); } @Override public void handleMessage(Message msg) { Connection connection = mConnectionRef.get(); if (connection != null) { final int what = msg.what; final int requestId = msg.arg1; final int arg = msg.arg2; final Object obj = msg.obj; final Bundle data = msg.peekData(); if (!processMessage(connection, what, requestId, arg, obj, data)) { if (DEBUG) { Log.d(TAG, "Unhandled message from server: " + msg); } } } } private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { - String error = - data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR); + String error = (data == null ? null : + data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR)); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; } } }
true
true
private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { String error = data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; }
private boolean processMessage(Connection connection, int what, int requestId, int arg, Object obj, Bundle data) { switch (what) { case MediaRouteProviderService.SERVICE_MSG_GENERIC_FAILURE: connection.onGenericFailure(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_GENERIC_SUCCESS: connection.onGenericSuccess(requestId); return true; case MediaRouteProviderService.SERVICE_MSG_REGISTERED: if (obj == null || obj instanceof Bundle) { return connection.onRegistered(requestId, arg, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_DESCRIPTOR_CHANGED: if (obj == null || obj instanceof Bundle) { return connection.onDescriptorChanged((Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_SUCCEEDED: if (obj == null || obj instanceof Bundle) { return connection.onControlRequestSucceeded( requestId, (Bundle)obj); } break; case MediaRouteProviderService.SERVICE_MSG_CONTROL_REQUEST_FAILED: if (obj == null || obj instanceof Bundle) { String error = (data == null ? null : data.getString(MediaRouteProviderService.SERVICE_DATA_ERROR)); return connection.onControlRequestFailed( requestId, error, (Bundle)obj); } break; } return false; }
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/filedetector/FileInfoInstancesCreatingThread.java b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/filedetector/FileInfoInstancesCreatingThread.java index 56f9156..a60bb37 100644 --- a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/filedetector/FileInfoInstancesCreatingThread.java +++ b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/filedetector/FileInfoInstancesCreatingThread.java @@ -1,138 +1,140 @@ package jp.ac.osaka_u.ist.sdl.ectec.analyzer.filedetector; import java.util.SortedSet; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import jp.ac.osaka_u.ist.sdl.ectec.data.FileInfo; import jp.ac.osaka_u.ist.sdl.ectec.settings.MessagePrinter; /** * A thread class to create instances of FileInfo * * @author k-hotta * */ public class FileInfoInstancesCreatingThread implements Runnable { /** * the file path and lds of revisions when it was changed */ private final ConcurrentMap<String, SortedSet<ChangeOnFile>> changedFiles; /** * the key is the id of a revision and the value is the id of the previous * revision of the key revision */ private final ConcurrentMap<Long, Long> revisionsMap; /** * the instances of FileInfo */ private final ConcurrentMap<Long, FileInfo> files; /** * the file paths to be analyzed */ private final String[] targetPaths; /** * the index that points current processing state */ private final AtomicInteger index; /** * the id of the latest revision */ private final long lastRevisionId; public FileInfoInstancesCreatingThread( final ConcurrentMap<String, SortedSet<ChangeOnFile>> changedFiles, final ConcurrentMap<Long, Long> revisionsMap, final ConcurrentMap<Long, FileInfo> files, final String[] targetPaths, final AtomicInteger index, final long lastRevisionId) { this.changedFiles = changedFiles; this.revisionsMap = revisionsMap; this.files = files; this.targetPaths = targetPaths; this.index = index; this.lastRevisionId = lastRevisionId; } @Override public void run() { while (true) { final int currentIndex = index.getAndIncrement(); if (currentIndex >= targetPaths.length) { break; } final String path = targetPaths[currentIndex]; MessagePrinter.println("\tanalyzing " + path + " [" + (currentIndex + 1) + "/" + targetPaths.length + "]"); // get the ids of revisions where this file was updated final SortedSet<ChangeOnFile> changes = changedFiles.get(path); if (changes == null) { MessagePrinter.ePrintln("something is wrong when analyzing " + path); continue; } // create new instances of FileInfo ChangeOnFile currentChange = null; for (final ChangeOnFile nextChange : changes) { if (currentChange == null) { currentChange = nextChange; continue; } final long revision = nextChange.getChagnedRevisionId(); final long previousRevision = revisionsMap.get(revision); switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, - currentChange.getChagnedRevisionId(), revision - 1); + currentChange.getChagnedRevisionId(), + previousRevision); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, - currentChange.getChagnedRevisionId(), revision - 1); + currentChange.getChagnedRevisionId(), + previousRevision); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } currentChange = nextChange; } // treat the last change switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } } } }
false
true
public void run() { while (true) { final int currentIndex = index.getAndIncrement(); if (currentIndex >= targetPaths.length) { break; } final String path = targetPaths[currentIndex]; MessagePrinter.println("\tanalyzing " + path + " [" + (currentIndex + 1) + "/" + targetPaths.length + "]"); // get the ids of revisions where this file was updated final SortedSet<ChangeOnFile> changes = changedFiles.get(path); if (changes == null) { MessagePrinter.ePrintln("something is wrong when analyzing " + path); continue; } // create new instances of FileInfo ChangeOnFile currentChange = null; for (final ChangeOnFile nextChange : changes) { if (currentChange == null) { currentChange = nextChange; continue; } final long revision = nextChange.getChagnedRevisionId(); final long previousRevision = revisionsMap.get(revision); switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), revision - 1); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), revision - 1); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } currentChange = nextChange; } // treat the last change switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } } }
public void run() { while (true) { final int currentIndex = index.getAndIncrement(); if (currentIndex >= targetPaths.length) { break; } final String path = targetPaths[currentIndex]; MessagePrinter.println("\tanalyzing " + path + " [" + (currentIndex + 1) + "/" + targetPaths.length + "]"); // get the ids of revisions where this file was updated final SortedSet<ChangeOnFile> changes = changedFiles.get(path); if (changes == null) { MessagePrinter.ePrintln("something is wrong when analyzing " + path); continue; } // create new instances of FileInfo ChangeOnFile currentChange = null; for (final ChangeOnFile nextChange : changes) { if (currentChange == null) { currentChange = nextChange; continue; } final long revision = nextChange.getChagnedRevisionId(); final long previousRevision = revisionsMap.get(revision); switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), previousRevision); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), previousRevision); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } currentChange = nextChange; } // treat the last change switch (currentChange.getChangeType()) { case ADD: final FileInfo addedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(addedFile.getId(), addedFile); break; case CHANGE: final FileInfo changedFile = new FileInfo(path, currentChange.getChagnedRevisionId(), lastRevisionId); files.put(changedFile.getId(), changedFile); break; case DELETE: break; } } }
diff --git a/src/com/mojang/mojam/entity/building/Turret.java b/src/com/mojang/mojam/entity/building/Turret.java index 5933d127..bab2d54e 100644 --- a/src/com/mojang/mojam/entity/building/Turret.java +++ b/src/com/mojang/mojam/entity/building/Turret.java @@ -1,173 +1,173 @@ package com.mojang.mojam.entity.building; import java.awt.Color; import java.util.Set; import com.mojang.mojam.MojamComponent; import com.mojang.mojam.entity.Bullet; import com.mojang.mojam.entity.Entity; import com.mojang.mojam.entity.mob.DropTrap; import com.mojang.mojam.entity.mob.Mob; import com.mojang.mojam.entity.mob.RailDroid; import com.mojang.mojam.entity.mob.SpikeTrap; import com.mojang.mojam.gui.TitleMenu; import com.mojang.mojam.level.IEditable; import com.mojang.mojam.level.tile.Tile; import com.mojang.mojam.screen.Art; import com.mojang.mojam.screen.Bitmap; import com.mojang.mojam.screen.Screen; /** * Defense turret. Automatically aims and shoots at the nearest monster. */ public class Turret extends Building implements IEditable { private static final float BULLET_DAMAGE = .75f; private int delayTicks = 0; private int delay; public int team; public int radius; public int radiusSqr; private int[] upgradeRadius = new int[] { 3 * Tile.WIDTH, 5 * Tile.WIDTH, 7 * Tile.WIDTH }; private int[] upgradeDelay = new int[] { 24, 21, 18 }; private int facing = 0; private Bitmap areaBitmap; private static final int RADIUS_COLOR = new Color(240, 210, 190).getRGB(); public static final int COLOR = 0xff990066; /** * Constructor * * @param x Initial X coordinate * @param y Initial Y coordinate * @param team Team number */ public Turret(double x, double y, int team) { super(x, y, team); this.team = team; setStartHealth(10); freezeTime = 10; areaBitmap = Bitmap.rangeBitmap(radius,RADIUS_COLOR); } @Override public void init() { makeUpgradeableWithCosts(new int[] { TitleMenu.difficulty.calculateCosts(500), TitleMenu.difficulty.calculateCosts(1000), TitleMenu.difficulty.calculateCosts(5000)}); } @Override public void tick() { super.tick(); if (--freezeTime > 0) return; if (--delayTicks > 0) return; if (!isCarried()) { // find target Set<Entity> entities = level.getEntities(pos.x - radius, pos.y - radius, pos.x + radius, pos.y + radius); Entity closest = null; double closestDist = 99999999.0f; for (Entity e : entities) { if (!(e instanceof Mob) || (e instanceof RailDroid && e.team == this.team) || e instanceof Bomb || e instanceof SpikeTrap || - e instanceof DropTrap) + e instanceof DropTrap || e instanceof ShopItem) continue; if (!((Mob) e).isNotFriendOf(this)) continue; final double dist = e.pos.distSqr(pos); Bullet bullet = new Bullet(this, pos.x, pos.y, 0); if (dist < radiusSqr && dist < closestDist && !isTargetBehindWall(e.pos.x, e.pos.y, bullet)) { closestDist = dist; closest = e; } } if (closest != null) { // shoot double invDist = 1.0 / Math.sqrt(closestDist); double yd = closest.pos.y - pos.y; double xd = closest.pos.x - pos.x; double angle = (Math.atan2(yd, xd) + Math.PI * 1.625); facing = (8 + (int) (angle / Math.PI * 4)) & 7; Bullet bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); bullet.pos.y -= 10; level.addEntity(bullet); if (upgradeLevel > 0) { Bullet second_bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); level.addEntity(second_bullet); if (facing == 0 || facing == 4) { bullet.pos.x -= 5; second_bullet.pos.x += 5; } } delayTicks = delay; } } } @Override public void render(Screen screen) { if((justDroppedTicks-- > 0 || highlight) && MojamComponent.localTeam==team) { drawRadius(screen); } super.render(screen); } @Override public Bitmap getSprite() { switch (upgradeLevel) { case 1: return Art.turret2[facing][0]; case 2: return Art.turret3[facing][0]; default: return Art.turret[facing][0]; } } @Override protected void upgradeComplete() { maxHealth += 10; health = maxHealth; delay = upgradeDelay[upgradeLevel]; radius = upgradeRadius[upgradeLevel]; radiusSqr = radius * radius; areaBitmap = Bitmap.rangeBitmap(radius,RADIUS_COLOR); if (upgradeLevel != 0) justDroppedTicks = 80; //show the radius for a brief time } public void drawRadius(Screen screen) { screen.alphaBlit(areaBitmap, (int) pos.x-radius, (int) pos.y-radius - yOffs, 0x22); } @Override public int getColor() { return Turret.COLOR; } @Override public int getMiniMapColor() { return Turret.COLOR; } @Override public String getName() { return "TURRET"; } @Override public Bitmap getBitMapForEditor() { return Art.turret[0][0]; } }
true
true
public void tick() { super.tick(); if (--freezeTime > 0) return; if (--delayTicks > 0) return; if (!isCarried()) { // find target Set<Entity> entities = level.getEntities(pos.x - radius, pos.y - radius, pos.x + radius, pos.y + radius); Entity closest = null; double closestDist = 99999999.0f; for (Entity e : entities) { if (!(e instanceof Mob) || (e instanceof RailDroid && e.team == this.team) || e instanceof Bomb || e instanceof SpikeTrap || e instanceof DropTrap) continue; if (!((Mob) e).isNotFriendOf(this)) continue; final double dist = e.pos.distSqr(pos); Bullet bullet = new Bullet(this, pos.x, pos.y, 0); if (dist < radiusSqr && dist < closestDist && !isTargetBehindWall(e.pos.x, e.pos.y, bullet)) { closestDist = dist; closest = e; } } if (closest != null) { // shoot double invDist = 1.0 / Math.sqrt(closestDist); double yd = closest.pos.y - pos.y; double xd = closest.pos.x - pos.x; double angle = (Math.atan2(yd, xd) + Math.PI * 1.625); facing = (8 + (int) (angle / Math.PI * 4)) & 7; Bullet bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); bullet.pos.y -= 10; level.addEntity(bullet); if (upgradeLevel > 0) { Bullet second_bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); level.addEntity(second_bullet); if (facing == 0 || facing == 4) { bullet.pos.x -= 5; second_bullet.pos.x += 5; } } delayTicks = delay; } } }
public void tick() { super.tick(); if (--freezeTime > 0) return; if (--delayTicks > 0) return; if (!isCarried()) { // find target Set<Entity> entities = level.getEntities(pos.x - radius, pos.y - radius, pos.x + radius, pos.y + radius); Entity closest = null; double closestDist = 99999999.0f; for (Entity e : entities) { if (!(e instanceof Mob) || (e instanceof RailDroid && e.team == this.team) || e instanceof Bomb || e instanceof SpikeTrap || e instanceof DropTrap || e instanceof ShopItem) continue; if (!((Mob) e).isNotFriendOf(this)) continue; final double dist = e.pos.distSqr(pos); Bullet bullet = new Bullet(this, pos.x, pos.y, 0); if (dist < radiusSqr && dist < closestDist && !isTargetBehindWall(e.pos.x, e.pos.y, bullet)) { closestDist = dist; closest = e; } } if (closest != null) { // shoot double invDist = 1.0 / Math.sqrt(closestDist); double yd = closest.pos.y - pos.y; double xd = closest.pos.x - pos.x; double angle = (Math.atan2(yd, xd) + Math.PI * 1.625); facing = (8 + (int) (angle / Math.PI * 4)) & 7; Bullet bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); bullet.pos.y -= 10; level.addEntity(bullet); if (upgradeLevel > 0) { Bullet second_bullet = new Bullet(this, xd * invDist, yd * invDist, BULLET_DAMAGE * ((upgradeLevel + 1) / 2.f)); level.addEntity(second_bullet); if (facing == 0 || facing == 4) { bullet.pos.x -= 5; second_bullet.pos.x += 5; } } delayTicks = delay; } } }
diff --git a/bundles/org.eclipse.equinox.coordinator/src/org/eclipse/equinox/coordinator/Activator.java b/bundles/org.eclipse.equinox.coordinator/src/org/eclipse/equinox/coordinator/Activator.java index 42e1ad95..fc890d6d 100644 --- a/bundles/org.eclipse.equinox.coordinator/src/org/eclipse/equinox/coordinator/Activator.java +++ b/bundles/org.eclipse.equinox.coordinator/src/org/eclipse/equinox/coordinator/Activator.java @@ -1,47 +1,47 @@ /******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.coordinator; import java.util.Dictionary; import java.util.Hashtable; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.coordinator.Coordinator; public class Activator implements BundleActivator { // Static so the factory can be used by both DS and standard OSGi. static volatile CoordinatorServiceFactory factory; private ServiceRegistration<Coordinator> registration; public void start(BundleContext bundleContext) throws Exception { // Instantiate the factory to be used by both DS and standard OSGi. In the case of DS, the // start method is guaranteed to be called before any components are created. factory = new CoordinatorServiceFactory(bundleContext); if (Boolean.valueOf(bundleContext.getProperty("equinox.use.ds")).booleanValue()) //$NON-NLS-1$ return; // If this property is set we assume DS is being used. Dictionary<String, Object> properties = new Hashtable<String, Object>(); // TODO Add desired properties (bundle vendor, etc.). - @SuppressWarnings({"unchecked", "hiding"}) + @SuppressWarnings({"unchecked"}) // Use local variable to avoid suppressing unchecked warnings at method level. - ServiceRegistration<Coordinator> registration = (ServiceRegistration<Coordinator>) bundleContext.registerService(Coordinator.class.getName(), factory, properties); - this.registration = registration; + ServiceRegistration<Coordinator> reg = (ServiceRegistration<Coordinator>) bundleContext.registerService(Coordinator.class.getName(), factory, properties); + this.registration = reg; } public void stop(BundleContext bundleContext) throws Exception { // Will be null when using DS. if (registration != null) registration.unregister(); factory.shutdown(); } }
false
true
public void start(BundleContext bundleContext) throws Exception { // Instantiate the factory to be used by both DS and standard OSGi. In the case of DS, the // start method is guaranteed to be called before any components are created. factory = new CoordinatorServiceFactory(bundleContext); if (Boolean.valueOf(bundleContext.getProperty("equinox.use.ds")).booleanValue()) //$NON-NLS-1$ return; // If this property is set we assume DS is being used. Dictionary<String, Object> properties = new Hashtable<String, Object>(); // TODO Add desired properties (bundle vendor, etc.). @SuppressWarnings({"unchecked", "hiding"}) // Use local variable to avoid suppressing unchecked warnings at method level. ServiceRegistration<Coordinator> registration = (ServiceRegistration<Coordinator>) bundleContext.registerService(Coordinator.class.getName(), factory, properties); this.registration = registration; }
public void start(BundleContext bundleContext) throws Exception { // Instantiate the factory to be used by both DS and standard OSGi. In the case of DS, the // start method is guaranteed to be called before any components are created. factory = new CoordinatorServiceFactory(bundleContext); if (Boolean.valueOf(bundleContext.getProperty("equinox.use.ds")).booleanValue()) //$NON-NLS-1$ return; // If this property is set we assume DS is being used. Dictionary<String, Object> properties = new Hashtable<String, Object>(); // TODO Add desired properties (bundle vendor, etc.). @SuppressWarnings({"unchecked"}) // Use local variable to avoid suppressing unchecked warnings at method level. ServiceRegistration<Coordinator> reg = (ServiceRegistration<Coordinator>) bundleContext.registerService(Coordinator.class.getName(), factory, properties); this.registration = reg; }
diff --git a/src/pleocmd/itfc/gui/ErrorDialog.java b/src/pleocmd/itfc/gui/ErrorDialog.java index 1b5719e..216e171 100644 --- a/src/pleocmd/itfc/gui/ErrorDialog.java +++ b/src/pleocmd/itfc/gui/ErrorDialog.java @@ -1,250 +1,251 @@ package pleocmd.itfc.gui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import pleocmd.Log; import pleocmd.cfg.ConfigCollection; import pleocmd.cfg.Configuration; import pleocmd.cfg.ConfigurationInterface; import pleocmd.cfg.Group; import pleocmd.exc.ConfigurationException; import pleocmd.itfc.gui.Layouter.Button; public final class ErrorDialog extends JDialog implements ConfigurationInterface { private static final long serialVersionUID = -8104196615240425295L; private static ErrorDialog errorDialog; private final Layouter layErrorPanel; private final JScrollPane spErrorPanel; private boolean canDisposeIfHidden; private int errorCount; private final Map<AbstractButton, String> map = new HashMap<AbstractButton, String>(); private boolean ignoreChange; private final ConfigCollection<String> cfgSuppressed = new ConfigCollection<String>( "Suppressed", ConfigCollection.Type.Set) { @Override protected String createItem(final String itemAsString) throws ConfigurationException { return itemAsString; } }; private ErrorDialog() { errorDialog = this; setTitle("Error"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { close(); } }); // Add components final Layouter lay = new Layouter(this); final JPanel panel = new JPanel(); layErrorPanel = new Layouter(panel); layErrorPanel.nextComponentsAlwaysOnLastLine(); layErrorPanel.addVerticalSpacer(); spErrorPanel = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); lay.addWholeLine(spErrorPanel, true); spErrorPanel.setBorder(null); lay.addButton("Reset", "", "Clears the list of suppressed error messages", new Runnable() { @Override public void run() { reset(); } }); lay.addSpacer(); final JButton btn = lay.addButton(Button.Ok, new Runnable() { @Override public void run() { close(); } }); getRootPane().setDefaultButton(btn); btn.requestFocusInWindow(); setAlwaysOnTop(true); setModal(true); + pack(); try { Configuration.the().registerConfigurableObject(this, getClass().getSimpleName()); } catch (final ConfigurationException e) { Log.error(e); } } public static ErrorDialog the() { if (errorDialog == null) new ErrorDialog(); return errorDialog; } public static void show(final Log log) { EventQueue.invokeLater(new Runnable() { @Override public void run() { the().showLog(log); } }); } protected void showLog(final Log log) { final String caller = log.getCaller().toString(); if (cfgSuppressed.contains(caller)) return; final JLabel lblT, lblC; final JTextArea lblM; final JCheckBox cbS; if (errorCount > 0) layErrorPanel.addWholeLine(new JSeparator(), false); layErrorPanel.add(lblT = new JLabel(log.getFormattedTime()), false); layErrorPanel.add(lblC = new JLabel(log.getFormattedCaller()), false); layErrorPanel.addSpacer(); layErrorPanel.add(cbS = new JCheckBox("Suppress"), false); layErrorPanel.newLine(); layErrorPanel.addWholeLine(lblM = new JTextArea(log.getMsg()), false); lblM.setLineWrap(true); lblM.setWrapStyleWord(true); lblM.setEditable(false); lblM.setOpaque(false); lblM.setForeground(Color.RED); map.put(cbS, caller); cbS.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final boolean sel = cbS.isSelected(); lblT.setForeground(sel ? Color.GRAY : cbS.getForeground()); lblC.setForeground(sel ? Color.GRAY : cbS.getForeground()); lblM.setForeground(sel ? Color.GRAY : Color.RED); try { changeSuppress(caller, sel); } catch (final ConfigurationException exc) { Log.error(exc); } } }); ++errorCount; final Dimension pref = getPreferredSize(); if (errorCount > 5) { pref.height = getHeight(); pref.width += spErrorPanel.getVerticalScrollBar().getWidth(); } setSize(pref); setLocationRelativeTo(null); setVisible(true); } protected void changeSuppress(final String caller, final boolean add) throws ConfigurationException { if (ignoreChange) return; if (add) cfgSuppressed.addContent(caller); else cfgSuppressed.removeContent(caller); ignoreChange = true; try { final Component[] comps = layErrorPanel.getContainer() .getComponents(); for (final Component comp : comps) if (comp instanceof AbstractButton && map.get(comp).equals(caller)) if (((AbstractButton) comp).isSelected() ^ add) ((AbstractButton) comp).doClick(); } finally { ignoreChange = false; } } protected void reset() { cfgSuppressed.clearContent(); ignoreChange = true; try { final Component[] comps = layErrorPanel.getContainer() .getComponents(); for (final Component comp : comps) if (comp instanceof AbstractButton) if (((AbstractButton) comp).isSelected()) ((AbstractButton) comp).doClick(); } finally { ignoreChange = false; } } protected void close() { errorCount = 0; map.clear(); layErrorPanel.clear(); layErrorPanel.nextComponentsAlwaysOnLastLine(); layErrorPanel.addVerticalSpacer(); pack(); if (canDisposeIfHidden) dispose(); else setVisible(false); } public static void canDisposeIfHidden() { if (errorDialog != null) { errorDialog.canDisposeIfHidden = true; if (!errorDialog.isVisible()) errorDialog.dispose(); } } public Group getSkeleton(final String groupName) { return new Group(groupName).add(cfgSuppressed); } public void configurationAboutToBeChanged() { // nothing to do } public void configurationChanged(final Group group) { // nothing to do } public List<Group> configurationWriteback() { return Configuration.asList(getSkeleton(getClass().getSimpleName())); } }
true
true
private ErrorDialog() { errorDialog = this; setTitle("Error"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { close(); } }); // Add components final Layouter lay = new Layouter(this); final JPanel panel = new JPanel(); layErrorPanel = new Layouter(panel); layErrorPanel.nextComponentsAlwaysOnLastLine(); layErrorPanel.addVerticalSpacer(); spErrorPanel = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); lay.addWholeLine(spErrorPanel, true); spErrorPanel.setBorder(null); lay.addButton("Reset", "", "Clears the list of suppressed error messages", new Runnable() { @Override public void run() { reset(); } }); lay.addSpacer(); final JButton btn = lay.addButton(Button.Ok, new Runnable() { @Override public void run() { close(); } }); getRootPane().setDefaultButton(btn); btn.requestFocusInWindow(); setAlwaysOnTop(true); setModal(true); try { Configuration.the().registerConfigurableObject(this, getClass().getSimpleName()); } catch (final ConfigurationException e) { Log.error(e); } }
private ErrorDialog() { errorDialog = this; setTitle("Error"); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { close(); } }); // Add components final Layouter lay = new Layouter(this); final JPanel panel = new JPanel(); layErrorPanel = new Layouter(panel); layErrorPanel.nextComponentsAlwaysOnLastLine(); layErrorPanel.addVerticalSpacer(); spErrorPanel = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); lay.addWholeLine(spErrorPanel, true); spErrorPanel.setBorder(null); lay.addButton("Reset", "", "Clears the list of suppressed error messages", new Runnable() { @Override public void run() { reset(); } }); lay.addSpacer(); final JButton btn = lay.addButton(Button.Ok, new Runnable() { @Override public void run() { close(); } }); getRootPane().setDefaultButton(btn); btn.requestFocusInWindow(); setAlwaysOnTop(true); setModal(true); pack(); try { Configuration.the().registerConfigurableObject(this, getClass().getSimpleName()); } catch (final ConfigurationException e) { Log.error(e); } }
diff --git a/rdfbean-core/src/main/java/com/mysema/rdfbean/object/DefaultConfiguration.java b/rdfbean-core/src/main/java/com/mysema/rdfbean/object/DefaultConfiguration.java index ec522131..085ca68e 100644 --- a/rdfbean-core/src/main/java/com/mysema/rdfbean/object/DefaultConfiguration.java +++ b/rdfbean-core/src/main/java/com/mysema/rdfbean/object/DefaultConfiguration.java @@ -1,261 +1,261 @@ /* * Copyright (c) 2010 Mysema Ltd. * All rights reserved. * */ package com.mysema.rdfbean.object; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Pattern; import javax.annotation.Nullable; import com.mysema.commons.lang.Assert; import com.mysema.rdfbean.CORE; import com.mysema.rdfbean.annotations.ClassMapping; import com.mysema.rdfbean.annotations.Context; import com.mysema.rdfbean.annotations.MappedClasses; import com.mysema.rdfbean.model.FetchStrategy; import com.mysema.rdfbean.model.ID; import com.mysema.rdfbean.model.RDF; import com.mysema.rdfbean.model.RDFS; import com.mysema.rdfbean.model.UID; import com.mysema.rdfbean.model.XSD; import com.mysema.rdfbean.owl.OWL; import com.mysema.rdfbean.xsd.ConverterRegistry; import com.mysema.rdfbean.xsd.ConverterRegistryImpl; /** * Default implementation of the Configuration interface * * @author sasa * */ public final class DefaultConfiguration implements Configuration { private static final Pattern jarUrlSeparator = Pattern.compile("!"); private static final Set<String> buildinNamespaces = new HashSet<String>(); static { buildinNamespaces.add(RDF.NS); buildinNamespaces.add(RDFS.NS); buildinNamespaces.add(XSD.NS); buildinNamespaces.add(OWL.NS); buildinNamespaces.add(CORE.NS); } private final Set<MappedClass> mappedClasses = new LinkedHashSet<MappedClass>(); private final ConverterRegistry converterRegistry = new ConverterRegistryImpl(); @Nullable private UID defaultContext; private List<FetchStrategy> fetchStrategies = Collections.emptyList(); private final MappedClassFactory mappedClassFactory = new MappedClassFactory(); private final Set<String> restrictedResources = new HashSet<String>(buildinNamespaces); private final Map<UID, List<MappedClass>> type2classes = new HashMap<UID, List<MappedClass>>(); public DefaultConfiguration() {} public DefaultConfiguration(Class<?>... classes) { addClasses(classes); } public DefaultConfiguration(Package... packages) { addPackages(packages); } public void addClasses(Class<?>... classes) { for (Class<?> clazz : classes) { if (clazz.getAnnotation(ClassMapping.class) != null){ MappedClass mappedClass = mappedClassFactory.getMappedClass(clazz); if (mappedClass.getUID() != null) { List<MappedClass> classList = type2classes.get(mappedClass.getUID()); if (classList == null) { classList = new ArrayList<MappedClass>(); type2classes.put(mappedClass.getUID(), classList); } classList.add(mappedClass); } mappedClasses.add(mappedClass); }else{ throw new IllegalArgumentException("No @ClassMapping annotation for " + clazz.getName()); } } } public void addPackages(Package... packages) { for (Package pack : packages) { MappedClasses classes = pack.getAnnotation(MappedClasses.class); if (classes != null) { addClasses(classes.value()); }else{ throw new IllegalArgumentException("No @MappedClasses annotation for " + pack.getName()); } } } @Override public boolean allowCreate(Class<?> clazz) { return true; } public boolean allowRead(MappedPath path) { // TODO filter unmapped types? return true; } @Override @Nullable public UID createURI(Object instance) { Class<?> clazz = instance.getClass(); UID context = getContext(clazz, null); if (context != null) { return new UID(context.getId() + "#", clazz.getSimpleName() + "-" + UUID.randomUUID().toString()); } return null; } @Override @Nullable public UID getContext(Class<?> javaClass, @Nullable ID subject) { Context ctxAnno = javaClass.getAnnotation(Context.class); if (ctxAnno == null) { Package pack = javaClass.getPackage(); ctxAnno = pack.getAnnotation(Context.class); } if (ctxAnno != null) { return new UID(ctxAnno.value()); } else { return defaultContext; } } @Override public ConverterRegistry getConverterRegistry() { return converterRegistry; } public List<FetchStrategy> getFetchStrategies() { return fetchStrategies; } @Override public MappedClass getMappedClass(Class<?> javaClass) { return mappedClassFactory.getMappedClass(javaClass); } @Override public Set<MappedClass> getMappedClasses() { return mappedClasses; } public List<MappedClass> getMappedClasses(UID uid) { return type2classes.get(Assert.notNull(uid,"uid")); } public boolean isMapped(Class<?> clazz){ return clazz.getAnnotation(ClassMapping.class) != null; } @Override public boolean isRestricted(UID uid) { return restrictedResources.contains(uid.getId()) || restrictedResources.contains(uid.ns()); } public void scanPackages(Package... packages){ ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (Package pkg : packages){ try { for (Class<?> cl : scanPackage(classLoader, pkg)){ if (cl.getAnnotation(ClassMapping.class) != null){ addClasses(cl); } } } catch (IOException e) { throw new ConfigurationException(e); } catch (ClassNotFoundException e) { throw new ConfigurationException(e); } } } Set<Class<?>> scanPackage(ClassLoader classLoader, Package pkg) throws IOException, ClassNotFoundException { Enumeration<URL> urls = classLoader.getResources(pkg.getName().replace('.', '/')); Set<Class<?>> classes = new HashSet<Class<?>>(); while (urls.hasMoreElements()){ URL url = urls.nextElement(); if (url.getProtocol().equals("jar")){ String[] fileAndPath = jarUrlSeparator.split(url.getFile().substring(5)); JarFile jarFile = new JarFile(fileAndPath[0]); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class") && entry.getName().startsWith(fileAndPath[1].substring(1))){ String className = entry.getName().substring(0, entry.getName().length()-6).replace('/', '.'); classes.add(Class.forName(className)); } } }else if (url.getProtocol().equals("file")){ Deque<File> files = new ArrayDeque<File>(); String packagePath; try { - packagePath = url.toURI().getPath(); - files.add(new File(packagePath)); - } catch (URISyntaxException e) { - throw new IOException(e); - } + packagePath = url.toURI().getPath(); + files.add(new File(packagePath)); + } catch (URISyntaxException e) { + throw new IOException(e); + } while (!files.isEmpty()){ File file = files.pop(); for (File child : file.listFiles()){ if (child.getName().endsWith(".class")){ String fileName = child.getPath().substring(packagePath.length()+1).replace('/', '.'); String className = pkg.getName() + "." + fileName.substring(0, fileName.length()-6); classes.add(Class.forName(className)); }else if (child.isDirectory()){ files.add(child); } } } }else{ throw new IllegalArgumentException("Illegal url : " + url); } } return classes; } public void setDefaultContext(String ctx) { this.defaultContext = new UID(ctx); } public void setFetchStrategies(List<FetchStrategy> fetchStrategies) { this.fetchStrategies = fetchStrategies; } }
true
true
Set<Class<?>> scanPackage(ClassLoader classLoader, Package pkg) throws IOException, ClassNotFoundException { Enumeration<URL> urls = classLoader.getResources(pkg.getName().replace('.', '/')); Set<Class<?>> classes = new HashSet<Class<?>>(); while (urls.hasMoreElements()){ URL url = urls.nextElement(); if (url.getProtocol().equals("jar")){ String[] fileAndPath = jarUrlSeparator.split(url.getFile().substring(5)); JarFile jarFile = new JarFile(fileAndPath[0]); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class") && entry.getName().startsWith(fileAndPath[1].substring(1))){ String className = entry.getName().substring(0, entry.getName().length()-6).replace('/', '.'); classes.add(Class.forName(className)); } } }else if (url.getProtocol().equals("file")){ Deque<File> files = new ArrayDeque<File>(); String packagePath; try { packagePath = url.toURI().getPath(); files.add(new File(packagePath)); } catch (URISyntaxException e) { throw new IOException(e); } while (!files.isEmpty()){ File file = files.pop(); for (File child : file.listFiles()){ if (child.getName().endsWith(".class")){ String fileName = child.getPath().substring(packagePath.length()+1).replace('/', '.'); String className = pkg.getName() + "." + fileName.substring(0, fileName.length()-6); classes.add(Class.forName(className)); }else if (child.isDirectory()){ files.add(child); } } } }else{ throw new IllegalArgumentException("Illegal url : " + url); } } return classes; }
Set<Class<?>> scanPackage(ClassLoader classLoader, Package pkg) throws IOException, ClassNotFoundException { Enumeration<URL> urls = classLoader.getResources(pkg.getName().replace('.', '/')); Set<Class<?>> classes = new HashSet<Class<?>>(); while (urls.hasMoreElements()){ URL url = urls.nextElement(); if (url.getProtocol().equals("jar")){ String[] fileAndPath = jarUrlSeparator.split(url.getFile().substring(5)); JarFile jarFile = new JarFile(fileAndPath[0]); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class") && entry.getName().startsWith(fileAndPath[1].substring(1))){ String className = entry.getName().substring(0, entry.getName().length()-6).replace('/', '.'); classes.add(Class.forName(className)); } } }else if (url.getProtocol().equals("file")){ Deque<File> files = new ArrayDeque<File>(); String packagePath; try { packagePath = url.toURI().getPath(); files.add(new File(packagePath)); } catch (URISyntaxException e) { throw new IOException(e); } while (!files.isEmpty()){ File file = files.pop(); for (File child : file.listFiles()){ if (child.getName().endsWith(".class")){ String fileName = child.getPath().substring(packagePath.length()+1).replace('/', '.'); String className = pkg.getName() + "." + fileName.substring(0, fileName.length()-6); classes.add(Class.forName(className)); }else if (child.isDirectory()){ files.add(child); } } } }else{ throw new IllegalArgumentException("Illegal url : " + url); } } return classes; }
diff --git a/src/net/sf/freecol/common/model/Turn.java b/src/net/sf/freecol/common/model/Turn.java index 13de42056..d90ca4119 100644 --- a/src/net/sf/freecol/common/model/Turn.java +++ b/src/net/sf/freecol/common/model/Turn.java @@ -1,193 +1,193 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.model; /** * Represents a given turn in the game. */ public class Turn { public static enum Season { YEAR, SPRING, AUTUMN } public static final int STARTING_YEAR = 1492; public static final int SEASON_YEAR = 1600; private static final int OFFSET = SEASON_YEAR - STARTING_YEAR - 1; /** * The numerical value of the Turn, never less than one. * */ private int turn; public Turn(int turn) { this.turn = turn; } /** * Increases the turn number by one. */ public void increase() { turn++; } /** * Gets the turn number. * @return The number of turns. */ public int getNumber() { return turn; } /** * Sets the turn number. * @param turn The number of turns. */ public void setNumber(int turn) { this.turn = turn; } /** * Gets the age. * * @return The age: * <br> * <br>1 - if before {@link #SEASON_YEAR} * <br>2 - if between 1600 and 1700. * <br>3 - if after 1700. */ public int getAge() { if (getYear() < SEASON_YEAR) { return 1; } else if (getYear() < 1700) { return 2; } else { return 3; } } /** * Checks if this turn is equal to another turn. */ public boolean equals(Object o) { if (o instanceof Turn) { return turn == ((Turn) o).turn; } else { return false; } } /** * Gets the year the given turn is in. * @return The calculated year based on the turn * number. */ public static int getYear(int turn) { int c = turn - OFFSET; if (c < 0) { return STARTING_YEAR + turn - 1; } else { return SEASON_YEAR + c/2 - 1; } } /** * Gets the year this turn is in. * @return The calculated year based on the turn * number. */ public int getYear() { return getYear(turn); } /** * Returns a string representation of this turn. * @return A string with the format: "<i>[season] year</i>". * Examples: "Spring 1602", "1503"... */ public String toString() { return toString(turn); } /** * Returns a non-localized string representation of the given turn. * @return A string with the format: "<i>season year</i>". * Examples: "SPRING 1602", "YEAR 1503"... */ public static String toString(int turn) { return getSeason(turn).toString() + " " + Integer.toString(getYear(turn)); } /** * Return the Season of the given Turn number. * * @param turn an <code>int</code> value * @return a <code>Season</code> value */ public static Season getSeason(int turn) { int c = turn - OFFSET; - if (c < 0) { + if (c <= 1) { return Season.YEAR; } else if (c % 2 == 0) { return Season.SPRING; } else { return Season.AUTUMN; } } /** * Return the Season of this Turn. * * @return a <code>Season</code> value */ public Season getSeason() { return getSeason(turn); } /** * Describe <code>getLabel</code> method here. * * @return a <code>StringTemplate</code> value */ public StringTemplate getLabel() { return getLabel(turn); } /** * Describe <code>getLabel</code> method here. * * @param turn an <code>int</code> value * @return a <code>StringTemplate</code> value */ public static StringTemplate getLabel(int turn) { return StringTemplate.template("year." + getSeason(turn)) .addAmount("%year%", getYear(turn)); } }
true
true
public static Season getSeason(int turn) { int c = turn - OFFSET; if (c < 0) { return Season.YEAR; } else if (c % 2 == 0) { return Season.SPRING; } else { return Season.AUTUMN; } }
public static Season getSeason(int turn) { int c = turn - OFFSET; if (c <= 1) { return Season.YEAR; } else if (c % 2 == 0) { return Season.SPRING; } else { return Season.AUTUMN; } }
diff --git a/openFaces/source/org/openfaces/renderkit/table/SelectRowCheckboxRenderer.java b/openFaces/source/org/openfaces/renderkit/table/SelectRowCheckboxRenderer.java index 3f2d98643..e98dceacf 100644 --- a/openFaces/source/org/openfaces/renderkit/table/SelectRowCheckboxRenderer.java +++ b/openFaces/source/org/openfaces/renderkit/table/SelectRowCheckboxRenderer.java @@ -1,78 +1,78 @@ /* * OpenFaces - JSF Component Library 2.0 * Copyright (C) 2007-2011, TeamDev Ltd. * [email protected] * Unless agreed in writing the contents of this file are subject to * the GNU Lesser General Public License Version 2.1 (the "LGPL" License). * 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. * Please visit http://openfaces.org/licensing/ for more details. */ package org.openfaces.renderkit.table; import org.openfaces.component.table.AbstractTable; import org.openfaces.component.table.AbstractTableSelection; import org.openfaces.component.table.BaseColumn; import org.openfaces.component.table.SelectRowCheckbox; import org.openfaces.component.table.TreeTable; import org.openfaces.renderkit.select.SelectBooleanCheckboxRenderer; import org.openfaces.util.Components; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import java.io.IOException; public class SelectRowCheckboxRenderer extends SelectBooleanCheckboxRenderer { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { SelectRowCheckbox selectRowCheckbox = (SelectRowCheckbox) component; checkUsageContext(selectRowCheckbox); selectRowCheckbox.setStyleClass("o_selectRowCheckbox"); selectRowCheckbox.setValue(false); super.encodeBegin(context, component); } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { super.encodeEnd(context, component); } private static void checkUsageContext(SelectRowCheckbox selectRowCheckbox) { FacesContext context = FacesContext.getCurrentInstance(); UIComponent component = selectRowCheckbox.getParent(); while (component != null) { if (component instanceof BaseColumn) { BaseColumn column = (BaseColumn) component; AbstractTable table = Components.getParentWithClass(column, AbstractTable.class); if (table == null) throw new FacesException("<o:selectRowCheckbox> can only be used in columns of table components " + "(<o:dataTable> or <o:treeTable)"); AbstractTableSelection selection = table.getSelection(); if (selection == null) throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or " + "TreeTable with multiple selection. clientId = " + selectRowCheckbox.getClientId(context)); boolean multipleRowSelection = selection.isMultipleSelectionAllowed(); if (!multipleRowSelection) throw new IllegalStateException("<o:selectRowCheckbox> can only be inserted into a DataTable or " + - "TreeTable with multiple selection. clientId = " + selectRowCheckbox.getClientId(context)); + "TreeTable with multiple selection, but single selection is used here. clientId = " + selectRowCheckbox.getClientId(context)); selectRowCheckbox.setTriStateAllowed(table instanceof TreeTable); return; } UIComponent parent = component.getParent(); if (parent != null && parent.getFacets().containsValue(component)) throw new FacesException("<o:selectRowCheckbox> can't be placed inside of column's facets -- " + "it should be among regular child components of <o:column>, or another column tag. " + "clientId = " + selectRowCheckbox.getClientId(context)); component = parent; } throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or TreeTable " + "components. clientId = " + selectRowCheckbox.getClientId(context)); } }
true
true
private static void checkUsageContext(SelectRowCheckbox selectRowCheckbox) { FacesContext context = FacesContext.getCurrentInstance(); UIComponent component = selectRowCheckbox.getParent(); while (component != null) { if (component instanceof BaseColumn) { BaseColumn column = (BaseColumn) component; AbstractTable table = Components.getParentWithClass(column, AbstractTable.class); if (table == null) throw new FacesException("<o:selectRowCheckbox> can only be used in columns of table components " + "(<o:dataTable> or <o:treeTable)"); AbstractTableSelection selection = table.getSelection(); if (selection == null) throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or " + "TreeTable with multiple selection. clientId = " + selectRowCheckbox.getClientId(context)); boolean multipleRowSelection = selection.isMultipleSelectionAllowed(); if (!multipleRowSelection) throw new IllegalStateException("<o:selectRowCheckbox> can only be inserted into a DataTable or " + "TreeTable with multiple selection. clientId = " + selectRowCheckbox.getClientId(context)); selectRowCheckbox.setTriStateAllowed(table instanceof TreeTable); return; } UIComponent parent = component.getParent(); if (parent != null && parent.getFacets().containsValue(component)) throw new FacesException("<o:selectRowCheckbox> can't be placed inside of column's facets -- " + "it should be among regular child components of <o:column>, or another column tag. " + "clientId = " + selectRowCheckbox.getClientId(context)); component = parent; } throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or TreeTable " + "components. clientId = " + selectRowCheckbox.getClientId(context)); }
private static void checkUsageContext(SelectRowCheckbox selectRowCheckbox) { FacesContext context = FacesContext.getCurrentInstance(); UIComponent component = selectRowCheckbox.getParent(); while (component != null) { if (component instanceof BaseColumn) { BaseColumn column = (BaseColumn) component; AbstractTable table = Components.getParentWithClass(column, AbstractTable.class); if (table == null) throw new FacesException("<o:selectRowCheckbox> can only be used in columns of table components " + "(<o:dataTable> or <o:treeTable)"); AbstractTableSelection selection = table.getSelection(); if (selection == null) throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or " + "TreeTable with multiple selection. clientId = " + selectRowCheckbox.getClientId(context)); boolean multipleRowSelection = selection.isMultipleSelectionAllowed(); if (!multipleRowSelection) throw new IllegalStateException("<o:selectRowCheckbox> can only be inserted into a DataTable or " + "TreeTable with multiple selection, but single selection is used here. clientId = " + selectRowCheckbox.getClientId(context)); selectRowCheckbox.setTriStateAllowed(table instanceof TreeTable); return; } UIComponent parent = component.getParent(); if (parent != null && parent.getFacets().containsValue(component)) throw new FacesException("<o:selectRowCheckbox> can't be placed inside of column's facets -- " + "it should be among regular child components of <o:column>, or another column tag. " + "clientId = " + selectRowCheckbox.getClientId(context)); component = parent; } throw new IllegalStateException("<o:selectRowCheckbox> can only be used in a DataTable or TreeTable " + "components. clientId = " + selectRowCheckbox.getClientId(context)); }
diff --git a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIConfirmForm.java b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIConfirmForm.java index c340a0f0..022f3d09 100644 --- a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIConfirmForm.java +++ b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UIConfirmForm.java @@ -1,78 +1,78 @@ /* * Copyright (C) 2003-2009 eXo Platform SAS. * * 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. * * 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.exoplatform.calendar.webui.popup; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.lifecycle.UIFormLifecycle; import org.exoplatform.webui.form.UIForm; import org.exoplatform.webui.form.UIFormInputInfo; /** * Created by The eXo Platform SAS * Author : eXoPlatform * [email protected] * May 20, 2009 */ @ComponentConfig ( lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIForm.gtmpl" ) public class UIConfirmForm extends UIForm implements UIPopupComponent{ public static String CONFIRM_TRUE = "true".intern(); public static String CONFIRM_FALSE = "false".intern(); private String config_id = ""; public UIConfirmForm() { addUIFormInput(new UIFormInputInfo("confirm", "confirm", null)) ; } public void setConfirmMessage(String confirmMessage) { getUIFormInputInfo("confirm").setValue(confirmMessage) ; getUIFormInputInfo("confirm").setLabel("") ; } @Override public String event(String name) throws Exception { StringBuilder b = new StringBuilder() ; - b.append("javascript:eXo.webui.UIForm.submitForm('").append(getConfig_id()).append("','"); + b.append("javascript:webui.UIForm.submitForm('").append(getConfig_id()).append("','"); b.append(name).append("',true)"); return b.toString() ; } public void setConfig_id(String config_id) { this.config_id = config_id; } public String getConfig_id() { return config_id; } public void activate() throws Exception { } public void deActivate() throws Exception { } }
true
true
public String event(String name) throws Exception { StringBuilder b = new StringBuilder() ; b.append("javascript:eXo.webui.UIForm.submitForm('").append(getConfig_id()).append("','"); b.append(name).append("',true)"); return b.toString() ; }
public String event(String name) throws Exception { StringBuilder b = new StringBuilder() ; b.append("javascript:webui.UIForm.submitForm('").append(getConfig_id()).append("','"); b.append(name).append("',true)"); return b.toString() ; }
diff --git a/src/com/android/camera/EffectsRecorder.java b/src/com/android/camera/EffectsRecorder.java index bb7c8136..737e828f 100644 --- a/src/com/android/camera/EffectsRecorder.java +++ b/src/com/android/camera/EffectsRecorder.java @@ -1,891 +1,898 @@ /* * Copyright (C) 2011 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.camera; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.filterfw.GraphEnvironment; import android.filterfw.core.Filter; import android.filterfw.core.GLEnvironment; import android.filterfw.core.GraphRunner; import android.filterfw.core.GraphRunner.OnRunnerDoneListener; import android.filterfw.geometry.Point; import android.filterfw.geometry.Quad; import android.filterpacks.videoproc.BackDropperFilter; import android.filterpacks.videoproc.BackDropperFilter.LearningDoneListener; import android.filterpacks.videosink.MediaEncoderFilter.OnRecordingDoneListener; import android.filterpacks.videosrc.SurfaceTextureSource.SurfaceTextureSourceListener; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.media.MediaRecorder; import android.media.CamcorderProfile; import android.os.ConditionVariable; import android.os.Handler; import android.os.Looper; import android.os.ParcelFileDescriptor; import android.os.SystemProperties; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import java.io.IOException; import java.io.FileNotFoundException; import java.io.File; import java.lang.Runnable; import java.io.FileDescriptor; /** * Encapsulates the mobile filter framework components needed to record video with * effects applied. Modeled after MediaRecorder. */ public class EffectsRecorder { public static final int EFFECT_NONE = 0; public static final int EFFECT_GOOFY_FACE = 1; public static final int EFFECT_BACKDROPPER = 2; public static final int EFFECT_GF_SQUEEZE = 0; public static final int EFFECT_GF_BIG_EYES = 1; public static final int EFFECT_GF_BIG_MOUTH = 2; public static final int EFFECT_GF_SMALL_MOUTH = 3; public static final int EFFECT_GF_BIG_NOSE = 4; public static final int EFFECT_GF_SMALL_EYES = 5; public static final int NUM_OF_GF_EFFECTS = EFFECT_GF_SMALL_EYES + 1; public static final int EFFECT_MSG_STARTED_LEARNING = 0; public static final int EFFECT_MSG_DONE_LEARNING = 1; public static final int EFFECT_MSG_SWITCHING_EFFECT = 2; public static final int EFFECT_MSG_EFFECTS_STOPPED = 3; public static final int EFFECT_MSG_RECORDING_DONE = 4; private Context mContext; private Handler mHandler; private boolean mReleased; private Camera mCameraDevice; private CamcorderProfile mProfile; private double mCaptureRate = 0; private SurfaceHolder mPreviewSurfaceHolder; private int mPreviewWidth; private int mPreviewHeight; private MediaRecorder.OnInfoListener mInfoListener; private MediaRecorder.OnErrorListener mErrorListener; private String mOutputFile; private FileDescriptor mFd; private int mOrientationHint = 0; private long mMaxFileSize = 0; private int mMaxDurationMs = 0; private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_BACK; private boolean mAppIsLandscape; private int mEffect = EFFECT_NONE; private int mCurrentEffect = EFFECT_NONE; private EffectsListener mEffectsListener; private Object mEffectParameter; private GraphEnvironment mGraphEnv; private int mGraphId; private GraphRunner mRunner = null; private GraphRunner mOldRunner = null; private SurfaceTexture mTextureSource; private static final String mVideoRecordSound = "/system/media/audio/ui/VideoRecord.ogg"; private SoundPlayer mRecordSound; private static final int STATE_CONFIGURE = 0; private static final int STATE_WAITING_FOR_SURFACE = 1; private static final int STATE_STARTING_PREVIEW = 2; private static final int STATE_PREVIEW = 3; private static final int STATE_RECORD = 4; private static final int STATE_RELEASED = 5; private int mState = STATE_CONFIGURE; private boolean mLogVerbose = Log.isLoggable(TAG, Log.VERBOSE); private static final String TAG = "effectsrecorder"; /** Determine if a given effect is supported at runtime * Some effects require libraries not available on all devices */ public static boolean isEffectSupported(int effectId) { switch (effectId) { case EFFECT_GOOFY_FACE: return Filter.isAvailable("com.google.android.filterpacks.facedetect.GoofyRenderFilter"); case EFFECT_BACKDROPPER: return Filter.isAvailable("android.filterpacks.videoproc.BackDropperFilter"); default: return false; } } public EffectsRecorder(Context context) { if (mLogVerbose) Log.v(TAG, "EffectsRecorder created (" + this + ")"); mContext = context; mHandler = new Handler(Looper.getMainLooper()); // Construct sound player; use enforced sound output if necessary File recordSoundFile = new File(mVideoRecordSound); try { ParcelFileDescriptor recordSoundParcel = ParcelFileDescriptor.open(recordSoundFile, ParcelFileDescriptor.MODE_READ_ONLY); AssetFileDescriptor recordSoundAsset = new AssetFileDescriptor(recordSoundParcel, 0, AssetFileDescriptor.UNKNOWN_LENGTH); if (SystemProperties.get("ro.camera.sound.forced", "0").equals("0")) { if (mLogVerbose) Log.v(TAG, "Standard recording sound"); mRecordSound = new SoundPlayer(recordSoundAsset, false); } else { if (mLogVerbose) Log.v(TAG, "Forced recording sound"); mRecordSound = new SoundPlayer(recordSoundAsset, true); } } catch (java.io.FileNotFoundException e) { Log.e(TAG, "System video record sound not found"); mRecordSound = null; } } public void setCamera(Camera cameraDevice) { switch (mState) { case STATE_PREVIEW: throw new RuntimeException("setCamera cannot be called while previewing!"); case STATE_RECORD: throw new RuntimeException("setCamera cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setCamera called on an already released recorder!"); default: break; } mCameraDevice = cameraDevice; } public void setProfile(CamcorderProfile profile) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setProfile cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setProfile called on an already released recorder!"); default: break; } mProfile = profile; } public void setOutputFile(String outputFile) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setOutputFile cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setOutputFile called on an already released recorder!"); default: break; } mOutputFile = outputFile; mFd = null; } public void setOutputFile(FileDescriptor fd) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setOutputFile cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setOutputFile called on an already released recorder!"); default: break; } mOutputFile = null; mFd = fd; } /** * Sets the maximum filesize (in bytes) of the recording session. * This will be passed on to the MediaEncoderFilter and then to the * MediaRecorder ultimately. If zero or negative, the MediaRecorder will * disable the limit */ public synchronized void setMaxFileSize(long maxFileSize) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setMaxFileSize cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setMaxFileSize called on an already released recorder!"); default: break; } mMaxFileSize = maxFileSize; } /** * Sets the maximum recording duration (in ms) for the next recording session * Setting it to zero (the default) disables the limit. */ public synchronized void setMaxDuration(int maxDurationMs) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setMaxDuration cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setMaxDuration called on an already released recorder!"); default: break; } mMaxDurationMs = maxDurationMs; } public void setCaptureRate(double fps) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setCaptureRate cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setCaptureRate called on an already released recorder!"); default: break; } if (mLogVerbose) Log.v(TAG, "Setting time lapse capture rate to " + fps + " fps"); mCaptureRate = fps; } public void setPreviewDisplay(SurfaceHolder previewSurfaceHolder, int previewWidth, int previewHeight) { if (mLogVerbose) Log.v(TAG, "setPreviewDisplay (" + this + ")"); switch (mState) { case STATE_RECORD: throw new RuntimeException("setPreviewDisplay cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setPreviewDisplay called on an already released recorder!"); default: break; } mPreviewSurfaceHolder = previewSurfaceHolder; mPreviewWidth = previewWidth; mPreviewHeight = previewHeight; switch (mState) { case STATE_WAITING_FOR_SURFACE: startPreview(); break; case STATE_STARTING_PREVIEW: case STATE_PREVIEW: initializeEffect(true); break; } } public void setEffect(int effect, Object effectParameter) { if (mLogVerbose) Log.v(TAG, "setEffect: effect ID " + effect + ", parameter " + effectParameter.toString() ); switch (mState) { case STATE_RECORD: throw new RuntimeException("setEffect cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setEffect called on an already released recorder!"); default: break; } mEffect = effect; mEffectParameter = effectParameter; if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { initializeEffect(false); } } public interface EffectsListener { public void onEffectsUpdate(int effectId, int effectMsg); public void onEffectsError(Exception exception, String filePath); } public void setEffectsListener(EffectsListener listener) { mEffectsListener = listener; } private void setFaceDetectOrientation() { if (mCurrentEffect == EFFECT_GOOFY_FACE) { Filter rotateFilter = mRunner.getGraph().getFilter("rotate"); Filter metaRotateFilter = mRunner.getGraph().getFilter("metarotate"); rotateFilter.setInputValue("rotation", mOrientationHint); int reverseDegrees = (360 - mOrientationHint) % 360; metaRotateFilter.setInputValue("rotation", reverseDegrees); } } private void setRecordingOrientation() { if ( mState != STATE_RECORD && mRunner != null) { Point bl = new Point(0, 0); Point br = new Point(1, 0); Point tl = new Point(0, 1); Point tr = new Point(1, 1); Quad recordingRegion; if (mCameraFacing == Camera.CameraInfo.CAMERA_FACING_BACK) { // The back camera is not mirrored, so use a identity transform recordingRegion = new Quad(bl, br, tl, tr); } else { // Recording region needs to be tweaked for front cameras, since they // mirror their preview if (mOrientationHint == 0 || mOrientationHint == 180) { // Horizontal flip in landscape recordingRegion = new Quad(br, bl, tr, tl); } else { // Horizontal flip in portrait recordingRegion = new Quad(tl, tr, bl, br); } } Filter recorder = mRunner.getGraph().getFilter("recorder"); recorder.setInputValue("inputRegion", recordingRegion); } } public void setOrientationHint(int degrees) { switch (mState) { case STATE_RELEASED: throw new RuntimeException( "setOrientationHint called on an already released recorder!"); default: break; } if (mLogVerbose) Log.v(TAG, "Setting orientation hint to: " + degrees); mOrientationHint = degrees; setFaceDetectOrientation(); setRecordingOrientation(); } /** Passes the native orientation of the Camera app (device dependent) * to allow for correct output aspect ratio. Defaults to portrait */ public void setAppToLandscape(boolean landscape) { if (mState != STATE_CONFIGURE) { throw new RuntimeException( "setAppToLandscape called after configuration!"); } mAppIsLandscape = landscape; } public void setCameraFacing(int facing) { switch (mState) { case STATE_RELEASED: throw new RuntimeException( "setCameraFacing called on alrady released recorder!"); default: break; } mCameraFacing = facing; setRecordingOrientation(); } public void setOnInfoListener(MediaRecorder.OnInfoListener infoListener) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setInfoListener cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setInfoListener called on an already released recorder!"); default: break; } mInfoListener = infoListener; } public void setOnErrorListener(MediaRecorder.OnErrorListener errorListener) { switch (mState) { case STATE_RECORD: throw new RuntimeException("setErrorListener cannot be called while recording!"); case STATE_RELEASED: throw new RuntimeException("setErrorListener called on an already released recorder!"); default: break; } mErrorListener = errorListener; } private void initializeFilterFramework() { mGraphEnv = new GraphEnvironment(); mGraphEnv.createGLEnvironment(); if (mLogVerbose) { Log.v(TAG, "Effects framework initializing. Recording size " + mProfile.videoFrameWidth + ", " + mProfile.videoFrameHeight); } if (!mAppIsLandscape) { int tmp; tmp = mProfile.videoFrameWidth; mProfile.videoFrameWidth = mProfile.videoFrameHeight; mProfile.videoFrameHeight = tmp; } mGraphEnv.addReferences( "textureSourceCallback", mSourceReadyCallback, "recordingWidth", mProfile.videoFrameWidth, "recordingHeight", mProfile.videoFrameHeight, "recordingProfile", mProfile, "learningDoneListener", mLearningDoneListener, "recordingDoneListener", mRecordingDoneListener); mRunner = null; mGraphId = -1; mCurrentEffect = EFFECT_NONE; } private synchronized void initializeEffect(boolean forceReset) { if (forceReset || mCurrentEffect != mEffect || mCurrentEffect == EFFECT_BACKDROPPER) { if (mLogVerbose) { Log.v(TAG, "Effect initializing. Preview size " + mPreviewWidth + ", " + mPreviewHeight); } mGraphEnv.addReferences( "previewSurface", mPreviewSurfaceHolder.getSurface(), "previewWidth", mPreviewWidth, "previewHeight", mPreviewHeight, "orientation", mOrientationHint); if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Inform video camera. sendMessage(mCurrentEffect, EFFECT_MSG_SWITCHING_EFFECT); } switch (mEffect) { case EFFECT_GOOFY_FACE: mGraphId = mGraphEnv.loadGraph(mContext, R.raw.goofy_face); break; case EFFECT_BACKDROPPER: sendMessage(EFFECT_BACKDROPPER, EFFECT_MSG_STARTED_LEARNING); mGraphId = mGraphEnv.loadGraph(mContext, R.raw.backdropper); break; default: throw new RuntimeException("Unknown effect ID" + mEffect + "!"); } mCurrentEffect = mEffect; mOldRunner = mRunner; mRunner = mGraphEnv.getRunner(mGraphId, GraphEnvironment.MODE_ASYNCHRONOUS); mRunner.setDoneCallback(mRunnerDoneCallback); if (mLogVerbose) { Log.v(TAG, "New runner: " + mRunner + ". Old runner: " + mOldRunner); } if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Stop existing runner. // The stop callback will take care of starting new runner. mCameraDevice.stopPreview(); try { mCameraDevice.setPreviewTexture(null); } catch(IOException e) { throw new RuntimeException("Unable to connect camera to effect input", e); } mOldRunner.stop(); } } switch (mCurrentEffect) { case EFFECT_GOOFY_FACE: tryEnableVideoStabilization(true); Filter goofyFilter = mRunner.getGraph().getFilter("goofyrenderer"); goofyFilter.setInputValue("currentEffect", ((Integer)mEffectParameter).intValue()); break; case EFFECT_BACKDROPPER: tryEnableVideoStabilization(false); Filter backgroundSrc = mRunner.getGraph().getFilter("background"); backgroundSrc.setInputValue("sourceUrl", (String)mEffectParameter); + // For front camera, the background video needs to be mirrored in the + // backdropper filter + if (mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) { + Filter replacer = mRunner.getGraph().getFilter("replacer"); + replacer.setInputValue("mirrorBg", true); + if (mLogVerbose) Log.v(TAG, "Setting the background to be mirrored"); + } break; default: break; } setFaceDetectOrientation(); setRecordingOrientation(); } public synchronized void startPreview() { if (mLogVerbose) Log.v(TAG, "Starting preview (" + this + ")"); switch (mState) { case STATE_STARTING_PREVIEW: case STATE_PREVIEW: // Already running preview Log.w(TAG, "startPreview called when already running preview"); return; case STATE_RECORD: throw new RuntimeException("Cannot start preview when already recording!"); case STATE_RELEASED: throw new RuntimeException("setEffect called on an already released recorder!"); default: break; } if (mEffect == EFFECT_NONE) { throw new RuntimeException("No effect selected!"); } if (mEffectParameter == null) { throw new RuntimeException("No effect parameter provided!"); } if (mProfile == null) { throw new RuntimeException("No recording profile provided!"); } if (mPreviewSurfaceHolder == null) { if (mLogVerbose) Log.v(TAG, "Passed a null surface holder; waiting for valid one"); mState = STATE_WAITING_FOR_SURFACE; return; } if (mCameraDevice == null) { throw new RuntimeException("No camera to record from!"); } if (mLogVerbose) Log.v(TAG, "Initializing filter graph"); initializeFilterFramework(); initializeEffect(true); if (mLogVerbose) Log.v(TAG, "Starting filter graph"); mState = STATE_STARTING_PREVIEW; mRunner.run(); // Rest of preview startup handled in mSourceReadyCallback } private SurfaceTextureSourceListener mSourceReadyCallback = new SurfaceTextureSourceListener() { public void onSurfaceTextureSourceReady(SurfaceTexture source) { if (mLogVerbose) Log.v(TAG, "SurfaceTexture ready callback received"); synchronized(EffectsRecorder.this) { mTextureSource = source; if (mState == STATE_CONFIGURE) { // Stop preview happened while the runner was doing startup tasks // Since we haven't started anything up, don't do anything // Rest of cleanup will happen in onRunnerDone if (mLogVerbose) Log.v(TAG, "Ready callback: Already stopped, skipping."); return; } if (mState == STATE_RELEASED) { // EffectsRecorder has been released, so don't touch the camera device // or anything else if (mLogVerbose) Log.v(TAG, "Ready callback: Already released, skipping."); return; } if (source == null) { if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW || mState == STATE_RECORD) { // A null source here means the graph is shutting down // unexpectedly, so we need to turn off preview before // the surface texture goes away. mCameraDevice.stopPreview(); try { mCameraDevice.setPreviewTexture(null); } catch(IOException e) { throw new RuntimeException("Unable to disconnect " + "camera from effect input", e); } } return; } // Lock AE/AWB to reduce transition flicker tryEnable3ALocks(true); mCameraDevice.stopPreview(); if (mLogVerbose) Log.v(TAG, "Runner active, connecting effects preview"); try { mCameraDevice.setPreviewTexture(mTextureSource); } catch(IOException e) { throw new RuntimeException("Unable to connect camera to effect input", e); } mCameraDevice.startPreview(); // Unlock AE/AWB after preview started tryEnable3ALocks(false); mState = STATE_PREVIEW; if (mLogVerbose) Log.v(TAG, "Start preview/effect switch complete"); } } }; private LearningDoneListener mLearningDoneListener = new LearningDoneListener() { public void onLearningDone(BackDropperFilter filter) { if (mLogVerbose) Log.v(TAG, "Learning done callback triggered"); // Called in a processing thread, so have to post message back to UI // thread sendMessage(EFFECT_BACKDROPPER, EFFECT_MSG_DONE_LEARNING); enable3ALocks(true); } }; // A callback to finalize the media after the recording is done. private OnRecordingDoneListener mRecordingDoneListener = new OnRecordingDoneListener() { // Forward the callback to the VideoCamera object (as an asynchronous event). public void onRecordingDone() { if (mLogVerbose) Log.v(TAG, "Recording done callback triggered"); sendMessage(EFFECT_NONE, EFFECT_MSG_RECORDING_DONE); } }; public synchronized void startRecording() { if (mLogVerbose) Log.v(TAG, "Starting recording (" + this + ")"); switch (mState) { case STATE_RECORD: throw new RuntimeException("Already recording, cannot begin anew!"); case STATE_RELEASED: throw new RuntimeException("startRecording called on an already released recorder!"); default: break; } if ((mOutputFile == null) && (mFd == null)) { throw new RuntimeException("No output file name or descriptor provided!"); } if (mState == STATE_CONFIGURE) { startPreview(); } Filter recorder = mRunner.getGraph().getFilter("recorder"); if (mFd != null) { recorder.setInputValue("outputFileDescriptor", mFd); } else { recorder.setInputValue("outputFile", mOutputFile); } // It is ok to set the audiosource without checking for timelapse here // since that check will be done in the MediaEncoderFilter itself recorder.setInputValue("audioSource", MediaRecorder.AudioSource.CAMCORDER); recorder.setInputValue("recordingProfile", mProfile); recorder.setInputValue("orientationHint", mOrientationHint); // Important to set the timelapseinterval to 0 if the capture rate is not >0 // since the recorder does not get created every time the recording starts. // The recorder infers whether the capture is timelapsed based on the value of // this interval boolean captureTimeLapse = mCaptureRate > 0; if (captureTimeLapse) { double timeBetweenFrameCapture = 1 / mCaptureRate; recorder.setInputValue("timelapseRecordingIntervalUs", (long) (1000000 * timeBetweenFrameCapture)); } else { recorder.setInputValue("timelapseRecordingIntervalUs", 0L); } if (mInfoListener != null) { recorder.setInputValue("infoListener", mInfoListener); } if (mErrorListener != null) { recorder.setInputValue("errorListener", mErrorListener); } recorder.setInputValue("maxFileSize", mMaxFileSize); recorder.setInputValue("maxDurationMs", mMaxDurationMs); recorder.setInputValue("recording", true); if (mRecordSound != null) mRecordSound.play(); mState = STATE_RECORD; } public synchronized void stopRecording() { if (mLogVerbose) Log.v(TAG, "Stop recording (" + this + ")"); switch (mState) { case STATE_CONFIGURE: case STATE_STARTING_PREVIEW: case STATE_PREVIEW: Log.w(TAG, "StopRecording called when recording not active!"); return; case STATE_RELEASED: throw new RuntimeException("stopRecording called on released EffectsRecorder!"); default: break; } Filter recorder = mRunner.getGraph().getFilter("recorder"); recorder.setInputValue("recording", false); if (mRecordSound != null) mRecordSound.play(); mState = STATE_PREVIEW; } // Stop and release effect resources public synchronized void stopPreview() { if (mLogVerbose) Log.v(TAG, "Stopping preview (" + this + ")"); switch (mState) { case STATE_CONFIGURE: Log.w(TAG, "StopPreview called when preview not active!"); return; case STATE_RELEASED: throw new RuntimeException("stopPreview called on released EffectsRecorder!"); default: break; } if (mState == STATE_RECORD) { stopRecording(); } mCurrentEffect = EFFECT_NONE; mCameraDevice.stopPreview(); try { mCameraDevice.setPreviewTexture(null); } catch(IOException e) { throw new RuntimeException("Unable to connect camera to effect input", e); } mState = STATE_CONFIGURE; mOldRunner = mRunner; mRunner.stop(); mRunner = null; // Rest of stop and release handled in mRunnerDoneCallback } // Try to enable/disable video stabilization if supported; otherwise return false boolean tryEnableVideoStabilization(boolean toggle) { Camera.Parameters params = mCameraDevice.getParameters(); String vstabSupported = params.get("video-stabilization-supported"); if ("true".equals(vstabSupported)) { if (mLogVerbose) Log.v(TAG, "Setting video stabilization to " + toggle); params.set("video-stabilization", toggle ? "true" : "false"); mCameraDevice.setParameters(params); return true; } if (mLogVerbose) Log.v(TAG, "Video stabilization not supported"); return false; } // Try to enable/disable 3A locks if supported; otherwise return false boolean tryEnable3ALocks(boolean toggle) { Camera.Parameters params = mCameraDevice.getParameters(); if (params.isAutoExposureLockSupported() && params.isAutoWhiteBalanceLockSupported() ) { params.setAutoExposureLock(toggle); params.setAutoWhiteBalanceLock(toggle); mCameraDevice.setParameters(params); return true; } return false; } // Try to enable/disable 3A locks if supported; otherwise, throw error // Use this when locks are essential to success void enable3ALocks(boolean toggle) { Camera.Parameters params = mCameraDevice.getParameters(); if (!tryEnable3ALocks(toggle)) { throw new RuntimeException("Attempt to lock 3A on camera with no locking support!"); } } private OnRunnerDoneListener mRunnerDoneCallback = new OnRunnerDoneListener() { public void onRunnerDone(int result) { synchronized(EffectsRecorder.this) { if (mLogVerbose) { Log.v(TAG, "Graph runner done (" + EffectsRecorder.this + ", mRunner " + mRunner + ", mOldRunner " + mOldRunner + ")"); } if (result == GraphRunner.RESULT_ERROR) { // Handle error case Log.e(TAG, "Error running filter graph!"); raiseError(mRunner == null ? null : mRunner.getError()); } if (mOldRunner != null) { // Tear down old graph if available if (mLogVerbose) Log.v(TAG, "Tearing down old graph."); GLEnvironment glEnv = mGraphEnv.getContext().getGLEnvironment(); if (glEnv != null && !glEnv.isActive()) { glEnv.activate(); } mOldRunner.getGraph().tearDown(mGraphEnv.getContext()); if (glEnv != null && glEnv.isActive()) { glEnv.deactivate(); } mOldRunner = null; } if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects, start up the new runner if (mLogVerbose) Log.v(TAG, "Previous effect halted, starting new effect."); tryEnable3ALocks(false); mRunner.run(); } else if (mState != STATE_RELEASED) { // Shutting down effects if (mLogVerbose) Log.v(TAG, "Runner halted, restoring direct preview"); tryEnable3ALocks(false); sendMessage(EFFECT_NONE, EFFECT_MSG_EFFECTS_STOPPED); } else { // STATE_RELEASED - camera will be/has been released as well, do nothing. } } } }; // Indicates that all camera/recording activity needs to halt public synchronized void release() { if (mLogVerbose) Log.v(TAG, "Releasing (" + this + ")"); switch (mState) { case STATE_RECORD: case STATE_STARTING_PREVIEW: case STATE_PREVIEW: stopPreview(); // Fall-through default: mRecordSound.release(); mState = STATE_RELEASED; break; } } private void sendMessage(final int effect, final int msg) { if (mEffectsListener != null) { mHandler.post(new Runnable() { public void run() { mEffectsListener.onEffectsUpdate(effect, msg); } }); } } private void raiseError(final Exception exception) { if (mEffectsListener != null) { mHandler.post(new Runnable() { public void run() { if (mFd != null) { mEffectsListener.onEffectsError(exception, null); } else { mEffectsListener.onEffectsError(exception, mOutputFile); } } }); } } }
true
true
private synchronized void initializeEffect(boolean forceReset) { if (forceReset || mCurrentEffect != mEffect || mCurrentEffect == EFFECT_BACKDROPPER) { if (mLogVerbose) { Log.v(TAG, "Effect initializing. Preview size " + mPreviewWidth + ", " + mPreviewHeight); } mGraphEnv.addReferences( "previewSurface", mPreviewSurfaceHolder.getSurface(), "previewWidth", mPreviewWidth, "previewHeight", mPreviewHeight, "orientation", mOrientationHint); if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Inform video camera. sendMessage(mCurrentEffect, EFFECT_MSG_SWITCHING_EFFECT); } switch (mEffect) { case EFFECT_GOOFY_FACE: mGraphId = mGraphEnv.loadGraph(mContext, R.raw.goofy_face); break; case EFFECT_BACKDROPPER: sendMessage(EFFECT_BACKDROPPER, EFFECT_MSG_STARTED_LEARNING); mGraphId = mGraphEnv.loadGraph(mContext, R.raw.backdropper); break; default: throw new RuntimeException("Unknown effect ID" + mEffect + "!"); } mCurrentEffect = mEffect; mOldRunner = mRunner; mRunner = mGraphEnv.getRunner(mGraphId, GraphEnvironment.MODE_ASYNCHRONOUS); mRunner.setDoneCallback(mRunnerDoneCallback); if (mLogVerbose) { Log.v(TAG, "New runner: " + mRunner + ". Old runner: " + mOldRunner); } if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Stop existing runner. // The stop callback will take care of starting new runner. mCameraDevice.stopPreview(); try { mCameraDevice.setPreviewTexture(null); } catch(IOException e) { throw new RuntimeException("Unable to connect camera to effect input", e); } mOldRunner.stop(); } } switch (mCurrentEffect) { case EFFECT_GOOFY_FACE: tryEnableVideoStabilization(true); Filter goofyFilter = mRunner.getGraph().getFilter("goofyrenderer"); goofyFilter.setInputValue("currentEffect", ((Integer)mEffectParameter).intValue()); break; case EFFECT_BACKDROPPER: tryEnableVideoStabilization(false); Filter backgroundSrc = mRunner.getGraph().getFilter("background"); backgroundSrc.setInputValue("sourceUrl", (String)mEffectParameter); break; default: break; } setFaceDetectOrientation(); setRecordingOrientation(); }
private synchronized void initializeEffect(boolean forceReset) { if (forceReset || mCurrentEffect != mEffect || mCurrentEffect == EFFECT_BACKDROPPER) { if (mLogVerbose) { Log.v(TAG, "Effect initializing. Preview size " + mPreviewWidth + ", " + mPreviewHeight); } mGraphEnv.addReferences( "previewSurface", mPreviewSurfaceHolder.getSurface(), "previewWidth", mPreviewWidth, "previewHeight", mPreviewHeight, "orientation", mOrientationHint); if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Inform video camera. sendMessage(mCurrentEffect, EFFECT_MSG_SWITCHING_EFFECT); } switch (mEffect) { case EFFECT_GOOFY_FACE: mGraphId = mGraphEnv.loadGraph(mContext, R.raw.goofy_face); break; case EFFECT_BACKDROPPER: sendMessage(EFFECT_BACKDROPPER, EFFECT_MSG_STARTED_LEARNING); mGraphId = mGraphEnv.loadGraph(mContext, R.raw.backdropper); break; default: throw new RuntimeException("Unknown effect ID" + mEffect + "!"); } mCurrentEffect = mEffect; mOldRunner = mRunner; mRunner = mGraphEnv.getRunner(mGraphId, GraphEnvironment.MODE_ASYNCHRONOUS); mRunner.setDoneCallback(mRunnerDoneCallback); if (mLogVerbose) { Log.v(TAG, "New runner: " + mRunner + ". Old runner: " + mOldRunner); } if (mState == STATE_PREVIEW || mState == STATE_STARTING_PREVIEW) { // Switching effects while running. Stop existing runner. // The stop callback will take care of starting new runner. mCameraDevice.stopPreview(); try { mCameraDevice.setPreviewTexture(null); } catch(IOException e) { throw new RuntimeException("Unable to connect camera to effect input", e); } mOldRunner.stop(); } } switch (mCurrentEffect) { case EFFECT_GOOFY_FACE: tryEnableVideoStabilization(true); Filter goofyFilter = mRunner.getGraph().getFilter("goofyrenderer"); goofyFilter.setInputValue("currentEffect", ((Integer)mEffectParameter).intValue()); break; case EFFECT_BACKDROPPER: tryEnableVideoStabilization(false); Filter backgroundSrc = mRunner.getGraph().getFilter("background"); backgroundSrc.setInputValue("sourceUrl", (String)mEffectParameter); // For front camera, the background video needs to be mirrored in the // backdropper filter if (mCameraFacing == Camera.CameraInfo.CAMERA_FACING_FRONT) { Filter replacer = mRunner.getGraph().getFilter("replacer"); replacer.setInputValue("mirrorBg", true); if (mLogVerbose) Log.v(TAG, "Setting the background to be mirrored"); } break; default: break; } setFaceDetectOrientation(); setRecordingOrientation(); }
diff --git a/core/src/com/google/zxing/datamatrix/decoder/DecodedBitStreamParser.java b/core/src/com/google/zxing/datamatrix/decoder/DecodedBitStreamParser.java index 16ce63d6..791f4648 100644 --- a/core/src/com/google/zxing/datamatrix/decoder/DecodedBitStreamParser.java +++ b/core/src/com/google/zxing/datamatrix/decoder/DecodedBitStreamParser.java @@ -1,462 +1,462 @@ /* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.datamatrix.decoder; import com.google.zxing.FormatException; import com.google.zxing.common.BitSource; import com.google.zxing.common.DecoderResult; import java.io.UnsupportedEncodingException; import java.util.Vector; /** * <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes * in one Data Matrix Code. This class decodes the bits back into text.</p> * * <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> * * @author [email protected] (Brian Brown) * @author Sean Owen */ final class DecodedBitStreamParser { /** * See ISO 16022:2006, Annex C Table C.1 * The C40 Basic Character Set (*'s used for placeholders for the shift values) */ private static final char[] C40_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static final char[] C40_SHIFT2_SET_CHARS = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' }; /** * See ISO 16022:2006, Annex C Table C.2 * The Text Basic Character Set (*'s used for placeholders for the shift values) */ private static final char[] TEXT_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static final char[] TEXT_SHIFT3_SET_CHARS = { '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 }; private static final int PAD_ENCODE = 0; // Not really an encoding private static final int ASCII_ENCODE = 1; private static final int C40_ENCODE = 2; private static final int TEXT_ENCODE = 3; private static final int ANSIX12_ENCODE = 4; private static final int EDIFACT_ENCODE = 5; private static final int BASE256_ENCODE = 6; private DecodedBitStreamParser() { } static DecoderResult decode(byte[] bytes) throws FormatException { BitSource bits = new BitSource(bytes); StringBuffer result = new StringBuffer(100); StringBuffer resultTrailer = new StringBuffer(0); Vector byteSegments = new Vector(1); int mode = ASCII_ENCODE; do { if (mode == ASCII_ENCODE) { mode = decodeAsciiSegment(bits, result, resultTrailer); } else { switch (mode) { case C40_ENCODE: decodeC40Segment(bits, result); break; case TEXT_ENCODE: decodeTextSegment(bits, result); break; case ANSIX12_ENCODE: decodeAnsiX12Segment(bits, result); break; case EDIFACT_ENCODE: decodeEdifactSegment(bits, result); break; case BASE256_ENCODE: decodeBase256Segment(bits, result, byteSegments); break; default: throw FormatException.getFormatInstance(); } mode = ASCII_ENCODE; } } while (mode != PAD_ENCODE && bits.available() > 0); if (resultTrailer.length() > 0) { result.append(resultTrailer.toString()); } return new DecoderResult(bytes, result.toString(), byteSegments.isEmpty() ? null : byteSegments, null); } /** * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 */ private static int decodeAsciiSegment(BitSource bits, StringBuffer result, StringBuffer resultTrailer) throws FormatException { boolean upperShift = false; do { int oneByte = bits.readBits(8); if (oneByte == 0) { throw FormatException.getFormatInstance(); } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) oneByte = upperShift ? (oneByte + 128) : oneByte; upperShift = false; result.append((char) (oneByte - 1)); return ASCII_ENCODE; } else if (oneByte == 129) { // Pad return PAD_ENCODE; } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) int value = oneByte - 130; if (value < 10) { // padd with '0' for single digit values result.append('0'); } result.append(value); } else if (oneByte == 230) { // Latch to C40 encodation return C40_ENCODE; } else if (oneByte == 231) { // Latch to Base 256 encodation return BASE256_ENCODE; } else if (oneByte == 232) { // FNC1 //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 233) { // Structured Append //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 234) { // Reader Programming //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) upperShift = true; } else if (oneByte == 236) { // 05 Macro result.append("[)>\u001E05\u001D"); resultTrailer.insert(0, "\u001E\u0004"); } else if (oneByte == 237) { // 06 Macro result.append("[)>\u001E06\u001D"); resultTrailer.insert(0, "\u001E\u0004"); } else if (oneByte == 238) { // Latch to ANSI X12 encodation return ANSIX12_ENCODE; } else if (oneByte == 239) { // Latch to Text encodation return TEXT_ENCODE; } else if (oneByte == 240) { // Latch to EDIFACT encodation return EDIFACT_ENCODE; } else if (oneByte == 241) { // ECI Character // TODO(bbrown): I think we need to support ECI //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte >= 242) { // Not to be used in ASCII encodation throw FormatException.getFormatInstance(); } } while (bits.available() > 0); return ASCII_ENCODE; } /** * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 */ private static void decodeC40Segment(BitSource bits, StringBuffer result) throws FormatException { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); int shift = 0; for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (C40_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (cValue + 224)); upperShift = false; } else { result.append((char) (cValue + 96)); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } /** * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 */ private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; + int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); - int shift = 0; for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } /** * See ISO 16022:2006, 5.2.7 */ private static void decodeAnsiX12Segment(BitSource bits, StringBuffer result) throws FormatException { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; if (cValue == 0) { // X12 segment terminator <CR> result.append('\r'); } else if (cValue == 1) { // X12 segment separator * result.append('*'); } else if (cValue == 2) { // X12 sub-element separator > result.append('>'); } else if (cValue == 3) { // space result.append(' '); } else if (cValue < 14) { // 0 - 9 result.append((char) (cValue + 44)); } else if (cValue < 40) { // A - Z result.append((char) (cValue + 51)); } else { throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); } private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { int fullBitValue = (firstByte << 8) + secondByte - 1; int temp = fullBitValue / 1600; result[0] = temp; fullBitValue -= temp * 1600; temp = fullBitValue / 40; result[1] = temp; result[2] = fullBitValue - temp * 40; } /** * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 */ private static void decodeEdifactSegment(BitSource bits, StringBuffer result) { boolean unlatch = false; do { // If there is only two or less bytes left then it will be encoded as ASCII if (bits.available() <= 16) { return; } for (int i = 0; i < 4; i++) { int edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x2B67) { // 011111 unlatch = true; // If we encounter the unlatch code then continue reading because the Codeword triple // is padded with 0's } if (!unlatch) { if ((edifactValue & 32) == 0) { // no 1 in the leading (6th) bit edifactValue |= 64; // Add a leading 01 to the 6 bit binary value } result.append(edifactValue); } } } while (!unlatch && bits.available() > 0); } /** * See ISO 16022:2006, 5.2.9 and Annex B, B.2 */ private static void decodeBase256Segment(BitSource bits, StringBuffer result, Vector byteSegments) throws FormatException { // Figure out how long the Base 256 Segment is. int d1 = bits.readBits(8); int count; if (d1 == 0) { // Read the remainder of the symbol count = bits.available() / 8; } else if (d1 < 250) { count = d1; } else { count = 250 * (d1 - 249) + bits.readBits(8); } byte[] bytes = new byte[count]; for (int i = 0; i < count; i++) { // Have seen this particular error in the wild, such as at // http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2 if (bits.available() < 8) { throw FormatException.getFormatInstance(); } bytes[i] = unrandomize255State(bits.readBits(8), i); } byteSegments.addElement(bytes); try { result.append(new String(bytes, "ISO8859_1")); } catch (UnsupportedEncodingException uee) { throw new RuntimeException("Platform does not support required encoding: " + uee); } } /** * See ISO 16022:2006, Annex B, B.2 */ private static byte unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return (byte) (tempVariable >= 0 ? tempVariable : (tempVariable + 256)); } }
false
true
private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); int shift = 0; for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); }
private static void decodeTextSegment(BitSource bits, StringBuffer result) throws FormatException { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time boolean upperShift = false; int[] cValues = new int[3]; int shift = 0; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.append((char) (cValue + 128)); upperShift = false; } else { result.append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw FormatException.getFormatInstance(); } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw FormatException.getFormatInstance(); } shift = 0; break; case 3: if (upperShift) { result.append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw FormatException.getFormatInstance(); } } } while (bits.available() > 0); }
diff --git a/library/src/ros/android/util/WiFiChecker.java b/library/src/ros/android/util/WiFiChecker.java index 80b1337..5a76d17 100644 --- a/library/src/ros/android/util/WiFiChecker.java +++ b/library/src/ros/android/util/WiFiChecker.java @@ -1,252 +1,264 @@ /* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ros.android.util; import android.util.Log; import android.net.wifi.WifiManager; import android.net.wifi.WifiConfiguration; import android.net.wifi.SupplicantState; import android.net.wifi.WifiInfo; import android.content.Context; /** * Threaded WiFi checker. Checks and tests if the WiFi is configured properly and if not, connects to the correct network. * * @author [email protected] */ public class WiFiChecker { public interface SuccessHandler { /** Called on success with a description of the robot that got checked. */ void handleSuccess(); } public interface FailureHandler { /** * Called on failure with a short description of why it failed, like * "exception" or "timeout". */ void handleFailure(String reason); } public interface ReconnectionHandler { /** Called to prompt the user to connect to a different network */ boolean doReconnection(String from, String to); } private CheckerThread checkerThread; private SuccessHandler foundWiFiCallback; private FailureHandler failureCallback; private ReconnectionHandler reconnectionCallback; /** Constructor. Should not take any time. */ public WiFiChecker(SuccessHandler foundWiFiCallback, FailureHandler failureCallback, ReconnectionHandler reconnectionCallback) { this.foundWiFiCallback = foundWiFiCallback; this.failureCallback = failureCallback; this.reconnectionCallback = reconnectionCallback; } /** * Start the checker thread with the given robotId. If the thread is * already running, kill it first and then start anew. Returns immediately. */ public void beginChecking(RobotId robotId, WifiManager manager) { stopChecking(); //If there's no wifi tag in the robot id, skip this step if (robotId.getWifi() == null) { foundWiFiCallback.handleSuccess(); return; } checkerThread = new CheckerThread(robotId, manager); checkerThread.start(); } /** Stop the checker thread. */ public void stopChecking() { if (checkerThread != null && checkerThread.isAlive()) { checkerThread.interrupt(); } } public static boolean wifiValid(RobotId robotId, WifiManager wifiManager) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (robotId.getWifi() == null) { //Does not matter what wifi network, always valid. return true; } if (wifiManager.isWifiEnabled()) { if (wifiInfo != null) { Log.d("WiFiChecker", "WiFi Info: " + wifiInfo.toString() + " IP " + wifiInfo.getIpAddress()); if (wifiInfo.getSSID() != null && wifiInfo.getIpAddress() != 0 && wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) { if (wifiInfo.getSSID().equals(robotId.getWifi())) { return true; } } } } return false; } private class CheckerThread extends Thread { private RobotId robotId; private WifiManager wifiManager; public CheckerThread(RobotId robotId, WifiManager wifi) { this.robotId = robotId; this.wifiManager = wifi; setDaemon(true); // don't require callers to explicitly kill all the old checker threads. setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { failureCallback.handleFailure("exception: " + ex.getMessage()); } }); } private boolean wifiValid() { return WiFiChecker.wifiValid(robotId, wifiManager); } @Override public void run() { try { if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else if (reconnectionCallback.doReconnection(wifiManager.getConnectionInfo().getSSID(), robotId.getWifi())) { + Log.d("WiFiChecker", "Disable networking"); + wifiManager.setWifiEnabled(false); + int i = 0; + while (i < 30 && wifiManager.isWifiEnabled()) { + Log.d("WiFiChecker", "Waiting for WiFi enable"); + Thread.sleep(1000L); + i++; + } + if (wifiManager.isWifiEnabled()) { + failureCallback.handleFailure("Un-able to shutdown WiFi"); + return; + } Log.d("WiFiChecker", "Wait for networking"); wifiManager.setWifiEnabled(true); - int i = 0; while (i < 30 && !wifiManager.isWifiEnabled()) { Log.d("WiFiChecker", "Waiting for WiFi enable"); Thread.sleep(1000L); i++; } if (!wifiManager.isWifiEnabled()) { failureCallback.handleFailure("Un-able to connect to WiFi"); return; } int n = -1; int priority = -1; WifiConfiguration wc = null; String SSID = "\"" + robotId.getWifi() + "\""; for (WifiConfiguration test : wifiManager.getConfiguredNetworks()) { Log.d("WiFiChecker", "WIFI " + test.toString()); if (test.priority > priority) { priority = test.priority; } if (test.SSID.equals(SSID)) { n = test.networkId; wc = test; } + test.status = WifiConfiguration.Status.DISABLED; } if (wc != null) { if (wc.priority != priority) { wc.priority = priority + 1; } wc.status = WifiConfiguration.Status.DISABLED; wifiManager.updateNetwork(wc); } //Add new network. if (n == -1) { Log.d("WiFiChecker", "WIFI Unknown"); wc = new WifiConfiguration(); wc.SSID = "\"" + robotId.getWifi() + "\""; if (robotId.getWifiPassword() != null) { wc.preSharedKey = "\"" + robotId.getWifiPassword() + "\""; } else { wc.preSharedKey = null; } wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); n = wifiManager.addNetwork(wc); Log.d("WiFiChecker", "add Network returned " + n); if (n == -1) { failureCallback.handleFailure("Failed to configure WiFi"); } } //Connect to the network boolean b = wifiManager.enableNetwork(n, true); Log.d("WiFiChecker", "enableNetwork returned " + b); if (b) { wifiManager.reconnect(); Log.d("WiFiChecker", "Wait for wifi network"); i = 0; while (i < 90 && !wifiValid()) { Log.d("WiFiChecker", "Waiting for network: " + i + " " + wifiManager.getWifiState()); Thread.sleep(1000L); i++; } if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else { failureCallback.handleFailure("WiFi connection timed out"); } } } else { failureCallback.handleFailure("Wrong WiFi network"); } } catch (Throwable ex) { Log.e("RosAndroid", "Exception while searching for WiFi for " + robotId.getWifi(), ex); failureCallback.handleFailure(ex.toString()); } } } }
false
true
public void run() { try { if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else if (reconnectionCallback.doReconnection(wifiManager.getConnectionInfo().getSSID(), robotId.getWifi())) { Log.d("WiFiChecker", "Wait for networking"); wifiManager.setWifiEnabled(true); int i = 0; while (i < 30 && !wifiManager.isWifiEnabled()) { Log.d("WiFiChecker", "Waiting for WiFi enable"); Thread.sleep(1000L); i++; } if (!wifiManager.isWifiEnabled()) { failureCallback.handleFailure("Un-able to connect to WiFi"); return; } int n = -1; int priority = -1; WifiConfiguration wc = null; String SSID = "\"" + robotId.getWifi() + "\""; for (WifiConfiguration test : wifiManager.getConfiguredNetworks()) { Log.d("WiFiChecker", "WIFI " + test.toString()); if (test.priority > priority) { priority = test.priority; } if (test.SSID.equals(SSID)) { n = test.networkId; wc = test; } } if (wc != null) { if (wc.priority != priority) { wc.priority = priority + 1; } wc.status = WifiConfiguration.Status.DISABLED; wifiManager.updateNetwork(wc); } //Add new network. if (n == -1) { Log.d("WiFiChecker", "WIFI Unknown"); wc = new WifiConfiguration(); wc.SSID = "\"" + robotId.getWifi() + "\""; if (robotId.getWifiPassword() != null) { wc.preSharedKey = "\"" + robotId.getWifiPassword() + "\""; } else { wc.preSharedKey = null; } wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); n = wifiManager.addNetwork(wc); Log.d("WiFiChecker", "add Network returned " + n); if (n == -1) { failureCallback.handleFailure("Failed to configure WiFi"); } } //Connect to the network boolean b = wifiManager.enableNetwork(n, true); Log.d("WiFiChecker", "enableNetwork returned " + b); if (b) { wifiManager.reconnect(); Log.d("WiFiChecker", "Wait for wifi network"); i = 0; while (i < 90 && !wifiValid()) { Log.d("WiFiChecker", "Waiting for network: " + i + " " + wifiManager.getWifiState()); Thread.sleep(1000L); i++; } if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else { failureCallback.handleFailure("WiFi connection timed out"); } } } else { failureCallback.handleFailure("Wrong WiFi network"); } } catch (Throwable ex) { Log.e("RosAndroid", "Exception while searching for WiFi for " + robotId.getWifi(), ex); failureCallback.handleFailure(ex.toString()); } }
public void run() { try { if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else if (reconnectionCallback.doReconnection(wifiManager.getConnectionInfo().getSSID(), robotId.getWifi())) { Log.d("WiFiChecker", "Disable networking"); wifiManager.setWifiEnabled(false); int i = 0; while (i < 30 && wifiManager.isWifiEnabled()) { Log.d("WiFiChecker", "Waiting for WiFi enable"); Thread.sleep(1000L); i++; } if (wifiManager.isWifiEnabled()) { failureCallback.handleFailure("Un-able to shutdown WiFi"); return; } Log.d("WiFiChecker", "Wait for networking"); wifiManager.setWifiEnabled(true); while (i < 30 && !wifiManager.isWifiEnabled()) { Log.d("WiFiChecker", "Waiting for WiFi enable"); Thread.sleep(1000L); i++; } if (!wifiManager.isWifiEnabled()) { failureCallback.handleFailure("Un-able to connect to WiFi"); return; } int n = -1; int priority = -1; WifiConfiguration wc = null; String SSID = "\"" + robotId.getWifi() + "\""; for (WifiConfiguration test : wifiManager.getConfiguredNetworks()) { Log.d("WiFiChecker", "WIFI " + test.toString()); if (test.priority > priority) { priority = test.priority; } if (test.SSID.equals(SSID)) { n = test.networkId; wc = test; } test.status = WifiConfiguration.Status.DISABLED; } if (wc != null) { if (wc.priority != priority) { wc.priority = priority + 1; } wc.status = WifiConfiguration.Status.DISABLED; wifiManager.updateNetwork(wc); } //Add new network. if (n == -1) { Log.d("WiFiChecker", "WIFI Unknown"); wc = new WifiConfiguration(); wc.SSID = "\"" + robotId.getWifi() + "\""; if (robotId.getWifiPassword() != null) { wc.preSharedKey = "\"" + robotId.getWifiPassword() + "\""; } else { wc.preSharedKey = null; } wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); n = wifiManager.addNetwork(wc); Log.d("WiFiChecker", "add Network returned " + n); if (n == -1) { failureCallback.handleFailure("Failed to configure WiFi"); } } //Connect to the network boolean b = wifiManager.enableNetwork(n, true); Log.d("WiFiChecker", "enableNetwork returned " + b); if (b) { wifiManager.reconnect(); Log.d("WiFiChecker", "Wait for wifi network"); i = 0; while (i < 90 && !wifiValid()) { Log.d("WiFiChecker", "Waiting for network: " + i + " " + wifiManager.getWifiState()); Thread.sleep(1000L); i++; } if (wifiValid()) { foundWiFiCallback.handleSuccess(); } else { failureCallback.handleFailure("WiFi connection timed out"); } } } else { failureCallback.handleFailure("Wrong WiFi network"); } } catch (Throwable ex) { Log.e("RosAndroid", "Exception while searching for WiFi for " + robotId.getWifi(), ex); failureCallback.handleFailure(ex.toString()); } }
diff --git a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/EquinoxLauncherCUAction.java b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/EquinoxLauncherCUAction.java index 8ab325ef2..ad189a57a 100644 --- a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/EquinoxLauncherCUAction.java +++ b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/EquinoxLauncherCUAction.java @@ -1,89 +1,89 @@ /******************************************************************************* * Copyright (c) 2008 Code 9 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: * Code 9 - initial API and implementation * IBM - ongoing development ******************************************************************************/ package org.eclipse.equinox.p2.publisher.eclipse; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.publisher.eclipse.GeneratorBundleInfo; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.publisher.*; import org.eclipse.equinox.p2.publisher.actions.IVersionAdvice; import org.osgi.framework.Version; /** * Create CUs for all Equinox launcher related IUs for the given set of configurations * such that the launcher is configured as the startup code and the fragments * are configured as the launcher.library. * <p> * This action expects to have find the versions of the launcher and launcher fragments * via IVersionAdvice in the supplied info object. * </p> */ public class EquinoxLauncherCUAction extends AbstractPublisherAction { public static final String ORG_ECLIPSE_EQUINOX_LAUNCHER = "org.eclipse.equinox.launcher"; //$NON-NLS-1$ private String flavor; private String[] configSpecs; public EquinoxLauncherCUAction(String flavor, String[] configSpecs) { this.flavor = flavor; this.configSpecs = configSpecs; } public IStatus perform(IPublisherInfo info, IPublisherResult results, IProgressMonitor monitor) { publishCU(ORG_ECLIPSE_EQUINOX_LAUNCHER, null, info, results); publishLauncherFragmentCUs(info, results); return Status.OK_STATUS; } /** * For each of the configurations we are publishing, create a launcher fragment * CU if there is version advice for the fragment. */ private void publishLauncherFragmentCUs(IPublisherInfo info, IPublisherResult results) { for (int i = 0; i < configSpecs.length; i++) { String configSpec = configSpecs[i]; String id = ORG_ECLIPSE_EQUINOX_LAUNCHER + '.' + configSpec; publishCU(id, configSpec, info, results); } } /** * Publish a CU for the IU of the given id in the given config spec. If the IU is the * launcher bundle iu then set it up as the startup JAR. If it is a launcher fragment then * configure it in as the launcher.library for this configuration. */ private void publishCU(String id, String configSpec, IPublisherInfo info, IPublisherResult results) { Collection advice = info.getAdvice(configSpec, true, id, null, IVersionAdvice.class); for (Iterator j = advice.iterator(); j.hasNext();) { IVersionAdvice versionSpec = (IVersionAdvice) j.next(); Version version = versionSpec.getVersion(IInstallableUnit.NAMESPACE_IU_ID, id); if (version == null) continue; GeneratorBundleInfo bundle = new GeneratorBundleInfo(); bundle.setSymbolicName(id); bundle.setVersion(version.toString()); if (id.equals(ORG_ECLIPSE_EQUINOX_LAUNCHER)) { bundle.setSpecialConfigCommands("addProgramArg(programArg:-startup);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:-startup);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } else { bundle.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } String filter = configSpec == null ? null : createFilterSpec(configSpec); - IInstallableUnit cu = BundlesAction.createBundleConfigurationUnit(id, version, false, bundle, flavor, null); + IInstallableUnit cu = BundlesAction.createBundleConfigurationUnit(id, version, false, bundle, flavor, filter); if (cu != null) results.addIU(cu, IPublisherResult.ROOT); } } }
true
true
private void publishCU(String id, String configSpec, IPublisherInfo info, IPublisherResult results) { Collection advice = info.getAdvice(configSpec, true, id, null, IVersionAdvice.class); for (Iterator j = advice.iterator(); j.hasNext();) { IVersionAdvice versionSpec = (IVersionAdvice) j.next(); Version version = versionSpec.getVersion(IInstallableUnit.NAMESPACE_IU_ID, id); if (version == null) continue; GeneratorBundleInfo bundle = new GeneratorBundleInfo(); bundle.setSymbolicName(id); bundle.setVersion(version.toString()); if (id.equals(ORG_ECLIPSE_EQUINOX_LAUNCHER)) { bundle.setSpecialConfigCommands("addProgramArg(programArg:-startup);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:-startup);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } else { bundle.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } String filter = configSpec == null ? null : createFilterSpec(configSpec); IInstallableUnit cu = BundlesAction.createBundleConfigurationUnit(id, version, false, bundle, flavor, null); if (cu != null) results.addIU(cu, IPublisherResult.ROOT); } }
private void publishCU(String id, String configSpec, IPublisherInfo info, IPublisherResult results) { Collection advice = info.getAdvice(configSpec, true, id, null, IVersionAdvice.class); for (Iterator j = advice.iterator(); j.hasNext();) { IVersionAdvice versionSpec = (IVersionAdvice) j.next(); Version version = versionSpec.getVersion(IInstallableUnit.NAMESPACE_IU_ID, id); if (version == null) continue; GeneratorBundleInfo bundle = new GeneratorBundleInfo(); bundle.setSymbolicName(id); bundle.setVersion(version.toString()); if (id.equals(ORG_ECLIPSE_EQUINOX_LAUNCHER)) { bundle.setSpecialConfigCommands("addProgramArg(programArg:-startup);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:-startup);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } else { bundle.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ bundle.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ } String filter = configSpec == null ? null : createFilterSpec(configSpec); IInstallableUnit cu = BundlesAction.createBundleConfigurationUnit(id, version, false, bundle, flavor, filter); if (cu != null) results.addIU(cu, IPublisherResult.ROOT); } }
diff --git a/jsf-ri/src/com/sun/faces/renderkit/html_basic/SelectManyCheckboxListRenderer.java b/jsf-ri/src/com/sun/faces/renderkit/html_basic/SelectManyCheckboxListRenderer.java index abc3b95d0..1162647aa 100644 --- a/jsf-ri/src/com/sun/faces/renderkit/html_basic/SelectManyCheckboxListRenderer.java +++ b/jsf-ri/src/com/sun/faces/renderkit/html_basic/SelectManyCheckboxListRenderer.java @@ -1,408 +1,409 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /** * $Id: SelectManyCheckboxListRenderer.java,v 1.62 2008/01/15 20:34:50 rlubke Exp $ * * (C) Copyright International Business Machines Corp., 2001,2002 * The source code for this program is not published or otherwise * divested of its trade secrets, irrespective of what has been * deposited with the U. S. Copyright Office. */ // SelectManyCheckboxListRenderer.java package com.sun.faces.renderkit.html_basic; import java.io.IOException; import java.util.Iterator; import javax.faces.component.UIComponent; import javax.faces.component.ValueHolder; import javax.faces.component.UINamingContainer; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.convert.Converter; import javax.faces.model.SelectItem; import javax.faces.model.SelectItemGroup; import com.sun.faces.renderkit.Attribute; import com.sun.faces.renderkit.AttributeManager; import com.sun.faces.renderkit.RenderKitUtils; import com.sun.faces.util.Util; import com.sun.faces.util.RequestStateManager; /** * <B>SelectManyCheckboxListRenderer</B> is a class that renders the * current value of <code>UISelectMany<code> component as a list of checkboxes. */ public class SelectManyCheckboxListRenderer extends MenuRenderer { private static final Attribute[] ATTRIBUTES = AttributeManager.getAttributes(AttributeManager.Key.SELECTMANYCHECKBOX); // ---------------------------------------------------------- Public Methods @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { rendererParamsNotNull(context, component); if (!shouldEncode(component)) { return; } ResponseWriter writer = context.getResponseWriter(); assert(writer != null); String alignStr; Object borderObj; boolean alignVertical = false; int border = 0; if (null != (alignStr = (String) component.getAttributes().get("layout"))) { alignVertical = alignStr.equalsIgnoreCase("pageDirection"); } if (null != (borderObj = component.getAttributes().get("border"))) { border = (Integer) borderObj; } Converter converter = null; if(component instanceof ValueHolder) { converter = ((ValueHolder)component).getConverter(); } renderBeginText(component, border, alignVertical, context, true); Iterator<SelectItem> items = RenderKitUtils.getSelectItems(context, component); Object currentSelections = getCurrentSelectedValues(component); Object[] submittedValues = getSubmittedSelectedValues(component); int idx = -1; while (items.hasNext()) { SelectItem curItem = items.next(); idx++; // If we come across a group of options, render them as a nested // table. if (curItem instanceof SelectItemGroup) { // write out the label for the group. if (curItem.getLabel() != null) { if (alignVertical) { writer.startElement("tr", component); } writer.startElement("td", component); writer.writeText(curItem.getLabel(), component, "label"); writer.endElement("td"); if (alignVertical) { writer.endElement("tr"); } } if (alignVertical) { writer.startElement("tr", component); } writer.startElement("td", component); writer.writeText("\n", component, null); renderBeginText(component, 0, alignVertical, context, false); // render options of this group. SelectItem[] itemsArray = ((SelectItemGroup) curItem).getSelectItems(); for (int i = 0; i < itemsArray.length; ++i) { renderOption(context, component, converter, itemsArray[i], currentSelections, submittedValues, alignVertical, i); } renderEndText(component, alignVertical, context); writer.endElement("td"); if (alignVertical) { writer.endElement("tr"); writer.writeText("\n", component, null); } } else { renderOption(context, component, converter, curItem, currentSelections, submittedValues, alignVertical, idx); } } renderEndText(component, alignVertical, context); } // ------------------------------------------------------- Protected Methods protected void renderBeginText(UIComponent component, int border, boolean alignVertical, FacesContext context, boolean outerTable) throws IOException { ResponseWriter writer = context.getResponseWriter(); assert(writer != null); writer.startElement("table", component); if (border != Integer.MIN_VALUE) { writer.writeAttribute("border", border, "border"); } // render style and styleclass attribute on the outer table instead of // rendering it as pass through attribute on every option in the list. if (outerTable) { // render "id" only for outerTable. if (shouldWriteIdAttribute(component)) { writeIdAttributeIfNecessary(context, writer, component); } String styleClass = (String) component.getAttributes().get( "styleClass"); String style = (String) component.getAttributes().get("style"); if (styleClass != null) { writer.writeAttribute("class", styleClass, "class"); } if (style != null) { writer.writeAttribute("style", style, "style"); } } writer.writeText("\n", component, null); if (!alignVertical) { writer.writeText("\t", component, null); writer.startElement("tr", component); writer.writeText("\n", component, null); } } protected void renderEndText(UIComponent component, boolean alignVertical, FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); assert(writer != null); if (!alignVertical) { writer.writeText("\t", component, null); writer.endElement("tr"); writer.writeText("\n", component, null); } writer.endElement("table"); } protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, boolean alignVertical, int itemNumber) throws IOException { ResponseWriter writer = context.getResponseWriter(); assert (writer != null); if (alignVertical) { writer.writeText("\t", component, null); writer.startElement("tr", component); writer.writeText("\n", component, null); } writer.startElement("td", component); writer.writeText("\n", component, null); writer.startElement("input", component); writer.writeAttribute("name", component.getClientId(context), "clientId"); String idString = component.getClientId(context) + UINamingContainer.getSeparatorChar(context) + Integer.toString(itemNumber); writer.writeAttribute("id", idString, "id"); String valueString = getFormattedValue(context, component, curItem.getValue(), converter); writer.writeAttribute("value", valueString, "value"); writer.writeAttribute("type", "checkbox", null); Object valuesArray; Object itemValue; if (submittedValues != null) { valuesArray = submittedValues; itemValue = valueString; } else { valuesArray = currentSelections; itemValue = curItem.getValue(); } RequestStateManager.set(context, RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME, component); if (isSelected(context, component, itemValue, valuesArray, converter)) { writer.writeAttribute(getSelectedTextString(), Boolean.TRUE, null); } // Don't render the disabled attribute twice if the 'parent' // component is already marked disabled. if (!Util.componentIsDisabled(component)) { if (curItem.isDisabled()) { writer.writeAttribute("disabled", true, "disabled"); } } // Apply HTML 4.x attributes specified on UISelectMany component to all // items in the list except styleClass and style which are rendered as // attributes of outer most table. RenderKitUtils.renderPassThruAttributes(context, writer, component, ATTRIBUTES, getNonOnChangeBehaviors(component)); RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, component); RenderKitUtils.renderOnchange(context, component); writer.endElement("input"); writer.startElement("label", component); writer.writeAttribute("for", idString, "for"); // disable the check box if the attribute is set. boolean componentDisabled = Util.componentIsDisabled(component); // Set up the label's class, if appropriate StringBuilder labelClass = new StringBuilder(); String style; // If disabledClass or enabledClass set, add it to the label's class if (componentDisabled || curItem.isDisabled()) { style = (String) component. getAttributes().get("disabledClass"); } else { // enabled style = (String) component. getAttributes().get("enabledClass"); } if (style != null) { labelClass.append(style); } // If selectedClass or unselectedClass set, add it to the label's class if (isSelected(context, component, itemValue, valuesArray, converter)) { style = (String) component. getAttributes().get("selectedClass"); } else { // not selected style = (String) component. getAttributes().get("unselectedClass"); } if (style != null) { if (labelClass.length() > 0) { labelClass.append(' '); } labelClass.append(style); } writer.writeAttribute("class", labelClass.toString(), "labelClass"); String itemLabel = curItem.getLabel(); - if (itemLabel != null) { - writer.writeText(" ", component, null); - if (!curItem.isEscape()) { - // It seems the ResponseWriter API should - // have a writeText() with a boolean property - // to determine if it content written should - // be escaped or not. - writer.write(itemLabel); - } else { - writer.writeText(itemLabel, component, "label"); - } + if (itemLabel == null) { + itemLabel = valueString; + } + writer.writeText(" ", component, null); + if (!curItem.isEscape()) { + // It seems the ResponseWriter API should + // have a writeText() with a boolean property + // to determine if it content written should + // be escaped or not. + writer.write(itemLabel); + } else { + writer.writeText(itemLabel, component, "label"); } if (isSelected(context, component, itemValue, valuesArray, converter)) { } else { // not selected } writer.endElement("label"); writer.endElement("td"); writer.writeText("\n", component, null); if (alignVertical) { writer.writeText("\t", component, null); writer.endElement("tr"); writer.writeText("\n", component, null); } } @Deprecated protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, boolean alignVertical, int itemNumber) throws IOException { renderOption(context, component, converter, curItem, getCurrentSelectedValues(component), getSubmittedSelectedValues(component), alignVertical, itemNumber); } // ------------------------------------------------- Package Private Methods String getSelectedTextString() { return "checked"; } } // end of class SelectManyCheckboxListRenderer
true
true
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, boolean alignVertical, int itemNumber) throws IOException { ResponseWriter writer = context.getResponseWriter(); assert (writer != null); if (alignVertical) { writer.writeText("\t", component, null); writer.startElement("tr", component); writer.writeText("\n", component, null); } writer.startElement("td", component); writer.writeText("\n", component, null); writer.startElement("input", component); writer.writeAttribute("name", component.getClientId(context), "clientId"); String idString = component.getClientId(context) + UINamingContainer.getSeparatorChar(context) + Integer.toString(itemNumber); writer.writeAttribute("id", idString, "id"); String valueString = getFormattedValue(context, component, curItem.getValue(), converter); writer.writeAttribute("value", valueString, "value"); writer.writeAttribute("type", "checkbox", null); Object valuesArray; Object itemValue; if (submittedValues != null) { valuesArray = submittedValues; itemValue = valueString; } else { valuesArray = currentSelections; itemValue = curItem.getValue(); } RequestStateManager.set(context, RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME, component); if (isSelected(context, component, itemValue, valuesArray, converter)) { writer.writeAttribute(getSelectedTextString(), Boolean.TRUE, null); } // Don't render the disabled attribute twice if the 'parent' // component is already marked disabled. if (!Util.componentIsDisabled(component)) { if (curItem.isDisabled()) { writer.writeAttribute("disabled", true, "disabled"); } } // Apply HTML 4.x attributes specified on UISelectMany component to all // items in the list except styleClass and style which are rendered as // attributes of outer most table. RenderKitUtils.renderPassThruAttributes(context, writer, component, ATTRIBUTES, getNonOnChangeBehaviors(component)); RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, component); RenderKitUtils.renderOnchange(context, component); writer.endElement("input"); writer.startElement("label", component); writer.writeAttribute("for", idString, "for"); // disable the check box if the attribute is set. boolean componentDisabled = Util.componentIsDisabled(component); // Set up the label's class, if appropriate StringBuilder labelClass = new StringBuilder(); String style; // If disabledClass or enabledClass set, add it to the label's class if (componentDisabled || curItem.isDisabled()) { style = (String) component. getAttributes().get("disabledClass"); } else { // enabled style = (String) component. getAttributes().get("enabledClass"); } if (style != null) { labelClass.append(style); } // If selectedClass or unselectedClass set, add it to the label's class if (isSelected(context, component, itemValue, valuesArray, converter)) { style = (String) component. getAttributes().get("selectedClass"); } else { // not selected style = (String) component. getAttributes().get("unselectedClass"); } if (style != null) { if (labelClass.length() > 0) { labelClass.append(' '); } labelClass.append(style); } writer.writeAttribute("class", labelClass.toString(), "labelClass"); String itemLabel = curItem.getLabel(); if (itemLabel != null) { writer.writeText(" ", component, null); if (!curItem.isEscape()) { // It seems the ResponseWriter API should // have a writeText() with a boolean property // to determine if it content written should // be escaped or not. writer.write(itemLabel); } else { writer.writeText(itemLabel, component, "label"); } } if (isSelected(context, component, itemValue, valuesArray, converter)) { } else { // not selected } writer.endElement("label"); writer.endElement("td"); writer.writeText("\n", component, null); if (alignVertical) { writer.writeText("\t", component, null); writer.endElement("tr"); writer.writeText("\n", component, null); } }
protected void renderOption(FacesContext context, UIComponent component, Converter converter, SelectItem curItem, Object currentSelections, Object[] submittedValues, boolean alignVertical, int itemNumber) throws IOException { ResponseWriter writer = context.getResponseWriter(); assert (writer != null); if (alignVertical) { writer.writeText("\t", component, null); writer.startElement("tr", component); writer.writeText("\n", component, null); } writer.startElement("td", component); writer.writeText("\n", component, null); writer.startElement("input", component); writer.writeAttribute("name", component.getClientId(context), "clientId"); String idString = component.getClientId(context) + UINamingContainer.getSeparatorChar(context) + Integer.toString(itemNumber); writer.writeAttribute("id", idString, "id"); String valueString = getFormattedValue(context, component, curItem.getValue(), converter); writer.writeAttribute("value", valueString, "value"); writer.writeAttribute("type", "checkbox", null); Object valuesArray; Object itemValue; if (submittedValues != null) { valuesArray = submittedValues; itemValue = valueString; } else { valuesArray = currentSelections; itemValue = curItem.getValue(); } RequestStateManager.set(context, RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME, component); if (isSelected(context, component, itemValue, valuesArray, converter)) { writer.writeAttribute(getSelectedTextString(), Boolean.TRUE, null); } // Don't render the disabled attribute twice if the 'parent' // component is already marked disabled. if (!Util.componentIsDisabled(component)) { if (curItem.isDisabled()) { writer.writeAttribute("disabled", true, "disabled"); } } // Apply HTML 4.x attributes specified on UISelectMany component to all // items in the list except styleClass and style which are rendered as // attributes of outer most table. RenderKitUtils.renderPassThruAttributes(context, writer, component, ATTRIBUTES, getNonOnChangeBehaviors(component)); RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer, component); RenderKitUtils.renderOnchange(context, component); writer.endElement("input"); writer.startElement("label", component); writer.writeAttribute("for", idString, "for"); // disable the check box if the attribute is set. boolean componentDisabled = Util.componentIsDisabled(component); // Set up the label's class, if appropriate StringBuilder labelClass = new StringBuilder(); String style; // If disabledClass or enabledClass set, add it to the label's class if (componentDisabled || curItem.isDisabled()) { style = (String) component. getAttributes().get("disabledClass"); } else { // enabled style = (String) component. getAttributes().get("enabledClass"); } if (style != null) { labelClass.append(style); } // If selectedClass or unselectedClass set, add it to the label's class if (isSelected(context, component, itemValue, valuesArray, converter)) { style = (String) component. getAttributes().get("selectedClass"); } else { // not selected style = (String) component. getAttributes().get("unselectedClass"); } if (style != null) { if (labelClass.length() > 0) { labelClass.append(' '); } labelClass.append(style); } writer.writeAttribute("class", labelClass.toString(), "labelClass"); String itemLabel = curItem.getLabel(); if (itemLabel == null) { itemLabel = valueString; } writer.writeText(" ", component, null); if (!curItem.isEscape()) { // It seems the ResponseWriter API should // have a writeText() with a boolean property // to determine if it content written should // be escaped or not. writer.write(itemLabel); } else { writer.writeText(itemLabel, component, "label"); } if (isSelected(context, component, itemValue, valuesArray, converter)) { } else { // not selected } writer.endElement("label"); writer.endElement("td"); writer.writeText("\n", component, null); if (alignVertical) { writer.writeText("\t", component, null); writer.endElement("tr"); writer.writeText("\n", component, null); } }
diff --git a/RecognitionWin.java b/RecognitionWin.java index e3e446b..edba164 100644 --- a/RecognitionWin.java +++ b/RecognitionWin.java @@ -1,57 +1,57 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JFrame; @SuppressWarnings("serial") public class RecognitionWin extends JFrame { private ImagesPanel imagesPanel; private JButton btnReset; private BufferedImage image; public RecognitionWin() { setTitle("Handwritten Digit Recognition"); setSize(710, 480); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setLayout(null); ImagesPanel imagesPanel = new ImagesPanel(); - JButton btnReset = new JButton("Reset"); + btnReset = new JButton("Reset"); btnReset.setBounds(565, 400, 100, 25); btnReset.setFocusPainted(false); btnReset.addActionListener(new ResetButtonListener()); getContentPane().add(btnReset); getContentPane().add(imagesPanel); } public void loadImage() { boolean[][] data = Shared.drawPanel.getData(); image = new BufferedImage(280, 280, BufferedImage.TYPE_BYTE_BINARY); for (int i = 0; i < data.length; i++) for (int j = 0; j < data[i].length; j++) { int color = (data[i][j])? -1 : -16777216; image.setRGB(i, j, color); } if (imagesPanel != null) imagesPanel.repaint(); } public BufferedImage getImage() { return image; } private class ResetButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { dispose(); Shared.drawWin = new DrawWin(); } } }
true
true
public RecognitionWin() { setTitle("Handwritten Digit Recognition"); setSize(710, 480); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setLayout(null); ImagesPanel imagesPanel = new ImagesPanel(); JButton btnReset = new JButton("Reset"); btnReset.setBounds(565, 400, 100, 25); btnReset.setFocusPainted(false); btnReset.addActionListener(new ResetButtonListener()); getContentPane().add(btnReset); getContentPane().add(imagesPanel); }
public RecognitionWin() { setTitle("Handwritten Digit Recognition"); setSize(710, 480); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setLayout(null); ImagesPanel imagesPanel = new ImagesPanel(); btnReset = new JButton("Reset"); btnReset.setBounds(565, 400, 100, 25); btnReset.setFocusPainted(false); btnReset.addActionListener(new ResetButtonListener()); getContentPane().add(btnReset); getContentPane().add(imagesPanel); }
diff --git a/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/EditStoryActivity.java b/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/EditStoryActivity.java index 91f76fc..3361746 100644 --- a/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/EditStoryActivity.java +++ b/src/ca/ualberta/CMPUT301F13T02/chooseyouradventure/EditStoryActivity.java @@ -1,353 +1,354 @@ /* * Copyright (c) 2013, TeamCMPUT301F13T02 * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the {organization} nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ca.ualberta.CMPUT301F13T02.chooseyouradventure; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; /** * This Activity allows a story's author to edit a story by adding adding pages, * deleting pages, setting the first page, or deleting the story. * * This class is part of the view of the application. * * TODO Delete functionality not yet hooked up */ public class EditStoryActivity extends Activity { private ListView treePage; private Button createNew2; private Button deleteStory; private ArrayList<String> pageText = new ArrayList<String>(); private ArrayList<Page> pageList = new ArrayList<Page>(); private ArrayAdapter<String> adapter; private ControllerApp app; private static final int HELP_INDEX = 0; /** * This binds the buttons the the views to this activity * and sets the appropriate onclick listeners */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_story_activity); treePage = (ListView) findViewById(R.id.treeView); createNew2 = (Button) findViewById(R.id.createButton2); deleteStory = (Button) findViewById(R.id.deleteButton); createNew2.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { createPage(); } catch (HandlerException e) { // TODO Auto-generated catch block e.printStackTrace(); } adapter.notifyDataSetChanged(); } }); deleteStory.setOnClickListener(new OnClickListener() { public void onClick(View v) { //deleteCurrentStory(); } }); app = (ControllerApp) getApplication(); pageList = app.getStory().getPages(); pageText = app.updateView(pageList, pageText); /** * Activity to restructure Click and longClick listeners to work in a list view * directly based on http://android.konreu.com/developer-how-to/click-long-press-event-listeners-list-activity/ */ treePage.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> av, View v, int pos, long listNum) { onListItemClick(v,pos,listNum); } }); adapter = new ArrayAdapter<String>(this, R.layout.list_item_base, pageText); treePage.setAdapter(adapter); } @Override public void onStart() { super.onStart(); refresh(); } /** * Inflate the options menu; this adds items to the action bar if it is present * * @param menu The menu to inflate * @return Success */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem help = menu.add(0, HELP_INDEX, HELP_INDEX, "Help"); help.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); return true; } /** * Callback for clicking an item in the menu. * * @param item The item that was clicked * @return Success */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case HELP_INDEX: ScrollView scrollView = new ScrollView(this); WebView view = new WebView(this); view.loadData(getString(R.string.edit_story_help), "text/html", "UTF-8"); scrollView.addView(view); scrollView.setPadding(10, 10, 10, 10); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.help); builder.setPositiveButton(R.string.ok, null); builder.setView(scrollView); builder.show(); break; } return true; } /** * Click listener for the list of pages. It simply calls pageOptions * and passes it the position of the selected page. * @param v * @param pos * @param id */ protected void onListItemClick(View v, int pos, long id) { pageOptions(pos); } /** * This creates a page * @throws HandlerException */ private void createPage() throws HandlerException{ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Create New"); final LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); final EditText alertEdit = new EditText(this); layout.addView(alertEdit); final EditText alertEdit3 = new EditText(this); final CheckBox check = new CheckBox(this); final EditText alertEdit2 = new EditText(this); if(app.getStory().isUsesCombat()){ final TextView alertText = new TextView(this); alertText.setText("Fighting Fragment?"); layout.addView(alertText); layout.addView(check); final TextView alertText2 = new TextView(this); alertText2.setText("Health of the Enemy on this Page?"); layout.addView(alertText2); alertEdit2.setText("0"); layout.addView(alertEdit2); final TextView alertText3 = new TextView(this); alertText3.setText("Name of the Enemy on this Page?"); layout.addView(alertText3); alertEdit3.setText("Enemy"); layout.addView(alertEdit3); } builder.setView(layout); builder.setMessage("Enter the title of your new page") .setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String pageTitle = alertEdit.getText().toString(); app.updateTitle(pageTitle, check.isChecked(), alertEdit2.getText().toString(), alertEdit3.getText().toString()); refresh(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } /** * This shows the user a list of options on a story * @param Input from longclick */ public void pageOptions(final int pos){ - final Page currentPage = pageList.get(pos); + final Page currentPage = app.getStory().getPages().get(pos); final Page FP = app.getStory().getFirstpage(); String[] titlesA = {"Goto/Edit","Page Properties","Cancel"}; String[] titlesB = {"Goto/Edit","Page Properties","Assign as First Page","Delete","Cancel"}; final String[] titles; if(currentPage == FP){titles = titlesA;} else{titles = titlesB;} AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder titleEditor = new AlertDialog.Builder(this); final EditText alertEdit = new EditText(this); final EditText alertEdit3 = new EditText(this); final CheckBox check = new CheckBox(this); final EditText alertEdit2 = new EditText(this); final LinearLayout layout = new LinearLayout(this); final TextView alertText2 = new TextView(this); final TextView alertText = new TextView(this); final TextView alertText3 = new TextView(this); builder.setTitle(R.string.page_options); builder.setItems(titles, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch(item){ case(0): app.setEditing(true); app.jump(ViewPageActivity.class,app.getStory(),app.getStory().getPages().get(pos)); break; case(1): titleEditor.setTitle("Create New"); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(alertEdit); if(app.getStory().isUsesCombat()){ alertText.setText("Fighting Fragment?"); layout.addView(alertText); + check.setChecked(currentPage.isFightingFrag()); layout.addView(check); alertText2.setText("Health of the Enemy on this Page?"); layout.addView(alertText2); - alertEdit2.setText("0"); + alertEdit2.setText("" + currentPage.getEnemyHealth()); layout.addView(alertEdit2); alertText3.setText("Name of the Enemy on this Page?"); layout.addView(alertText3); - alertEdit3.setText("Enemy"); + alertEdit3.setText("" + currentPage.getEnemyName()); layout.addView(alertEdit3); } titleEditor.setView(layout); titleEditor.setMessage("Enter the title of your new page") .setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String pageTitle = alertEdit.getText().toString(); app.updateTitle(pageTitle, currentPage); refresh(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); titleEditor.show(); break; case(2): app.updateFP(currentPage); refresh(); break; case(3): app.removePage(currentPage); refresh(); break; } } }); builder.show(); } /** * This rebuilds the ListView by recollecting data from the controller */ public void refresh(){ pageList = app.getStory().getPages(); pageText = app.updateView(pageList, pageText); adapter.notifyDataSetChanged(); } }
false
true
public void pageOptions(final int pos){ final Page currentPage = pageList.get(pos); final Page FP = app.getStory().getFirstpage(); String[] titlesA = {"Goto/Edit","Page Properties","Cancel"}; String[] titlesB = {"Goto/Edit","Page Properties","Assign as First Page","Delete","Cancel"}; final String[] titles; if(currentPage == FP){titles = titlesA;} else{titles = titlesB;} AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder titleEditor = new AlertDialog.Builder(this); final EditText alertEdit = new EditText(this); final EditText alertEdit3 = new EditText(this); final CheckBox check = new CheckBox(this); final EditText alertEdit2 = new EditText(this); final LinearLayout layout = new LinearLayout(this); final TextView alertText2 = new TextView(this); final TextView alertText = new TextView(this); final TextView alertText3 = new TextView(this); builder.setTitle(R.string.page_options); builder.setItems(titles, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch(item){ case(0): app.setEditing(true); app.jump(ViewPageActivity.class,app.getStory(),app.getStory().getPages().get(pos)); break; case(1): titleEditor.setTitle("Create New"); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(alertEdit); if(app.getStory().isUsesCombat()){ alertText.setText("Fighting Fragment?"); layout.addView(alertText); layout.addView(check); alertText2.setText("Health of the Enemy on this Page?"); layout.addView(alertText2); alertEdit2.setText("0"); layout.addView(alertEdit2); alertText3.setText("Name of the Enemy on this Page?"); layout.addView(alertText3); alertEdit3.setText("Enemy"); layout.addView(alertEdit3); } titleEditor.setView(layout); titleEditor.setMessage("Enter the title of your new page") .setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String pageTitle = alertEdit.getText().toString(); app.updateTitle(pageTitle, currentPage); refresh(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); titleEditor.show(); break; case(2): app.updateFP(currentPage); refresh(); break; case(3): app.removePage(currentPage); refresh(); break; } } }); builder.show(); }
public void pageOptions(final int pos){ final Page currentPage = app.getStory().getPages().get(pos); final Page FP = app.getStory().getFirstpage(); String[] titlesA = {"Goto/Edit","Page Properties","Cancel"}; String[] titlesB = {"Goto/Edit","Page Properties","Assign as First Page","Delete","Cancel"}; final String[] titles; if(currentPage == FP){titles = titlesA;} else{titles = titlesB;} AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder titleEditor = new AlertDialog.Builder(this); final EditText alertEdit = new EditText(this); final EditText alertEdit3 = new EditText(this); final CheckBox check = new CheckBox(this); final EditText alertEdit2 = new EditText(this); final LinearLayout layout = new LinearLayout(this); final TextView alertText2 = new TextView(this); final TextView alertText = new TextView(this); final TextView alertText3 = new TextView(this); builder.setTitle(R.string.page_options); builder.setItems(titles, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch(item){ case(0): app.setEditing(true); app.jump(ViewPageActivity.class,app.getStory(),app.getStory().getPages().get(pos)); break; case(1): titleEditor.setTitle("Create New"); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(alertEdit); if(app.getStory().isUsesCombat()){ alertText.setText("Fighting Fragment?"); layout.addView(alertText); check.setChecked(currentPage.isFightingFrag()); layout.addView(check); alertText2.setText("Health of the Enemy on this Page?"); layout.addView(alertText2); alertEdit2.setText("" + currentPage.getEnemyHealth()); layout.addView(alertEdit2); alertText3.setText("Name of the Enemy on this Page?"); layout.addView(alertText3); alertEdit3.setText("" + currentPage.getEnemyName()); layout.addView(alertEdit3); } titleEditor.setView(layout); titleEditor.setMessage("Enter the title of your new page") .setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String pageTitle = alertEdit.getText().toString(); app.updateTitle(pageTitle, currentPage); refresh(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); titleEditor.show(); break; case(2): app.updateFP(currentPage); refresh(); break; case(3): app.removePage(currentPage); refresh(); break; } } }); builder.show(); }
diff --git a/src/util/Camera.java b/src/util/Camera.java index b50298b..0bf3e2a 100644 --- a/src/util/Camera.java +++ b/src/util/Camera.java @@ -1,340 +1,337 @@ package util; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import util.math.MathUtils; import util.math.Quaternion; public class Camera { private Vector3f centerPosition = new Vector3f(0f, 0f, -1f); // world space coordinates. private Vector3f eyePosition = new Vector3f(0f, 0f, 0f); // world space coordinates. // Orientation of camera axes. private Quaternion orientation = new Quaternion(0f, 0f, 0f, 1f); // Identity. // Standard reference axes. public static final Vector3f X_AXIS = new Vector3f(1f, 0f, 0f); public static final Vector3f Y_AXIS = new Vector3f(0f, 1f, 0f); public static final Vector3f Z_AXIS = new Vector3f(0f, 0f, 1f); private Vector3f l = new Vector3f(-1f, 0f, 0f); // left local camera vector. private Vector3f f = new Vector3f(0f, 0f, -1f); // forward local camera vector. private Vector3f u = new Vector3f(0f, 1f, 0f); // up local camera vector. // -------------------------------------------------------------------------- public void setPosition(float x, float y, float z) { eyePosition.x = x; eyePosition.y = y; eyePosition.z = z; } // -------------------------------------------------------------------------- public void setPosition(Vector3f position) { setPosition(position.x, position.y, position.z); } // -------------------------------------------------------------------------- /** * Translates the Camera using world space axes. * * @param x - movement magnitude along world space x-axis. * @param y - movement magnitude along world space y-axis. * @param z - movement magnitude along world space z-axis. */ public void translate(float x, float y, float z) { eyePosition.x += x; eyePosition.y += y; eyePosition.z += z; } /** * Translates the Camera using world space axes. * * @param vec - Vector with movement magnitudes along world space x, y, and * z axes. */ // -------------------------------------------------------------------------- public void translate(Vector3f vec) { translate(vec.x, vec.y, vec.z); } // -------------------------------------------------------------------------- /** * Translates the camera relative to itself. * * @param left - translation distance along camera's local left-direction. * @param up - translation distance along camera's local up-direction. * @param forward - translation distance along camera's local forward-direction. */ public void translateRelative(float left, float up, float forward) { eyePosition.x += (left * l.x) + (up * u.x) + (forward * f.x); eyePosition.y += (left * l.y) + (up * u.y) + (forward * f.y); eyePosition.z += (left * l.z) + (up * u.z) + (forward * f.z); } // -------------------------------------------------------------------------- public void translateRelative(Vector3f vec) { translateRelative(vec.x, vec.y, vec.z); } // -------------------------------------------------------------------------- /** * @return a new {@link Vector3f} representing the current eye position of * the Camera. */ public Vector3f getPosition() { return new Vector3f(eyePosition.x, eyePosition.y, eyePosition.z); } // -------------------------------------------------------------------------- /** * Places the camera world position coordinates into dest. */ public void getPosition(Vector3f dest) { dest.x = eyePosition.x; dest.y = eyePosition.y; dest.z = eyePosition.z; } // -------------------------------------------------------------------------- /** * Position the camera at (eyeX, eyeY, eyeZ) in world space, so that it is * facing the point (centerX, centerY, centerZ) in the center of its view, * and with up vector given by (upX, upY, upZ). * * @param eyeX * @param eyeY * @param eyeZ * @param centerX * @param centerY * @param centerZ * @param upX * @param upY * @param upZ */ public void lookAt(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { centerPosition.x = centerX; centerPosition.y = centerY; centerPosition.z = centerZ; eyePosition.x = eyeX; eyePosition.y = eyeY; eyePosition.z = eyeZ; // f = centerPosition - eyePosition. Vector3f.sub(centerPosition, eyePosition, f); // Do nothing if centerPosition ~= eyePostion. if (f.length() <= MathUtils.EPSILON) return; f.normalise(); u.x = upX; u.y = upY; u.z = upZ; // l = u x f Vector3f.cross(u, f, l); l.normalise(); // u = f x l Vector3f.cross(f, l, u); // Flip f so it points along camera's local z-axis. f.scale(-1f); // Flip l so it points along camera's local x-axis. l.scale(-1f); // Construct orientation from the basis vectors s, u, f. orientation.fromAxes(l, u, f); // Reset camera's f and l vectors. f.scale(-1f); l.scale(-1f); } // -------------------------------------------------------------------------- /** * Position the Camera at <code>eyePos</code> in world space, so that it is * facing with the point <code>centerPos</code> in the center of its view, * and with up direction given by <code>upDir</code>. * * @param eyePos - world space position of Camera. * @param centerPos - world space target the Camera is pointed at. * @param upDir - world space up direction for Camera. */ public void lookAt(Vector3f eyePos, Vector3f centerPos, Vector3f upDir) { lookAt(eyePos.x, eyePos.y, eyePos.z, centerPos.x, centerPos.y, centerPos.z, upDir.x, upDir.y, upDir.z); } // -------------------------------------------------------------------------- public void lookAt(float centerX, float centerY, float centerZ) { centerPosition.x = centerX; centerPosition.y = centerY; centerPosition.z = centerZ; // f = center - eye. Vector3f.sub(centerPosition, eyePosition, f); // If center ~= eyePosition, do nothing. if (f.lengthSquared() <= MathUtils.EPSILON) return; f.normalise(); // The following projects u onto the plane defined by the point eyePosition, // and the normal f. The goal is to rotate u so that it is orthogonal to f, // while attempting to keep u's orientation close to its previous direction. { // Borrow l vector for calculation, so we don't have to allocate a // new vector. // l = eye + u Vector3f.add(eyePosition, u, l); - // t = f dot u - float t = Vector3f.dot(f, u); + // t = -1 * (f dot u) + float t = -1f * Vector3f.dot(f, u); // Move point l in the normal direction, f, by t units so that it is // on the plane. - if (t < 0) { - t *= -1; - } l.x += t * f.x; l.y += t * f.y; l.z += t * f.z; // u = l - eye. Vector3f.sub(l, eyePosition, u); u.normalise(); } // Update l vector given new f and u vectors. // l = u x f Vector3f.cross(u, f, l); // If f and u are no longer orthogonal, make them so. if (Vector3f.dot(f, u) > MathUtils.EPSILON) { // u = f x l Vector3f.cross(f, l, u); u.normalise(); } // Flip f so it points along camera's local z-axis. f.scale(-1f); // Flip l so it points along camera's local x-axis. l.scale(-1f); // Construct orientation from the basis vectors l, u, f, which make up the // camera's local right handed coordinate system. orientation.fromAxes(l, u, f); // Reset camera's f and l vectors, so f points forward, and l points to the // left, as seen by the camera. f.scale(-1f); l.scale(-1f); } // -------------------------------------------------------------------------- public void lookAt(Vector3f centerPos) { lookAt(centerPos.x, centerPos.y, centerPos.z); } // -------------------------------------------------------------------------- public void rotate(Vector3f axis, float angle) { Quaternion p = new Quaternion(axis, angle); Quaternion.mult(p, orientation, orientation); orientation.normalize(); } // -------------------------------------------------------------------------- public void roll(float angle) { Vector3f localZAxis = new Vector3f(Z_AXIS); orientation.rotate(localZAxis); Quaternion q = new Quaternion(localZAxis, angle); // Update camera's local left and up vectors. q.rotate(l); q.rotate(u); // orientation = q * orientation. Quaternion.mult(q, orientation, orientation); } // -------------------------------------------------------------------------- public void pitch(float angle) { Vector3f localXAxis = new Vector3f(X_AXIS); orientation.rotate(localXAxis); Quaternion q = new Quaternion(localXAxis, angle); // Update camera's local up and forward vectors. q.rotate(u); q.rotate(f); // orientation = q * orientation. Quaternion.mult(q, orientation, orientation); } // -------------------------------------------------------------------------- public void yaw(float angle) { Vector3f localYAxis = new Vector3f(Y_AXIS); orientation.rotate(localYAxis); Quaternion q = new Quaternion(localYAxis, angle); // Update camera's local left and forward vectors. q.rotate(l); q.rotate(f); // orientation = q * orientation. Quaternion.mult(q, orientation, orientation); } // -------------------------------------------------------------------------- /** * Gets a new {@link Matrix4f} view matrix representation for this Camera. * In OpenGL parlance the view matrix transforms points from World Space to * Camera Space. * * @return a new view matrix */ public Matrix4f getViewMatrix() { orientation.normalize(); // Each column of the viewMatrix describes a camera basis vector using // world space coordinates. // // | s_x | u_x | f_x | 0 | // | s_y | u_y | f_y | 0 | // | s_z | u_z | f_z | 0 | // | 0 | 0 | 0 | 1 | Matrix4f viewMatrix = orientation.toRotationMatrix(); // Transpose the viewMatrix so that each column describes a world space // basis vector using camera space coordinates. // // | s_x | s_y | s_z | 0 | // | u_x | u_y | u_z | 0 | // | f_x | f_y | f_z | 0 | // | 0 | 0 | 0 | 1 | viewMatrix.transpose(); // Apply inverse translation from world space origin to // the camera's eye position. Vector3f dist = new Vector3f(); dist.x = (-1) * eyePosition.x; dist.y = (-1) * eyePosition.y; dist.z = (-1) * eyePosition.z; viewMatrix.translate(dist); return viewMatrix; } }
false
true
public void lookAt(float centerX, float centerY, float centerZ) { centerPosition.x = centerX; centerPosition.y = centerY; centerPosition.z = centerZ; // f = center - eye. Vector3f.sub(centerPosition, eyePosition, f); // If center ~= eyePosition, do nothing. if (f.lengthSquared() <= MathUtils.EPSILON) return; f.normalise(); // The following projects u onto the plane defined by the point eyePosition, // and the normal f. The goal is to rotate u so that it is orthogonal to f, // while attempting to keep u's orientation close to its previous direction. { // Borrow l vector for calculation, so we don't have to allocate a // new vector. // l = eye + u Vector3f.add(eyePosition, u, l); // t = f dot u float t = Vector3f.dot(f, u); // Move point l in the normal direction, f, by t units so that it is // on the plane. if (t < 0) { t *= -1; } l.x += t * f.x; l.y += t * f.y; l.z += t * f.z; // u = l - eye. Vector3f.sub(l, eyePosition, u); u.normalise(); } // Update l vector given new f and u vectors. // l = u x f Vector3f.cross(u, f, l); // If f and u are no longer orthogonal, make them so. if (Vector3f.dot(f, u) > MathUtils.EPSILON) { // u = f x l Vector3f.cross(f, l, u); u.normalise(); } // Flip f so it points along camera's local z-axis. f.scale(-1f); // Flip l so it points along camera's local x-axis. l.scale(-1f); // Construct orientation from the basis vectors l, u, f, which make up the // camera's local right handed coordinate system. orientation.fromAxes(l, u, f); // Reset camera's f and l vectors, so f points forward, and l points to the // left, as seen by the camera. f.scale(-1f); l.scale(-1f); }
public void lookAt(float centerX, float centerY, float centerZ) { centerPosition.x = centerX; centerPosition.y = centerY; centerPosition.z = centerZ; // f = center - eye. Vector3f.sub(centerPosition, eyePosition, f); // If center ~= eyePosition, do nothing. if (f.lengthSquared() <= MathUtils.EPSILON) return; f.normalise(); // The following projects u onto the plane defined by the point eyePosition, // and the normal f. The goal is to rotate u so that it is orthogonal to f, // while attempting to keep u's orientation close to its previous direction. { // Borrow l vector for calculation, so we don't have to allocate a // new vector. // l = eye + u Vector3f.add(eyePosition, u, l); // t = -1 * (f dot u) float t = -1f * Vector3f.dot(f, u); // Move point l in the normal direction, f, by t units so that it is // on the plane. l.x += t * f.x; l.y += t * f.y; l.z += t * f.z; // u = l - eye. Vector3f.sub(l, eyePosition, u); u.normalise(); } // Update l vector given new f and u vectors. // l = u x f Vector3f.cross(u, f, l); // If f and u are no longer orthogonal, make them so. if (Vector3f.dot(f, u) > MathUtils.EPSILON) { // u = f x l Vector3f.cross(f, l, u); u.normalise(); } // Flip f so it points along camera's local z-axis. f.scale(-1f); // Flip l so it points along camera's local x-axis. l.scale(-1f); // Construct orientation from the basis vectors l, u, f, which make up the // camera's local right handed coordinate system. orientation.fromAxes(l, u, f); // Reset camera's f and l vectors, so f points forward, and l points to the // left, as seen by the camera. f.scale(-1f); l.scale(-1f); }
diff --git a/src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/BaseDao.java b/src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/BaseDao.java index 39ac803fb..87b5106ba 100644 --- a/src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/BaseDao.java +++ b/src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/BaseDao.java @@ -1,90 +1,92 @@ /******************************************************************************* * * Copyright 2012 Impetus Infotech. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. ******************************************************************************/ package com.impetus.kundera.tests.crossdatastore.useraddress.dao; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import com.impetus.client.cassandra.common.CassandraConstants; public class BaseDao { EntityManagerFactory emf; EntityManager em; public EntityManager getEntityManager(String pu, Map propertyMap) { if (emf == null) { if (propertyMap.isEmpty()) { propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0); } Map mapOfExternalProperties = new HashMap<String, Map>(); mapOfExternalProperties.put("addCassandra", propertyMap); + mapOfExternalProperties.put("piccandra", propertyMap); + mapOfExternalProperties.put("secIdxAddCassandra", propertyMap); emf = Persistence.createEntityManagerFactory(pu, mapOfExternalProperties); em = emf.createEntityManager(); } if (em == null) { em = emf.createEntityManager(); } return em; } public EntityManager getEntityManager(String pu) { if (emf == null) { emf = Persistence.createEntityManagerFactory(pu, new HashMap()); em = emf.createEntityManager(); } if (em == null) { em = emf.createEntityManager(); } return em; } public void closeEntityManager() { if (em != null) { em.close(); em = null; } } public void closeEntityManagerFactory() { if (emf != null) { emf.close(); } emf = null; } }
true
true
public EntityManager getEntityManager(String pu, Map propertyMap) { if (emf == null) { if (propertyMap.isEmpty()) { propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0); } Map mapOfExternalProperties = new HashMap<String, Map>(); mapOfExternalProperties.put("addCassandra", propertyMap); emf = Persistence.createEntityManagerFactory(pu, mapOfExternalProperties); em = emf.createEntityManager(); } if (em == null) { em = emf.createEntityManager(); } return em; }
public EntityManager getEntityManager(String pu, Map propertyMap) { if (emf == null) { if (propertyMap.isEmpty()) { propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0); } Map mapOfExternalProperties = new HashMap<String, Map>(); mapOfExternalProperties.put("addCassandra", propertyMap); mapOfExternalProperties.put("piccandra", propertyMap); mapOfExternalProperties.put("secIdxAddCassandra", propertyMap); emf = Persistence.createEntityManagerFactory(pu, mapOfExternalProperties); em = emf.createEntityManager(); } if (em == null) { em = emf.createEntityManager(); } return em; }
diff --git a/src/test/net/sf/clirr/checks/AbstractCheckTestCase.java b/src/test/net/sf/clirr/checks/AbstractCheckTestCase.java index 4dc9fd0..190a62b 100644 --- a/src/test/net/sf/clirr/checks/AbstractCheckTestCase.java +++ b/src/test/net/sf/clirr/checks/AbstractCheckTestCase.java @@ -1,94 +1,88 @@ package net.sf.clirr.checks; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import junit.framework.TestCase; import net.sf.clirr.Checker; import net.sf.clirr.CheckerFactory; import net.sf.clirr.event.ApiDifference; import net.sf.clirr.framework.ClassChangeCheck; import net.sf.clirr.framework.ClassSelector; import org.apache.bcel.util.ClassSet; /** * Abstract Baseclass to test individual Checks. * @author lkuehne */ public abstract class AbstractCheckTestCase extends TestCase { protected final File getTestInputDir() { // property is set in project.properties return new File(System.getProperty("testinput")); } protected void verify( Checker checker, ClassSet baseline, ClassSet current, ApiDifference[] expected) { } protected File[] getBaseLine() { return new File[]{ new File(getTestInputDir(), "testlib-v1.jar") }; } protected File[] getCurrent() { return new File[]{ new File(getTestInputDir(), "testlib-v2.jar") }; } protected void verify(ApiDifference[] expected) + throws Exception { TestDiffListener tdl = new TestDiffListener(); Checker checker = CheckerFactory.createChecker(createCheck(tdl)); ClassSelector classSelector = createClassSelector(); - try - { - checker.reportDiffs( - getBaseLine(), getCurrent(), - new URLClassLoader(new URL[]{}), - new URLClassLoader(new URL[]{}), - classSelector); - } - catch(Exception ex) - { - fail("Exception generated:" + ex.getMessage()); - } + checker.reportDiffs( + getBaseLine(), getCurrent(), + new URLClassLoader(new URL[]{}), + new URLClassLoader(new URL[]{}), + classSelector); tdl.checkExpected(expected); } /** * Creates an object which selects the appropriate classes from the * test jars for this test. * <p> * This base implementation returns a selector which selects all classes * in the base "testlib" package (but no sub-packages). Tests which wish * to select different classes from the test jars should override this * method. */ protected ClassSelector createClassSelector() { // only check classes in the base "testlib" package of the jars ClassSelector classSelector = new ClassSelector(ClassSelector.MODE_IF); classSelector.addPackage("testlib"); return classSelector; } /** * Creates a check and sets it up so ApiDifferences are reported to the test diff listener. * * @param tdl the test diff listener that records the recognized api changes. * @return the confiured check */ protected abstract ClassChangeCheck createCheck(TestDiffListener tdl); }
false
true
protected void verify(ApiDifference[] expected) { TestDiffListener tdl = new TestDiffListener(); Checker checker = CheckerFactory.createChecker(createCheck(tdl)); ClassSelector classSelector = createClassSelector(); try { checker.reportDiffs( getBaseLine(), getCurrent(), new URLClassLoader(new URL[]{}), new URLClassLoader(new URL[]{}), classSelector); } catch(Exception ex) { fail("Exception generated:" + ex.getMessage()); } tdl.checkExpected(expected); }
protected void verify(ApiDifference[] expected) throws Exception { TestDiffListener tdl = new TestDiffListener(); Checker checker = CheckerFactory.createChecker(createCheck(tdl)); ClassSelector classSelector = createClassSelector(); checker.reportDiffs( getBaseLine(), getCurrent(), new URLClassLoader(new URL[]{}), new URLClassLoader(new URL[]{}), classSelector); tdl.checkExpected(expected); }
diff --git a/apps/lifelinesresearchportal/org/molgenis/lifelinesresearchportal/plugins/plinkdownload/PlinkDownload.java b/apps/lifelinesresearchportal/org/molgenis/lifelinesresearchportal/plugins/plinkdownload/PlinkDownload.java index f26e6f7f7..0368ac8c8 100644 --- a/apps/lifelinesresearchportal/org/molgenis/lifelinesresearchportal/plugins/plinkdownload/PlinkDownload.java +++ b/apps/lifelinesresearchportal/org/molgenis/lifelinesresearchportal/plugins/plinkdownload/PlinkDownload.java @@ -1,226 +1,226 @@ /* * Date: December 24, 2010 Template: PluginScreenJavaTemplateGen.java.ftl * generator: org.molgenis.generators.ui.PluginScreenJavaTemplateGen 3.3.3 * * THIS FILE IS A TEMPLATE. PLEASE EDIT :-) */ package org.molgenis.lifelinesresearchportal.plugins.plinkdownload; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.molgenis.framework.db.Database; import org.molgenis.framework.ui.EasyPluginController; import org.molgenis.framework.ui.ScreenController; import org.molgenis.framework.ui.ScreenView; import org.molgenis.framework.ui.html.ActionInput; import org.molgenis.framework.ui.html.DivPanel; import org.molgenis.framework.ui.html.Paragraph; import org.molgenis.framework.ui.html.VerticalLayout; import org.molgenis.pheno.Measurement; import org.molgenis.util.Tuple; import org.molgenis.util.plink.datatypes.FamEntry; import org.molgenis.util.plink.writers.FamFileWriter; public class PlinkDownload extends EasyPluginController { private static final long serialVersionUID = -4185405160313262242L; public PlinkDownload(String name, ScreenController<?> parent) { super(name, parent); } private DivPanel mainPanel = null; private DivPanel downloadPanel = null; // private AbstractRefInput<Measurement> measurements; private ActionInput genPlink; @Override public void reload(Database db) { try { if (mainPanel == null) { mainPanel = new DivPanel(); Paragraph manual = new Paragraph( "<strong>Here you can generate PLINK files " + "for your GWAS analyses</strong><br /><br />After choosing a phenotype, two text files " + "will be ready for you on Target GPFS storage: one (TPED) containing SNP and genotype information where " + "one row is a SNP; one (TFAM) containing individual and family information, " + "where one row is an individual.<br />The first 4 columns of a TPED file are " + "the same as a standard 4-column MAP file. Then all genotypes are listed for " + "all individuals for each particular SNP on each line. The TFAM file is just " + "the first six columns of a standard PED file. In other words, we have just " + "taken the standard PED/MAP file format, but swapped all the genotype " + "information between files, after rotating it 90 degrees.<br />Read more on the " + "<a href='http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml' target='_blank'>" + "PLINK documentation website</a>."); // final Builder<Measurement> xrefInputBuilder = // new XrefInput.Builder<Measurement>(Measurement.NAME, // Measurement.class); // final List<QueryRule> queryRules = Arrays.asList( // new QueryRule(Measurement.DATATYPE, Operator.LIKE, // "NUMBER%")); // xrefInputBuilder.setFilters(queryRules); // // //create xrefInput // measurements = xrefInputBuilder.build(); // measurements.setLabel("Select your phenotype:"); // genPlink = new ActionInput("genPlink", "", "Generate"); // // mainPanel.add(manual); // mainPanel.add(measurements); // mainPanel.add(genPlink); } } catch (Exception e) { this.setError("Something went wrong while loading the page: " + e.getMessage()); e.printStackTrace(); } } @Override public ScreenView getView() { VerticalLayout view = new VerticalLayout(); if (downloadPanel != null) { view.add(downloadPanel); } view.add(mainPanel); return view; } @Override public void handleRequest(Database db, Tuple request) { String action = request.getAction(); if (action.equals("genPlink")) { // Get selected phenotype int measurementId = -1;// request.getInt(measurements.getName()); Measurement meas; try { meas = db.findById(Measurement.class, measurementId); } catch (Exception e) { this.setError("Something went wrong while finding your phenotype: " + e.getMessage()); e.printStackTrace(); return; } // Get measurement for sex int sexMeasId; try { sexMeasId = db.query(Measurement.class).eq(Measurement.NAME, "GESLACHT").find().get(0).getId(); } catch (Exception e) { this.setError("Something went wrong while finding the Sex(GESLACHT) phenotype: " + e.getMessage()); e.printStackTrace(); return; } // PLEASE NOTE THAT YOU MUST CALL IT A TFAM FILE // because it belongs to a transposed PED (--->TPED) file // while TFAM format is equivalent to FAM format.. // info: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml File tmpDir = new File(System.getProperty("java.io.tmpdir")); File famExport = new File(tmpDir.getAbsolutePath() + File.separatorChar + meas.getName() + "_" + System.nanoTime() + ".tfam"); FamFileWriter ffw; try { ffw = new FamFileWriter(famExport); } catch (Exception e) { this.setError("Something went wrong while initializing the TFAM file writer: " + e.getMessage()); e.printStackTrace(); return; } List<FamEntry> entries = new ArrayList<FamEntry>(); List<Object[]> parts; try { @SuppressWarnings( { "deprecation", "rawtypes", "unchecked" }) List<Object[]> parts2 = db .getEntityManager() .createQuery( "SELECT ov.target.name, " + "MAX ( CASE WHEN (ov.feature.id = :sexId) THEN ov.value ELSE null END ), " + "MAX ( CASE WHEN (ov.feature.id = :mesId) THEN ov.value ELSE null END ) " + "FROM ObservedValue ov WHERE ov.feature = :sexId OR ov.feature = :mesId GROUP BY ov.target.name") .setParameter("sexId", sexMeasId).setParameter("mesId", measurementId).getResultList(); parts = parts2; // strange! // parts = db.find(ObservationTarget.class); } catch (Exception e) { this.setError("Something went wrong while finding the participants: " + e.getMessage()); e.printStackTrace(); return; } List<String> skipList = new ArrayList<String>(); List<String> skipListNoVal = new ArrayList<String>(); List<String> skipListDouble = new ArrayList<String>(); for (final Object[] part : parts) { final Integer targetId = Integer.parseInt(part[0].toString()); final String sexVal = (String) part[1]; final String phenoVal = (String) part[2]; double pheno = StringUtils.isNotEmpty(phenoVal) ? Double.parseDouble(phenoVal) : -9; try { entries.add(new FamEntry("LIFELINES", targetId.toString(), "0", "0", (byte) Integer .parseInt(sexVal), pheno)); } catch (NumberFormatException nfe) { this.setError(String.format("Dataset contains a non double value: %s", phenoVal)); return; } } try { - ffw.writeAll(entries); - ffw.close(); + ffw.write(entries); } catch(IOException e) { this.setError("Something went wrong while writing the entries: " + e.getMessage()); - e.printStackTrace(); return; + } finally { + ffw.close(); } downloadPanel = new DivPanel(); downloadPanel.setStyle("border: 1px solid red; margin: 10px 10px 10px 0px; padding: 10px; width: auto"); downloadPanel.add(new Paragraph( "<strong>Your PLINK files are ready on Target GPFS storage [under construction]:</strong>")); downloadPanel.add(new Paragraph("TPED file")); downloadPanel.add(new Paragraph("<a href='tmpfile/" + famExport.getName() + "'>TFAM file</a>")); } } }
false
true
public void handleRequest(Database db, Tuple request) { String action = request.getAction(); if (action.equals("genPlink")) { // Get selected phenotype int measurementId = -1;// request.getInt(measurements.getName()); Measurement meas; try { meas = db.findById(Measurement.class, measurementId); } catch (Exception e) { this.setError("Something went wrong while finding your phenotype: " + e.getMessage()); e.printStackTrace(); return; } // Get measurement for sex int sexMeasId; try { sexMeasId = db.query(Measurement.class).eq(Measurement.NAME, "GESLACHT").find().get(0).getId(); } catch (Exception e) { this.setError("Something went wrong while finding the Sex(GESLACHT) phenotype: " + e.getMessage()); e.printStackTrace(); return; } // PLEASE NOTE THAT YOU MUST CALL IT A TFAM FILE // because it belongs to a transposed PED (--->TPED) file // while TFAM format is equivalent to FAM format.. // info: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml File tmpDir = new File(System.getProperty("java.io.tmpdir")); File famExport = new File(tmpDir.getAbsolutePath() + File.separatorChar + meas.getName() + "_" + System.nanoTime() + ".tfam"); FamFileWriter ffw; try { ffw = new FamFileWriter(famExport); } catch (Exception e) { this.setError("Something went wrong while initializing the TFAM file writer: " + e.getMessage()); e.printStackTrace(); return; } List<FamEntry> entries = new ArrayList<FamEntry>(); List<Object[]> parts; try { @SuppressWarnings( { "deprecation", "rawtypes", "unchecked" }) List<Object[]> parts2 = db .getEntityManager() .createQuery( "SELECT ov.target.name, " + "MAX ( CASE WHEN (ov.feature.id = :sexId) THEN ov.value ELSE null END ), " + "MAX ( CASE WHEN (ov.feature.id = :mesId) THEN ov.value ELSE null END ) " + "FROM ObservedValue ov WHERE ov.feature = :sexId OR ov.feature = :mesId GROUP BY ov.target.name") .setParameter("sexId", sexMeasId).setParameter("mesId", measurementId).getResultList(); parts = parts2; // strange! // parts = db.find(ObservationTarget.class); } catch (Exception e) { this.setError("Something went wrong while finding the participants: " + e.getMessage()); e.printStackTrace(); return; } List<String> skipList = new ArrayList<String>(); List<String> skipListNoVal = new ArrayList<String>(); List<String> skipListDouble = new ArrayList<String>(); for (final Object[] part : parts) { final Integer targetId = Integer.parseInt(part[0].toString()); final String sexVal = (String) part[1]; final String phenoVal = (String) part[2]; double pheno = StringUtils.isNotEmpty(phenoVal) ? Double.parseDouble(phenoVal) : -9; try { entries.add(new FamEntry("LIFELINES", targetId.toString(), "0", "0", (byte) Integer .parseInt(sexVal), pheno)); } catch (NumberFormatException nfe) { this.setError(String.format("Dataset contains a non double value: %s", phenoVal)); return; } } try { ffw.writeAll(entries); ffw.close(); } catch(IOException e) { this.setError("Something went wrong while writing the entries: " + e.getMessage()); e.printStackTrace(); return; } downloadPanel = new DivPanel(); downloadPanel.setStyle("border: 1px solid red; margin: 10px 10px 10px 0px; padding: 10px; width: auto"); downloadPanel.add(new Paragraph( "<strong>Your PLINK files are ready on Target GPFS storage [under construction]:</strong>")); downloadPanel.add(new Paragraph("TPED file")); downloadPanel.add(new Paragraph("<a href='tmpfile/" + famExport.getName() + "'>TFAM file</a>")); } }
public void handleRequest(Database db, Tuple request) { String action = request.getAction(); if (action.equals("genPlink")) { // Get selected phenotype int measurementId = -1;// request.getInt(measurements.getName()); Measurement meas; try { meas = db.findById(Measurement.class, measurementId); } catch (Exception e) { this.setError("Something went wrong while finding your phenotype: " + e.getMessage()); e.printStackTrace(); return; } // Get measurement for sex int sexMeasId; try { sexMeasId = db.query(Measurement.class).eq(Measurement.NAME, "GESLACHT").find().get(0).getId(); } catch (Exception e) { this.setError("Something went wrong while finding the Sex(GESLACHT) phenotype: " + e.getMessage()); e.printStackTrace(); return; } // PLEASE NOTE THAT YOU MUST CALL IT A TFAM FILE // because it belongs to a transposed PED (--->TPED) file // while TFAM format is equivalent to FAM format.. // info: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml File tmpDir = new File(System.getProperty("java.io.tmpdir")); File famExport = new File(tmpDir.getAbsolutePath() + File.separatorChar + meas.getName() + "_" + System.nanoTime() + ".tfam"); FamFileWriter ffw; try { ffw = new FamFileWriter(famExport); } catch (Exception e) { this.setError("Something went wrong while initializing the TFAM file writer: " + e.getMessage()); e.printStackTrace(); return; } List<FamEntry> entries = new ArrayList<FamEntry>(); List<Object[]> parts; try { @SuppressWarnings( { "deprecation", "rawtypes", "unchecked" }) List<Object[]> parts2 = db .getEntityManager() .createQuery( "SELECT ov.target.name, " + "MAX ( CASE WHEN (ov.feature.id = :sexId) THEN ov.value ELSE null END ), " + "MAX ( CASE WHEN (ov.feature.id = :mesId) THEN ov.value ELSE null END ) " + "FROM ObservedValue ov WHERE ov.feature = :sexId OR ov.feature = :mesId GROUP BY ov.target.name") .setParameter("sexId", sexMeasId).setParameter("mesId", measurementId).getResultList(); parts = parts2; // strange! // parts = db.find(ObservationTarget.class); } catch (Exception e) { this.setError("Something went wrong while finding the participants: " + e.getMessage()); e.printStackTrace(); return; } List<String> skipList = new ArrayList<String>(); List<String> skipListNoVal = new ArrayList<String>(); List<String> skipListDouble = new ArrayList<String>(); for (final Object[] part : parts) { final Integer targetId = Integer.parseInt(part[0].toString()); final String sexVal = (String) part[1]; final String phenoVal = (String) part[2]; double pheno = StringUtils.isNotEmpty(phenoVal) ? Double.parseDouble(phenoVal) : -9; try { entries.add(new FamEntry("LIFELINES", targetId.toString(), "0", "0", (byte) Integer .parseInt(sexVal), pheno)); } catch (NumberFormatException nfe) { this.setError(String.format("Dataset contains a non double value: %s", phenoVal)); return; } } try { ffw.write(entries); } catch(IOException e) { this.setError("Something went wrong while writing the entries: " + e.getMessage()); return; } finally { ffw.close(); } downloadPanel = new DivPanel(); downloadPanel.setStyle("border: 1px solid red; margin: 10px 10px 10px 0px; padding: 10px; width: auto"); downloadPanel.add(new Paragraph( "<strong>Your PLINK files are ready on Target GPFS storage [under construction]:</strong>")); downloadPanel.add(new Paragraph("TPED file")); downloadPanel.add(new Paragraph("<a href='tmpfile/" + famExport.getName() + "'>TFAM file</a>")); } }
diff --git a/main/tests/server/src/com/google/refine/tests/importers/ExcelImporterTests.java b/main/tests/server/src/com/google/refine/tests/importers/ExcelImporterTests.java index c26129dd..40a8c203 100644 --- a/main/tests/server/src/com/google/refine/tests/importers/ExcelImporterTests.java +++ b/main/tests/server/src/com/google/refine/tests/importers/ExcelImporterTests.java @@ -1,199 +1,199 @@ /* Copyright 2011, Thomas F. Morris All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.google.refine.tests.importers; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.json.JSONArray; import org.json.JSONException; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.refine.importers.ExcelImporter; import com.google.refine.util.JSONUtilities; public class ExcelImporterTests extends ImporterTest { private static final double EPSILON = 0.0000001; private static final int SHEETS = 3; private static final int ROWS = 5; private static final int COLUMNS = 6; //private static final File xlsxFile = createSpreadsheet(true); private static final File xlsFile = createSpreadsheet(false); @Override @BeforeTest public void init() { logger = LoggerFactory.getLogger(this.getClass()); } //System Under Test ExcelImporter SUT = null; @Override @BeforeMethod public void setUp(){ super.setUp(); SUT = new ExcelImporter(); } @Override @AfterMethod public void tearDown(){ SUT = null; super.tearDown(); } //---------------------read tests------------------------ @Test public void readXls() throws FileNotFoundException{ JSONArray sheets = new JSONArray(); JSONUtilities.append(sheets, 0); // JSONUtilities.append(sheets, 1); // JSONUtilities.append(sheets, 2); whenGetArrayOption("sheets", options, sheets); whenGetIntegerOption("ignoreLines", options, 0); whenGetIntegerOption("headerLines", options, 0); whenGetIntegerOption("skipDataLines", options, 0); whenGetIntegerOption("limit", options, -1); whenGetBooleanOption("storeBlankCellsAsNulls",options,true); InputStream stream = new FileInputStream(xlsFile); try { parseOneFile(SUT, stream); } catch (Exception e) { Assert.fail(e.getMessage()); } Assert.assertEquals(project.rows.size(), ROWS); Assert.assertEquals(project.rows.get(1).cells.size(), COLUMNS); Assert.assertEquals(((Number)project.rows.get(1).getCellValue(0)).doubleValue(),1.1, EPSILON); Assert.assertEquals(((Number)project.rows.get(2).getCellValue(0)).doubleValue(),2.2, EPSILON); Assert.assertFalse((Boolean)project.rows.get(1).getCellValue(1)); Assert.assertTrue((Boolean)project.rows.get(2).getCellValue(1)); Assert.assertEquals((String)project.rows.get(1).getCellValue(4)," Row 1 Col 5"); Assert.assertNull((String)project.rows.get(1).getCellValue(5)); try { verify(options, times(1)).getInt("ignoreLines"); verify(options, times(1)).getInt("headerLines"); verify(options, times(1)).getInt("skipDataLines"); verify(options, times(1)).getInt("limit"); verify(options, times(1)).getBoolean("storeBlankCellsAsNulls"); } catch (JSONException e) { Assert.fail("JSON exception",e); } } private static File createSpreadsheet(boolean xml) { final Workbook wb = xml ? new XSSFWorkbook() : new HSSFWorkbook(); for (int s = 0; s < SHEETS; s++) { Sheet sheet = wb.createSheet("Test Sheet " + s); for (int row = 0; row < ROWS; row++) { int col = 0; Row r = sheet.createRow(row); Cell c; c = r.createCell(col++); c.setCellValue(row * 1.1); // double c = r.createCell(col++); c.setCellValue(row % 2 == 0); // boolean c = r.createCell(col++); c.setCellValue(Calendar.getInstance()); // calendar c = r.createCell(col++); c.setCellValue(new Date()); // date c = r.createCell(col++); c.setCellValue(" Row " + row + " Col " + col); // string c = r.createCell(col++); c.setCellValue(""); // string // HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); // hl.setLabel(cellData.text); // hl.setAddress(cellData.link); } } File file = null; try { - file = File.createTempFile("oepnrefine-importer-test", xml ? ".xlsx" : ".xls"); + file = File.createTempFile("openrefine-importer-test", xml ? ".xlsx" : ".xls"); file.deleteOnExit(); OutputStream outputStream = new FileOutputStream(file); wb.write(outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { return null; } return file; } }
true
true
private static File createSpreadsheet(boolean xml) { final Workbook wb = xml ? new XSSFWorkbook() : new HSSFWorkbook(); for (int s = 0; s < SHEETS; s++) { Sheet sheet = wb.createSheet("Test Sheet " + s); for (int row = 0; row < ROWS; row++) { int col = 0; Row r = sheet.createRow(row); Cell c; c = r.createCell(col++); c.setCellValue(row * 1.1); // double c = r.createCell(col++); c.setCellValue(row % 2 == 0); // boolean c = r.createCell(col++); c.setCellValue(Calendar.getInstance()); // calendar c = r.createCell(col++); c.setCellValue(new Date()); // date c = r.createCell(col++); c.setCellValue(" Row " + row + " Col " + col); // string c = r.createCell(col++); c.setCellValue(""); // string // HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); // hl.setLabel(cellData.text); // hl.setAddress(cellData.link); } } File file = null; try { file = File.createTempFile("oepnrefine-importer-test", xml ? ".xlsx" : ".xls"); file.deleteOnExit(); OutputStream outputStream = new FileOutputStream(file); wb.write(outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { return null; } return file; }
private static File createSpreadsheet(boolean xml) { final Workbook wb = xml ? new XSSFWorkbook() : new HSSFWorkbook(); for (int s = 0; s < SHEETS; s++) { Sheet sheet = wb.createSheet("Test Sheet " + s); for (int row = 0; row < ROWS; row++) { int col = 0; Row r = sheet.createRow(row); Cell c; c = r.createCell(col++); c.setCellValue(row * 1.1); // double c = r.createCell(col++); c.setCellValue(row % 2 == 0); // boolean c = r.createCell(col++); c.setCellValue(Calendar.getInstance()); // calendar c = r.createCell(col++); c.setCellValue(new Date()); // date c = r.createCell(col++); c.setCellValue(" Row " + row + " Col " + col); // string c = r.createCell(col++); c.setCellValue(""); // string // HSSFHyperlink hl = new HSSFHyperlink(HSSFHyperlink.LINK_URL); // hl.setLabel(cellData.text); // hl.setAddress(cellData.link); } } File file = null; try { file = File.createTempFile("openrefine-importer-test", xml ? ".xlsx" : ".xls"); file.deleteOnExit(); OutputStream outputStream = new FileOutputStream(file); wb.write(outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { return null; } return file; }
diff --git a/tutorials/src/tutorial/directmessenger/Sender.java b/tutorials/src/tutorial/directmessenger/Sender.java index 1e47c74..14696b6 100644 --- a/tutorials/src/tutorial/directmessenger/Sender.java +++ b/tutorials/src/tutorial/directmessenger/Sender.java @@ -1,294 +1,293 @@ /* * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by Sun Microsystems, Inc. for JXTA(TM) technology." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this software * without prior written permission. For written permission, please contact * Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", nor may * "JXTA" appear in their name, without prior written permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of Project JXTA. For more information on Project JXTA, please see * http://www.jxta.org. * * This license is based on the BSD license adopted by the Apache Foundation. */ package tutorial.directmessenger; import net.jxta.endpoint.EndpointListener; import net.jxta.endpoint.EndpointService; import net.jxta.platform.NetworkManager; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import net.jxta.document.AdvertisementFactory; import net.jxta.document.StructuredDocumentFactory; import net.jxta.document.XMLDocument; import net.jxta.endpoint.EndpointAddress; import net.jxta.endpoint.Message; import net.jxta.endpoint.MessageElement; import net.jxta.endpoint.MessageSender; import net.jxta.endpoint.Messenger; import net.jxta.endpoint.StringMessageElement; import net.jxta.peergroup.PeerGroup; import net.jxta.protocol.RouteAdvertisement; /** * Simple example to illustrate the use of direct messengers. A direct messenger * is acquired directly from the a physical message transport and bypasses the * normal JXTA network virtualization layers. There are several reasons why an * an application might want to use direct messengers : * <dl> * <dt>Dedicated Resource</dt> * <dd>Each direct messenger is a dedicated resource and is available only to * the application or service which creates it. The messenger is not shared * with other uses.</dd> * <dt>Latency & Throughput</dt> * <dd>Because the messenger bypasses the JXTA network virtualization layers * it may offer somewhat better throughput and latency than regular shared * JXTA virtual messengers.</dd> * <dt>Presence & Disconnection</dt> * <dd>Direct messengers are more immediately responsive to connection status * changes. If the remote side closes the connection the application or * service can recognize the state change immediately.</dd> * </dl> * Using direct messengers is not * <dl> * <dt>Not Always Available</dt> * <dd>Creation of a direct messenger to another peer requires that the remote * peer be directly reachable. In many cases this will not be possible. This * usually means that it is necessary to support both direct messengers and * indirect messengers in your application. Additionally, there may be extra * overhead introduced into your application as a result of attempting to * create direct messengers.</dd> * <dt>Consume Extra Resources</dt> * <dd>The resources used by direct messengers are not available to other JXTA * applications and services (nor the rest of the system).</dd> * <dt>Require More "Maintenance"</dt> * <dd>If the remote peer's addresses change or the connection is closed your * application will need to re-open the direct messenger. Normally the JXTA * network virtualization layer hides all this work from your application. * HTTP direct messengers (because of proxies) commonly require frequent * re-creation.</dd> * </dl> */ public class Sender { /** * The number of responses after which we will stop. */ static final int TOTAL_RESPONSES = 10; /** * Our listener for "chatAnnounce" messages. */ private static class ChatAnnounceReceiver implements EndpointListener { /** * The endpoint with which this listener is registered. */ private final EndpointService endpoint; /** * The number of responses we have sent. */ private final AtomicInteger responses = new AtomicInteger(0); public ChatAnnounceReceiver(EndpointService endpoint) { this.endpoint = endpoint; } /** * {@inheritDoc} * <p/> * Receive a message sent to "chatAnnounce". We expect that the message * will contain a "ChatAnnounce" message element containing a JXTA * Route Advertisement for the peer which wishes us to send a response. */ public void processIncomingMessage(Message msg, EndpointAddress source, EndpointAddress destination) { MessageElement announce = msg.getMessageElement("ChatAnnounce"); if(null == announce) { // It doesn't seem to be the right kind of message. return; } RouteAdvertisement route; try { XMLDocument routeDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(announce); route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(routeDoc); } catch(Exception bad) { System.err.println("### - Bad Route"); bad.printStackTrace(System.err); return; } System.out.println("Announcement from " + route.getDestPeerID() ); // We have received an announcement from some peer. We will attempt // to create a direct messenger to respond to the announcement. // Currently we look for only TCP messengers. for(EndpointAddress anEA : route.getDestEndpointAddresses()) { MessageSender tcp = (MessageSender) endpoint.getMessageTransport("tcp"); // Search for "tcp" endpoint addresses. if("tcp".equals(anEA.getProtocolName())) { EndpointAddress destAddress; if(endpoint.getGroup().equals(tcp.getEndpointService().getGroup())) { // The TCP message transport is in our peer group. We can address the message directly. destAddress = new EndpointAddress(anEA, "chatService", route.getDestPeerID().getUniqueValue().toString() ); } else { // When a message transport receives a message it passes it to the endpoint service in it's own // peer group for processing. If our peer group is not the same as the message transports then // the endpoint service which will receive the message is not the same message service with // which we registered our message listener. There is a solution though : Each endpoint service // which uses message transports from it's parent peer groups will also register a redirection // listener for messages destined for that endpoint service. The listener is named // "EndpointService:"<PeerGroupID-unique value>" with the parameter being a concatination of the // service name and parameter separated by a "/". destAddress = new EndpointAddress(anEA, "EndpointService:jxta-NetGroup", "chatService" + "/" + route.getDestPeerID().getUniqueValue().toString() ); } // We have an address be believe is worth trying. We will // attempt to create a messenger to the address. Messenger directMessenger = null; try { directMessenger = tcp.getMessenger(destAddress, null); if(null == directMessenger) { // The current address was unreachable. Try another. System.err.println("### - getMessenger() failed for " + anEA ); continue; } // We have a direct messenger. Try to send a response. System.out.println("Sending response to " + anEA ); String chatMessage = "Hello from " + endpoint.getGroup().getPeerID() + " via " + anEA + " @ " + new Date(); Message chat = new Message(); chat.addMessageElement(new StringMessageElement("Chat", chatMessage, null)); - // FIXME directMessenger.sendMessageB(chat, null, null); - directMessenger.sendMessageB(chat, "EndpointService:jxta-NetGroup", "chatService/" + route.getDestPeerID().getUniqueValue().toString()); + directMessenger.sendMessageB(chat, null, null); // The message has been sent. // Decide if we have sent enough responses. int totalSent = responses.incrementAndGet(); if(totalSent >= TOTAL_RESPONSES) { synchronized(shutDown) { // We have sent all the responses we wanted to. Signal shutdown. stopped = true; shutDown.notifyAll(); } } break; } catch(IOException failed) { failed.printStackTrace(System.err); } finally { if(null != directMessenger) { directMessenger.close(); } } } } } } private static boolean stopped = false; private static String shutDown = new String("shutdown"); /** * main * * @param args command line args */ public static void main(String args[]) { try { // Configure and start JXTA. NetworkManager manager = new NetworkManager(NetworkManager.ConfigMode.ADHOC, "DirectMessengerSender", new File(new File(".cache"), "DirectMessengerSender").toURI()); manager.startNetwork(); PeerGroup npg = manager.getNetPeerGroup(); // Register an endpoint listener for "chatAnnounce" messages. EndpointService endpoint = npg.getEndpointService(); EndpointListener chatAnnouncelistener = new ChatAnnounceReceiver(endpoint); endpoint.addIncomingMessageListener(chatAnnouncelistener, "chatAnnounce", null ); // Continue until shutdown synchronized(shutDown) { try { while(!stopped) { shutDown.wait(5000); } } catch( InterruptedException woken ) { Thread.interrupted(); } } // De-register "chatAnnounce" listener. endpoint.removeIncomingMessageListener( "chatAnnounce", null ); // Stop JXTA. manager.stopNetwork(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } }
true
true
public void processIncomingMessage(Message msg, EndpointAddress source, EndpointAddress destination) { MessageElement announce = msg.getMessageElement("ChatAnnounce"); if(null == announce) { // It doesn't seem to be the right kind of message. return; } RouteAdvertisement route; try { XMLDocument routeDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(announce); route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(routeDoc); } catch(Exception bad) { System.err.println("### - Bad Route"); bad.printStackTrace(System.err); return; } System.out.println("Announcement from " + route.getDestPeerID() ); // We have received an announcement from some peer. We will attempt // to create a direct messenger to respond to the announcement. // Currently we look for only TCP messengers. for(EndpointAddress anEA : route.getDestEndpointAddresses()) { MessageSender tcp = (MessageSender) endpoint.getMessageTransport("tcp"); // Search for "tcp" endpoint addresses. if("tcp".equals(anEA.getProtocolName())) { EndpointAddress destAddress; if(endpoint.getGroup().equals(tcp.getEndpointService().getGroup())) { // The TCP message transport is in our peer group. We can address the message directly. destAddress = new EndpointAddress(anEA, "chatService", route.getDestPeerID().getUniqueValue().toString() ); } else { // When a message transport receives a message it passes it to the endpoint service in it's own // peer group for processing. If our peer group is not the same as the message transports then // the endpoint service which will receive the message is not the same message service with // which we registered our message listener. There is a solution though : Each endpoint service // which uses message transports from it's parent peer groups will also register a redirection // listener for messages destined for that endpoint service. The listener is named // "EndpointService:"<PeerGroupID-unique value>" with the parameter being a concatination of the // service name and parameter separated by a "/". destAddress = new EndpointAddress(anEA, "EndpointService:jxta-NetGroup", "chatService" + "/" + route.getDestPeerID().getUniqueValue().toString() ); } // We have an address be believe is worth trying. We will // attempt to create a messenger to the address. Messenger directMessenger = null; try { directMessenger = tcp.getMessenger(destAddress, null); if(null == directMessenger) { // The current address was unreachable. Try another. System.err.println("### - getMessenger() failed for " + anEA ); continue; } // We have a direct messenger. Try to send a response. System.out.println("Sending response to " + anEA ); String chatMessage = "Hello from " + endpoint.getGroup().getPeerID() + " via " + anEA + " @ " + new Date(); Message chat = new Message(); chat.addMessageElement(new StringMessageElement("Chat", chatMessage, null)); // FIXME directMessenger.sendMessageB(chat, null, null); directMessenger.sendMessageB(chat, "EndpointService:jxta-NetGroup", "chatService/" + route.getDestPeerID().getUniqueValue().toString()); // The message has been sent. // Decide if we have sent enough responses. int totalSent = responses.incrementAndGet(); if(totalSent >= TOTAL_RESPONSES) { synchronized(shutDown) { // We have sent all the responses we wanted to. Signal shutdown. stopped = true; shutDown.notifyAll(); } } break; } catch(IOException failed) { failed.printStackTrace(System.err); } finally { if(null != directMessenger) { directMessenger.close(); } } } } }
public void processIncomingMessage(Message msg, EndpointAddress source, EndpointAddress destination) { MessageElement announce = msg.getMessageElement("ChatAnnounce"); if(null == announce) { // It doesn't seem to be the right kind of message. return; } RouteAdvertisement route; try { XMLDocument routeDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(announce); route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(routeDoc); } catch(Exception bad) { System.err.println("### - Bad Route"); bad.printStackTrace(System.err); return; } System.out.println("Announcement from " + route.getDestPeerID() ); // We have received an announcement from some peer. We will attempt // to create a direct messenger to respond to the announcement. // Currently we look for only TCP messengers. for(EndpointAddress anEA : route.getDestEndpointAddresses()) { MessageSender tcp = (MessageSender) endpoint.getMessageTransport("tcp"); // Search for "tcp" endpoint addresses. if("tcp".equals(anEA.getProtocolName())) { EndpointAddress destAddress; if(endpoint.getGroup().equals(tcp.getEndpointService().getGroup())) { // The TCP message transport is in our peer group. We can address the message directly. destAddress = new EndpointAddress(anEA, "chatService", route.getDestPeerID().getUniqueValue().toString() ); } else { // When a message transport receives a message it passes it to the endpoint service in it's own // peer group for processing. If our peer group is not the same as the message transports then // the endpoint service which will receive the message is not the same message service with // which we registered our message listener. There is a solution though : Each endpoint service // which uses message transports from it's parent peer groups will also register a redirection // listener for messages destined for that endpoint service. The listener is named // "EndpointService:"<PeerGroupID-unique value>" with the parameter being a concatination of the // service name and parameter separated by a "/". destAddress = new EndpointAddress(anEA, "EndpointService:jxta-NetGroup", "chatService" + "/" + route.getDestPeerID().getUniqueValue().toString() ); } // We have an address be believe is worth trying. We will // attempt to create a messenger to the address. Messenger directMessenger = null; try { directMessenger = tcp.getMessenger(destAddress, null); if(null == directMessenger) { // The current address was unreachable. Try another. System.err.println("### - getMessenger() failed for " + anEA ); continue; } // We have a direct messenger. Try to send a response. System.out.println("Sending response to " + anEA ); String chatMessage = "Hello from " + endpoint.getGroup().getPeerID() + " via " + anEA + " @ " + new Date(); Message chat = new Message(); chat.addMessageElement(new StringMessageElement("Chat", chatMessage, null)); directMessenger.sendMessageB(chat, null, null); // The message has been sent. // Decide if we have sent enough responses. int totalSent = responses.incrementAndGet(); if(totalSent >= TOTAL_RESPONSES) { synchronized(shutDown) { // We have sent all the responses we wanted to. Signal shutdown. stopped = true; shutDown.notifyAll(); } } break; } catch(IOException failed) { failed.printStackTrace(System.err); } finally { if(null != directMessenger) { directMessenger.close(); } } } } }
diff --git a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceProvider.java b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceProvider.java index a0a85edd3..52f886e48 100755 --- a/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceProvider.java +++ b/railo-java/railo-core/src/railo/commons/io/res/type/s3/S3ResourceProvider.java @@ -1,330 +1,330 @@ package railo.commons.io.res.type.s3; import java.io.IOException; import java.util.Map; import railo.commons.io.res.Resource; import railo.commons.io.res.ResourceLock; import railo.commons.io.res.ResourceProvider; import railo.commons.io.res.Resources; import railo.commons.lang.StringUtil; import railo.commons.lang.types.RefInteger; import railo.commons.lang.types.RefIntegerImpl; import railo.runtime.PageContext; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.net.s3.Properties; import railo.runtime.util.ApplicationContextPro; public final class S3ResourceProvider implements ResourceProvider { private int socketTimeout=-1; private int lockTimeout=20000; private int cache=20000; private ResourceLock lock; private String scheme="s3"; private Map arguments; /** * initalize ram resource * @param scheme * @param arguments * @return RamResource */ public ResourceProvider init(String scheme,Map arguments) { if(!StringUtil.isEmpty(scheme))this.scheme=scheme; if(arguments!=null) { this.arguments=arguments; // socket-timeout String strTimeout = (String) arguments.get("socket-timeout"); if(strTimeout!=null) { socketTimeout=toIntValue(strTimeout,socketTimeout); } // lock-timeout strTimeout=(String) arguments.get("lock-timeout"); if(strTimeout!=null) { lockTimeout=toIntValue(strTimeout,lockTimeout); } // cache String strCache=(String) arguments.get("cache"); if(strCache!=null) { cache=toIntValue(strCache,cache); } } return this; } private int toIntValue(String str, int defaultValue) { try{ return Integer.parseInt(str); } catch(Throwable t){ return defaultValue; } } /** * @see railo.commons.io.res.ResourceProvider#getScheme() */ public String getScheme() { return scheme; } public Resource getResource(String path) { path=railo.commons.io.res.util.ResourceUtil.removeScheme(scheme, path); S3 s3 = new S3(); RefInteger storage=new RefIntegerImpl(S3.STORAGE_UNKNOW); //path=loadWithOldPattern(s3,storage,path); path=loadWithNewPattern(s3,storage,path); return new S3Resource(s3,storage.toInt(),this,path,true); } public static String loadWithNewPattern(S3 s3,RefInteger storage, String path) { PageContext pc = ThreadLocalPageContext.get(); Properties prop=null; if(pc!=null){ prop=((ApplicationContextPro)pc.getApplicationContext()).getS3(); } - else prop=new Properties(); + if(prop==null) prop=new Properties(); int defaultLocation = prop.getDefaultLocation(); storage.setValue(defaultLocation); String accessKeyId = prop.getAccessKeyId(); String secretAccessKey = prop.getSecretAccessKey(); int atIndex=path.indexOf('@'); int slashIndex=path.indexOf('/'); if(slashIndex==-1){ slashIndex=path.length(); path+="/"; } int index; // key/id if(atIndex!=-1) { index=path.indexOf(':'); if(index!=-1 && index<atIndex) { accessKeyId=path.substring(0,index); secretAccessKey=path.substring(index+1,atIndex); index=secretAccessKey.indexOf(':'); if(index!=-1) { String strStorage=secretAccessKey.substring(index+1).trim().toLowerCase(); secretAccessKey=secretAccessKey.substring(0,index); //print.out("storage:"+strStorage); storage.setValue(S3.toIntStorage(strStorage, defaultLocation)); } } else accessKeyId=path.substring(0,atIndex); } path=prettifyPath(path.substring(atIndex+1)); index=path.indexOf('/'); s3.setHost(prop.getHost()); if(index==-1){ if(path.equalsIgnoreCase(S3Constants.HOST) || path.equalsIgnoreCase(prop.getHost())){ s3.setHost(path); path="/"; } } else { String host=path.substring(0,index); if(host.equalsIgnoreCase(S3Constants.HOST) || host.equalsIgnoreCase(prop.getHost())){ s3.setHost(host); path=path.substring(index); } } s3.setSecretAccessKey(secretAccessKey); s3.setAccessKeyId(accessKeyId); return path; } /*public static void main(String[] args) { // s3://bucket/x/y/sample.txt // s3://accessKeyId:awsSecretKey@bucket/x/y/sample.txt String secretAccessKey="R/sOy3hgimrI8D9c0lFHchoivecnOZ8LyVmJpRFQ"; String accessKeyId="1DHC5C5FVD7YEPR4DBG2"; Properties prop=new Properties(); prop.setAccessKeyId(accessKeyId); prop.setSecretAccessKey(secretAccessKey); test("s3://"+accessKeyId+":"+secretAccessKey+"@s3.amazonaws.com/dudi/peter.txt"); test("s3://"+accessKeyId+":"+secretAccessKey+"@dudi/peter.txt"); test("s3:///dudi/peter.txt"); test("s3://dudi/peter.txt"); } private static void test(String path) { Properties prop=new Properties(); prop.setAccessKeyId("123456"); prop.setSecretAccessKey("abcdefghji"); String scheme="s3"; path=railo.commons.io.res.util.ResourceUtil.removeScheme(scheme, path); S3 s3 = new S3(); RefInteger storage=new RefIntegerImpl(S3.STORAGE_UNKNOW); path=loadWithNewPattern(s3,prop,storage,path); print.o(s3); print.o(path); }*/ private static String prettifyPath(String path) { path=path.replace('\\','/'); return StringUtil.replace(path, "//", "/", false); // TODO /aaa/../bbb/ } public static String loadWithOldPattern(S3 s3,RefInteger storage, String path) { String accessKeyId = null; String secretAccessKey = null; String host = null; //int port = 21; //print.out("raw:"+path); int atIndex=path.indexOf('@'); int slashIndex=path.indexOf('/'); if(slashIndex==-1){ slashIndex=path.length(); path+="/"; } int index; // key/id if(atIndex!=-1) { index=path.indexOf(':'); if(index!=-1 && index<atIndex) { accessKeyId=path.substring(0,index); secretAccessKey=path.substring(index+1,atIndex); index=secretAccessKey.indexOf(':'); if(index!=-1) { String strStorage=secretAccessKey.substring(index+1).trim().toLowerCase(); secretAccessKey=secretAccessKey.substring(0,index); //print.out("storage:"+strStorage); storage.setValue(S3.toIntStorage(strStorage, S3.STORAGE_UNKNOW)); } } else accessKeyId=path.substring(0,atIndex); } path=prettifyPath(path.substring(atIndex+1)); index=path.indexOf('/'); if(index==-1){ host=path; path="/"; } else { host=path.substring(0,index); path=path.substring(index); } s3.setHost(host); s3.setSecretAccessKey(secretAccessKey); s3.setAccessKeyId(accessKeyId); return path; } /** * @see railo.commons.io.res.ResourceProvider#isAttributesSupported() */ public boolean isAttributesSupported() { return false; } /** * @see railo.commons.io.res.ResourceProvider#isCaseSensitive() */ public boolean isCaseSensitive() { return true; } /** * @see railo.commons.io.res.ResourceProvider#isModeSupported() */ public boolean isModeSupported() { return false; } /** * @see railo.commons.io.res.ResourceProvider#lock(railo.commons.io.res.Resource) */ public void lock(Resource res) throws IOException { lock.lock(res); } /** * @see railo.commons.io.res.ResourceProvider#read(railo.commons.io.res.Resource) */ public void read(Resource res) throws IOException { lock.read(res); } public void setResources(Resources res) { lock=res.createResourceLock(lockTimeout,true); } /** * @see railo.commons.io.res.ResourceProvider#unlock(railo.commons.io.res.Resource) */ public void unlock(Resource res) { lock.unlock(res); } /** * @return the socketTimeout */ public int getSocketTimeout() { return socketTimeout; } /** * @return the lockTimeout */ public int getLockTimeout() { return lockTimeout; } /** * @return the cache */ public int getCache() { return cache; } /** * @see railo.commons.io.res.ResourceProvider#getArguments() */ public Map getArguments() { return arguments; } }
true
true
public static String loadWithNewPattern(S3 s3,RefInteger storage, String path) { PageContext pc = ThreadLocalPageContext.get(); Properties prop=null; if(pc!=null){ prop=((ApplicationContextPro)pc.getApplicationContext()).getS3(); } else prop=new Properties(); int defaultLocation = prop.getDefaultLocation(); storage.setValue(defaultLocation); String accessKeyId = prop.getAccessKeyId(); String secretAccessKey = prop.getSecretAccessKey(); int atIndex=path.indexOf('@'); int slashIndex=path.indexOf('/'); if(slashIndex==-1){ slashIndex=path.length(); path+="/"; } int index; // key/id if(atIndex!=-1) { index=path.indexOf(':'); if(index!=-1 && index<atIndex) { accessKeyId=path.substring(0,index); secretAccessKey=path.substring(index+1,atIndex); index=secretAccessKey.indexOf(':'); if(index!=-1) { String strStorage=secretAccessKey.substring(index+1).trim().toLowerCase(); secretAccessKey=secretAccessKey.substring(0,index); //print.out("storage:"+strStorage); storage.setValue(S3.toIntStorage(strStorage, defaultLocation)); } } else accessKeyId=path.substring(0,atIndex); } path=prettifyPath(path.substring(atIndex+1)); index=path.indexOf('/'); s3.setHost(prop.getHost()); if(index==-1){ if(path.equalsIgnoreCase(S3Constants.HOST) || path.equalsIgnoreCase(prop.getHost())){ s3.setHost(path); path="/"; } } else { String host=path.substring(0,index); if(host.equalsIgnoreCase(S3Constants.HOST) || host.equalsIgnoreCase(prop.getHost())){ s3.setHost(host); path=path.substring(index); } } s3.setSecretAccessKey(secretAccessKey); s3.setAccessKeyId(accessKeyId); return path; }
public static String loadWithNewPattern(S3 s3,RefInteger storage, String path) { PageContext pc = ThreadLocalPageContext.get(); Properties prop=null; if(pc!=null){ prop=((ApplicationContextPro)pc.getApplicationContext()).getS3(); } if(prop==null) prop=new Properties(); int defaultLocation = prop.getDefaultLocation(); storage.setValue(defaultLocation); String accessKeyId = prop.getAccessKeyId(); String secretAccessKey = prop.getSecretAccessKey(); int atIndex=path.indexOf('@'); int slashIndex=path.indexOf('/'); if(slashIndex==-1){ slashIndex=path.length(); path+="/"; } int index; // key/id if(atIndex!=-1) { index=path.indexOf(':'); if(index!=-1 && index<atIndex) { accessKeyId=path.substring(0,index); secretAccessKey=path.substring(index+1,atIndex); index=secretAccessKey.indexOf(':'); if(index!=-1) { String strStorage=secretAccessKey.substring(index+1).trim().toLowerCase(); secretAccessKey=secretAccessKey.substring(0,index); //print.out("storage:"+strStorage); storage.setValue(S3.toIntStorage(strStorage, defaultLocation)); } } else accessKeyId=path.substring(0,atIndex); } path=prettifyPath(path.substring(atIndex+1)); index=path.indexOf('/'); s3.setHost(prop.getHost()); if(index==-1){ if(path.equalsIgnoreCase(S3Constants.HOST) || path.equalsIgnoreCase(prop.getHost())){ s3.setHost(path); path="/"; } } else { String host=path.substring(0,index); if(host.equalsIgnoreCase(S3Constants.HOST) || host.equalsIgnoreCase(prop.getHost())){ s3.setHost(host); path=path.substring(index); } } s3.setSecretAccessKey(secretAccessKey); s3.setAccessKeyId(accessKeyId); return path; }
diff --git a/KajonaLanguageEditorGui/src/main/java/de/mulchprod/kajona/languageeditor/gui/tree/GuiTreeNode.java b/KajonaLanguageEditorGui/src/main/java/de/mulchprod/kajona/languageeditor/gui/tree/GuiTreeNode.java index d2880bf..e8e83da 100644 --- a/KajonaLanguageEditorGui/src/main/java/de/mulchprod/kajona/languageeditor/gui/tree/GuiTreeNode.java +++ b/KajonaLanguageEditorGui/src/main/java/de/mulchprod/kajona/languageeditor/gui/tree/GuiTreeNode.java @@ -1,51 +1,51 @@ /* * Kajona Language File Editor Gui * * 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, 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 * * (c) MulchProductions, www.mulchprod.de, www.kajona.de * */ package de.mulchprod.kajona.languageeditor.gui.tree; import javax.swing.tree.DefaultMutableTreeNode; /** * * @author sidler */ public class GuiTreeNode extends DefaultMutableTreeNode { private TreeNode referencingTreeNode; public GuiTreeNode(TreeNode referencingTreeNode) { this.referencingTreeNode = referencingTreeNode; } @Override public String toString() { String addon = ""; - if(referencingTreeNode.getReferencingObject() != null) + if(referencingTreeNode.getReferencingObject() != null && referencingTreeNode.getType() != NodeType.KEY) addon = " ("+referencingTreeNode.getReferencingObject().getAllKeys().size()+")"; return referencingTreeNode.getNodeName()+addon; } public TreeNode getReferencingTreeNode() { return referencingTreeNode; } }
true
true
public String toString() { String addon = ""; if(referencingTreeNode.getReferencingObject() != null) addon = " ("+referencingTreeNode.getReferencingObject().getAllKeys().size()+")"; return referencingTreeNode.getNodeName()+addon; }
public String toString() { String addon = ""; if(referencingTreeNode.getReferencingObject() != null && referencingTreeNode.getType() != NodeType.KEY) addon = " ("+referencingTreeNode.getReferencingObject().getAllKeys().size()+")"; return referencingTreeNode.getNodeName()+addon; }
diff --git a/LanPlayer/LanPlayer/src/lanplayer/MusicData.java b/LanPlayer/LanPlayer/src/lanplayer/MusicData.java index bb430b1..34aa5ce 100644 --- a/LanPlayer/LanPlayer/src/lanplayer/MusicData.java +++ b/LanPlayer/LanPlayer/src/lanplayer/MusicData.java @@ -1,152 +1,152 @@ package lanplayer; import java.io.File; import java.net.MalformedURLException; import java.util.Date; import javax.sound.sampled.UnsupportedAudioFileException; import utilities.SimpleDate; public class MusicData implements Comparable<MusicData> { private MusicInfo musicInfo; private File musicFile; private String ip = ""; private String title = null; private String artist = null; private String album = null; private TrackNumber trackno = null; private String duration = null; private Date date; private int rating = 0; private int skip = 0; private int played = 0; private int position = -1; public int getPosition() { return position; } public File getMusicFile() { return musicFile; } public String getIp() { return ip; } public int getRating() { return rating; } public int getSkip() { return skip; } public int getPlayed() { return played; } public String getTitle() { if(title != null && !title.isEmpty()) return title; title = musicInfo == null ? "" : musicInfo.getTitle(); return title; } public String getAlbum() { if(album != null && !album.isEmpty()) return album; album = musicInfo == null ? "" : musicInfo.getAlbum(); return album; } public String getArtist() { if(artist != null && !artist.isEmpty()) return artist; artist = musicInfo == null ? "" : musicInfo.getArtist(); return artist; } public String getDuraction() { if(duration != null && !duration.isEmpty()) return duration; duration = musicInfo == null ? "" : musicInfo.getDuration(); return duration; } public TrackNumber getTrackNumber() { if(trackno != null && album != null) return trackno; trackno = musicInfo == null ? new TrackNumber(0,null) : musicInfo.getTrackNumber(); return trackno; } public SimpleDate getSimpleDate() { return new SimpleDate(this.date); } public MusicData() { } /** * MUSICDATA * @param position * @param musicFile * @param title * @param artist * @param album * @param trackno * @param duration * @param played * @param rating * @param skip * @param date * @param ip * @throws MalformedURLException * @throws UnsupportedAudioFileException */ public MusicData(int position, File musicFile, String title, String artist, String album, String trackno, String duration, int played, int rating, int skip, Date date, String ip) throws MalformedURLException, UnsupportedAudioFileException { this.position = position; this.musicFile = musicFile; this.ip = ip; this.rating = rating; this.skip = skip; this.played = played; this.date = date; this.title = title; this.artist = artist; this.album = album; this.duration = duration; try { int tryTrackNo = Integer.parseInt(trackno); this.trackno = new TrackNumber(tryTrackNo, album); } catch(NumberFormatException nfe) { } - if(title == null || artist == null || album == null || trackno == null || duration == null - || title.isEmpty() || artist.isEmpty() || album.isEmpty() || trackno.isEmpty() || duration.isEmpty()) { + if(title == null || artist == null || album == null || trackno == null || duration == null) { + // || title.isEmpty() || artist.isEmpty() || album.isEmpty() || trackno.isEmpty() || duration.isEmpty()) { String extension = musicFile.getName().substring(musicFile.getName().lastIndexOf("."), musicFile.getName().length()); if(extension.equals(".mp3")) { musicInfo = new MP3Info(musicFile); } else if(extension.equals(".xm")) { musicInfo = new ModInfo(musicFile); } } } public String toString() { return position + ""; } @Override public int compareTo(MusicData other) { if(other == null) return 1; return new Integer(this.getPosition()).compareTo(new Integer(other.getPosition())); } }
true
true
public MusicData(int position, File musicFile, String title, String artist, String album, String trackno, String duration, int played, int rating, int skip, Date date, String ip) throws MalformedURLException, UnsupportedAudioFileException { this.position = position; this.musicFile = musicFile; this.ip = ip; this.rating = rating; this.skip = skip; this.played = played; this.date = date; this.title = title; this.artist = artist; this.album = album; this.duration = duration; try { int tryTrackNo = Integer.parseInt(trackno); this.trackno = new TrackNumber(tryTrackNo, album); } catch(NumberFormatException nfe) { } if(title == null || artist == null || album == null || trackno == null || duration == null || title.isEmpty() || artist.isEmpty() || album.isEmpty() || trackno.isEmpty() || duration.isEmpty()) { String extension = musicFile.getName().substring(musicFile.getName().lastIndexOf("."), musicFile.getName().length()); if(extension.equals(".mp3")) { musicInfo = new MP3Info(musicFile); } else if(extension.equals(".xm")) { musicInfo = new ModInfo(musicFile); } } }
public MusicData(int position, File musicFile, String title, String artist, String album, String trackno, String duration, int played, int rating, int skip, Date date, String ip) throws MalformedURLException, UnsupportedAudioFileException { this.position = position; this.musicFile = musicFile; this.ip = ip; this.rating = rating; this.skip = skip; this.played = played; this.date = date; this.title = title; this.artist = artist; this.album = album; this.duration = duration; try { int tryTrackNo = Integer.parseInt(trackno); this.trackno = new TrackNumber(tryTrackNo, album); } catch(NumberFormatException nfe) { } if(title == null || artist == null || album == null || trackno == null || duration == null) { // || title.isEmpty() || artist.isEmpty() || album.isEmpty() || trackno.isEmpty() || duration.isEmpty()) { String extension = musicFile.getName().substring(musicFile.getName().lastIndexOf("."), musicFile.getName().length()); if(extension.equals(".mp3")) { musicInfo = new MP3Info(musicFile); } else if(extension.equals(".xm")) { musicInfo = new ModInfo(musicFile); } } }
diff --git a/rtty_dev/src/ukhas/Gps_coordinate.java b/rtty_dev/src/ukhas/Gps_coordinate.java index 284f15b..102bea7 100644 --- a/rtty_dev/src/ukhas/Gps_coordinate.java +++ b/rtty_dev/src/ukhas/Gps_coordinate.java @@ -1,178 +1,182 @@ // Copyright 2012 (C) Matthew Brejza // // 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. package ukhas; public class Gps_coordinate { public double latitude = 0; public double longitude = 0; public boolean latlong_valid = false; public double altitude = 0; public boolean alt_valid = false; public Gps_coordinate(){ } public Gps_coordinate(double lat, double longi, double alt) { Set_altitude(alt); Set_decimal(lat, longi); } public Gps_coordinate(String lat, String longi, String alt) { Set_str(lat,longi); Set_altitude(alt); } //uses meters public void Set_altitude(double alt) { if (alt > -500 && alt < 50000000) { altitude = alt; alt_valid = true; } else { alt_valid = false; } } public void Set_altitude(String alt) { try { double a = Double.parseDouble(alt); Set_altitude(a); } catch (Exception e) { alt_valid = false; } } public void Set_str(String lat, String longi) { //different formats: //NMEA: (-)DDMM.mmm... (-)DDDMM.mmm... //decimal: (-)(D)D.ddd... (-)(DD)D.ddd... //int: something else, no decimal places int offset_lat=0; int offset_long=0; if (lat.length() < 3 || lat.length() < 3) { latlong_valid = false; return; } if (lat.charAt(0) == '-') offset_lat = 1; + else if (lat.charAt(0) == '+') + lat = lat.substring(1); if (longi.charAt(0) == '-') offset_long = 1; + else if (longi.charAt(0) == '+') + longi = longi.substring(1); int i,j; i = lat.indexOf('.'); j = longi.indexOf('.'); try { if (i < 0 || j < 0) // 1/10s of a microdegree { Set_decimal(Double.parseDouble(lat)/1e7, Double.parseDouble(longi)/1e7); return; } else if (i == 4+offset_lat) //NMEA { if (j == 5 + offset_long) //confirmed NMEA { int la1 = Integer.parseInt(lat.substring(0, offset_lat+2)); //get the (-)DD part int lo1 = Integer.parseInt(longi.substring(0, offset_long+3)); //get the (-)DDD part double la2 = Double.parseDouble(lat.substring(offset_lat+2,lat.length())); //get the MM.mmmm part double lo2 = Double.parseDouble(longi.substring(offset_long+3,longi.length())); //get the MM.mmmm part - if (la1 < 0) + if (offset_lat > 0) la2 = -1 * la2; - if (lo1 < 0) + if (offset_long > 0) lo2 = -1 * lo2; Set_decimal((double)la1 + la2/60,(double)lo1 + lo2/60); } else { latlong_valid = false; return; } } else if (i > 4+offset_lat || j > 5+offset_lat) //junk { latlong_valid = false; return; } else //decimal { Set_decimal(Double.parseDouble(lat), Double.parseDouble(longi)); } } catch (Exception e) { latlong_valid = false; return; } } public void Set_decimal(double lat, double longi) { if (verify(lat,longi)) { latitude = lat; longitude = longi; latlong_valid = true; } else latlong_valid = false; } public void Set_NMEA(String lat, String longi) { } public void Set_NMEA(String lat, String longi, char NS, char EW) { } private boolean verify(double lat, double longi) { if (lat < 90 && lat > -90 && longi > -180 && longi < 180) return true; else return false; } }
false
true
public void Set_str(String lat, String longi) { //different formats: //NMEA: (-)DDMM.mmm... (-)DDDMM.mmm... //decimal: (-)(D)D.ddd... (-)(DD)D.ddd... //int: something else, no decimal places int offset_lat=0; int offset_long=0; if (lat.length() < 3 || lat.length() < 3) { latlong_valid = false; return; } if (lat.charAt(0) == '-') offset_lat = 1; if (longi.charAt(0) == '-') offset_long = 1; int i,j; i = lat.indexOf('.'); j = longi.indexOf('.'); try { if (i < 0 || j < 0) // 1/10s of a microdegree { Set_decimal(Double.parseDouble(lat)/1e7, Double.parseDouble(longi)/1e7); return; } else if (i == 4+offset_lat) //NMEA { if (j == 5 + offset_long) //confirmed NMEA { int la1 = Integer.parseInt(lat.substring(0, offset_lat+2)); //get the (-)DD part int lo1 = Integer.parseInt(longi.substring(0, offset_long+3)); //get the (-)DDD part double la2 = Double.parseDouble(lat.substring(offset_lat+2,lat.length())); //get the MM.mmmm part double lo2 = Double.parseDouble(longi.substring(offset_long+3,longi.length())); //get the MM.mmmm part if (la1 < 0) la2 = -1 * la2; if (lo1 < 0) lo2 = -1 * lo2; Set_decimal((double)la1 + la2/60,(double)lo1 + lo2/60); } else { latlong_valid = false; return; } } else if (i > 4+offset_lat || j > 5+offset_lat) //junk { latlong_valid = false; return; } else //decimal { Set_decimal(Double.parseDouble(lat), Double.parseDouble(longi)); } } catch (Exception e) { latlong_valid = false; return; } }
public void Set_str(String lat, String longi) { //different formats: //NMEA: (-)DDMM.mmm... (-)DDDMM.mmm... //decimal: (-)(D)D.ddd... (-)(DD)D.ddd... //int: something else, no decimal places int offset_lat=0; int offset_long=0; if (lat.length() < 3 || lat.length() < 3) { latlong_valid = false; return; } if (lat.charAt(0) == '-') offset_lat = 1; else if (lat.charAt(0) == '+') lat = lat.substring(1); if (longi.charAt(0) == '-') offset_long = 1; else if (longi.charAt(0) == '+') longi = longi.substring(1); int i,j; i = lat.indexOf('.'); j = longi.indexOf('.'); try { if (i < 0 || j < 0) // 1/10s of a microdegree { Set_decimal(Double.parseDouble(lat)/1e7, Double.parseDouble(longi)/1e7); return; } else if (i == 4+offset_lat) //NMEA { if (j == 5 + offset_long) //confirmed NMEA { int la1 = Integer.parseInt(lat.substring(0, offset_lat+2)); //get the (-)DD part int lo1 = Integer.parseInt(longi.substring(0, offset_long+3)); //get the (-)DDD part double la2 = Double.parseDouble(lat.substring(offset_lat+2,lat.length())); //get the MM.mmmm part double lo2 = Double.parseDouble(longi.substring(offset_long+3,longi.length())); //get the MM.mmmm part if (offset_lat > 0) la2 = -1 * la2; if (offset_long > 0) lo2 = -1 * lo2; Set_decimal((double)la1 + la2/60,(double)lo1 + lo2/60); } else { latlong_valid = false; return; } } else if (i > 4+offset_lat || j > 5+offset_lat) //junk { latlong_valid = false; return; } else //decimal { Set_decimal(Double.parseDouble(lat), Double.parseDouble(longi)); } } catch (Exception e) { latlong_valid = false; return; } }
diff --git a/src/henplus/commands/ResultSetRenderer.java b/src/henplus/commands/ResultSetRenderer.java index aab5dbb..33c4146 100644 --- a/src/henplus/commands/ResultSetRenderer.java +++ b/src/henplus/commands/ResultSetRenderer.java @@ -1,173 +1,180 @@ /* * This is free software, licensed under the Gnu Public License (GPL) get a copy from <http://www.gnu.org/licenses/gpl.html> $Id: * ResultSetRenderer.java,v 1.22 2005-06-18 04:58:13 hzeller Exp $ author: Henner Zeller <[email protected]> */ package henplus.commands; import henplus.HenPlus; import henplus.Interruptable; import henplus.OutputDevice; import henplus.view.Column; import henplus.view.ColumnMetaData; import henplus.view.TableRenderer; import java.io.Reader; import java.sql.Clob; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; /** * document me. */ public class ResultSetRenderer implements Interruptable { private final ResultSet _rset; private final ResultSetMetaData _meta; private final TableRenderer _table; private final int _columns; private final int[] _showColumns; private boolean _beyondLimit; private long _firstRowTime; private final long _clobLimit = 8192; private final int _rowLimit; private volatile boolean _running; public ResultSetRenderer(final ResultSet rset, final String columnDelimiter, final boolean enableHeader, final boolean enableFooter, final int limit, final OutputDevice out, final int[] show) throws SQLException { _rset = rset; _beyondLimit = false; _firstRowTime = -1; _showColumns = show; _rowLimit = limit; _meta = rset.getMetaData(); _columns = show != null ? show.length : _meta.getColumnCount(); _table = new TableRenderer(getDisplayMeta(_meta), out, columnDelimiter, enableHeader, enableFooter); } public ResultSetRenderer(final ResultSet rset, final String columnDelimiter, final boolean enableHeader, final boolean enableFooter, final int limit, final OutputDevice out) throws SQLException { this(rset, columnDelimiter, enableHeader, enableFooter, limit, out, null); } // Interruptable interface. @Override public synchronized void interrupt() { _running = false; } public ColumnMetaData[] getDisplayMetaData() { return _table.getMetaData(); } private String readClob(final Clob c) throws SQLException { if (c == null) { return null; } final StringBuilder result = new StringBuilder(); long restLimit = _clobLimit; try { final Reader in = c.getCharacterStream(); final char[] buf = new char[4096]; int r; while (restLimit > 0 && (r = in.read(buf, 0, (int) Math.min(buf.length, restLimit))) > 0) { result.append(buf, 0, r); restLimit -= r; } } catch (final Exception e) { HenPlus.msg().println(e.toString()); } if (restLimit == 0) { result.append("..."); } return result.toString(); } public int execute() throws SQLException { int rows = 0; _running = true; try { while (_running && _rset.next()) { final Column[] currentRow = new Column[_columns]; for (int i = 0; i < _columns; ++i) { final int col = _showColumns != null ? _showColumns[i] : i + 1; String colString; - if (_meta.getColumnType(col) == Types.CLOB) { - colString = readClob(_rset.getClob(col)); - } else { - colString = _rset.getString(col); + switch (_meta.getColumnType(col)) { + case Types.CLOB: + colString = readClob(_rset.getClob(col)); + break; + case Types.BIT: + case Types.BOOLEAN: + colString = _rset.getObject(col) == null ? null : Boolean.toString(_rset.getBoolean(col)); + break; + default: + colString = _rset.getString(col); + break; } final Column thisCol = new Column(colString); currentRow[i] = thisCol; } if (_firstRowTime < 0) { // read first row completely. _firstRowTime = System.currentTimeMillis(); } _table.addRow(currentRow); ++rows; if (rows >= _rowLimit) { _beyondLimit = true; break; } } _table.closeTable(); if (!_running) { try { _rset.getStatement().cancel(); } catch (final Exception e) { HenPlus.msg().println("cancel statement failed: " + e.getMessage()); } } } finally { _rset.close(); } return rows; } public boolean limitReached() { return _beyondLimit; } public long getFirstRowTime() { return _firstRowTime; } /** * determine meta data necesary for display. */ private ColumnMetaData[] getDisplayMeta(final ResultSetMetaData m) throws SQLException { final ColumnMetaData[] result = new ColumnMetaData[_columns]; for (int i = 0; i < result.length; ++i) { final int col = _showColumns != null ? _showColumns[i] : i + 1; int alignment = ColumnMetaData.ALIGN_LEFT; final String columnLabel = m.getColumnLabel(col); /* * int width = Math.max(m.getColumnDisplaySize(i), * columnLabel.length()); */ switch (m.getColumnType(col)) { case Types.NUMERIC: case Types.INTEGER: case Types.REAL: case Types.SMALLINT: case Types.TINYINT: alignment = ColumnMetaData.ALIGN_RIGHT; break; } result[i] = new ColumnMetaData(columnLabel, alignment); } return result; } } /* * Local variables: c-basic-offset: 4 compile-command: * "ant -emacs -find build.xml" End: */
true
true
public int execute() throws SQLException { int rows = 0; _running = true; try { while (_running && _rset.next()) { final Column[] currentRow = new Column[_columns]; for (int i = 0; i < _columns; ++i) { final int col = _showColumns != null ? _showColumns[i] : i + 1; String colString; if (_meta.getColumnType(col) == Types.CLOB) { colString = readClob(_rset.getClob(col)); } else { colString = _rset.getString(col); } final Column thisCol = new Column(colString); currentRow[i] = thisCol; } if (_firstRowTime < 0) { // read first row completely. _firstRowTime = System.currentTimeMillis(); } _table.addRow(currentRow); ++rows; if (rows >= _rowLimit) { _beyondLimit = true; break; } } _table.closeTable(); if (!_running) { try { _rset.getStatement().cancel(); } catch (final Exception e) { HenPlus.msg().println("cancel statement failed: " + e.getMessage()); } } } finally { _rset.close(); } return rows; }
public int execute() throws SQLException { int rows = 0; _running = true; try { while (_running && _rset.next()) { final Column[] currentRow = new Column[_columns]; for (int i = 0; i < _columns; ++i) { final int col = _showColumns != null ? _showColumns[i] : i + 1; String colString; switch (_meta.getColumnType(col)) { case Types.CLOB: colString = readClob(_rset.getClob(col)); break; case Types.BIT: case Types.BOOLEAN: colString = _rset.getObject(col) == null ? null : Boolean.toString(_rset.getBoolean(col)); break; default: colString = _rset.getString(col); break; } final Column thisCol = new Column(colString); currentRow[i] = thisCol; } if (_firstRowTime < 0) { // read first row completely. _firstRowTime = System.currentTimeMillis(); } _table.addRow(currentRow); ++rows; if (rows >= _rowLimit) { _beyondLimit = true; break; } } _table.closeTable(); if (!_running) { try { _rset.getStatement().cancel(); } catch (final Exception e) { HenPlus.msg().println("cancel statement failed: " + e.getMessage()); } } } finally { _rset.close(); } return rows; }
diff --git a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/utils/LabelProviderFactory.java b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/utils/LabelProviderFactory.java index 4af41e4..00a9eb1 100644 --- a/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/utils/LabelProviderFactory.java +++ b/com.heroku.eclipse.ui/src/com/heroku/eclipse/ui/utils/LabelProviderFactory.java @@ -1,202 +1,202 @@ package com.heroku.eclipse.ui.utils; import java.util.List; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.swt.graphics.Image; import com.heroku.api.App; import com.heroku.api.Collaborator; import com.heroku.api.Proc; import com.heroku.eclipse.core.services.HerokuServices; import com.heroku.eclipse.core.services.model.HerokuProc; import com.heroku.eclipse.core.services.model.KeyValue; /** * Factory reponsible for creating various labels for App and Proc instances * * @author [email protected] */ public class LabelProviderFactory { /* * ========================================== * App Element * ========================================== */ /** * @param services * @param procListCallback * @return the fitting LabelProvider */ public static ColumnLabelProvider createName(final HerokuServices services, final RunnableWithReturn<List<HerokuProc>, App> procListCallback) { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getName(); } else if (element instanceof HerokuProc) { HerokuProc proc = (HerokuProc) element; return proc.getDynoName() + " (" + proc.getHerokuProc().getPrettyState() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } return ""; //$NON-NLS-1$ } @Override public Image getImage(Object element) { if (element instanceof App) { List<HerokuProc> l = procListCallback.run((App) element); if (l != null) { ProcessState total = ProcessState.UNKNOWN; for (HerokuProc p : l) { ProcessState s = ProcessState.parseRest(p.getHerokuProc().getState()); if (s.ordinal() < total.ordinal()) { total = s; } } return getStateIcon(total); } } - else if (element instanceof Proc) { - Proc p = (Proc) element; - return getStateIcon(ProcessState.parseRest(p.getState())); + else if (element instanceof HerokuProc) { + HerokuProc p = (HerokuProc) element; + return getStateIcon(ProcessState.parseRest(p.getHerokuProc().getState())); } return super.getImage(element); } private Image getStateIcon(ProcessState state) { if (state == ProcessState.IDLE) { return IconKeys.getImage(IconKeys.ICON_PROCESS_IDLE); } else if (state == ProcessState.UP) { return IconKeys.getImage(IconKeys.ICON_PROCESS_UP); } else { return IconKeys.getImage(IconKeys.ICON_PROCESS_UNKNOWN); } } }; } /** * @return the name of an App as a LabelProvider */ public static ColumnLabelProvider createApp_Name() { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getName(); } return ""; //$NON-NLS-1$ } }; } /** * @return the git URL of an App as a LabelProvider */ public static ColumnLabelProvider createApp_GitUrl() { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getGitUrl(); } return ""; //$NON-NLS-1$ } }; } /** * @return the web URL of an App as a LabelProvider */ public static ColumnLabelProvider createApp_Url() { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getWebUrl(); } return ""; //$NON-NLS-1$ } }; } /* * ========================================== * Contributor Element * ========================================== */ /** * @return the email address of a collaborator as a LabelProvider */ public static ColumnLabelProvider createCollaborator_Email() { return new ColumnLabelProvider() { @Override public String getText(Object element) { Collaborator c = (Collaborator) element; return c.getEmail(); } }; } /** * @param ownerCheckCallback * @return the LabelProvider indicating an App owner */ public static ColumnLabelProvider createCollaborator_Owner(final RunnableWithReturn<Boolean, Collaborator> ownerCheckCallback) { return new ColumnLabelProvider() { @Override public String getText(Object element) { return ""; //$NON-NLS-1$ } @Override public Image getImage(Object element) { if (ownerCheckCallback.run((Collaborator) element)) { return IconKeys.getImage(IconKeys.ICON_APPLICATION_OWNER); } return super.getImage(element); } }; } /* * ========================================== * Environment variables * ========================================== */ /** * @return the name of an environment variable as a LabelProvider */ public static ColumnLabelProvider createEnv_Key() { return new ColumnLabelProvider() { @Override public String getText(Object element) { return ((KeyValue)element).getKey(); } }; } /** * @return the value of an environment variable as a LabelProvider */ public static ColumnLabelProvider createEnv_Value() { return new ColumnLabelProvider() { @Override public String getText(Object element) { return ((KeyValue)element).getValue(); } }; } }
true
true
public static ColumnLabelProvider createName(final HerokuServices services, final RunnableWithReturn<List<HerokuProc>, App> procListCallback) { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getName(); } else if (element instanceof HerokuProc) { HerokuProc proc = (HerokuProc) element; return proc.getDynoName() + " (" + proc.getHerokuProc().getPrettyState() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } return ""; //$NON-NLS-1$ } @Override public Image getImage(Object element) { if (element instanceof App) { List<HerokuProc> l = procListCallback.run((App) element); if (l != null) { ProcessState total = ProcessState.UNKNOWN; for (HerokuProc p : l) { ProcessState s = ProcessState.parseRest(p.getHerokuProc().getState()); if (s.ordinal() < total.ordinal()) { total = s; } } return getStateIcon(total); } } else if (element instanceof Proc) { Proc p = (Proc) element; return getStateIcon(ProcessState.parseRest(p.getState())); } return super.getImage(element); } private Image getStateIcon(ProcessState state) { if (state == ProcessState.IDLE) { return IconKeys.getImage(IconKeys.ICON_PROCESS_IDLE); } else if (state == ProcessState.UP) { return IconKeys.getImage(IconKeys.ICON_PROCESS_UP); } else { return IconKeys.getImage(IconKeys.ICON_PROCESS_UNKNOWN); } } }; }
public static ColumnLabelProvider createName(final HerokuServices services, final RunnableWithReturn<List<HerokuProc>, App> procListCallback) { return new ColumnLabelProvider() { @Override public String getText(Object element) { if (element instanceof App) { App app = (App) element; return app.getName(); } else if (element instanceof HerokuProc) { HerokuProc proc = (HerokuProc) element; return proc.getDynoName() + " (" + proc.getHerokuProc().getPrettyState() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } return ""; //$NON-NLS-1$ } @Override public Image getImage(Object element) { if (element instanceof App) { List<HerokuProc> l = procListCallback.run((App) element); if (l != null) { ProcessState total = ProcessState.UNKNOWN; for (HerokuProc p : l) { ProcessState s = ProcessState.parseRest(p.getHerokuProc().getState()); if (s.ordinal() < total.ordinal()) { total = s; } } return getStateIcon(total); } } else if (element instanceof HerokuProc) { HerokuProc p = (HerokuProc) element; return getStateIcon(ProcessState.parseRest(p.getHerokuProc().getState())); } return super.getImage(element); } private Image getStateIcon(ProcessState state) { if (state == ProcessState.IDLE) { return IconKeys.getImage(IconKeys.ICON_PROCESS_IDLE); } else if (state == ProcessState.UP) { return IconKeys.getImage(IconKeys.ICON_PROCESS_UP); } else { return IconKeys.getImage(IconKeys.ICON_PROCESS_UNKNOWN); } } }; }
diff --git a/src/gui/MyPage.java b/src/gui/MyPage.java index e755099..7bca0da 100644 --- a/src/gui/MyPage.java +++ b/src/gui/MyPage.java @@ -1,556 +1,556 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gui; import db.DatabaseHandler; import main.Register; import map.MapViewer; import util.GeneralUtil; import util.Vec2; import javax.swing.*; import java.awt.*; import java.sql.SQLException; public class MyPage extends javax.swing.JFrame implements MapViewer.MapViewerListener{ /** * Creates new form MyPage */ private DatabaseHandler mHandler; private Register mRegister; private int farmerID; private MapViewer map; private JFrame previous; private double farmX, farmY; private MainMenu main; public MyPage(MainMenu main, JFrame previous, int farmerID, DatabaseHandler mHandler, Register mRegister){ this.main = main; map = new MapViewer(); Vec2 pos = mRegister.getFarmerLocation(); map.setMapCenter(mRegister.getFarmerLocation()); map.addMarker("Home", pos.x, pos.y, GeneralUtil.farmColor); this.mRegister = mRegister; this.farmerID = farmerID; this.mHandler = mHandler; initComponents(); this.setLocationRelativeTo(previous); this.previous = previous; this.previous.setFocusable(false); this.previous.setVisible(false); this.farmX = 0; this.farmY = 0; this.map.addListener(this); } /** * 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() { label1 = new java.awt.Label(); label2 = new java.awt.Label(); label3 = new java.awt.Label(); label4 = new java.awt.Label(); label5 = new java.awt.Label(); label15 = new java.awt.Label(); textField1 = new java.awt.TextField(); textField2 = new java.awt.TextField(); textField3 = new java.awt.TextField(); textField4 = new java.awt.TextField(); label6 = new java.awt.Label(); label7 = new java.awt.Label(); jPasswordField1 = new javax.swing.JPasswordField(); label8 = new java.awt.Label(); jPasswordField2 = new javax.swing.JPasswordField(); label9 = new java.awt.Label(); jPasswordField3 = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); label10 = new java.awt.Label(); label11 = new java.awt.Label(); textField5 = new java.awt.TextField(); label12 = new java.awt.Label(); textField6 = new java.awt.TextField(); label13 = new java.awt.Label(); textField7 = new java.awt.TextField(); label14 = new java.awt.Label(); textField8 = new java.awt.TextField(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); textField9 = new java.awt.TextField(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); map.getMap().setPreferredSize(new Dimension(200,200)); label1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label1.setText("MinSide"); /* Redundant? String mobilnr = textField3.getText(); String email = textField4.getText(); String gpsw = jPasswordField1.getText(); String npsw = jPasswordField2.getText(); String npswg = jPasswordField3.getText(); // Kontaktpersons-informasjon String kfornavn = textField5.getText(); String ketternavn = textField6.getText(); String kmobilnr = textField7.getText(); String kemail = textField8.getText(); */ String username = ""; try { username = mHandler.getFarmerUsername(farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); } label15.setText("Brukernavn"); textField9.setText(username); Object[] farmer; Object[] contact; try { farmer = mHandler.getFarmerInformation(this.farmerID); contact = mHandler.getFarmerContactInformation(this.farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); return; } String fFirstName; String fLastName; String fCellPhone; String fMail; if(farmer != null){ String farmerFullName = (String)farmer[0]; fFirstName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(0,farmerFullName.lastIndexOf(" ")) : farmerFullName; fLastName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(farmerFullName.lastIndexOf(" ")+1 != farmerFullName.length() ? farmerFullName.lastIndexOf(" ")+1 : farmerFullName.lastIndexOf(" ")) : ""; - fCellPhone = (String)contact[1]; - fMail = (String)contact[2]; + fCellPhone = (String)farmer[1]; + fMail = (String)farmer[2]; }else{ fFirstName = ""; fLastName = ""; fCellPhone = ""; fMail = ""; } String kFirstName; String kLastName; String kCellPhone; String kMail; if(contact != null){ String contactFullName = (String)contact[0]; kFirstName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(0,contactFullName.lastIndexOf(" ")) : contactFullName; kLastName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(contactFullName.lastIndexOf(" ")+1 != contactFullName.length() ? contactFullName.lastIndexOf(" ")+1 : contactFullName.lastIndexOf(" ")) : ""; kCellPhone = (String)contact[1]; kMail = (String)contact[2]; }else{ kFirstName = ""; kLastName = ""; kCellPhone = ""; kMail = ""; } label2.setText("Fornavn"); textField1.setText(fFirstName); label3.setText("Etternavn"); textField2.setText(fLastName); label4.setText("Mobilnummer"); textField3.setText(fCellPhone); label5.setText("E-post"); textField4.setText(fMail); label6.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N label6.setText("Skriv inn evt. endringer og trykk \"Lagre endringer nederst\""); label7.setText("Gammelt passord"); jPasswordField1.setText("jPasswordField1"); label8.setText("Nytt passord"); jPasswordField2.setText("jPasswordField2"); label9.setText("Gjenta nytt passord"); jPasswordField3.setText("jPasswordField3"); jButton1.setText("Lagre endringer"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); label10.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label10.setText("Kontaktperson"); label11.setText("Fornavn"); textField5.setText(kFirstName); label12.setText("Etternavn"); textField6.setText(kLastName); label13.setText("Mobilnummer"); textField7.setText(kCellPhone); jLabel1.setText("Gårdens plassering"); label14.setText("E-post"); textField8.setText(kMail); jMenu1.setText("File"); jMenuItem3.setText("Til hovedmeny"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 175, Short.MAX_VALUE) ); jMenuItem1.setText("Logg ut"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setText("Exit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(77, 77, 77))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(label15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(map.getMap(), javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel1)) .addGap(20, 20, 20)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(label15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(textField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(map.getMap(), javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1))) .addContainerGap()) ); pack(); }// </editor-fold> /** * Exits the program, from the Menu Bar */ private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed System.exit(0); }//GEN-LAST:event_jMenuItem2ActionPerformed /** * Accept the new information about the user and his/her contact person and save it */ private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed //Bondens informasjon String account = textField9.getText(); String mfornavn = textField1.getText(); String metternavn = textField2.getText(); String mobilnr = textField3.getText(); String email = textField4.getText(); String gpsw = charToString(jPasswordField1.getPassword()); String npsw = charToString(jPasswordField2.getPassword()); String npswg = charToString(jPasswordField3.getPassword()); String farmerName = mfornavn + " "+ metternavn; try { mHandler.setFarmerInformation(farmerID, account, farmerName, mobilnr, email); } catch (SQLException e) { e.printStackTrace(); Error error = new Error(this, e.getMessage()); error.setVisible(true); } // Kontaktpersons-informasjon String kfornavn = textField5.getText(); String ketternavn = textField6.getText(); String kmobilnr = textField7.getText(); String kemail = textField8.getText(); String kfarmerName = kfornavn + " " + ketternavn; try { if(mHandler.hasFarmerContact(farmerID)){ mHandler.updateFarmerContact(farmerID, kfarmerName, kmobilnr, kemail); }else{ mHandler.setFarmerContact(farmerID, kfarmerName, kmobilnr, kemail); } }catch(SQLException e){ e.printStackTrace(); Error error = new Error(this, e.getMessage()); error.setVisible(true); } if(!(npsw.equals("jPasswordField2") && npswg.equals("jPasswordField3"))){ if((farmerID = mHandler.authenticate(account, gpsw)) != -1){ if(npsw.equals(npswg)){ try { mHandler.resetPassword(farmerID,npsw); } catch (SQLException e) { e.printStackTrace(); Error error = new Error(this, e.getMessage()); error.setVisible(true); } } } } mRegister.setFarmerLocation(this.farmX, this.farmY); this.main.setFocusable(true); this.main.setVisible(true); this.main.setLocationRelativeTo(this); this.dispose(); } /** * Logs out of the program, from the Menu Bar */ private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed Welcome welcome = new Welcome(main.main, this, mHandler); welcome.setVisible(true); this.dispose(); }//GEN-LAST:event_jMenuItem1ActionPerformed /** * Go to MainMenu, from the Menu Bar */ private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed this.main.setFocusable(true); this.main.setVisible(true); this.main.setLocationRelativeTo(this); this.dispose(); }//GEN-LAST:event_jMenuItem3ActionPerformed private String charToString(char[] array){ StringBuilder sb = new StringBuilder(); for(char c : array){ sb.append(c); } return sb.toString(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JPasswordField jPasswordField2; private javax.swing.JPasswordField jPasswordField3; private java.awt.Label label1; private java.awt.Label label10; private java.awt.Label label11; private java.awt.Label label12; private java.awt.Label label13; private java.awt.Label label14; private java.awt.Label label15; private java.awt.Label label2; private java.awt.Label label3; private java.awt.Label label4; private java.awt.Label label5; private java.awt.Label label6; private java.awt.Label label7; private java.awt.Label label8; private java.awt.Label label9; private java.awt.TextField textField1; private java.awt.TextField textField2; private java.awt.TextField textField3; private java.awt.TextField textField4; private java.awt.TextField textField5; private java.awt.TextField textField6; private java.awt.TextField textField7; private java.awt.TextField textField8; private java.awt.TextField textField9; private javax.swing.JPanel jPanel1; private javax.swing.JLabel jLabel1; @Override public void nodeClicked(MapViewer.NodeInfo n) { //Do nothing } @Override public void mapClicked(double x, double y) { System.out.println("Hello we clicked something at" + x + ", " + y); this.farmX = x; this.farmY = y; this.map.removeMarkers(); this.map.addMarker("Home", x, y, GeneralUtil.farmColor); } // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { label1 = new java.awt.Label(); label2 = new java.awt.Label(); label3 = new java.awt.Label(); label4 = new java.awt.Label(); label5 = new java.awt.Label(); label15 = new java.awt.Label(); textField1 = new java.awt.TextField(); textField2 = new java.awt.TextField(); textField3 = new java.awt.TextField(); textField4 = new java.awt.TextField(); label6 = new java.awt.Label(); label7 = new java.awt.Label(); jPasswordField1 = new javax.swing.JPasswordField(); label8 = new java.awt.Label(); jPasswordField2 = new javax.swing.JPasswordField(); label9 = new java.awt.Label(); jPasswordField3 = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); label10 = new java.awt.Label(); label11 = new java.awt.Label(); textField5 = new java.awt.TextField(); label12 = new java.awt.Label(); textField6 = new java.awt.TextField(); label13 = new java.awt.Label(); textField7 = new java.awt.TextField(); label14 = new java.awt.Label(); textField8 = new java.awt.TextField(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); textField9 = new java.awt.TextField(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); map.getMap().setPreferredSize(new Dimension(200,200)); label1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label1.setText("MinSide"); /* Redundant? String mobilnr = textField3.getText(); String email = textField4.getText(); String gpsw = jPasswordField1.getText(); String npsw = jPasswordField2.getText(); String npswg = jPasswordField3.getText(); // Kontaktpersons-informasjon String kfornavn = textField5.getText(); String ketternavn = textField6.getText(); String kmobilnr = textField7.getText(); String kemail = textField8.getText(); */ String username = ""; try { username = mHandler.getFarmerUsername(farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); } label15.setText("Brukernavn"); textField9.setText(username); Object[] farmer; Object[] contact; try { farmer = mHandler.getFarmerInformation(this.farmerID); contact = mHandler.getFarmerContactInformation(this.farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); return; } String fFirstName; String fLastName; String fCellPhone; String fMail; if(farmer != null){ String farmerFullName = (String)farmer[0]; fFirstName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(0,farmerFullName.lastIndexOf(" ")) : farmerFullName; fLastName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(farmerFullName.lastIndexOf(" ")+1 != farmerFullName.length() ? farmerFullName.lastIndexOf(" ")+1 : farmerFullName.lastIndexOf(" ")) : ""; fCellPhone = (String)contact[1]; fMail = (String)contact[2]; }else{ fFirstName = ""; fLastName = ""; fCellPhone = ""; fMail = ""; } String kFirstName; String kLastName; String kCellPhone; String kMail; if(contact != null){ String contactFullName = (String)contact[0]; kFirstName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(0,contactFullName.lastIndexOf(" ")) : contactFullName; kLastName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(contactFullName.lastIndexOf(" ")+1 != contactFullName.length() ? contactFullName.lastIndexOf(" ")+1 : contactFullName.lastIndexOf(" ")) : ""; kCellPhone = (String)contact[1]; kMail = (String)contact[2]; }else{ kFirstName = ""; kLastName = ""; kCellPhone = ""; kMail = ""; } label2.setText("Fornavn"); textField1.setText(fFirstName); label3.setText("Etternavn"); textField2.setText(fLastName); label4.setText("Mobilnummer"); textField3.setText(fCellPhone); label5.setText("E-post"); textField4.setText(fMail); label6.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N label6.setText("Skriv inn evt. endringer og trykk \"Lagre endringer nederst\""); label7.setText("Gammelt passord"); jPasswordField1.setText("jPasswordField1"); label8.setText("Nytt passord"); jPasswordField2.setText("jPasswordField2"); label9.setText("Gjenta nytt passord"); jPasswordField3.setText("jPasswordField3"); jButton1.setText("Lagre endringer"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); label10.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label10.setText("Kontaktperson"); label11.setText("Fornavn"); textField5.setText(kFirstName); label12.setText("Etternavn"); textField6.setText(kLastName); label13.setText("Mobilnummer"); textField7.setText(kCellPhone); jLabel1.setText("Gårdens plassering"); label14.setText("E-post"); textField8.setText(kMail); jMenu1.setText("File"); jMenuItem3.setText("Til hovedmeny"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 175, Short.MAX_VALUE) ); jMenuItem1.setText("Logg ut"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setText("Exit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(77, 77, 77))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(label15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(map.getMap(), javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel1)) .addGap(20, 20, 20)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(label15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(textField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(map.getMap(), javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1))) .addContainerGap()) ); pack(); }// </editor-fold>
private void initComponents() { label1 = new java.awt.Label(); label2 = new java.awt.Label(); label3 = new java.awt.Label(); label4 = new java.awt.Label(); label5 = new java.awt.Label(); label15 = new java.awt.Label(); textField1 = new java.awt.TextField(); textField2 = new java.awt.TextField(); textField3 = new java.awt.TextField(); textField4 = new java.awt.TextField(); label6 = new java.awt.Label(); label7 = new java.awt.Label(); jPasswordField1 = new javax.swing.JPasswordField(); label8 = new java.awt.Label(); jPasswordField2 = new javax.swing.JPasswordField(); label9 = new java.awt.Label(); jPasswordField3 = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); label10 = new java.awt.Label(); label11 = new java.awt.Label(); textField5 = new java.awt.TextField(); label12 = new java.awt.Label(); textField6 = new java.awt.TextField(); label13 = new java.awt.Label(); textField7 = new java.awt.TextField(); label14 = new java.awt.Label(); textField8 = new java.awt.TextField(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); textField9 = new java.awt.TextField(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); map.getMap().setPreferredSize(new Dimension(200,200)); label1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label1.setText("MinSide"); /* Redundant? String mobilnr = textField3.getText(); String email = textField4.getText(); String gpsw = jPasswordField1.getText(); String npsw = jPasswordField2.getText(); String npswg = jPasswordField3.getText(); // Kontaktpersons-informasjon String kfornavn = textField5.getText(); String ketternavn = textField6.getText(); String kmobilnr = textField7.getText(); String kemail = textField8.getText(); */ String username = ""; try { username = mHandler.getFarmerUsername(farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); } label15.setText("Brukernavn"); textField9.setText(username); Object[] farmer; Object[] contact; try { farmer = mHandler.getFarmerInformation(this.farmerID); contact = mHandler.getFarmerContactInformation(this.farmerID); } catch (SQLException e) { Error error = new Error(this, e.getMessage()); error.setVisible(true); return; } String fFirstName; String fLastName; String fCellPhone; String fMail; if(farmer != null){ String farmerFullName = (String)farmer[0]; fFirstName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(0,farmerFullName.lastIndexOf(" ")) : farmerFullName; fLastName = farmerFullName.lastIndexOf(" ") != -1 ? farmerFullName.substring(farmerFullName.lastIndexOf(" ")+1 != farmerFullName.length() ? farmerFullName.lastIndexOf(" ")+1 : farmerFullName.lastIndexOf(" ")) : ""; fCellPhone = (String)farmer[1]; fMail = (String)farmer[2]; }else{ fFirstName = ""; fLastName = ""; fCellPhone = ""; fMail = ""; } String kFirstName; String kLastName; String kCellPhone; String kMail; if(contact != null){ String contactFullName = (String)contact[0]; kFirstName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(0,contactFullName.lastIndexOf(" ")) : contactFullName; kLastName = contactFullName.lastIndexOf(" ") != -1 ? contactFullName.substring(contactFullName.lastIndexOf(" ")+1 != contactFullName.length() ? contactFullName.lastIndexOf(" ")+1 : contactFullName.lastIndexOf(" ")) : ""; kCellPhone = (String)contact[1]; kMail = (String)contact[2]; }else{ kFirstName = ""; kLastName = ""; kCellPhone = ""; kMail = ""; } label2.setText("Fornavn"); textField1.setText(fFirstName); label3.setText("Etternavn"); textField2.setText(fLastName); label4.setText("Mobilnummer"); textField3.setText(fCellPhone); label5.setText("E-post"); textField4.setText(fMail); label6.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N label6.setText("Skriv inn evt. endringer og trykk \"Lagre endringer nederst\""); label7.setText("Gammelt passord"); jPasswordField1.setText("jPasswordField1"); label8.setText("Nytt passord"); jPasswordField2.setText("jPasswordField2"); label9.setText("Gjenta nytt passord"); jPasswordField3.setText("jPasswordField3"); jButton1.setText("Lagre endringer"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); label10.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N label10.setText("Kontaktperson"); label11.setText("Fornavn"); textField5.setText(kFirstName); label12.setText("Etternavn"); textField6.setText(kLastName); label13.setText("Mobilnummer"); textField7.setText(kCellPhone); jLabel1.setText("Gårdens plassering"); label14.setText("E-post"); textField8.setText(kMail); jMenu1.setText("File"); jMenuItem3.setText("Til hovedmeny"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 175, Short.MAX_VALUE) ); jMenuItem1.setText("Logg ut"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setText("Exit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE) .addComponent(jPasswordField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(77, 77, 77))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField3, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(label15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(56, 56, 56) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(map.getMap(), javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel1)) .addGap(20, 20, 20)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(label15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(label12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(textField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(map.getMap(), javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPasswordField3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1))) .addContainerGap()) ); pack(); }// </editor-fold>
diff --git a/src/main/java/com/onarandombox/MultiverseCore/MVPermissions.java b/src/main/java/com/onarandombox/MultiverseCore/MVPermissions.java index 27a84cb..b8822eb 100644 --- a/src/main/java/com/onarandombox/MultiverseCore/MVPermissions.java +++ b/src/main/java/com/onarandombox/MultiverseCore/MVPermissions.java @@ -1,124 +1,123 @@ package com.onarandombox.MultiverseCore; import java.util.List; import java.util.logging.Level; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import com.pneumaticraft.commandhandler.PermissionsInterface; public class MVPermissions implements PermissionsInterface { private MultiverseCore plugin; private PermissionHandler permissions = null; /** * Constructor FTW * * @param plugin Pass along the Core Plugin. */ public MVPermissions(MultiverseCore plugin) { this.plugin = plugin; // We have to see if permissions was loaded before MV was if (this.plugin.getServer().getPluginManager().getPlugin("Permissions") != null) { this.setPermissions(((Permissions) this.plugin.getServer().getPluginManager().getPlugin("Permissions")).getHandler()); this.plugin.log(Level.INFO, "- Attached to Permissions"); } } /** * Check if a Player can teleport to the Destination world from there current world. * * @param p * @param w * @return */ public Boolean canTravelFromWorld(Player p, MVWorld w) { List<String> blackList = w.getWorldBlacklist(); boolean returnValue = true; for (String s : blackList) { if (s.equalsIgnoreCase(p.getWorld().getName())) { returnValue = false; break; } } return returnValue; } public boolean canTravelFromLocation(Player teleporter, Location location) { if(!this.plugin.isMVWorld(location.getWorld().getName())){ return false; } return canTravelFromWorld(teleporter, this.plugin.getMVWorld(location.getWorld().getName())); } /** * Check if the Player has the permissions to enter this world. * * @param p * @param w * @return */ public Boolean canEnterWorld(Player p, MVWorld w) { return this.hasPermission(p, "multiverse.access." + w.getName(), false); } public Boolean canEnterLocation(Player p, Location l) { if(l == null) { return false; } String worldName = l.getWorld().getName(); if(!this.plugin.isMVWorld(worldName)) { return false; } return this.hasPermission(p, "multiverse.access." + worldName, false); } public void setPermissions(PermissionHandler handler) { this.permissions = handler; } public boolean hasPermission(CommandSender sender, String node, boolean isOpRequired) { if (!(sender instanceof Player)) { return true; } Player player = (Player) sender; boolean opFallback = this.plugin.getConfig().getBoolean("opfallback", true); if (this.permissions != null && this.permissions.has(player, node)) { // If Permissions is enabled we check against them. return true; - } else if (sender.hasPermission(node) && !opFallback) { + } else if (sender.hasPermission(node)) { // If Now check the bukkit permissions - // OpFallback must be disabled for this to work return true; } else if (player.isOp() && opFallback) { // If Player is Op we always let them use it if they have the fallback enabled! return true; } // If the Player doesn't have Permissions and isn't an Op then // we return true if OP is not required, otherwise we return false // This allows us to act as a default permission guidance // If they have the op fallback disabled, NO commands will work without a permissions plugin. return !isOpRequired && opFallback; } public String getType() { if (this.permissions != null) { return "Permissions " + this.plugin.getServer().getPluginManager().getPlugin("Permissions").getDescription().getVersion(); } return "Bukkit Permissions/OPs.txt"; } }
false
true
public boolean hasPermission(CommandSender sender, String node, boolean isOpRequired) { if (!(sender instanceof Player)) { return true; } Player player = (Player) sender; boolean opFallback = this.plugin.getConfig().getBoolean("opfallback", true); if (this.permissions != null && this.permissions.has(player, node)) { // If Permissions is enabled we check against them. return true; } else if (sender.hasPermission(node) && !opFallback) { // If Now check the bukkit permissions // OpFallback must be disabled for this to work return true; } else if (player.isOp() && opFallback) { // If Player is Op we always let them use it if they have the fallback enabled! return true; } // If the Player doesn't have Permissions and isn't an Op then // we return true if OP is not required, otherwise we return false // This allows us to act as a default permission guidance // If they have the op fallback disabled, NO commands will work without a permissions plugin. return !isOpRequired && opFallback; }
public boolean hasPermission(CommandSender sender, String node, boolean isOpRequired) { if (!(sender instanceof Player)) { return true; } Player player = (Player) sender; boolean opFallback = this.plugin.getConfig().getBoolean("opfallback", true); if (this.permissions != null && this.permissions.has(player, node)) { // If Permissions is enabled we check against them. return true; } else if (sender.hasPermission(node)) { // If Now check the bukkit permissions return true; } else if (player.isOp() && opFallback) { // If Player is Op we always let them use it if they have the fallback enabled! return true; } // If the Player doesn't have Permissions and isn't an Op then // we return true if OP is not required, otherwise we return false // This allows us to act as a default permission guidance // If they have the op fallback disabled, NO commands will work without a permissions plugin. return !isOpRequired && opFallback; }
diff --git a/src/cytoscape/view/NetworkViewManager.java b/src/cytoscape/view/NetworkViewManager.java index 7d5a52a01..48604d72a 100644 --- a/src/cytoscape/view/NetworkViewManager.java +++ b/src/cytoscape/view/NetworkViewManager.java @@ -1,349 +1,349 @@ package cytoscape.view; import cytoscape.Cytoscape; import cytoscape.CyNetwork; import cytoscape.CyNode; import cytoscape.CyEdge; import cytoscape.view.CyMenus; import cytoscape.view.CyNetworkView; import cytoscape.view.CyNodeView; import cytoscape.view.CyEdgeView; import cytoscape.giny.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; import java.beans.*; public class NetworkViewManager implements PropertyChangeListener, InternalFrameListener, WindowFocusListener, ChangeListener { private java.awt.Container container; private Map networkViewMap; private Map componentMap; private int viewCount = 0; protected CytoscapeDesktop cytoscapeDesktop; protected int VIEW_TYPE; protected SwingPropertyChangeSupport pcs = new SwingPropertyChangeSupport( this ); protected static int frame_count = 0; /** * Constructor for overiding the default Desktop view type */ public NetworkViewManager ( CytoscapeDesktop desktop, int view_type ) { this.cytoscapeDesktop = desktop; VIEW_TYPE = view_type; initialize(); } public NetworkViewManager ( CytoscapeDesktop desktop ) { this.cytoscapeDesktop = desktop; VIEW_TYPE = cytoscapeDesktop.getViewType(); initialize(); } protected void initialize () { if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { //create a Tabbed Style NetworkView manager container = new JTabbedPane( JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT ); ( ( JTabbedPane )container).addChangeListener( this ); } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { container = new JDesktopPane(); //container.addComponentListener( this ); } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { container = null; } // add Help hooks cytoscapeDesktop.getHelpBroker().enableHelp(container, "network-view-manager", null); networkViewMap = new HashMap(); componentMap = new HashMap(); } public SwingPropertyChangeSupport getSwingPropertyChangeSupport() { return pcs; } public JTabbedPane getTabbedPane () { if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { return ( JTabbedPane )container; } return null; } public JDesktopPane getDesktopPane () { if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { return ( JDesktopPane )container; } return null; } //------------------------------// // Fire Events when a Managed Network View gets the Focus /** * For Tabbed Panes */ public void stateChanged ( ChangeEvent e ) { String network_id = ( String )componentMap.get( ( ( JTabbedPane )container).getSelectedComponent() ); if ( network_id == null ) { return; } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, network_id ); } /** * For Internal Frames */ public void internalFrameActivated(InternalFrameEvent e) { String network_id = ( String )componentMap.get( e.getInternalFrame() ); if ( network_id == null ) { return; } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, network_id ); } public void internalFrameClosed(InternalFrameEvent e) {} public void internalFrameClosing(InternalFrameEvent e) {} public void internalFrameDeactivated(InternalFrameEvent e) {} public void internalFrameDeiconified(InternalFrameEvent e) {} public void internalFrameIconified(InternalFrameEvent e) {} public void internalFrameOpened(InternalFrameEvent e) { internalFrameActivated( e ); } /** * For Exteernal Frames */ public void windowGainedFocus(WindowEvent e) { String network_id = ( String )componentMap.get( e.getWindow() ); // System.out.println( " Window Gained Focus: "+ network_id ); if ( network_id == null ) { return; } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, network_id ); } public void windowLostFocus(WindowEvent e) {} /** * This handles all of the incoming PropertyChangeEvents. If you are going to have * multiple NetworkViewManagers, then this method should be extended such that the * desired behaviour is achieved, assuming of course that you want your * NetworkViewManagers to behave differently. */ public void propertyChange ( PropertyChangeEvent e ) { // handle events // handle focus event if ( e.getPropertyName() == CytoscapeDesktop.NETWORK_VIEW_FOCUS ) { String network_id = ( String )e.getNewValue(); e = null; setFocus( network_id ); } // handle putting a newly created CyNetworkView into a Container else if ( e.getPropertyName() == CytoscapeDesktop.NETWORK_VIEW_CREATED ) { CyNetworkView new_view = ( CyNetworkView )e.getNewValue(); createContainer( new_view ); e = null; } // handle a NetworkView destroyed else if ( e.getPropertyName() == CytoscapeDesktop.NETWORK_VIEW_DESTROYED ) { CyNetworkView view = ( CyNetworkView )e.getNewValue(); removeView( view ); e = null; } } /** * Fires a PropertyChangeEvent */ public void firePropertyChange ( String property_type, Object old_value, Object new_value ) { pcs.firePropertyChange( new PropertyChangeEvent( this, property_type, old_value, new_value ) ); } /** * Sets the focus of the passed network, if possible * The Network ID corresponds to the CyNetworkView.getNetwork().getIdentifier() */ protected void setFocus ( String network_id ) { if ( networkViewMap.containsKey( network_id ) ) { // there is a NetworkView for this network if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { try { ( ( JTabbedPane )container ). setSelectedComponent( (Component)networkViewMap.get( network_id ) ); } catch ( Exception e ) { // e.printStackTrace(); // System.err.println( "Network View unable to be focused" ); } } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { try { ( ( JInternalFrame )networkViewMap.get( network_id ) ).setIcon( false ); ( ( JInternalFrame )networkViewMap.get( network_id ) ).show(); ( ( JInternalFrame )networkViewMap.get( network_id ) ).setSelected( true ); } catch ( Exception e ) { System.err.println( "Network View unable to be focused" ); } } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { try { ( ( JFrame )networkViewMap.get( network_id ) ).requestFocus(); //( ( JFrame )networkViewMap.get( network_id ) ).setVisible( true ); } catch ( Exception e ) { System.err.println( "Network View unable to be focused" ); } } } } protected void removeView ( CyNetworkView view ) { if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { try { ( ( JTabbedPane )container ). remove( (Component)networkViewMap.get( view.getNetwork().getIdentifier() ) ); } catch ( Exception e ) { // possible error } } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { try { ( ( JInternalFrame )networkViewMap.get( view.getNetwork().getIdentifier() ) ).dispose(); } catch ( Exception e ) { System.err.println( "Network View unable to be killed" ); } } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { try { ( ( JFrame )networkViewMap.get( view.getNetwork().getIdentifier() ) ).dispose(); } catch ( Exception e ) { System.err.println( "Network View unable to be killed" ); } } networkViewMap.remove( view.getNetwork().getIdentifier() ); } /** * Contains a CyNetworkView according to the view type of this NetworkViewManager */ protected void createContainer ( final CyNetworkView view ) { if ( networkViewMap.containsKey( view.getNetwork().getIdentifier() ) ) { // already contains return; } if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { // put the CyNetworkViews Component into the Tabbed Pane ( ( JTabbedPane )container ).addTab( view.getNetwork().getTitle(), view.getComponent() ); networkViewMap.put( view.getNetwork().getIdentifier(), view.getComponent() ); componentMap.put( view.getComponent(), view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { // create a new InternalFrame and put the CyNetworkViews Component into it JInternalFrame iframe = new JInternalFrame( view.getTitle(), true, true, true, true ); iframe.addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { - Cytoscape.destroyNetwork(view.getNetwork()); } } ); + Cytoscape.destroyNetworkView(view); } } ); ( ( JDesktopPane )container ).add( iframe ); iframe.getContentPane().add( view.getComponent() ); iframe.pack(); iframe.setSize( 400, 400 ); iframe.setVisible( true ); iframe.addInternalFrameListener( this ); networkViewMap.put( view.getNetwork().getIdentifier(), iframe ); componentMap.put( iframe, view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { // create a new JFrame and put the CyNetworkViews Component into it JFrame frame = new JFrame( view.getNetwork().getTitle() ); frame.getContentPane().add( view.getComponent() ); frame.pack(); frame.setSize( 400, 400 ); frame.setVisible( true ); componentMap.put( frame, view.getNetwork().getIdentifier() ); networkViewMap.put( view.getNetwork().getIdentifier(), frame ); frame.addWindowFocusListener( this ); frame.setJMenuBar( cytoscapeDesktop.getCyMenus().getMenuBar()); } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, view.getNetwork().getIdentifier() ); } }
true
true
protected void createContainer ( final CyNetworkView view ) { if ( networkViewMap.containsKey( view.getNetwork().getIdentifier() ) ) { // already contains return; } if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { // put the CyNetworkViews Component into the Tabbed Pane ( ( JTabbedPane )container ).addTab( view.getNetwork().getTitle(), view.getComponent() ); networkViewMap.put( view.getNetwork().getIdentifier(), view.getComponent() ); componentMap.put( view.getComponent(), view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { // create a new InternalFrame and put the CyNetworkViews Component into it JInternalFrame iframe = new JInternalFrame( view.getTitle(), true, true, true, true ); iframe.addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { Cytoscape.destroyNetwork(view.getNetwork()); } } ); ( ( JDesktopPane )container ).add( iframe ); iframe.getContentPane().add( view.getComponent() ); iframe.pack(); iframe.setSize( 400, 400 ); iframe.setVisible( true ); iframe.addInternalFrameListener( this ); networkViewMap.put( view.getNetwork().getIdentifier(), iframe ); componentMap.put( iframe, view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { // create a new JFrame and put the CyNetworkViews Component into it JFrame frame = new JFrame( view.getNetwork().getTitle() ); frame.getContentPane().add( view.getComponent() ); frame.pack(); frame.setSize( 400, 400 ); frame.setVisible( true ); componentMap.put( frame, view.getNetwork().getIdentifier() ); networkViewMap.put( view.getNetwork().getIdentifier(), frame ); frame.addWindowFocusListener( this ); frame.setJMenuBar( cytoscapeDesktop.getCyMenus().getMenuBar()); } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, view.getNetwork().getIdentifier() ); }
protected void createContainer ( final CyNetworkView view ) { if ( networkViewMap.containsKey( view.getNetwork().getIdentifier() ) ) { // already contains return; } if ( VIEW_TYPE == CytoscapeDesktop.TABBED_VIEW ) { // put the CyNetworkViews Component into the Tabbed Pane ( ( JTabbedPane )container ).addTab( view.getNetwork().getTitle(), view.getComponent() ); networkViewMap.put( view.getNetwork().getIdentifier(), view.getComponent() ); componentMap.put( view.getComponent(), view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.INTERNAL_VIEW ) { // create a new InternalFrame and put the CyNetworkViews Component into it JInternalFrame iframe = new JInternalFrame( view.getTitle(), true, true, true, true ); iframe.addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { Cytoscape.destroyNetworkView(view); } } ); ( ( JDesktopPane )container ).add( iframe ); iframe.getContentPane().add( view.getComponent() ); iframe.pack(); iframe.setSize( 400, 400 ); iframe.setVisible( true ); iframe.addInternalFrameListener( this ); networkViewMap.put( view.getNetwork().getIdentifier(), iframe ); componentMap.put( iframe, view.getNetwork().getIdentifier() ); } else if ( VIEW_TYPE == CytoscapeDesktop.EXTERNAL_VIEW ) { // create a new JFrame and put the CyNetworkViews Component into it JFrame frame = new JFrame( view.getNetwork().getTitle() ); frame.getContentPane().add( view.getComponent() ); frame.pack(); frame.setSize( 400, 400 ); frame.setVisible( true ); componentMap.put( frame, view.getNetwork().getIdentifier() ); networkViewMap.put( view.getNetwork().getIdentifier(), frame ); frame.addWindowFocusListener( this ); frame.setJMenuBar( cytoscapeDesktop.getCyMenus().getMenuBar()); } firePropertyChange( CytoscapeDesktop.NETWORK_VIEW_FOCUSED, null, view.getNetwork().getIdentifier() ); }
diff --git a/src/org/fatecrafters/plugins/listeners/PlayerListener.java b/src/org/fatecrafters/plugins/listeners/PlayerListener.java index 4d2006f..51dc962 100644 --- a/src/org/fatecrafters/plugins/listeners/PlayerListener.java +++ b/src/org/fatecrafters/plugins/listeners/PlayerListener.java @@ -1,302 +1,302 @@ package org.fatecrafters.plugins.listeners; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.fatecrafters.plugins.RealisticBackpacks; import org.fatecrafters.plugins.util.MysqlFunctions; import org.fatecrafters.plugins.util.RBUtil; public class PlayerListener implements Listener { private final RealisticBackpacks plugin; private final HashMap<String, String> deadPlayers = new HashMap<String, String>(); private float walkSpeedMultiplier = 0.0F; public PlayerListener(final RealisticBackpacks plugin) { this.plugin = plugin; } @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL) - public void onRightClick(final PlayerInteractEvent e) { + public void onInteract(final PlayerInteractEvent e) { final Action act = e.getAction(); final Player p = e.getPlayer(); final ItemStack item = p.getItemInHand(); final String name = p.getName(); if (item.hasItemMeta()) { for (final String backpack : plugin.backpacks) { final List<String> key = plugin.backpackData.get(backpack); if (item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', key.get(3)))) { if (plugin.isUsingPerms() && !p.hasPermission("rb." + backpack + ".use")) { p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.messageData.get("openBackpackPermError"))); continue; } final String openWith = key.get(15); if (openWith != null) { if (openWith.equalsIgnoreCase("left_click")) { if (act.equals(Action.RIGHT_CLICK_AIR)) { continue; } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { continue; } } else if (openWith.equalsIgnoreCase("right_click")) { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } } else { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { e.setCancelled(true); p.updateInventory(); } Inventory inv = null; if (plugin.isUsingMysql()) { try { inv = MysqlFunctions.getBackpackInv(name, backpack); } catch (final SQLException e1) { e1.printStackTrace(); } if (inv == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } } else { final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e1) { e1.printStackTrace(); } } final FileConfiguration config = YamlConfiguration.loadConfiguration(file); if (config.getString(backpack + ".Inventory") == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } else { inv = RealisticBackpacks.NMS.stringToInventory(config.getString(backpack + ".Inventory"), key.get(3)); } } plugin.playerData.put(name, backpack); p.openInventory(inv); break; } } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDrop(final PlayerDropItemEvent e) { final Player p = e.getPlayer(); final String name = p.getName(); final ItemStack item = e.getItemDrop().getItemStack(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { if (plugin.slowedPlayers.contains(name)) { for (final String backpack : plugin.backpacks) { if (plugin.backpackItems.get(backpack).equals(item)) { plugin.slowedPlayers.remove(name); plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { p.setWalkSpeed(0.2F); } }); break; } } } } }); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPickup(final PlayerPickupItemEvent e) { final ItemStack item = e.getItem().getItemStack(); final Player p = e.getPlayer(); final String name = p.getName(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { for (final String backpack : plugin.backpacks) { if (!item.equals(plugin.backpackItems.get(backpack))) { continue; } final List<String> key = plugin.backpackData.get(backpack); if (!plugin.slowedPlayers.contains(name)) { plugin.slowedPlayers.add(name); } plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { p.setWalkSpeed(Float.parseFloat(key.get(9))); } }); break; } } }); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onMove(final PlayerMoveEvent e) { final Player p = e.getPlayer(); final String name = p.getName(); if (plugin.slowedPlayers.contains(name)) { return; } final Inventory inv = p.getInventory(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { final List<String> backpackList = new ArrayList<String>(); for (final String backpack : plugin.backpacks) { final List<String> key = plugin.backpackData.get(backpack); if (key.get(8).equals("true") && inv.contains(plugin.backpackItems.get(backpack))) { backpackList.add(backpack); } } final int listsize = backpackList.size(); if (listsize > 0) { if (listsize > 1) { if (plugin.isAveraging()) { float average = 0; for (final String backpack : backpackList) { average += Float.parseFloat(plugin.backpackData.get(backpack).get(9)); } walkSpeedMultiplier = average / listsize; } else if (plugin.isAdding()) { float sum = 0; for (final String backpack : backpackList) { sum += 0.2F - Float.parseFloat(plugin.backpackData.get(backpack).get(9)); } walkSpeedMultiplier = 0.2F - sum; } else { final List<Float> floatList = new ArrayList<Float>(); for (final String backpack : backpackList) { floatList.add(Float.parseFloat(plugin.backpackData.get(backpack).get(9))); } walkSpeedMultiplier = Collections.max(floatList); } } else if (listsize == 1) { for (final String backpack : backpackList) { walkSpeedMultiplier = Float.parseFloat(plugin.backpackData.get(backpack).get(9)); } } plugin.slowedPlayers.add(name); plugin.getServer().getScheduler().runTask(plugin, new Runnable() { @Override public void run() { p.setWalkSpeed(walkSpeedMultiplier); } }); } } }); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDeath(final PlayerDeathEvent e) { final Player p = e.getEntity(); final String name = p.getName(); for (final String backpack : plugin.backpacks) { if (!p.getInventory().contains(plugin.backpackItems.get(backpack))) { continue; } p.setWalkSpeed(0.2F); final List<String> key = plugin.backpackData.get(backpack); if (key.get(5) != null && key.get(5).equals("true")) { //Drop contents Inventory binv = null; if (plugin.isUsingMysql()) { try { binv = MysqlFunctions.getBackpackInv(name, backpack); } catch (final SQLException e1) { e1.printStackTrace(); } } else { final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); if (!file.exists()) { continue; } final FileConfiguration config = YamlConfiguration.loadConfiguration(file); if (config.getString(backpack + ".Inventory") == null) { continue; } binv = RealisticBackpacks.NMS.stringToInventory(config.getString(backpack + ".Inventory"), key.get(3)); } if (binv != null) { for (final ItemStack item : binv.getContents()) { if (item != null) { p.getWorld().dropItemNaturally(p.getLocation(), item); } } } RBUtil.destroyContents(name, backpack); } if (key.get(4) != null && key.get(4).equals("true")) { //Destroy contents RBUtil.destroyContents(name, backpack); p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.messageData.get("contentsDestroyed"))); } if (key.get(6) != null && key.get(6).equals("false")) { //Drop backpack e.getDrops().remove(plugin.backpackItems.get(backpack)); } if (key.get(7) != null && key.get(7).equals("true")) { deadPlayers.put(name, backpack); } } } @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onRespawn(final PlayerRespawnEvent e) { final Player p = e.getPlayer(); final String name = p.getName(); for (final String backpack : plugin.backpacks) { final List<String> key = plugin.backpackData.get(backpack); if (key.get(7) != null && key.get(7).equals("true") && deadPlayers.get(name) != null && deadPlayers.get(name).equals(backpack)) { //Keep backpack p.getInventory().addItem(plugin.backpackItems.get(backpack)); p.updateInventory(); deadPlayers.remove(name); } } } }
true
true
public void onRightClick(final PlayerInteractEvent e) { final Action act = e.getAction(); final Player p = e.getPlayer(); final ItemStack item = p.getItemInHand(); final String name = p.getName(); if (item.hasItemMeta()) { for (final String backpack : plugin.backpacks) { final List<String> key = plugin.backpackData.get(backpack); if (item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', key.get(3)))) { if (plugin.isUsingPerms() && !p.hasPermission("rb." + backpack + ".use")) { p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.messageData.get("openBackpackPermError"))); continue; } final String openWith = key.get(15); if (openWith != null) { if (openWith.equalsIgnoreCase("left_click")) { if (act.equals(Action.RIGHT_CLICK_AIR)) { continue; } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { continue; } } else if (openWith.equalsIgnoreCase("right_click")) { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } } else { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { e.setCancelled(true); p.updateInventory(); } Inventory inv = null; if (plugin.isUsingMysql()) { try { inv = MysqlFunctions.getBackpackInv(name, backpack); } catch (final SQLException e1) { e1.printStackTrace(); } if (inv == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } } else { final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e1) { e1.printStackTrace(); } } final FileConfiguration config = YamlConfiguration.loadConfiguration(file); if (config.getString(backpack + ".Inventory") == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } else { inv = RealisticBackpacks.NMS.stringToInventory(config.getString(backpack + ".Inventory"), key.get(3)); } } plugin.playerData.put(name, backpack); p.openInventory(inv); break; } } } }
public void onInteract(final PlayerInteractEvent e) { final Action act = e.getAction(); final Player p = e.getPlayer(); final ItemStack item = p.getItemInHand(); final String name = p.getName(); if (item.hasItemMeta()) { for (final String backpack : plugin.backpacks) { final List<String> key = plugin.backpackData.get(backpack); if (item.getItemMeta().hasDisplayName() && item.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', key.get(3)))) { if (plugin.isUsingPerms() && !p.hasPermission("rb." + backpack + ".use")) { p.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.messageData.get("openBackpackPermError"))); continue; } final String openWith = key.get(15); if (openWith != null) { if (openWith.equalsIgnoreCase("left_click")) { if (act.equals(Action.RIGHT_CLICK_AIR)) { continue; } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { continue; } } else if (openWith.equalsIgnoreCase("right_click")) { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } } else { if (act.equals(Action.LEFT_CLICK_AIR)) { continue; } if (act.equals(Action.LEFT_CLICK_BLOCK)) { continue; } } if (act.equals(Action.RIGHT_CLICK_BLOCK)) { e.setCancelled(true); p.updateInventory(); } Inventory inv = null; if (plugin.isUsingMysql()) { try { inv = MysqlFunctions.getBackpackInv(name, backpack); } catch (final SQLException e1) { e1.printStackTrace(); } if (inv == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } } else { final File file = new File(plugin.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (final IOException e1) { e1.printStackTrace(); } } final FileConfiguration config = YamlConfiguration.loadConfiguration(file); if (config.getString(backpack + ".Inventory") == null) { inv = plugin.getServer().createInventory(p, Integer.parseInt(key.get(0)), ChatColor.translateAlternateColorCodes('&', key.get(3))); } else { inv = RealisticBackpacks.NMS.stringToInventory(config.getString(backpack + ".Inventory"), key.get(3)); } } plugin.playerData.put(name, backpack); p.openInventory(inv); break; } } } }
diff --git a/cdi/plugins/org.jboss.tools.cdi.text.ext/src/org/jboss/tools/cdi/text/ext/hyperlink/EventAndObserverMethodHyperlinkDetector.java b/cdi/plugins/org.jboss.tools.cdi.text.ext/src/org/jboss/tools/cdi/text/ext/hyperlink/EventAndObserverMethodHyperlinkDetector.java index 3e7b881e1..fc0a4e69e 100644 --- a/cdi/plugins/org.jboss.tools.cdi.text.ext/src/org/jboss/tools/cdi/text/ext/hyperlink/EventAndObserverMethodHyperlinkDetector.java +++ b/cdi/plugins/org.jboss.tools.cdi.text.ext/src/org/jboss/tools/cdi/text/ext/hyperlink/EventAndObserverMethodHyperlinkDetector.java @@ -1,172 +1,168 @@ /******************************************************************************* * Copyright (c) 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.cdi.text.ext.hyperlink; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.ui.texteditor.ITextEditor; import org.jboss.tools.cdi.core.CDICoreNature; import org.jboss.tools.cdi.core.CDIUtil; import org.jboss.tools.cdi.core.IBean; import org.jboss.tools.cdi.core.ICDIProject; import org.jboss.tools.cdi.core.IClassBean; import org.jboss.tools.cdi.core.IInjectionPoint; import org.jboss.tools.cdi.core.IObserverMethod; import org.jboss.tools.cdi.core.IParameter; import org.jboss.tools.cdi.text.ext.CDIExtensionsPlugin; public class EventAndObserverMethodHyperlinkDetector extends AbstractHyperlinkDetector{ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class); if (region == null || !canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; int offset= region.getOffset(); IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false); if (input == null) return null; if (input.getResource() == null || input.getResource().getProject() == null) return null; IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); IRegion wordRegion= JavaWordFinder.findWord(document, offset); if (wordRegion == null) return null; IFile file = null; try { IResource resource = input.getCorrespondingResource(); if (resource instanceof IFile) file = (IFile) resource; } catch (JavaModelException e) { CDIExtensionsPlugin.log(e); } if(file == null) return null; CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(file.getProject()); if(cdiNature == null) return null; IJavaElement[] elements = null; try { elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength()); if (elements == null) return null; if(elements.length != 1) return null; ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>(); int position = 0; if(elements[0] instanceof IType){ ICompilationUnit cUnit = (ICompilationUnit)input; elements[0] = cUnit.getElementAt(wordRegion.getOffset()); if(elements[0] == null) return null; if(elements[0] instanceof IMethod){ position = offset; } } ICDIProject cdiProject = cdiNature.getDelegate(); if(cdiProject != null){ IInjectionPoint injectionPoint = findInjectedPoint(cdiProject, elements[0], position, file); Set<IParameter> param = findObserverParameter(cdiProject, elements[0], offset, file); if(injectionPoint != null){ Set<IObserverMethod> observerMethods = cdiProject.resolveObserverMethods(injectionPoint); if(observerMethods.size() == 1){ - for(IObserverMethod method : observerMethods){ - hyperlinks.add(new ObserverMethodHyperlink(region, method, document)); - } + hyperlinks.add(new ObserverMethodHyperlink(region, observerMethods.iterator().next(), document)); }else if(observerMethods.size() > 0){ hyperlinks.add(new ObserverMethodListHyperlink(textViewer, region, observerMethods, document)); } } else if(param != null) { Set<IInjectionPoint> events = new HashSet<IInjectionPoint>(); for (IParameter p: param) events.addAll(cdiProject.findObservedEvents(p)); if(events.size() == 1){ - for(IInjectionPoint event : events){ - hyperlinks.add(new EventHyperlink(region, event, document)); - } + hyperlinks.add(new EventHyperlink(region, events.iterator().next(), document)); }else if(events.size() > 0){ hyperlinks.add(new EventListHyperlink(textViewer, region, events, document)); } } } if (hyperlinks != null && !hyperlinks.isEmpty()) { return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]); } } catch (JavaModelException jme) { CDIExtensionsPlugin.log(jme); } return null; } private IInjectionPoint findInjectedPoint(ICDIProject cdiProject, IJavaElement element, int offset, IFile file){ Set<IBean> beans = cdiProject.getBeans(file.getFullPath()); return CDIUtil.findInjectionPoint(beans, element, offset); } private Set<IParameter> findObserverParameter(ICDIProject cdiProject, IJavaElement element, int offset, IFile file) throws JavaModelException { HashSet<IParameter> result = new HashSet<IParameter>(); Set<IBean> beans = cdiProject.getBeans(file.getFullPath()); for (IBean bean: beans) { if(bean instanceof IClassBean) { Set<IObserverMethod> observers = ((IClassBean)bean).getObserverMethods(); for (IObserverMethod bm: observers) { ISourceRange sr = bm.getMethod().getSourceRange(); if(sr.getOffset() <= offset && sr.getOffset() + sr.getLength() >= offset) { IObserverMethod obs = (IObserverMethod)bm; Set<IParameter> ps = obs.getObservedParameters(); if(!ps.isEmpty()) { result.add(ps.iterator().next()); } } } } } return result; } }
false
true
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class); if (region == null || !canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; int offset= region.getOffset(); IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false); if (input == null) return null; if (input.getResource() == null || input.getResource().getProject() == null) return null; IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); IRegion wordRegion= JavaWordFinder.findWord(document, offset); if (wordRegion == null) return null; IFile file = null; try { IResource resource = input.getCorrespondingResource(); if (resource instanceof IFile) file = (IFile) resource; } catch (JavaModelException e) { CDIExtensionsPlugin.log(e); } if(file == null) return null; CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(file.getProject()); if(cdiNature == null) return null; IJavaElement[] elements = null; try { elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength()); if (elements == null) return null; if(elements.length != 1) return null; ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>(); int position = 0; if(elements[0] instanceof IType){ ICompilationUnit cUnit = (ICompilationUnit)input; elements[0] = cUnit.getElementAt(wordRegion.getOffset()); if(elements[0] == null) return null; if(elements[0] instanceof IMethod){ position = offset; } } ICDIProject cdiProject = cdiNature.getDelegate(); if(cdiProject != null){ IInjectionPoint injectionPoint = findInjectedPoint(cdiProject, elements[0], position, file); Set<IParameter> param = findObserverParameter(cdiProject, elements[0], offset, file); if(injectionPoint != null){ Set<IObserverMethod> observerMethods = cdiProject.resolveObserverMethods(injectionPoint); if(observerMethods.size() == 1){ for(IObserverMethod method : observerMethods){ hyperlinks.add(new ObserverMethodHyperlink(region, method, document)); } }else if(observerMethods.size() > 0){ hyperlinks.add(new ObserverMethodListHyperlink(textViewer, region, observerMethods, document)); } } else if(param != null) { Set<IInjectionPoint> events = new HashSet<IInjectionPoint>(); for (IParameter p: param) events.addAll(cdiProject.findObservedEvents(p)); if(events.size() == 1){ for(IInjectionPoint event : events){ hyperlinks.add(new EventHyperlink(region, event, document)); } }else if(events.size() > 0){ hyperlinks.add(new EventListHyperlink(textViewer, region, events, document)); } } } if (hyperlinks != null && !hyperlinks.isEmpty()) { return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]); } } catch (JavaModelException jme) { CDIExtensionsPlugin.log(jme); } return null; }
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class); if (region == null || !canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor)) return null; int offset= region.getOffset(); IJavaElement input= EditorUtility.getEditorInputJavaElement(textEditor, false); if (input == null) return null; if (input.getResource() == null || input.getResource().getProject() == null) return null; IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); IRegion wordRegion= JavaWordFinder.findWord(document, offset); if (wordRegion == null) return null; IFile file = null; try { IResource resource = input.getCorrespondingResource(); if (resource instanceof IFile) file = (IFile) resource; } catch (JavaModelException e) { CDIExtensionsPlugin.log(e); } if(file == null) return null; CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(file.getProject()); if(cdiNature == null) return null; IJavaElement[] elements = null; try { elements = ((ICodeAssist)input).codeSelect(wordRegion.getOffset(), wordRegion.getLength()); if (elements == null) return null; if(elements.length != 1) return null; ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>(); int position = 0; if(elements[0] instanceof IType){ ICompilationUnit cUnit = (ICompilationUnit)input; elements[0] = cUnit.getElementAt(wordRegion.getOffset()); if(elements[0] == null) return null; if(elements[0] instanceof IMethod){ position = offset; } } ICDIProject cdiProject = cdiNature.getDelegate(); if(cdiProject != null){ IInjectionPoint injectionPoint = findInjectedPoint(cdiProject, elements[0], position, file); Set<IParameter> param = findObserverParameter(cdiProject, elements[0], offset, file); if(injectionPoint != null){ Set<IObserverMethod> observerMethods = cdiProject.resolveObserverMethods(injectionPoint); if(observerMethods.size() == 1){ hyperlinks.add(new ObserverMethodHyperlink(region, observerMethods.iterator().next(), document)); }else if(observerMethods.size() > 0){ hyperlinks.add(new ObserverMethodListHyperlink(textViewer, region, observerMethods, document)); } } else if(param != null) { Set<IInjectionPoint> events = new HashSet<IInjectionPoint>(); for (IParameter p: param) events.addAll(cdiProject.findObservedEvents(p)); if(events.size() == 1){ hyperlinks.add(new EventHyperlink(region, events.iterator().next(), document)); }else if(events.size() > 0){ hyperlinks.add(new EventListHyperlink(textViewer, region, events, document)); } } } if (hyperlinks != null && !hyperlinks.isEmpty()) { return (IHyperlink[])hyperlinks.toArray(new IHyperlink[hyperlinks.size()]); } } catch (JavaModelException jme) { CDIExtensionsPlugin.log(jme); } return null; }
diff --git a/src/main/java/de/jaschastarke/bukkit/lib/events/HangingBreakByPlayerBlockEvent.java b/src/main/java/de/jaschastarke/bukkit/lib/events/HangingBreakByPlayerBlockEvent.java index 9138b29..590d619 100644 --- a/src/main/java/de/jaschastarke/bukkit/lib/events/HangingBreakByPlayerBlockEvent.java +++ b/src/main/java/de/jaschastarke/bukkit/lib/events/HangingBreakByPlayerBlockEvent.java @@ -1,38 +1,40 @@ package de.jaschastarke.bukkit.lib.events; import java.util.ArrayList; import java.util.List; import org.bukkit.Material; import org.bukkit.entity.Hanging; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Painting; import org.bukkit.entity.Player; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingBreakEvent; import org.bukkit.inventory.ItemStack; public class HangingBreakByPlayerBlockEvent extends HangingBreakByEntityEvent { private final RemoveCause cause; private List<ItemStack> drops; public HangingBreakByPlayerBlockEvent(final Hanging hanging, final Player remover, final RemoveCause cause) { super(hanging, remover); this.cause = cause; drops = new ArrayList<ItemStack>(2); if (hanging instanceof Painting) { drops.add(new ItemStack(Material.PAINTING)); } else if (hanging instanceof ItemFrame) { drops.add(new ItemStack(Material.ITEM_FRAME)); - drops.add(((ItemFrame) hanging).getItem()); + ItemStack containedItem = ((ItemFrame) hanging).getItem(); + if (containedItem != null && containedItem.getType() != Material.AIR) + drops.add(containedItem); } } public Player getPlayer() { return (Player) getRemover(); } public HangingBreakEvent.RemoveCause getCause() { return cause; } public List<ItemStack> getDrops() { return drops; } }
true
true
public HangingBreakByPlayerBlockEvent(final Hanging hanging, final Player remover, final RemoveCause cause) { super(hanging, remover); this.cause = cause; drops = new ArrayList<ItemStack>(2); if (hanging instanceof Painting) { drops.add(new ItemStack(Material.PAINTING)); } else if (hanging instanceof ItemFrame) { drops.add(new ItemStack(Material.ITEM_FRAME)); drops.add(((ItemFrame) hanging).getItem()); } }
public HangingBreakByPlayerBlockEvent(final Hanging hanging, final Player remover, final RemoveCause cause) { super(hanging, remover); this.cause = cause; drops = new ArrayList<ItemStack>(2); if (hanging instanceof Painting) { drops.add(new ItemStack(Material.PAINTING)); } else if (hanging instanceof ItemFrame) { drops.add(new ItemStack(Material.ITEM_FRAME)); ItemStack containedItem = ((ItemFrame) hanging).getItem(); if (containedItem != null && containedItem.getType() != Material.AIR) drops.add(containedItem); } }
diff --git a/src/frontend/org/voltdb/Expectation.java b/src/frontend/org/voltdb/Expectation.java index f8d7fa1ba..967198039 100644 --- a/src/frontend/org/voltdb/Expectation.java +++ b/src/frontend/org/voltdb/Expectation.java @@ -1,125 +1,125 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * VoltDB 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. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import org.voltdb.VoltProcedure.VoltAbortException; public class Expectation { static enum Type { EXPECT_EMPTY, EXPECT_ONE_ROW, EXPECT_ZERO_OR_ONE_ROW, EXPECT_NON_EMPTY, EXPECT_SCALAR, EXPECT_SCALAR_LONG, EXPECT_SCALAR_MATCH, } final private Type m_type; final private long m_scalar; Expectation(Type t) { assert (t != null); m_type = t; m_scalar = 0; } Expectation(Type t, long scalar) { m_type = t; m_scalar = scalar; } static void fail(String procedureName, String stmtName, int batchIndex, String errMsg) throws VoltAbortException { String fullMsg = "Expectation failing in procedure: " + procedureName + "\n"; fullMsg += " Running SQL: " + stmtName + "\n"; fullMsg += " Error message: " + errMsg; throw new VoltAbortException(fullMsg); } static void check(String procedureName, String stmtName, int batchIndex, Expectation expectation, VoltTable table) throws VoltAbortException { if (expectation == null) return; assert(table != null); int rowCount = table.getRowCount(); switch (expectation.m_type) { case EXPECT_EMPTY: if (rowCount != 0) { fail(procedureName, stmtName, batchIndex, - String.format("Expected one row, but got %d", rowCount)); + String.format("Expected zero row, but got %d", rowCount)); } return; case EXPECT_ONE_ROW: if (rowCount != 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected one row, but got %d", rowCount)); } return; case EXPECT_ZERO_OR_ONE_ROW: if (rowCount > 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected zero or one rows, but got %d", rowCount)); } return; case EXPECT_NON_EMPTY: if (rowCount == 0) { fail(procedureName, stmtName, batchIndex, - String.format("Expected zero rows, but got %d", rowCount)); + String.format("Expected one or more rows, but got %d", rowCount)); } return; case EXPECT_SCALAR: if (checkScalar(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar value"); } return; case EXPECT_SCALAR_LONG: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } return; case EXPECT_SCALAR_MATCH: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } if (table.asScalarLong() != expectation.m_scalar) { fail(procedureName, stmtName, batchIndex, String.format("Expected scalar %d, but got %d", expectation.m_scalar, table.asScalarLong())); } return; } } static boolean checkScalar(VoltTable table) { if (table.getRowCount() != 1) return false; if (table.getColumnCount() != 1) return false; return true; } static boolean checkScalarLong(VoltTable table) { if (table.getRowCount() != 1) return false; if (table.getColumnCount() != 1) return false; if (table.getColumnType(0) != VoltType.BIGINT) return false; return true; } }
false
true
static void check(String procedureName, String stmtName, int batchIndex, Expectation expectation, VoltTable table) throws VoltAbortException { if (expectation == null) return; assert(table != null); int rowCount = table.getRowCount(); switch (expectation.m_type) { case EXPECT_EMPTY: if (rowCount != 0) { fail(procedureName, stmtName, batchIndex, String.format("Expected one row, but got %d", rowCount)); } return; case EXPECT_ONE_ROW: if (rowCount != 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected one row, but got %d", rowCount)); } return; case EXPECT_ZERO_OR_ONE_ROW: if (rowCount > 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected zero or one rows, but got %d", rowCount)); } return; case EXPECT_NON_EMPTY: if (rowCount == 0) { fail(procedureName, stmtName, batchIndex, String.format("Expected zero rows, but got %d", rowCount)); } return; case EXPECT_SCALAR: if (checkScalar(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar value"); } return; case EXPECT_SCALAR_LONG: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } return; case EXPECT_SCALAR_MATCH: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } if (table.asScalarLong() != expectation.m_scalar) { fail(procedureName, stmtName, batchIndex, String.format("Expected scalar %d, but got %d", expectation.m_scalar, table.asScalarLong())); } return; } }
static void check(String procedureName, String stmtName, int batchIndex, Expectation expectation, VoltTable table) throws VoltAbortException { if (expectation == null) return; assert(table != null); int rowCount = table.getRowCount(); switch (expectation.m_type) { case EXPECT_EMPTY: if (rowCount != 0) { fail(procedureName, stmtName, batchIndex, String.format("Expected zero row, but got %d", rowCount)); } return; case EXPECT_ONE_ROW: if (rowCount != 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected one row, but got %d", rowCount)); } return; case EXPECT_ZERO_OR_ONE_ROW: if (rowCount > 1) { fail(procedureName, stmtName, batchIndex, String.format("Expected zero or one rows, but got %d", rowCount)); } return; case EXPECT_NON_EMPTY: if (rowCount == 0) { fail(procedureName, stmtName, batchIndex, String.format("Expected one or more rows, but got %d", rowCount)); } return; case EXPECT_SCALAR: if (checkScalar(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar value"); } return; case EXPECT_SCALAR_LONG: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } return; case EXPECT_SCALAR_MATCH: if (checkScalarLong(table) == false) { fail(procedureName, stmtName, batchIndex, "Expected scalar long value"); } if (table.asScalarLong() != expectation.m_scalar) { fail(procedureName, stmtName, batchIndex, String.format("Expected scalar %d, but got %d", expectation.m_scalar, table.asScalarLong())); } return; } }
diff --git a/source/RMG/jing/rxn/PDepArrheniusKinetics.java b/source/RMG/jing/rxn/PDepArrheniusKinetics.java index a183f4d7..cb9b8ef3 100644 --- a/source/RMG/jing/rxn/PDepArrheniusKinetics.java +++ b/source/RMG/jing/rxn/PDepArrheniusKinetics.java @@ -1,162 +1,164 @@ //////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the // RMG Team ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// package jing.rxn; import jing.param.Pressure; import jing.param.Temperature; import jing.rxnSys.Logger; /** * A model of pressure-dependent reaction kinetics k(T, P) of the form * * k(T, P) = A(P) * T ^ n(P) * exp( -Ea(P) / R * T ) * * The values of A(P), n(P), and Ea(P) are stored for multiple pressures and * interpolation on a log P scale is used. * * @author jwallen */ public class PDepArrheniusKinetics implements PDepKinetics { /** * The list of pressures at which we have Arrhenius parameters. */ public Pressure[] pressures; /** * The list of Arrhenius kinetics fitted at each pressure. */ private ArrheniusKinetics[] kinetics; protected int numPressures = 0; public PDepArrheniusKinetics(int numP) { pressures = new Pressure[numP]; kinetics = new ArrheniusKinetics[numP]; setNumPressures(numP); } public void setKinetics(int index, Pressure P, ArrheniusKinetics kin) { if (index < 0 || index >= pressures.length) throw new RuntimeException(String.format("Cannot set kinetics with index %s because array is only of size %s",index,pressures.length)); pressures[index] = P; kinetics[index] = kin; } /** * Calculate the rate cofficient at the specified conditions. * @param T The temperature of interest * @param P The pressure of interest * @return The rate coefficient evaluated at T and P */ public double calculateRate(Temperature T, Pressure P) { int index1 = -1; int index2 = -1; for (int i = 0; i < pressures.length - 1; i++) { if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) { - index1 = i; index2 = i + 1; + index1 = i; + index2 = i + 1; + break; } } /* Chemkin 4 theory manual specifies: "If the rate of the reaction is desired for a pressure lower than any of those provided, the rate parameters provided for the lowest pressure are used. Likewise, if rate of the reaction is desired for a pressure higher than any of those provided, the rate parameters provided for the highest pressure are used." We take the same approach here, but warn the user (so they can fix their input file). */ if (P.getPa() < pressures[0].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is below minimum for this PLOG rate.",P.getAtm())); Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() )); return kinetics[0].calculateRate(T); } - if (P.getPa() > pressures[pressures.length].getPa()) + if (P.getPa() > pressures[pressures.length-1].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is above maximum for this PLOG rate.",P.getAtm())); - Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length].getAtm() )); + Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length-1].getAtm() )); return kinetics[pressures.length].calculateRate(T); } double logk1 = Math.log10(kinetics[index1].calculateRate(T)); double logk2 = Math.log10(kinetics[index2].calculateRate(T)); double logP0 = Math.log10(P.getBar()); double logP1 = Math.log10(pressures[index1].getBar()); double logP2 = Math.log10(pressures[index2].getBar()); double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1); return Math.pow(10, logk0); } public String toChemkinString() { String result = ""; for (int i = 0; i < pressures.length; i++) { double Ea_in_kcalmol = kinetics[i].getEValue(); double Ea = 0.0; if (ArrheniusKinetics.getEaUnits().equals("kcal/mol")) Ea = Ea_in_kcalmol; else if (ArrheniusKinetics.getEaUnits().equals("cal/mol")) Ea = Ea_in_kcalmol * 1000.0; else if (ArrheniusKinetics.getEaUnits().equals("kJ/mol")) Ea = Ea_in_kcalmol * 4.184; else if (ArrheniusKinetics.getEaUnits().equals("J/mol")) Ea = Ea_in_kcalmol * 4184.0; else if (ArrheniusKinetics.getEaUnits().equals("Kelvins")) Ea = Ea_in_kcalmol / 1.987e-3; result += String.format("PLOG / %10s %10.2e %10s %10s /\n", pressures[i].getAtm(), kinetics[i].getAValue(), kinetics[i].getNValue(), Ea); } return result; } public void setNumPressures(int numP) { numPressures = numP; } public int getNumPressures() { return numPressures; } public ArrheniusKinetics getKinetics(int i) { return kinetics[i]; } public void setPressures(Pressure[] ListOfPressures) { pressures = ListOfPressures; } public void setRateCoefficients(ArrheniusKinetics[] ListOfKinetics) { kinetics = ListOfKinetics; } public Pressure getPressure(int i) { return pressures[i]; } }
false
true
public double calculateRate(Temperature T, Pressure P) { int index1 = -1; int index2 = -1; for (int i = 0; i < pressures.length - 1; i++) { if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) { index1 = i; index2 = i + 1; } } /* Chemkin 4 theory manual specifies: "If the rate of the reaction is desired for a pressure lower than any of those provided, the rate parameters provided for the lowest pressure are used. Likewise, if rate of the reaction is desired for a pressure higher than any of those provided, the rate parameters provided for the highest pressure are used." We take the same approach here, but warn the user (so they can fix their input file). */ if (P.getPa() < pressures[0].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is below minimum for this PLOG rate.",P.getAtm())); Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() )); return kinetics[0].calculateRate(T); } if (P.getPa() > pressures[pressures.length].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is above maximum for this PLOG rate.",P.getAtm())); Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length].getAtm() )); return kinetics[pressures.length].calculateRate(T); } double logk1 = Math.log10(kinetics[index1].calculateRate(T)); double logk2 = Math.log10(kinetics[index2].calculateRate(T)); double logP0 = Math.log10(P.getBar()); double logP1 = Math.log10(pressures[index1].getBar()); double logP2 = Math.log10(pressures[index2].getBar()); double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1); return Math.pow(10, logk0); }
public double calculateRate(Temperature T, Pressure P) { int index1 = -1; int index2 = -1; for (int i = 0; i < pressures.length - 1; i++) { if (pressures[i].getBar() <= P.getBar() && P.getBar() <= pressures[i+1].getBar()) { index1 = i; index2 = i + 1; break; } } /* Chemkin 4 theory manual specifies: "If the rate of the reaction is desired for a pressure lower than any of those provided, the rate parameters provided for the lowest pressure are used. Likewise, if rate of the reaction is desired for a pressure higher than any of those provided, the rate parameters provided for the highest pressure are used." We take the same approach here, but warn the user (so they can fix their input file). */ if (P.getPa() < pressures[0].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is below minimum for this PLOG rate.",P.getAtm())); Logger.warning(String.format("Using rate for minimum %s Atm instead", pressures[0].getAtm() )); return kinetics[0].calculateRate(T); } if (P.getPa() > pressures[pressures.length-1].getPa()) { Logger.warning(String.format("Tried to evaluate rate coefficient at P=%s Atm, which is above maximum for this PLOG rate.",P.getAtm())); Logger.warning(String.format("Using rate for maximum %s Atm instead", pressures[pressures.length-1].getAtm() )); return kinetics[pressures.length].calculateRate(T); } double logk1 = Math.log10(kinetics[index1].calculateRate(T)); double logk2 = Math.log10(kinetics[index2].calculateRate(T)); double logP0 = Math.log10(P.getBar()); double logP1 = Math.log10(pressures[index1].getBar()); double logP2 = Math.log10(pressures[index2].getBar()); double logk0 = logk1 + (logk2 - logk1) / (logP2 - logP1) * (logP0 - logP1); return Math.pow(10, logk0); }
diff --git a/java.java b/java.java index 6978e51..3d0111c 100644 --- a/java.java +++ b/java.java @@ -1,7 +1,7 @@ class helloclass { public static void main(String args[]) { - system.out.println("Hello World"); + System.out.println("Hello World"); } }
true
true
public static void main(String args[]) { system.out.println("Hello World"); }
public static void main(String args[]) { System.out.println("Hello World"); }
diff --git a/src/test/java/SimpleTest.java b/src/test/java/SimpleTest.java index bd7507d..c97e1fa 100644 --- a/src/test/java/SimpleTest.java +++ b/src/test/java/SimpleTest.java @@ -1,11 +1,11 @@ import junit.framework.Assert; import org.testng.annotations.Test; public class SimpleTest { @Test public void alwaysTrue() { - Assert.assertTrue(false); + Assert.assertTrue(true); } }
true
true
public void alwaysTrue() { Assert.assertTrue(false); }
public void alwaysTrue() { Assert.assertTrue(true); }
diff --git a/src/main/java/org/mvel/integration/impl/ClassImportResolverFactory.java b/src/main/java/org/mvel/integration/impl/ClassImportResolverFactory.java index 8d88a485..b7f48816 100644 --- a/src/main/java/org/mvel/integration/impl/ClassImportResolverFactory.java +++ b/src/main/java/org/mvel/integration/impl/ClassImportResolverFactory.java @@ -1,123 +1,126 @@ /** * MVEL (The MVFLEX Expression Language) * * Copyright (C) 2007 Christopher Brock, MVFLEX/Valhalla Project and the Codehaus * * 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.mvel.integration.impl; import org.mvel.integration.VariableResolver; import org.mvel.integration.VariableResolverFactory; import static org.mvel.util.ParseTools.createClass; import static org.mvel.util.ParseTools.getSimpleClassName; import org.mvel.ParserContext; import org.mvel.ParserConfiguration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ClassImportResolverFactory extends BaseVariableResolverFactory { private Set<String> packageImports; public ClassImportResolverFactory() { super(); variableResolvers = new HashMap<String, VariableResolver>(); } public ClassImportResolverFactory(ParserConfiguration ctx, VariableResolverFactory nextFactory) { packageImports = ctx.getPackageImports(); Map<String, Object> classes = ctx.getImports(); this.nextFactory = nextFactory; this.variableResolvers = new HashMap<String,VariableResolver>(); for (String s : classes.keySet()) { variableResolvers.put(s, new SimpleValueResolver(classes.get(s))); } } public VariableResolver createVariable(String name, Object value) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } return nextFactory.createVariable(name, value); } public VariableResolver createVariable(String name, Object value, Class type) { if (nextFactory == null) { nextFactory = new MapVariableResolverFactory(new HashMap()); } return nextFactory.createVariable(name, value); } public Class addClass(Class clazz) { variableResolvers.put(getSimpleClassName(clazz), new SimpleValueResolver(clazz)); return clazz; } public boolean isTarget(String name) { return variableResolvers.containsKey(name); } public boolean isResolveable(String name) { if (variableResolvers.containsKey(name) || isNextResolveable(name)) { return true; } else if (packageImports != null) { for (String s : packageImports) { try { addClass(createClass(s + "." + name)); return true; } catch (ClassNotFoundException e) { // do nothing; } + catch (NoClassDefFoundError e) { + // do nothing; + } } } return false; } public void clear() { variableResolvers.clear(); } public void setImportedClasses(Map<String, Class> imports) { if (imports == null) return; for (String var : imports.keySet()) { variableResolvers.put(var, new SimpleValueResolver(imports.get(var))); } } public Map<String, Object> getImportedClasses() { Map<String, Object> imports = new HashMap<String, Object>(); for (String var : variableResolvers.keySet()) { imports.put(var, variableResolvers.get(var).getValue()); } return imports; } public void addPackageImport(String packageName) { if (packageImports == null) packageImports = new HashSet<String>(); packageImports.add(packageName); } }
true
true
public boolean isResolveable(String name) { if (variableResolvers.containsKey(name) || isNextResolveable(name)) { return true; } else if (packageImports != null) { for (String s : packageImports) { try { addClass(createClass(s + "." + name)); return true; } catch (ClassNotFoundException e) { // do nothing; } } } return false; }
public boolean isResolveable(String name) { if (variableResolvers.containsKey(name) || isNextResolveable(name)) { return true; } else if (packageImports != null) { for (String s : packageImports) { try { addClass(createClass(s + "." + name)); return true; } catch (ClassNotFoundException e) { // do nothing; } catch (NoClassDefFoundError e) { // do nothing; } } } return false; }
diff --git a/problem/src/main/java/rinde/sim/pdptw/central/SolverValidator.java b/problem/src/main/java/rinde/sim/pdptw/central/SolverValidator.java index cada98ba..18e98b6f 100644 --- a/problem/src/main/java/rinde/sim/pdptw/central/SolverValidator.java +++ b/problem/src/main/java/rinde/sim/pdptw/central/SolverValidator.java @@ -1,221 +1,222 @@ /** * */ package rinde.sim.pdptw.central; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; import java.util.Collections; import java.util.List; import java.util.Set; import rinde.sim.pdptw.central.GlobalStateObject.VehicleStateObject; import rinde.sim.pdptw.common.ParcelDTO; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Provides methods for validating input to and output from {@link Solver}s. * Also provides {@link #wrap(Solver)} method which decorates any solver such * that both inputs and outputs are validated every time it is is called. * @author Rinde van Lon <[email protected]> */ public final class SolverValidator { private SolverValidator() {} /** * Decorates the original {@link Solver} such that both the inputs to the * solver and the outputs from the solver are validated. When an invalid input * or output is detected a {@link IllegalArgumentException is thrown}. * @param delegate The {@link Solver} that will be used for the actual * solving. * @return The wrapped solver. */ public static Solver wrap(Solver delegate) { return new SolverValidator.Validator(delegate); } /** * Validates the inputs for {@link Solver#solve(GlobalStateObject)} method. If * the input is not correct an {@link IllegalArgumentException} is thrown. * @param state The state to validate. * @return The state. */ public static GlobalStateObject validateInputs(GlobalStateObject state) { checkArgument(state.time >= 0, "Time must be >= 0, is %s.", state.time); final Set<ParcelDTO> inventoryParcels = newHashSet(); final boolean routeIsPresent = state.vehicles.get(0).route.isPresent(); final Set<ParcelDTO> allParcels = newHashSet(); for (final VehicleStateObject vs : state.vehicles) { checkArgument( vs.route.isPresent() == routeIsPresent, "Either a route should be present for all vehicles, or no route should be present for all vehicles."); if (vs.route.isPresent()) { for (final ParcelDTO p : vs.route.get()) { checkArgument( !allParcels.contains(p), "Found parcel which is already present in the route of another vehicle. Parcel %s.", p); } allParcels.addAll(vs.route.get()); } } for (int i = 0; i < state.vehicles.size(); i++) { final VehicleStateObject vs = state.vehicles.get(i); checkArgument(vs.remainingServiceTime >= 0, "Remaining service time must be >= 0, is %s.", vs.remainingServiceTime); checkArgument(vs.speed > 0, "Speed must be positive, is %s.", vs.speed); final Set<ParcelDTO> intersection = Sets.intersection( state.availableParcels, vs.contents); checkArgument( intersection.isEmpty(), "Parcels can not be available AND in the inventory of a vehicle, found: %s.", intersection); final Set<ParcelDTO> inventoryIntersection = Sets.intersection( inventoryParcels, vs.contents); checkArgument( inventoryIntersection.isEmpty(), "Parcels can not be in the inventory of two vehicles at the same time, found: %s.", inventoryIntersection); inventoryParcels.addAll(vs.contents); // if the destination parcel is not available, it must be in the // cargo of the vehicle if (vs.destination != null) { final boolean isAvailable = state.availableParcels .contains(vs.destination); final boolean isInCargo = vs.contents.contains(vs.destination); checkArgument( isAvailable != isInCargo, - "Destination must be either available (%s) or in the current vehicle's cargo (%s), but not both (i.e. XOR).", - isAvailable, isInCargo, vs.destination, vs.remainingServiceTime); + "Destination must be either available (%s) or in the current vehicle's cargo (%s), but not both (i.e. XOR). Destination: %s, vehicle: %s (out of %s), remaining service time: %s.", + isAvailable, isInCargo, vs.destination, i, state.vehicles.size(), + vs.remainingServiceTime); } if (vs.route.isPresent()) { checkRoute(vs, i); } } return state; } /** * Validate the route of a vehicle. * @param vs The vehicle to check. * @param i The index of the vehicle, only used to generate nice error * messages. * @throws IllegalArgumentException if the route is not correct. */ public static void checkRoute(VehicleStateObject vs, int i) { checkArgument(vs.route.isPresent()); checkArgument( vs.route.get().containsAll(vs.contents), "Vehicle %s's route doesn't contain all locations it has in cargo. Route: %s, cargo: %s.", i, vs.route.get(), vs.contents); if (vs.destination != null) { checkArgument(!vs.route.get().isEmpty() && vs.route.get().get(0) == vs.destination, "First location in route must equal destination (%s), route is: %s.", vs.destination, vs.route.get()); } for (final ParcelDTO dp : vs.route.get()) { final int freq = Collections.frequency(vs.route.get(), dp); if (vs.contents.contains(dp)) { checkArgument( freq == 1, "A parcel already in cargo should occur once in the route, found %s instance(s). Parcel: %s, route: %s.", freq, dp, vs.route.get()); } else { checkArgument( freq == 2, "A parcel that is still available should occur twice in the route, found %s instance(s). Parcel: %s, route: %s.", freq, dp, vs.route.get(), vs.remainingServiceTime); } } } /** * Validates the routes that are produced by a {@link Solver}. If one of the * routes is infeasible an {@link IllegalArgumentException} is thrown. * @param routes The routes that are validated. * @param state Parameter as specified by * {@link Solver#solve(GlobalStateObject)}. * @return The routes. */ public static ImmutableList<ImmutableList<ParcelDTO>> validateOutputs( ImmutableList<ImmutableList<ParcelDTO>> routes, GlobalStateObject state) { checkArgument( routes.size() == state.vehicles.size(), "There must be exactly one route for every vehicle, found %s routes with %s vehicles.", routes.size(), state.vehicles.size()); final Set<ParcelDTO> inputParcels = newHashSet(state.availableParcels); final Set<ParcelDTO> outputParcels = newHashSet(); for (int i = 0; i < routes.size(); i++) { final List<ParcelDTO> route = routes.get(i); final Set<ParcelDTO> routeSet = ImmutableSet.copyOf(route); checkArgument(routeSet.containsAll(state.vehicles.get(i).contents), "The route of vehicle %s doesn't visit all parcels in its cargo.", i); inputParcels.addAll(state.vehicles.get(i).contents); if (state.vehicles.get(i).destination != null) { checkArgument( route.get(0) == state.vehicles.get(i).destination, "The route of vehicle %s should start with its current destination: %s.", i, state.vehicles.get(i).destination); } for (final ParcelDTO p : route) { checkArgument(!outputParcels.contains(p), "Found a parcel which is already in another route: %s.", p); final int frequency = Collections.frequency(route, p); if (state.availableParcels.contains(p)) { // if the parcel is available, it needs to occur twice in // the route (once for pickup, once for delivery). checkArgument( frequency == 2, "Route %s: a parcel that is picked up needs to be delivered as well, so it should occur twice in the route, found %s occurence(s) of parcel %s.", i, frequency, p); } else { checkArgument( state.vehicles.get(i).contents.contains(p), "The parcel in this route is not available, which means it should be in the contents of this vehicle. Parcel: %s.", p); checkArgument( frequency == 1, "A parcel that is already in cargo should occur once in the route, found %s occurences of parcel %s.", frequency, p); } } outputParcels.addAll(route); } checkArgument( inputParcels.equals(outputParcels), "The number of distinct parcels in the routes should equal the number of parcels in the input, parcels that should be added in routes: %s, parcels that should be removed from routes: %s.", Sets.difference(inputParcels, outputParcels), Sets.difference(outputParcels, inputParcels)); return routes; } private static class Validator implements Solver { private final Solver delegateSolver; Validator(Solver delegate) { delegateSolver = delegate; } @Override public ImmutableList<ImmutableList<ParcelDTO>> solve(GlobalStateObject state) { return validateOutputs(delegateSolver.solve(validateInputs(state)), state); } } }
true
true
public static GlobalStateObject validateInputs(GlobalStateObject state) { checkArgument(state.time >= 0, "Time must be >= 0, is %s.", state.time); final Set<ParcelDTO> inventoryParcels = newHashSet(); final boolean routeIsPresent = state.vehicles.get(0).route.isPresent(); final Set<ParcelDTO> allParcels = newHashSet(); for (final VehicleStateObject vs : state.vehicles) { checkArgument( vs.route.isPresent() == routeIsPresent, "Either a route should be present for all vehicles, or no route should be present for all vehicles."); if (vs.route.isPresent()) { for (final ParcelDTO p : vs.route.get()) { checkArgument( !allParcels.contains(p), "Found parcel which is already present in the route of another vehicle. Parcel %s.", p); } allParcels.addAll(vs.route.get()); } } for (int i = 0; i < state.vehicles.size(); i++) { final VehicleStateObject vs = state.vehicles.get(i); checkArgument(vs.remainingServiceTime >= 0, "Remaining service time must be >= 0, is %s.", vs.remainingServiceTime); checkArgument(vs.speed > 0, "Speed must be positive, is %s.", vs.speed); final Set<ParcelDTO> intersection = Sets.intersection( state.availableParcels, vs.contents); checkArgument( intersection.isEmpty(), "Parcels can not be available AND in the inventory of a vehicle, found: %s.", intersection); final Set<ParcelDTO> inventoryIntersection = Sets.intersection( inventoryParcels, vs.contents); checkArgument( inventoryIntersection.isEmpty(), "Parcels can not be in the inventory of two vehicles at the same time, found: %s.", inventoryIntersection); inventoryParcels.addAll(vs.contents); // if the destination parcel is not available, it must be in the // cargo of the vehicle if (vs.destination != null) { final boolean isAvailable = state.availableParcels .contains(vs.destination); final boolean isInCargo = vs.contents.contains(vs.destination); checkArgument( isAvailable != isInCargo, "Destination must be either available (%s) or in the current vehicle's cargo (%s), but not both (i.e. XOR).", isAvailable, isInCargo, vs.destination, vs.remainingServiceTime); } if (vs.route.isPresent()) { checkRoute(vs, i); } } return state; }
public static GlobalStateObject validateInputs(GlobalStateObject state) { checkArgument(state.time >= 0, "Time must be >= 0, is %s.", state.time); final Set<ParcelDTO> inventoryParcels = newHashSet(); final boolean routeIsPresent = state.vehicles.get(0).route.isPresent(); final Set<ParcelDTO> allParcels = newHashSet(); for (final VehicleStateObject vs : state.vehicles) { checkArgument( vs.route.isPresent() == routeIsPresent, "Either a route should be present for all vehicles, or no route should be present for all vehicles."); if (vs.route.isPresent()) { for (final ParcelDTO p : vs.route.get()) { checkArgument( !allParcels.contains(p), "Found parcel which is already present in the route of another vehicle. Parcel %s.", p); } allParcels.addAll(vs.route.get()); } } for (int i = 0; i < state.vehicles.size(); i++) { final VehicleStateObject vs = state.vehicles.get(i); checkArgument(vs.remainingServiceTime >= 0, "Remaining service time must be >= 0, is %s.", vs.remainingServiceTime); checkArgument(vs.speed > 0, "Speed must be positive, is %s.", vs.speed); final Set<ParcelDTO> intersection = Sets.intersection( state.availableParcels, vs.contents); checkArgument( intersection.isEmpty(), "Parcels can not be available AND in the inventory of a vehicle, found: %s.", intersection); final Set<ParcelDTO> inventoryIntersection = Sets.intersection( inventoryParcels, vs.contents); checkArgument( inventoryIntersection.isEmpty(), "Parcels can not be in the inventory of two vehicles at the same time, found: %s.", inventoryIntersection); inventoryParcels.addAll(vs.contents); // if the destination parcel is not available, it must be in the // cargo of the vehicle if (vs.destination != null) { final boolean isAvailable = state.availableParcels .contains(vs.destination); final boolean isInCargo = vs.contents.contains(vs.destination); checkArgument( isAvailable != isInCargo, "Destination must be either available (%s) or in the current vehicle's cargo (%s), but not both (i.e. XOR). Destination: %s, vehicle: %s (out of %s), remaining service time: %s.", isAvailable, isInCargo, vs.destination, i, state.vehicles.size(), vs.remainingServiceTime); } if (vs.route.isPresent()) { checkRoute(vs, i); } } return state; }
diff --git a/eapli.expensemanager/src/Presentation/DefMeiosPagamento.java b/eapli.expensemanager/src/Presentation/DefMeiosPagamento.java index 3a0c499..3f3b04c 100644 --- a/eapli.expensemanager/src/Presentation/DefMeiosPagamento.java +++ b/eapli.expensemanager/src/Presentation/DefMeiosPagamento.java @@ -1,27 +1,27 @@ package Presentation; import Model.TipoPagamento; import Persistence.RepositorioTiposPagamento; import eapli.util.Console; import java.util.Scanner; public class DefMeiosPagamento { public void mainLoop() { System.out.println("* * * NOVO MEIO DE PAGAMENTO * * *\n"); RepositorioTiposPagamento rep = new RepositorioTiposPagamento(); rep.ListarTiposPagamento(); int escolha = Console.readInteger("Escolha um dos Tipos de Pagamento: "); TipoPagamento tipo = rep.getLista_tipos().get(escolha-1); String descricao = Console.readLine("Descrição: "); - DefMeioPagamentoController controller = new DefMeioPagamentoController(); - controller.NovoMeioPagamento(tipo,descricao); + //DefMeioPagamentoController controller = new DefMeioPagamentoController(); + //controller.NovoMeioPagamento(tipo,descricao); System.out.println("Novo Tipo de Pagamento adicionado com sucesso!"); } }
true
true
public void mainLoop() { System.out.println("* * * NOVO MEIO DE PAGAMENTO * * *\n"); RepositorioTiposPagamento rep = new RepositorioTiposPagamento(); rep.ListarTiposPagamento(); int escolha = Console.readInteger("Escolha um dos Tipos de Pagamento: "); TipoPagamento tipo = rep.getLista_tipos().get(escolha-1); String descricao = Console.readLine("Descrição: "); DefMeioPagamentoController controller = new DefMeioPagamentoController(); controller.NovoMeioPagamento(tipo,descricao); System.out.println("Novo Tipo de Pagamento adicionado com sucesso!"); }
public void mainLoop() { System.out.println("* * * NOVO MEIO DE PAGAMENTO * * *\n"); RepositorioTiposPagamento rep = new RepositorioTiposPagamento(); rep.ListarTiposPagamento(); int escolha = Console.readInteger("Escolha um dos Tipos de Pagamento: "); TipoPagamento tipo = rep.getLista_tipos().get(escolha-1); String descricao = Console.readLine("Descrição: "); //DefMeioPagamentoController controller = new DefMeioPagamentoController(); //controller.NovoMeioPagamento(tipo,descricao); System.out.println("Novo Tipo de Pagamento adicionado com sucesso!"); }
diff --git a/obdalib-core/src/main/java/it/unibz/krdb/obda/parser/SQLQueryTranslator.java b/obdalib-core/src/main/java/it/unibz/krdb/obda/parser/SQLQueryTranslator.java index b3737c62a..1b7193ba5 100644 --- a/obdalib-core/src/main/java/it/unibz/krdb/obda/parser/SQLQueryTranslator.java +++ b/obdalib-core/src/main/java/it/unibz/krdb/obda/parser/SQLQueryTranslator.java @@ -1,289 +1,290 @@ package it.unibz.krdb.obda.parser; /* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2013 Free University of Bozen-Bolzano * %% * 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. * #L% */ import it.unibz.krdb.sql.DBMetadata; import it.unibz.krdb.sql.ViewDefinition; import it.unibz.krdb.sql.api.Attribute; import it.unibz.krdb.sql.api.VisitedQuery; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.ParseException; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.AllColumns; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import net.sf.jsqlparser.statement.select.SelectItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SQLQueryTranslator { private DBMetadata dbMetaData; private Connection connection; private String database; //This field will contain all the target SQL from the //mappings that could not be parsed by the parser. private ArrayList<ViewDefinition> viewDefinitions; private static int id_counter; private static Logger log = LoggerFactory.getLogger(SQLQueryTranslator.class); public SQLQueryTranslator(DBMetadata dbMetaData) { connection=null; database=dbMetaData.getDriverName(); this.dbMetaData = dbMetaData; id_counter = 0; } /* * This constructor is used when the tables names and schemas are taken from the mappings * in MappingParser */ public SQLQueryTranslator(Connection conn) throws SQLException { connection=conn; database=connection.getMetaData().getDriverName(); this.viewDefinitions = new ArrayList<ViewDefinition>(); this.dbMetaData = null; id_counter = 0; } public SQLQueryTranslator() { database=null; connection=null; this.viewDefinitions = new ArrayList<ViewDefinition>(); this.dbMetaData = null; id_counter = 0; } /* * Returns all the target SQL from the * mappings that could not be parsed by the parser. */ public ArrayList<ViewDefinition> getViewDefinitions(){ return this.viewDefinitions; } /** * Called from ParsedMapping. Returns the query tree, even if there were * parsing errors. This is because the ParsedMapping only need the table names, * and it needs them, especially in the cases like "select *", that are treated like parsing * errors, but are treated by preprocessProjection * * @param query The sql query to be parsed * @return A VisitedQuery (possible with null values) */ public VisitedQuery constructParserNoView(String query){ return constructParser(query, false); } /** * Called from MappingAnalyzer:createLookupTable. Returns the parsed query, or, if there are * syntax error, the name of a generated view, even if there were * parsing errors. * * @param query The sql query to be parsed * @return A ParsedQuery (or a SELECT * FROM table with the generated view) */ public VisitedQuery constructParser(String query) { return constructParser(query, true); } private VisitedQuery constructParser (String query, boolean generateViews){ boolean errors=false; VisitedQuery queryParser = null; try { queryParser = new VisitedQuery(query); } catch (JSQLParserException e) { if(e.getCause() instanceof ParseException) log.warn("Parse exception, check no SQL reserved keywords have been used "+ e.getCause().getMessage()); errors=true; } if (queryParser == null || (errors && generateViews) ) { log.warn("The following query couldn't be parsed. This means Quest will need to use nested subqueries (views) to use this mappings. This is not good for SQL performance, specially in MySQL. Try to simplify your query to allow Quest to parse it. If you think this query is already simple and should be parsed by Quest, please contact the authors. \nQuery: '{}'", query); queryParser = createView(query); } return queryParser; } private VisitedQuery createView(String query){ String viewName = String.format("view_%s", id_counter++); if(database!=null){ ViewDefinition vd = createViewDefinition(viewName, query); if(dbMetaData != null) dbMetaData.add(vd); else viewDefinitions.add(vd); } VisitedQuery vt = createViewParsed(viewName, query); return vt; } /* * To create a view, I start building a new select statement and add the viewName information in a table in the FROMitem expression * We create a query that looks like SELECT * FROM viewName */ private VisitedQuery createViewParsed(String viewName, String query) { /* * Create a new SELECT statement containing the viewTable in the FROM clause */ PlainSelect body = new PlainSelect(); //create SELECT * ArrayList<SelectItem> list = new ArrayList<SelectItem>(); list.add(new AllColumns()); body.setSelectItems(list); // create FROM viewTable Table viewTable = new Table(null, viewName); body.setFromItem(viewTable); Select select= new Select(); select.setSelectBody(body); VisitedQuery queryParsed = null; try { queryParsed = new VisitedQuery(select); } catch (JSQLParserException e) { if(e.getCause() instanceof ParseException) log.warn("Parse exception, check no SQL reserved keywords have been used "+ e.getCause().getMessage()); } return queryParsed; } private ViewDefinition createViewDefinition(String viewName, String query) { int start = 6; // the keyword 'select' int end = query.toLowerCase().indexOf("from"); boolean uppercase=false; - boolean quoted = false; + boolean quoted; if (end == -1) { throw new RuntimeException("Error parsing SQL query: Couldn't find FROM clause"); } if (database.contains("Oracle") || database.contains("DB2") || database.contains("H2")) { // If the database engine is Oracle, H2 or DB2 unquoted columns are changed in uppercase uppercase=true; } String projection = query.substring(start, end).trim(); //split where comma is present but not inside quotes String[] columns = projection.split(",+(?![^\\(]*\\))"); ViewDefinition viewDefinition = new ViewDefinition(); viewDefinition.setName(viewName); viewDefinition.copy(query); for (int i = 0; i < columns.length; i++) { + quoted = false; String columnName = columns[i].trim(); /* * Take the alias name if the column name has it. */ String[] aliasSplitters = new String[2]; aliasSplitters[0] = " as "; aliasSplitters[1] = " AS "; for(String aliasSplitter : aliasSplitters){ if (columnName.contains(aliasSplitter)) { // has an alias columnName = columnName.split(aliasSplitter)[1].trim(); break; } } if(columnName.contains(" ")) columnName = columnName.split("\\s+(?![^']*')")[1].trim();; /* * Remove any identifier quotes * Example: * INPUT: "table"."column" * OUTPUT: table.column */ if (columnName.contains("\"")) { columnName = columnName.replaceAll("\"", ""); quoted=true; } else if (columnName.contains("`")) { columnName = columnName.replaceAll("`", ""); quoted=true; } else if (columnName.contains("[") && columnName.contains("]")) { columnName = columnName.replaceAll("[", "").replaceAll("]", ""); quoted=true; } /* * Get only the short name if the column name uses qualified name. * Example: * INPUT: table.column * OUTPUT: column */ if (columnName.contains(".")) { columnName = columnName.substring(columnName.lastIndexOf(".")+1, columnName.length()); // get only the name } if(!quoted){ if(uppercase) columnName=columnName.toUpperCase(); else columnName=columnName.toLowerCase(); } viewDefinition.setAttribute(i+1, new Attribute(columnName)); // the attribute index always start at 1 } return viewDefinition; } }
false
true
private ViewDefinition createViewDefinition(String viewName, String query) { int start = 6; // the keyword 'select' int end = query.toLowerCase().indexOf("from"); boolean uppercase=false; boolean quoted = false; if (end == -1) { throw new RuntimeException("Error parsing SQL query: Couldn't find FROM clause"); } if (database.contains("Oracle") || database.contains("DB2") || database.contains("H2")) { // If the database engine is Oracle, H2 or DB2 unquoted columns are changed in uppercase uppercase=true; } String projection = query.substring(start, end).trim(); //split where comma is present but not inside quotes String[] columns = projection.split(",+(?![^\\(]*\\))"); ViewDefinition viewDefinition = new ViewDefinition(); viewDefinition.setName(viewName); viewDefinition.copy(query); for (int i = 0; i < columns.length; i++) { String columnName = columns[i].trim(); /* * Take the alias name if the column name has it. */ String[] aliasSplitters = new String[2]; aliasSplitters[0] = " as "; aliasSplitters[1] = " AS "; for(String aliasSplitter : aliasSplitters){ if (columnName.contains(aliasSplitter)) { // has an alias columnName = columnName.split(aliasSplitter)[1].trim(); break; } } if(columnName.contains(" ")) columnName = columnName.split("\\s+(?![^']*')")[1].trim();; /* * Remove any identifier quotes * Example: * INPUT: "table"."column" * OUTPUT: table.column */ if (columnName.contains("\"")) { columnName = columnName.replaceAll("\"", ""); quoted=true; } else if (columnName.contains("`")) { columnName = columnName.replaceAll("`", ""); quoted=true; } else if (columnName.contains("[") && columnName.contains("]")) { columnName = columnName.replaceAll("[", "").replaceAll("]", ""); quoted=true; } /* * Get only the short name if the column name uses qualified name. * Example: * INPUT: table.column * OUTPUT: column */ if (columnName.contains(".")) { columnName = columnName.substring(columnName.lastIndexOf(".")+1, columnName.length()); // get only the name } if(!quoted){ if(uppercase) columnName=columnName.toUpperCase(); else columnName=columnName.toLowerCase(); } viewDefinition.setAttribute(i+1, new Attribute(columnName)); // the attribute index always start at 1 } return viewDefinition; }
private ViewDefinition createViewDefinition(String viewName, String query) { int start = 6; // the keyword 'select' int end = query.toLowerCase().indexOf("from"); boolean uppercase=false; boolean quoted; if (end == -1) { throw new RuntimeException("Error parsing SQL query: Couldn't find FROM clause"); } if (database.contains("Oracle") || database.contains("DB2") || database.contains("H2")) { // If the database engine is Oracle, H2 or DB2 unquoted columns are changed in uppercase uppercase=true; } String projection = query.substring(start, end).trim(); //split where comma is present but not inside quotes String[] columns = projection.split(",+(?![^\\(]*\\))"); ViewDefinition viewDefinition = new ViewDefinition(); viewDefinition.setName(viewName); viewDefinition.copy(query); for (int i = 0; i < columns.length; i++) { quoted = false; String columnName = columns[i].trim(); /* * Take the alias name if the column name has it. */ String[] aliasSplitters = new String[2]; aliasSplitters[0] = " as "; aliasSplitters[1] = " AS "; for(String aliasSplitter : aliasSplitters){ if (columnName.contains(aliasSplitter)) { // has an alias columnName = columnName.split(aliasSplitter)[1].trim(); break; } } if(columnName.contains(" ")) columnName = columnName.split("\\s+(?![^']*')")[1].trim();; /* * Remove any identifier quotes * Example: * INPUT: "table"."column" * OUTPUT: table.column */ if (columnName.contains("\"")) { columnName = columnName.replaceAll("\"", ""); quoted=true; } else if (columnName.contains("`")) { columnName = columnName.replaceAll("`", ""); quoted=true; } else if (columnName.contains("[") && columnName.contains("]")) { columnName = columnName.replaceAll("[", "").replaceAll("]", ""); quoted=true; } /* * Get only the short name if the column name uses qualified name. * Example: * INPUT: table.column * OUTPUT: column */ if (columnName.contains(".")) { columnName = columnName.substring(columnName.lastIndexOf(".")+1, columnName.length()); // get only the name } if(!quoted){ if(uppercase) columnName=columnName.toUpperCase(); else columnName=columnName.toLowerCase(); } viewDefinition.setAttribute(i+1, new Attribute(columnName)); // the attribute index always start at 1 } return viewDefinition; }
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/query/command/Parse.java b/araqne-logdb/src/main/java/org/araqne/logdb/query/command/Parse.java index a46db53c..3c63ce0e 100644 --- a/araqne-logdb/src/main/java/org/araqne/logdb/query/command/Parse.java +++ b/araqne-logdb/src/main/java/org/araqne/logdb/query/command/Parse.java @@ -1,203 +1,213 @@ /* * Copyright 2013 Eediom Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.araqne.logdb.query.command; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.araqne.log.api.LogParser; import org.araqne.log.api.LogParserInput; import org.araqne.log.api.LogParserOutput; import org.araqne.logdb.FieldOrdering; import org.araqne.logdb.QueryCommand; import org.araqne.logdb.Row; import org.araqne.logdb.RowBatch; import org.araqne.logdb.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @since 1.6.6 * @author xeraph * */ public class Parse extends QueryCommand implements ThreadSafe, FieldOrdering { private final Logger logger = LoggerFactory.getLogger(Parse.class); private final int parserVersion; private final String parserName; private final LogParser parser; private final boolean overlay; public Parse(String parserName, LogParser parser, boolean overlay) { this.parserName = parserName; this.parser = parser; this.parserVersion = parser.getVersion(); this.overlay = overlay; } @Override public String getName() { return "parse"; } @Override public List<String> getFieldOrder() { if (parser instanceof FieldOrdering) return ((FieldOrdering) parser).getFieldOrder(); return null; } @Override public void onPush(RowBatch rowBatch) { // TODO: boost v2 performance if (parserVersion == 2) { if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[rowBatch.selected[i]]; onPush(row); } } else { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; onPush(row); } } return; } int n = 0; if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { int p = rowBatch.selected[i]; Row row = rowBatch.rows[p]; - Row parsed = parseV1(row); - if (parsed != null) { - rowBatch.selected[n] = p; - rowBatch.rows[p] = parsed; - n++; + try { + Row parsed = parseV1(row); + if (parsed != null) { + rowBatch.selected[n] = p; + rowBatch.rows[p] = parsed; + n++; + } + } catch (Throwable t) { + if (logger.isDebugEnabled()) + logger.debug("araqne logdb: cannot parse " + row.map() + ", query - " + toString(), t); } } } else { rowBatch.selected = new int[rowBatch.size]; for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; - Row parsed = parseV1(row); - if (parsed != null) { - rowBatch.selected[n] = i; - rowBatch.rows[i] = parsed; - n++; + try { + Row parsed = parseV1(row); + if (parsed != null) { + rowBatch.selected[n] = i; + rowBatch.rows[i] = parsed; + n++; + } + } catch (Throwable t) { + if (logger.isDebugEnabled()) + logger.debug("araqne logdb: cannot parse " + row.map() + ", query - " + toString(), t); } } } if (!rowBatch.selectedInUse && rowBatch.size != n) rowBatch.selectedInUse = true; rowBatch.size = n; pushPipe(rowBatch); } @Override public void onPush(Row row) { try { LogParserInput input = new LogParserInput(); if (parserVersion == 2) { Object table = row.get("_table"); Object time = row.get("_time"); Object id = row.get("_id"); if (time != null && time instanceof Date) input.setDate((Date) time); else input.setDate(null); if (table != null && table instanceof String) input.setSource((String) table); else input.setSource(null); input.setData(row.map()); LogParserOutput output = parser.parse(input); if (output != null) { for (Map<String, Object> out : output.getRows()) { if (id != null && !out.containsKey("_id")) out.put("_id", id); if (time != null && !out.containsKey("_time")) out.put("_time", row.get("_time")); if (table != null && !out.containsKey("_table")) out.put("_table", row.get("_table")); if (overlay) { Map<String, Object> source = new HashMap<String, Object>(row.map()); source.putAll(out); pushPipe(new Row(source)); } else { pushPipe(new Row(out)); } } } } else { Row parsed = parseV1(row); if (parsed != null) pushPipe(parsed); } } catch (Throwable t) { if (logger.isDebugEnabled()) logger.debug("araqne logdb: cannot parse " + row.map() + ", query - " + toString(), t); } } private Row parseV1(Row row) { Map<String, Object> parsed = parser.parse(row.map()); if (parsed == null) return null; Object id = row.get("_id"); Object time = row.get("_time"); Object table = row.get("_table"); if (id != null && !parsed.containsKey("_id")) parsed.put("_id", id); if (time != null && !parsed.containsKey("_time")) parsed.put("_time", time); if (table != null && !parsed.containsKey("_table")) parsed.put("_table", table); if (overlay) { Map<String, Object> source = new HashMap<String, Object>(row.map()); source.putAll(parsed); return new Row(source); } else return new Row(parsed); } @Override public String toString() { if (parser instanceof ParseWithAnchor) { return ((ParseWithAnchor) parser).toQueryCommandString(); } else { return "parse " + parserName; } } }
false
true
public void onPush(RowBatch rowBatch) { // TODO: boost v2 performance if (parserVersion == 2) { if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[rowBatch.selected[i]]; onPush(row); } } else { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; onPush(row); } } return; } int n = 0; if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { int p = rowBatch.selected[i]; Row row = rowBatch.rows[p]; Row parsed = parseV1(row); if (parsed != null) { rowBatch.selected[n] = p; rowBatch.rows[p] = parsed; n++; } } } else { rowBatch.selected = new int[rowBatch.size]; for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; Row parsed = parseV1(row); if (parsed != null) { rowBatch.selected[n] = i; rowBatch.rows[i] = parsed; n++; } } } if (!rowBatch.selectedInUse && rowBatch.size != n) rowBatch.selectedInUse = true; rowBatch.size = n; pushPipe(rowBatch); }
public void onPush(RowBatch rowBatch) { // TODO: boost v2 performance if (parserVersion == 2) { if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[rowBatch.selected[i]]; onPush(row); } } else { for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; onPush(row); } } return; } int n = 0; if (rowBatch.selectedInUse) { for (int i = 0; i < rowBatch.size; i++) { int p = rowBatch.selected[i]; Row row = rowBatch.rows[p]; try { Row parsed = parseV1(row); if (parsed != null) { rowBatch.selected[n] = p; rowBatch.rows[p] = parsed; n++; } } catch (Throwable t) { if (logger.isDebugEnabled()) logger.debug("araqne logdb: cannot parse " + row.map() + ", query - " + toString(), t); } } } else { rowBatch.selected = new int[rowBatch.size]; for (int i = 0; i < rowBatch.size; i++) { Row row = rowBatch.rows[i]; try { Row parsed = parseV1(row); if (parsed != null) { rowBatch.selected[n] = i; rowBatch.rows[i] = parsed; n++; } } catch (Throwable t) { if (logger.isDebugEnabled()) logger.debug("araqne logdb: cannot parse " + row.map() + ", query - " + toString(), t); } } } if (!rowBatch.selectedInUse && rowBatch.size != n) rowBatch.selectedInUse = true; rowBatch.size = n; pushPipe(rowBatch); }
diff --git a/exchange2/src/com/android/exchange/EasAccountService.java b/exchange2/src/com/android/exchange/EasAccountService.java index 58ddaf37..533a5df5 100644 --- a/exchange2/src/com/android/exchange/EasAccountService.java +++ b/exchange2/src/com/android/exchange/EasAccountService.java @@ -1,882 +1,882 @@ /* * Copyright (C) 2011 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.exchange; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.TrafficStats; import android.os.RemoteException; import android.os.SystemClock; import android.provider.CalendarContract; import android.provider.ContactsContract; import android.text.TextUtils; import android.util.Log; import com.android.emailcommon.TrafficFlags; import com.android.emailcommon.mail.MessagingException; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.AccountColumns; import com.android.emailcommon.provider.EmailContent.HostAuthColumns; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.provider.Policy; import com.android.emailcommon.provider.ProviderUnavailableException; import com.android.emailcommon.service.EmailServiceStatus; import com.android.emailcommon.service.PolicyServiceProxy; import com.android.exchange.CommandStatusException.CommandStatus; import com.android.exchange.adapter.AccountSyncAdapter; import com.android.exchange.adapter.FolderSyncParser; import com.android.exchange.adapter.Parser.EasParserException; import com.android.exchange.adapter.PingParser; import com.android.exchange.adapter.Serializer; import com.android.exchange.adapter.Tags; import com.android.exchange.provider.MailboxUtilities; import com.google.common.annotations.VisibleForTesting; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.entity.ByteArrayEntity; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; /** * AccountMailbox handles sync for the EAS "account mailbox"; this includes sync of the mailbox list * as well as management of mailbox push (using the EAS "Ping" command */ public class EasAccountService extends EasSyncService { private static final String WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PING; private static final String AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX = " AND " + MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ") AND " + MailboxColumns.TYPE + "!=\"" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + '\"'; private static final String WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PUSH_HOLD; private static final String WHERE_ACCOUNT_KEY_AND_SERVER_ID = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SERVER_ID + "=?"; /** * We start with an 8 minute timeout, and increase/decrease by 3 minutes at a time. There's * no point having a timeout shorter than 5 minutes, I think; at that point, we can just let * the ping exception out. The maximum I use is 17 minutes, which is really an empirical * choice; too long and we risk silent connection loss and loss of push for that period. Too * short and we lose efficiency/battery life. * * If we ever have to drop the ping timeout, we'll never increase it again. There's no point * going into hysteresis; the NAT timeout isn't going to change without a change in connection, * which will cause the sync service to be restarted at the starting heartbeat and going through * the process again. */ static private final int PING_MINUTES = 60; // in seconds static private final int PING_FUDGE_LOW = 10; static private final int PING_STARTING_HEARTBEAT = (8*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_HEARTBEAT_INCREMENT = 3*PING_MINUTES; static private final int PROTOCOL_PING_STATUS_COMPLETED = 1; static private final int PROTOCOL_PING_STATUS_BAD_PARAMETERS = 3; static private final int PROTOCOL_PING_STATUS_RETRY = 8; // Fallbacks (in minutes) for ping loop failures static private final int MAX_PING_FAILURES = 1; static private final int PING_FALLBACK_INBOX = 5; static private final int PING_FALLBACK_PIM = 25; // The amount of time the account mailbox will sleep if there are no pingable mailboxes // This could happen if the sync time is set to "never"; we always want to check in from time // to time, however, for folder list/policy changes static private final int ACCOUNT_MAILBOX_SLEEP_TIME = 20*MINUTES; static private final String ACCOUNT_MAILBOX_SLEEP_TEXT = "Account mailbox sleeping for " + (ACCOUNT_MAILBOX_SLEEP_TIME / MINUTES) + "m"; // Our heartbeat when we are waiting for ping boxes to be ready /*package*/ int mPingForceHeartbeat = 2*PING_MINUTES; // The minimum heartbeat we will send /*package*/ int mPingMinHeartbeat = (5*PING_MINUTES)-PING_FUDGE_LOW; // The maximum heartbeat we will send /*package*/ int mPingMaxHeartbeat = (17*PING_MINUTES)-PING_FUDGE_LOW; // The ping time (in seconds) /*package*/ int mPingHeartbeat = PING_STARTING_HEARTBEAT; // The longest successful ping heartbeat private int mPingHighWaterMark = 0; // Whether we've ever lowered the heartbeat /*package*/ boolean mPingHeartbeatDropped = false; private final String[] mBindArguments = new String[2]; private ArrayList<String> mPingChangeList; protected EasAccountService(Context _context, Mailbox _mailbox) { super(_context, _mailbox); } @VisibleForTesting protected EasAccountService() { } @Override public void run() { mExitStatus = EXIT_DONE; try { // Make sure account and mailbox are still valid if (!setupService()) return; // If we've been stopped, we're done if (mStop) return; try { mDeviceId = ExchangeService.getDeviceId(mContext); int trafficFlags = TrafficFlags.getSyncFlags(mContext, mAccount); TrafficStats.setThreadStatsTag(trafficFlags | TrafficFlags.DATA_EMAIL); if ((mMailbox == null) || (mAccount == null)) { return; } else { sync(); } } catch (EasAuthenticationException e) { userLog("Caught authentication error"); mExitStatus = EXIT_LOGIN_FAILURE; } catch (IOException e) { String message = e.getMessage(); userLog("Caught IOException: ", (message == null) ? "No message" : message); mExitStatus = EXIT_IO_ERROR; } catch (Exception e) { userLog("Uncaught exception in AccountMailboxService", e); } finally { ExchangeService.done(this); if (!mStop) { userLog("Sync finished"); switch (mExitStatus) { case EXIT_SECURITY_FAILURE: // Ask for a new folder list. This should wake up the account mailbox; a // security error in account mailbox should start provisioning ExchangeService.reloadFolderList(mContext, mAccount.mId, true); break; case EXIT_EXCEPTION: errorLog("Sync ended due to an exception."); break; } } else { userLog("Stopped sync finished."); } // Make sure ExchangeService knows about this ExchangeService.kick("sync finished"); } } catch (ProviderUnavailableException e) { Log.e(TAG, "EmailProvider unavailable; sync ended prematurely"); } } /** * If possible, update the account to the new server address; report result * @param resp the EasResponse from the current POST * @return whether or not the redirect is handled and the POST should be retried */ private boolean canHandleAccountMailboxRedirect(EasResponse resp) { userLog("AccountMailbox redirect error"); HostAuth ha = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (ha != null && getValidateRedirect(resp, ha)) { // Update the account's HostAuth with new values ContentValues haValues = new ContentValues(); haValues.put(HostAuthColumns.ADDRESS, ha.mAddress); ha.update(mContext, haValues); return true; } return false; } /** * Performs FolderSync * * @throws IOException * @throws EasParserException */ public void sync() throws IOException, EasParserException { // Check that the account's mailboxes are consistent MailboxUtilities.checkMailboxConsistency(mContext, mAccount.mId); // Initialize exit status to success try { try { ExchangeService.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } if (mAccount.mSyncKey == null) { mAccount.mSyncKey = "0"; userLog("Account syncKey INIT to 0"); ContentValues cv = new ContentValues(); cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey); mAccount.update(mContext, cv); } boolean firstSync = mAccount.mSyncKey.equals("0"); if (firstSync) { userLog("Initial FolderSync"); } // When we first start up, change all mailboxes to push. ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING, new String[] {Long.toString(mAccount.mId)}) > 0) { ExchangeService.kick("change ping boxes to push"); } // Determine our protocol version, if we haven't already and save it in the Account // Also re-check protocol version at least once a day (in case of upgrade) if (mAccount.mProtocolVersion == null || firstSync || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) { userLog("Determine EAS protocol version"); EasResponse resp = sendHttpClientOptions(); try { int code = resp.getStatus(); userLog("OPTIONS response: ", code); if (code == HttpStatus.SC_OK) { Header header = resp.getHeader("MS-ASProtocolCommands"); userLog(header.getValue()); header = resp.getHeader("ms-asprotocolversions"); try { setupProtocolVersion(this, header); } catch (MessagingException e) { // Since we've already validated, this can't really happen // But if it does, we'll rethrow this... throw new IOException(e); } // Save the protocol version cv.clear(); // Save the protocol version in the account; if we're using 12.0 or greater, // set the flag for support of SmartForward cv.put(Account.PROTOCOL_VERSION, mProtocolVersion); if (mProtocolVersionDouble >= 12.0) { cv.put(Account.FLAGS, mAccount.mFlags | Account.FLAGS_SUPPORTS_SMART_FORWARD | Account.FLAGS_SUPPORTS_SEARCH | Account.FLAGS_SUPPORTS_GLOBAL_SEARCH); } mAccount.update(mContext, cv); cv.clear(); // Save the sync time of the account mailbox to current time cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); mMailbox.update(mContext, cv); } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) { // Cause this to re-run throw new IOException("Will retry after a brief hold..."); } else { errorLog("OPTIONS command failed; throwing IOException"); throw new IOException(); } } finally { resp.close(); } } // Change all pushable boxes to push when we start the account mailbox if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) { cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, ExchangeService.WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Push account; set pushable boxes to push..."); } } while (!isStopped()) { // If we're not allowed to sync (e.g. roaming policy), leave now if (!ExchangeService.canAutoSync(mAccount)) return; userLog("Sending Account syncKey: ", mAccount.mSyncKey); Serializer s = new Serializer(); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY) .text(mAccount.mSyncKey).end().end().done(); EasResponse resp = sendHttpClientPost("FolderSync", s.toByteArray()); try { if (isStopped()) break; int code = resp.getStatus(); if (code == HttpStatus.SC_OK) { if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); // Returns true if we need to sync again if (new FolderSyncParser(is, new AccountSyncAdapter(this)).parse()) { continue; } } } else if (EasResponse.isProvisionError(code)) { throw new CommandStatusException(CommandStatus.NEEDS_PROVISIONING); } else if (EasResponse.isAuthError(code)) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; return; } else if (code == EAS_REDIRECT_CODE && canHandleAccountMailboxRedirect(resp)) { // This will cause a retry of the FolderSync continue; } else { userLog("FolderSync response error: ", code); } } finally { resp.close(); } // Change all push/hold boxes to push cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Set push/hold boxes to push..."); } try { ExchangeService.callback() .syncMailboxListStatus(mAccount.mId, exitStatusToServiceStatus(mExitStatus), 0); } catch (RemoteException e1) { // Don't care if this fails } // Before each run of the pingLoop, if this Account has a PolicySet, make sure it's // active; otherwise, clear out the key/flag. This should cause a provisioning // error on the next POST, and start the security sequence over again String key = mAccount.mSecuritySyncKey; if (!TextUtils.isEmpty(key)) { Policy policy = Policy.restorePolicyWithId(mContext, mAccount.mPolicyKey); if ((policy != null) && !PolicyServiceProxy.isActive(mContext, policy)) { resetSecurityPolicies(); } } // Wait for push notifications. String threadName = Thread.currentThread().getName(); try { runPingLoop(); } catch (StaleFolderListException e) { // We break out if we get told about a stale folder list userLog("Ping interrupted; folder list requires sync..."); } catch (IllegalHeartbeatException e) { // If we're sending an illegal heartbeat, reset either the min or the max to // that heartbeat resetHeartbeats(e.mLegalHeartbeat); } finally { Thread.currentThread().setName(threadName); } } } catch (CommandStatusException e) { // If the sync error is a provisioning failure (perhaps policies changed), // let's try the provisioning procedure // Provisioning must only be attempted for the account mailbox - trying to // provision any other mailbox may result in race conditions and the // creation of multiple policy keys. int status = e.mStatus; if (CommandStatus.isNeedsProvisioning(status)) { if (!tryProvision(this)) { // Set the appropriate failure status mExitStatus = EasSyncService.EXIT_SECURITY_FAILURE; return; } } else if (CommandStatus.isDeniedAccess(status)) { mExitStatus = EasSyncService.EXIT_ACCESS_DENIED; try { ExchangeService.callback().syncMailboxListStatus(mAccount.mId, EmailServiceStatus.ACCESS_DENIED, 0); } catch (RemoteException e1) { // Don't care if this fails } return; } else { userLog("Unexpected status: " + CommandStatus.toString(status)); mExitStatus = EasSyncService.EXIT_EXCEPTION; } } catch (IOException e) { // We catch this here to send the folder sync status callback // A folder sync failed callback will get sent from run() try { if (!isStopped()) { // NOTE: The correct status is CONNECTION_ERROR, but the UI displays this, and // it's not really appropriate for EAS as this is not unexpected for a ping and // connection errors are retried in any case ExchangeService.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.SUCCESS, 0); } } catch (RemoteException e1) { // Don't care if this fails } throw e; } } /** * Reset either our minimum or maximum ping heartbeat to a heartbeat known to be legal * @param legalHeartbeat a known legal heartbeat (from the EAS server) */ /*package*/ void resetHeartbeats(int legalHeartbeat) { userLog("Resetting min/max heartbeat, legal = " + legalHeartbeat); // We are here because the current heartbeat (mPingHeartbeat) is invalid. Depending on // whether the argument is above or below the current heartbeat, we can infer the need to // change either the minimum or maximum heartbeat if (legalHeartbeat > mPingHeartbeat) { // The legal heartbeat is higher than the ping heartbeat; therefore, our minimum was // too low. We respond by raising either or both of the minimum heartbeat or the // force heartbeat to the argument value if (mPingMinHeartbeat < legalHeartbeat) { mPingMinHeartbeat = legalHeartbeat; } if (mPingForceHeartbeat < legalHeartbeat) { mPingForceHeartbeat = legalHeartbeat; } // If our minimum is now greater than the max, bring them together if (mPingMinHeartbeat > mPingMaxHeartbeat) { mPingMaxHeartbeat = legalHeartbeat; } } else if (legalHeartbeat < mPingHeartbeat) { // The legal heartbeat is lower than the ping heartbeat; therefore, our maximum was // too high. We respond by lowering the maximum to the argument value mPingMaxHeartbeat = legalHeartbeat; // If our maximum is now less than the minimum, bring them together if (mPingMaxHeartbeat < mPingMinHeartbeat) { mPingMinHeartbeat = legalHeartbeat; } } // Set current heartbeat to the legal heartbeat mPingHeartbeat = legalHeartbeat; // Allow the heartbeat logic to run mPingHeartbeatDropped = false; } private void pushFallback(long mailboxId) { Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (mailbox == null) { return; } ContentValues cv = new ContentValues(); int mins = PING_FALLBACK_PIM; if (mailbox.mType == Mailbox.TYPE_INBOX) { mins = PING_FALLBACK_INBOX; } cv.put(Mailbox.SYNC_INTERVAL, mins); mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null); errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync"); ExchangeService.kick("push fallback"); } /** * Simplistic attempt to determine a NAT timeout, based on experience with various carriers * and networks. The string "reset by peer" is very common in these situations, so we look for * that specifically. We may add additional tests here as more is learned. * @param message * @return whether this message is likely associated with a NAT failure */ private boolean isLikelyNatFailure(String message) { if (message == null) return false; if (message.contains("reset by peer")) { return true; } return false; } private void sleep(long ms, boolean runAsleep) { if (runAsleep) { ExchangeService.runAsleep(mMailboxId, ms+(5*SECONDS)); } try { Thread.sleep(ms); } catch (InterruptedException e) { // Doesn't matter whether we stop early; it's the thought that counts } finally { if (runAsleep) { ExchangeService.runAwake(mMailboxId); } } } @Override protected EasResponse sendPing(byte[] bytes, int heartbeat) throws IOException { Thread.currentThread().setName(mAccount.mDisplayName + ": Ping"); if (Eas.USER_LOG) { userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's'); } return sendHttpClientPost(EasSyncService.PING_COMMAND, new ByteArrayEntity(bytes), (heartbeat+5)*SECONDS); } private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30*MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; long inboxId = -1; android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE); while ((System.currentTimeMillis() < endTime) && !isStopped()) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); if (c == null) throw new ProviderUnavailableException(); notReadyMailboxes.clear(); readyMailboxes.clear(); // Look for an inbox, and remember its id if (inboxId == -1) { inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX); } try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); // See what type of box we've got and get authority int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); String authority = EmailContent.AUTHORITY; switch(mailboxType) { case Mailbox.TYPE_CALENDAR: authority = CalendarContract.AUTHORITY; break; case Mailbox.TYPE_CONTACTS: authority = ContactsContract.AUTHORITY; break; } // See whether we can ping for this mailbox int pingStatus; if (!ContentResolver.getSyncAutomatically(amAccount, authority)) { pingStatus = ExchangeService.PING_STATUS_DISABLED; } else { pingStatus = ExchangeService.pingStatus(mailboxId); } if (pingStatus == ExchangeService.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER) .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass) .end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) || (pingStatus == ExchangeService.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) { pushCount--; userLog(mailboxName, " disabled by user; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostAborted = false; mPostReset = false; // If we've been stopped, this is a good time to return if (isStopped()) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); try { int code = resp.getStatus(); userLog("Ping response: ", code); // If we're not allowed to sync (e.g. roaming policy), terminate gracefully // now; otherwise we might start a sync based on the response if (!ExchangeService.canAutoSync(mAccount)) { stop(); } // Return immediately if we've been asked to stop during the ping if (isStopped()) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { - // Make sure to clear out any pending sync errors - ExchangeService.removeFromSyncErrorMap(mMailboxId); if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and wasn't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > mPingMaxHeartbeat) { pingHeartbeat = mPingMaxHeartbeat; } userLog("Increase ping heartbeat to ", pingHeartbeat, "s"); } } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS || pingResult == PROTOCOL_PING_STATUS_RETRY) { // These errors appear to be server-related (I've seen a bad // parameters result with known good parameters...) userLog("Server error during Ping: " + pingResult); // Act as if we have an IOException (backoff, etc.) throw new IOException(); } + // Make sure to clear out any pending sync errors + ExchangeService.removeFromSyncErrorMap(mMailboxId); } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (EasResponse.isAuthError(code)) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } finally { resp.close(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is ExchangeService telling us to try // another ping. } else if (mPostAborted || isLikelyNatFailure(message)) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < mPingMinHeartbeat) { pingHeartbeat = mPingMinHeartbeat; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) ExchangeService abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException"); } } else if (hasMessage && message.contains("roken pipe")) { // The "broken pipe" error (uppercase or lowercase "b") seems to be an // internal error, so let's not throw an exception (which leads to delays) // but rather simply run through the loop again } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60*SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from ExchangeService when a sync ends sleep(2*SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10*SECONDS, true); } else if (inboxId == -1) { // In this case, we're still syncing mailboxes, so sleep for only a short time sleep(45*SECONDS, true); } else { // We've got nothing to do, so we'll check again in 20 minutes at which time // we'll update the folder list, check for policy changes and/or remote wipe, etc. // Let the device sleep in the meantime... userLog(ACCOUNT_MAILBOX_SLEEP_TEXT); sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; } private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { PingParser pp = new PingParser(is, this); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId: mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); if (c == null) throw new ProviderUnavailableException(); try { if (c.moveToFirst()) { /** * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = ExchangeService.getStatusType(status); // This check should always be true... if (type == ExchangeService.SYNC_PING) { int changeCount = ExchangeService.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one ExchangeService.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), ExchangeService.SYNC_PING, null); } } finally { c.close(); } } } return pp.getSyncStatus(); } /** * Translate exit status code to service status code (used in callbacks) * @param exitStatus the service's exit status * @return the corresponding service status */ private int exitStatusToServiceStatus(int exitStatus) { switch(exitStatus) { case EasSyncService.EXIT_SECURITY_FAILURE: return EmailServiceStatus.SECURITY_FAILURE; case EasSyncService.EXIT_LOGIN_FAILURE: return EmailServiceStatus.LOGIN_FAILED; default: return EmailServiceStatus.SUCCESS; } } }
false
true
private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30*MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; long inboxId = -1; android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE); while ((System.currentTimeMillis() < endTime) && !isStopped()) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); if (c == null) throw new ProviderUnavailableException(); notReadyMailboxes.clear(); readyMailboxes.clear(); // Look for an inbox, and remember its id if (inboxId == -1) { inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX); } try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); // See what type of box we've got and get authority int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); String authority = EmailContent.AUTHORITY; switch(mailboxType) { case Mailbox.TYPE_CALENDAR: authority = CalendarContract.AUTHORITY; break; case Mailbox.TYPE_CONTACTS: authority = ContactsContract.AUTHORITY; break; } // See whether we can ping for this mailbox int pingStatus; if (!ContentResolver.getSyncAutomatically(amAccount, authority)) { pingStatus = ExchangeService.PING_STATUS_DISABLED; } else { pingStatus = ExchangeService.pingStatus(mailboxId); } if (pingStatus == ExchangeService.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER) .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass) .end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) || (pingStatus == ExchangeService.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) { pushCount--; userLog(mailboxName, " disabled by user; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostAborted = false; mPostReset = false; // If we've been stopped, this is a good time to return if (isStopped()) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); try { int code = resp.getStatus(); userLog("Ping response: ", code); // If we're not allowed to sync (e.g. roaming policy), terminate gracefully // now; otherwise we might start a sync based on the response if (!ExchangeService.canAutoSync(mAccount)) { stop(); } // Return immediately if we've been asked to stop during the ping if (isStopped()) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { // Make sure to clear out any pending sync errors ExchangeService.removeFromSyncErrorMap(mMailboxId); if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and wasn't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > mPingMaxHeartbeat) { pingHeartbeat = mPingMaxHeartbeat; } userLog("Increase ping heartbeat to ", pingHeartbeat, "s"); } } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS || pingResult == PROTOCOL_PING_STATUS_RETRY) { // These errors appear to be server-related (I've seen a bad // parameters result with known good parameters...) userLog("Server error during Ping: " + pingResult); // Act as if we have an IOException (backoff, etc.) throw new IOException(); } } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (EasResponse.isAuthError(code)) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } finally { resp.close(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is ExchangeService telling us to try // another ping. } else if (mPostAborted || isLikelyNatFailure(message)) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < mPingMinHeartbeat) { pingHeartbeat = mPingMinHeartbeat; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) ExchangeService abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException"); } } else if (hasMessage && message.contains("roken pipe")) { // The "broken pipe" error (uppercase or lowercase "b") seems to be an // internal error, so let's not throw an exception (which leads to delays) // but rather simply run through the loop again } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60*SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from ExchangeService when a sync ends sleep(2*SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10*SECONDS, true); } else if (inboxId == -1) { // In this case, we're still syncing mailboxes, so sleep for only a short time sleep(45*SECONDS, true); } else { // We've got nothing to do, so we'll check again in 20 minutes at which time // we'll update the folder list, check for policy changes and/or remote wipe, etc. // Let the device sleep in the meantime... userLog(ACCOUNT_MAILBOX_SLEEP_TEXT); sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; }
private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30*MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; long inboxId = -1; android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE); while ((System.currentTimeMillis() < endTime) && !isStopped()) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); if (c == null) throw new ProviderUnavailableException(); notReadyMailboxes.clear(); readyMailboxes.clear(); // Look for an inbox, and remember its id if (inboxId == -1) { inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX); } try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); // See what type of box we've got and get authority int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); String authority = EmailContent.AUTHORITY; switch(mailboxType) { case Mailbox.TYPE_CALENDAR: authority = CalendarContract.AUTHORITY; break; case Mailbox.TYPE_CONTACTS: authority = ContactsContract.AUTHORITY; break; } // See whether we can ping for this mailbox int pingStatus; if (!ContentResolver.getSyncAutomatically(amAccount, authority)) { pingStatus = ExchangeService.PING_STATUS_DISABLED; } else { pingStatus = ExchangeService.pingStatus(mailboxId); } if (pingStatus == ExchangeService.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER) .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass) .end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING) || (pingStatus == ExchangeService.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) { pushCount--; userLog(mailboxName, " disabled by user; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; mPostAborted = false; mPostReset = false; // If we've been stopped, this is a good time to return if (isStopped()) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat); try { int code = resp.getStatus(); userLog("Ping response: ", code); // If we're not allowed to sync (e.g. roaming policy), terminate gracefully // now; otherwise we might start a sync based on the response if (!ExchangeService.canAutoSync(mAccount)) { stop(); } // Return immediately if we've been asked to stop during the ping if (isStopped()) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { if (!resp.isEmpty()) { InputStream is = resp.getInputStream(); int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and wasn't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > mPingMaxHeartbeat) { pingHeartbeat = mPingMaxHeartbeat; } userLog("Increase ping heartbeat to ", pingHeartbeat, "s"); } } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS || pingResult == PROTOCOL_PING_STATUS_RETRY) { // These errors appear to be server-related (I've seen a bad // parameters result with known good parameters...) userLog("Server error during Ping: " + pingResult); // Act as if we have an IOException (backoff, etc.) throw new IOException(); } // Make sure to clear out any pending sync errors ExchangeService.removeFromSyncErrorMap(mMailboxId); } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (EasResponse.isAuthError(code)) { mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } finally { resp.close(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostReset) { // Nothing to do in this case; this is ExchangeService telling us to try // another ping. } else if (mPostAborted || isLikelyNatFailure(message)) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < mPingMinHeartbeat) { pingHeartbeat = mPingMinHeartbeat; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted) { // There's no point in throwing here; this can happen in two cases // 1) An alarm, which indicates minutes without activity; no sense // backing off // 2) ExchangeService abort, due to sync of mailbox. Again, we want to // keep on trying to ping userLog("Ping aborted; retry"); } else if (pingLength < 2000) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException"); } } else if (hasMessage && message.contains("roken pipe")) { // The "broken pipe" error (uppercase or lowercase "b") seems to be an // internal error, so let's not throw an exception (which leads to delays) // but rather simply run through the loop again } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60*SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from ExchangeService when a sync ends sleep(2*SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10*SECONDS, true); } else if (inboxId == -1) { // In this case, we're still syncing mailboxes, so sleep for only a short time sleep(45*SECONDS, true); } else { // We've got nothing to do, so we'll check again in 20 minutes at which time // we'll update the folder list, check for policy changes and/or remote wipe, etc. // Let the device sleep in the meantime... userLog(ACCOUNT_MAILBOX_SLEEP_TEXT); sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true); } } // Save away the current heartbeat mPingHeartbeat = pingHeartbeat; }
diff --git a/frost-wot/lib/skinlfFix/com/l2fprod/gui/plaf/skin/impl/gtk/GtkTableHeaderRenderer.java b/frost-wot/lib/skinlfFix/com/l2fprod/gui/plaf/skin/impl/gtk/GtkTableHeaderRenderer.java index 0d6d52ea..2c8eb2f1 100644 --- a/frost-wot/lib/skinlfFix/com/l2fprod/gui/plaf/skin/impl/gtk/GtkTableHeaderRenderer.java +++ b/frost-wot/lib/skinlfFix/com/l2fprod/gui/plaf/skin/impl/gtk/GtkTableHeaderRenderer.java @@ -1,186 +1,188 @@ /* ==================================================================== * * Skin Look And Feel 1.2.5 License. * * Copyright (c) 2000-2003 L2FProd.com. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by L2FProd.com * (http://www.L2FProd.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Skin Look And Feel", "SkinLF" and "L2FProd.com" must not * be used to endorse or promote products derived from this software * without prior written permission. For written permission, please * contact [email protected]. * * 5. Products derived from this software may not be called "SkinLF" * nor may "SkinLF" appear in their names without prior written * permission of L2FProd.com. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL L2FPROD.COM OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ package com.l2fprod.gui.plaf.skin.impl.gtk; import java.awt.*; import javax.swing.*; import javax.swing.table.*; import com.l2fprod.gui.plaf.skin.DefaultButton; import frost.gui.SortedTable; /** * Description of the Class * * @author fred * @created 27 avril 2002 */ public class GtkTableHeaderRenderer extends DefaultTableCellRenderer implements javax.swing.plaf.UIResource { static class SortArrowIcon implements Icon { public static final int NONE = 0; public static final int DECENDING = 1; public static final int ASCENDING = 2; protected int direction; protected int width = 8; protected int height = 8; public SortArrowIcon(int direction) { this.direction = direction; } public int getIconWidth() { return width; } public int getIconHeight() { return height; } public void paintIcon(Component c, Graphics g, int x, int y) { Color bg = c.getBackground(); Color light = bg.brighter(); Color shade = bg.darker(); int w = width; int h = height; int m = w / 2; if (direction == ASCENDING) { g.setColor(shade); g.drawLine(x, y, x + w, y); g.drawLine(x, y, x + m, y + h); g.setColor(light); g.drawLine(x + w, y, x + m, y + h); } if (direction == DECENDING) { g.setColor(shade); g.drawLine(x + m, y, x, y + h); g.setColor(light); g.drawLine(x, y + h, x + w, y + h); g.drawLine(x + m, y, x + w, y + h); } } } public static Icon NONSORTED = new SortArrowIcon(SortArrowIcon.NONE); public static Icon ASCENDING = new SortArrowIcon(SortArrowIcon.ASCENDING); public static Icon DECENDING = new SortArrowIcon(SortArrowIcon.DECENDING); boolean isSelected; boolean hasFocus; transient DefaultButton itemSelected, itemUnselected; /** * Constructor for the GtkTableHeaderRenderer object */ public GtkTableHeaderRenderer(DefaultButton itemSelected, DefaultButton itemUnselected) { setOpaque(false); this.itemSelected = itemSelected; this.itemUnselected = itemUnselected; setHorizontalTextPosition(LEFT); setHorizontalAlignment(CENTER); } /** * Gets the TableCellRendererComponent attribute of the * GtkTableHeaderRenderer object * * @param table Description of Parameter * @param value Description of Parameter * @param isSelected Description of Parameter * @param hasFocus Description of Parameter * @param row Description of Parameter * @param column Description of Parameter * @return The TableCellRendererComponent value */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int index = -1; int modelIndex = -1; boolean ascending = true; + boolean isSortedTable = false; if (table != null) { if (table instanceof SortedTable) { + isSortedTable = true; SortedTable sortTable = (SortedTable) table; index = sortTable.getSortedColumnIndex(); ascending = sortTable.isSortedColumnAscending(); TableColumnModel colModel = table.getColumnModel(); modelIndex = colModel.getColumn(column).getModelIndex(); } JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } this.isSelected = isSelected; this.hasFocus = hasFocus; Icon icon = ascending ? ASCENDING : DECENDING; - setIcon(modelIndex == index ? icon : NONSORTED); + setIcon((modelIndex == index) && isSortedTable ? icon : NONSORTED); setText((value == null) ? "" : value.toString()); return this; } /** * Description of the Method * * @param g Description of Parameter */ protected void paintComponent(Graphics g) { if (isSelected || hasFocus) { itemSelected.paint(g, this); } else { itemUnselected.paint(g, this); } super.paintComponent(g); } }
false
true
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int index = -1; int modelIndex = -1; boolean ascending = true; if (table != null) { if (table instanceof SortedTable) { SortedTable sortTable = (SortedTable) table; index = sortTable.getSortedColumnIndex(); ascending = sortTable.isSortedColumnAscending(); TableColumnModel colModel = table.getColumnModel(); modelIndex = colModel.getColumn(column).getModelIndex(); } JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } this.isSelected = isSelected; this.hasFocus = hasFocus; Icon icon = ascending ? ASCENDING : DECENDING; setIcon(modelIndex == index ? icon : NONSORTED); setText((value == null) ? "" : value.toString()); return this; }
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int index = -1; int modelIndex = -1; boolean ascending = true; boolean isSortedTable = false; if (table != null) { if (table instanceof SortedTable) { isSortedTable = true; SortedTable sortTable = (SortedTable) table; index = sortTable.getSortedColumnIndex(); ascending = sortTable.isSortedColumnAscending(); TableColumnModel colModel = table.getColumnModel(); modelIndex = colModel.getColumn(column).getModelIndex(); } JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } this.isSelected = isSelected; this.hasFocus = hasFocus; Icon icon = ascending ? ASCENDING : DECENDING; setIcon((modelIndex == index) && isSortedTable ? icon : NONSORTED); setText((value == null) ? "" : value.toString()); return this; }
diff --git a/tests/org.jboss.tools.jst.jsp.test/src/org/jboss/tools/jst/jsp/test/ca/JsfJspJbide1717Test.java b/tests/org.jboss.tools.jst.jsp.test/src/org/jboss/tools/jst/jsp/test/ca/JsfJspJbide1717Test.java index 27d960c6..3ee4c93a 100644 --- a/tests/org.jboss.tools.jst.jsp.test/src/org/jboss/tools/jst/jsp/test/ca/JsfJspJbide1717Test.java +++ b/tests/org.jboss.tools.jst.jsp.test/src/org/jboss/tools/jst/jsp/test/ca/JsfJspJbide1717Test.java @@ -1,138 +1,138 @@ package org.jboss.tools.jst.jsp.test.ca; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal; import org.jboss.tools.common.test.util.TestProjectProvider; import org.jboss.tools.jst.jsp.test.TestUtil; import org.jboss.tools.test.util.xpl.EditorTestHelper; public class JsfJspJbide1717Test extends ContentAssistantTestCase { TestProjectProvider provider = null; boolean makeCopy = false; private static final String PROJECT_NAME = "JsfJbide1704Test"; private static final String PAGE_NAME = "/WebContent/pages/greeting.jsp"; private static final String INSERT_BEFORE_STRING = "<h:outputText"; private static final String INSERTION_BEGIN_STRING = "<h:outputText value=\""; private static final String INSERTION_END_STRING = "\" />"; private static final String JSF_EXPR_STRING = "#{msg.greeting}"; public static Test suite() { return new TestSuite(JsfJspJbide1717Test.class); } public void setUp() throws Exception { provider = new TestProjectProvider("org.jboss.tools.jst.jsp.test", null, PROJECT_NAME, makeCopy); project = provider.getProject(); Throwable exception = null; try { project.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (Exception x) { exception = x; x.printStackTrace(); } assertNull("An exception caught: " + (exception != null? exception.getMessage() : ""), exception); } protected void tearDown() throws Exception { if(provider != null) { provider.dispose(); } } - public void testJstJspJbide1641() { + public void testJstJspJbide1717() { openEditor(PAGE_NAME); // Find start of <h:outputText> tag String documentContent = document.get(); int start = (documentContent == null ? -1 : documentContent.indexOf(INSERT_BEFORE_STRING)); assertTrue("Cannot find the starting point in the test file \"" + PAGE_NAME + "\"", (start != -1)); // First of all perform the test on a region placed in one space behind empty-valued attribute - // this is to return normal list of attribute names proposal list String documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + INSERTION_END_STRING + documentContent.substring(start); int offsetToTest = start + INSERTION_BEGIN_STRING.length() + 2; jspTextEditor.setText(documentContentModified); ICompletionProposal[] result= null; String errorMessage = null; IContentAssistProcessor p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } List<String> customCompletionProposals = new ArrayList<String>(); for (int i = 0; i < result.length; i++) { // There should be at least one proposal of type CustomCompletionProposal in the result if (result[i] instanceof CustomCompletionProposal) { customCompletionProposals.add(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertFalse("Content Assistant returned no proposals of type CustomCompletionProposal.",customCompletionProposals.isEmpty()); try { EditorTestHelper.joinBackgroundActivities(); } catch (Exception e) { e.printStackTrace(); assertTrue("Waiting for the jobs to complete has failed.", false); } // Next perform the test on a region placed in one space behind an attribute those value is a container // (contains JSF expression) - this has to return the same normal list of attribute names proposal list as // we got at the first step (because the tag is the same, but only the attribute value is changed) documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + JSF_EXPR_STRING + INSERTION_END_STRING + documentContent.substring(start); offsetToTest = start + INSERTION_BEGIN_STRING.length() + JSF_EXPR_STRING.length() + 2; String visualizeCursorPosition = documentContentModified.substring(0, offsetToTest) + "|" + documentContentModified.substring(offsetToTest); jspTextEditor.setText(documentContentModified); p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } for (int i = 0; i < result.length; i++) { // There should be the same proposals as in the saved result if (result[i] instanceof CustomCompletionProposal) { assertTrue("Content Assistant returned additional proposal (proposal returned doesn't exist in the saved list).", customCompletionProposals.contains(((CustomCompletionProposal)result[i]).getReplacementString())); customCompletionProposals.remove(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertTrue("Content Assistant didn't returned some proposals.",customCompletionProposals.isEmpty()); closeEditor(); } }
true
true
public void testJstJspJbide1641() { openEditor(PAGE_NAME); // Find start of <h:outputText> tag String documentContent = document.get(); int start = (documentContent == null ? -1 : documentContent.indexOf(INSERT_BEFORE_STRING)); assertTrue("Cannot find the starting point in the test file \"" + PAGE_NAME + "\"", (start != -1)); // First of all perform the test on a region placed in one space behind empty-valued attribute - // this is to return normal list of attribute names proposal list String documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + INSERTION_END_STRING + documentContent.substring(start); int offsetToTest = start + INSERTION_BEGIN_STRING.length() + 2; jspTextEditor.setText(documentContentModified); ICompletionProposal[] result= null; String errorMessage = null; IContentAssistProcessor p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } List<String> customCompletionProposals = new ArrayList<String>(); for (int i = 0; i < result.length; i++) { // There should be at least one proposal of type CustomCompletionProposal in the result if (result[i] instanceof CustomCompletionProposal) { customCompletionProposals.add(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertFalse("Content Assistant returned no proposals of type CustomCompletionProposal.",customCompletionProposals.isEmpty()); try { EditorTestHelper.joinBackgroundActivities(); } catch (Exception e) { e.printStackTrace(); assertTrue("Waiting for the jobs to complete has failed.", false); } // Next perform the test on a region placed in one space behind an attribute those value is a container // (contains JSF expression) - this has to return the same normal list of attribute names proposal list as // we got at the first step (because the tag is the same, but only the attribute value is changed) documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + JSF_EXPR_STRING + INSERTION_END_STRING + documentContent.substring(start); offsetToTest = start + INSERTION_BEGIN_STRING.length() + JSF_EXPR_STRING.length() + 2; String visualizeCursorPosition = documentContentModified.substring(0, offsetToTest) + "|" + documentContentModified.substring(offsetToTest); jspTextEditor.setText(documentContentModified); p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } for (int i = 0; i < result.length; i++) { // There should be the same proposals as in the saved result if (result[i] instanceof CustomCompletionProposal) { assertTrue("Content Assistant returned additional proposal (proposal returned doesn't exist in the saved list).", customCompletionProposals.contains(((CustomCompletionProposal)result[i]).getReplacementString())); customCompletionProposals.remove(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertTrue("Content Assistant didn't returned some proposals.",customCompletionProposals.isEmpty()); closeEditor(); }
public void testJstJspJbide1717() { openEditor(PAGE_NAME); // Find start of <h:outputText> tag String documentContent = document.get(); int start = (documentContent == null ? -1 : documentContent.indexOf(INSERT_BEFORE_STRING)); assertTrue("Cannot find the starting point in the test file \"" + PAGE_NAME + "\"", (start != -1)); // First of all perform the test on a region placed in one space behind empty-valued attribute - // this is to return normal list of attribute names proposal list String documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + INSERTION_END_STRING + documentContent.substring(start); int offsetToTest = start + INSERTION_BEGIN_STRING.length() + 2; jspTextEditor.setText(documentContentModified); ICompletionProposal[] result= null; String errorMessage = null; IContentAssistProcessor p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } List<String> customCompletionProposals = new ArrayList<String>(); for (int i = 0; i < result.length; i++) { // There should be at least one proposal of type CustomCompletionProposal in the result if (result[i] instanceof CustomCompletionProposal) { customCompletionProposals.add(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertFalse("Content Assistant returned no proposals of type CustomCompletionProposal.",customCompletionProposals.isEmpty()); try { EditorTestHelper.joinBackgroundActivities(); } catch (Exception e) { e.printStackTrace(); assertTrue("Waiting for the jobs to complete has failed.", false); } // Next perform the test on a region placed in one space behind an attribute those value is a container // (contains JSF expression) - this has to return the same normal list of attribute names proposal list as // we got at the first step (because the tag is the same, but only the attribute value is changed) documentContentModified = documentContent.substring(0, start) + INSERTION_BEGIN_STRING + JSF_EXPR_STRING + INSERTION_END_STRING + documentContent.substring(start); offsetToTest = start + INSERTION_BEGIN_STRING.length() + JSF_EXPR_STRING.length() + 2; String visualizeCursorPosition = documentContentModified.substring(0, offsetToTest) + "|" + documentContentModified.substring(offsetToTest); jspTextEditor.setText(documentContentModified); p= TestUtil.getProcessor(viewer, offsetToTest, contentAssistant); if (p != null) { try { result= p.computeCompletionProposals(viewer, offsetToTest); } catch (Throwable x) { x.printStackTrace(); } errorMessage= p.getErrorMessage(); } for (int i = 0; i < result.length; i++) { // There should be the same proposals as in the saved result if (result[i] instanceof CustomCompletionProposal) { assertTrue("Content Assistant returned additional proposal (proposal returned doesn't exist in the saved list).", customCompletionProposals.contains(((CustomCompletionProposal)result[i]).getReplacementString())); customCompletionProposals.remove(((CustomCompletionProposal)result[i]).getReplacementString()); } } assertTrue("Content Assistant didn't returned some proposals.",customCompletionProposals.isEmpty()); closeEditor(); }
diff --git a/src/org/rsbot/script/web/RouteStep.java b/src/org/rsbot/script/web/RouteStep.java index b901aba5..1ec0288e 100644 --- a/src/org/rsbot/script/web/RouteStep.java +++ b/src/org/rsbot/script/web/RouteStep.java @@ -1,140 +1,140 @@ package org.rsbot.script.web; import org.rsbot.script.Random; import org.rsbot.script.Script; import org.rsbot.script.methods.MethodContext; import org.rsbot.script.methods.MethodProvider; import org.rsbot.script.randoms.LoginBot; import org.rsbot.script.wrappers.RSPath; import org.rsbot.script.wrappers.RSTile; import java.util.Collections; public class RouteStep extends MethodProvider { private final Type type; private RSTile[] path = null; private RSPath rspath = null; private Teleport teleport = null; public static enum Type { PATH, TELEPORT } public RouteStep(final MethodContext ctx, final Object step) { super(ctx); if (step instanceof Teleport) { this.type = Type.TELEPORT; this.teleport = (Teleport) step; } else if (step instanceof RSTile[]) { this.type = Type.PATH; this.path = (RSTile[]) step; } else if (step instanceof RSTile) { this.type = Type.PATH; this.path = new RSTile[]{(RSTile) step}; } else { throw new IllegalArgumentException("Step is of an invalid type!"); } } public boolean execute() { try { if (aScriptInactive()) { return false; } switch (type) { case PATH: if (path == null || inSomeRandom()) { return false; } - if (rspath == null || (rspath.getNext() == null && destOffScreen())) { + if (rspath == null || (rspath.getNext() == null && !destOffScreen())) { update(); } if (methods.calc.distanceTo(rspath.getEnd()) < 5) { rspath = null; path = null; return true; } sleep(random(50, 150)); return !inSomeRandom() && rspath.traverse(); case TELEPORT: if (inSomeRandom()) { return false; } if (teleport != null && teleport.perform()) { teleport = null; return true; } return false; } } catch (Exception e) { } return false; } public boolean finished() { return path == null && teleport == null; } public Teleport getTeleport() { return teleport; } public RSTile[] getPath() { switch (type) { case PATH: return path; case TELEPORT: return new RSTile[]{methods.players.getMyPlayer().getLocation(), teleport.teleportationLocation()}; } return null; } private boolean aScriptInactive() { for (final Script checkScript : Collections.unmodifiableCollection(methods.bot.getScriptHandler().getRunningScripts().values())) { if (!checkScript.isActive() || !checkScript.isRunning()) { return true; } if (checkScript.isPaused()) { sleep(500); return true; } } return Collections.unmodifiableCollection(methods.bot.getScriptHandler().getRunningScripts().values()).size() == 0; } private boolean inSomeRandom() { if (methods.bot.disableRandoms) { return false; } for (final Random random : methods.bot.getScriptHandler().getRandoms()) { if (random.isEnabled() && !(methods.bot.disableAutoLogin && random instanceof LoginBot)) { if (random.activateCondition()) { return true; } } } return false; } private boolean destOffScreen() { if (rspath.getNext() == null && methods.players.getMyPlayer().isMoving() && methods.walking.getDestination() == null) { sleep(random(200, 250)); if (methods.players.getMyPlayer().isMoving()) { sleep(random(100, 150)); if (methods.players.getMyPlayer().isMoving()) { return true; } } } return false; } public void update() { if (path != null && path.length > 1) { RSTile startTile = path[0]; RSTile endTile = path[path.length - 1]; path = methods.web.generateNodePath(startTile, endTile); rspath = path != null ? methods.walking.newTilePath(path) : rspath; } } }
true
true
public boolean execute() { try { if (aScriptInactive()) { return false; } switch (type) { case PATH: if (path == null || inSomeRandom()) { return false; } if (rspath == null || (rspath.getNext() == null && destOffScreen())) { update(); } if (methods.calc.distanceTo(rspath.getEnd()) < 5) { rspath = null; path = null; return true; } sleep(random(50, 150)); return !inSomeRandom() && rspath.traverse(); case TELEPORT: if (inSomeRandom()) { return false; } if (teleport != null && teleport.perform()) { teleport = null; return true; } return false; } } catch (Exception e) { } return false; }
public boolean execute() { try { if (aScriptInactive()) { return false; } switch (type) { case PATH: if (path == null || inSomeRandom()) { return false; } if (rspath == null || (rspath.getNext() == null && !destOffScreen())) { update(); } if (methods.calc.distanceTo(rspath.getEnd()) < 5) { rspath = null; path = null; return true; } sleep(random(50, 150)); return !inSomeRandom() && rspath.traverse(); case TELEPORT: if (inSomeRandom()) { return false; } if (teleport != null && teleport.perform()) { teleport = null; return true; } return false; } } catch (Exception e) { } return false; }
diff --git a/src/com/bekvon/bukkit/residence/protection/ClaimedResidence.java b/src/com/bekvon/bukkit/residence/protection/ClaimedResidence.java index 5f405f0..fd93399 100644 --- a/src/com/bekvon/bukkit/residence/protection/ClaimedResidence.java +++ b/src/com/bekvon/bukkit/residence/protection/ClaimedResidence.java @@ -1,680 +1,698 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bekvon.bukkit.residence.protection; import com.bekvon.bukkit.residence.Residence; import com.bekvon.bukkit.residence.economy.TransactionManager; import com.bekvon.bukkit.residence.permissions.PermissionGroup; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; /** * * @author Administrator */ public class ClaimedResidence { protected ClaimedResidence parent; protected Map<String, CuboidArea> areas; protected Map<String, ClaimedResidence> subzones; protected ResidencePermissions perms; protected Location tpLoc; protected String enterMessage; protected String leaveMessage; private ClaimedResidence() { subzones = Collections.synchronizedMap(new HashMap<String, ClaimedResidence>()); areas = Collections.synchronizedMap(new HashMap<String, CuboidArea>()); } public ClaimedResidence(String creator, String creationWorld) { this(); perms = new ResidencePermissions(this,creator, creationWorld); } public ClaimedResidence(String creator, String creationWorld, ClaimedResidence parentResidence) { this(creator, creationWorld); parent = parentResidence; } public void addArea(Player player, CuboidArea area, String name) { name = name.replace(".", "_"); name = name.replace(":", "_"); if(areas.containsKey(name)) { player.sendMessage("§cArea name already exists."); return; } if (!area.getWorld().getName().equalsIgnoreCase(perms.getWorld())) { player.sendMessage("§cArea is in a different world from residence."); return; } if(area.getSize()==0) { player.sendMessage("§cError, 0 sized area."); return; } if(!Residence.getPermissionManager().isResidenceAdmin(player)) { if (!this.perms.hasResidencePermission(player, true)) { player.sendMessage("§cYou dont have permission to do this."); return; } if (parent != null) { if (!parent.containsLoc(area.getHighLoc()) || !parent.containsLoc(area.getLowLoc())) { player.sendMessage("§cArea is not within parent area."); return; } if(!parent.getPermissions().hasResidencePermission(player, true) && !parent.getPermissions().playerHas(player.getName(),"subzone", true)) { player.sendMessage("§cYou dont have permission to make changes to the parent area."); return; } } PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(!group.canCreateResidences() && !Residence.getPermissionManager().hasAuthority(player, "residence.create", false)) { player.sendMessage("You dont have permission to create residences."); return; } if(areas.size()>=group.getMaxPhysicalPerResidence()) { player.sendMessage("§cYou've reached the max physical areas allowed for your residence."); return; } if(!group.inLimits(area)) { player.sendMessage("§cArea size is not within your allowed limits."); return; } if(group.getMinHeight()>area.getLowLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this deep, minimum height:" + group.getMinHeight()); return; } if(group.getMaxHeight()<area.getHighLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this high up, maximum height:" + group.getMaxHeight()); return; } if(parent==null && Residence.getConfig().enableEconomy()) { int chargeamount = (int) Math.ceil((double)area.getSize() * group.getCostPerBlock()); if(!TransactionManager.chargeEconomyMoney(player, chargeamount, "new residence area")) { return; } } } - String collideResidence = Residence.getResidenceManger().checkAreaCollision(area, this); - if(collideResidence!=null) + if(parent==null) { - player.sendMessage("§cArea collides with residence: §e" + collideResidence); - return; + String collideResidence = Residence.getResidenceManger().checkAreaCollision(area, this); + if(collideResidence!=null) + { + player.sendMessage("§cArea collides with residence: §e" + collideResidence); + return; + } + } + else + { + String[] subzones = parent.listSubzones(); + for(String sz : subzones) + { + ClaimedResidence res = parent.getSubzone(sz); + if(res!=null) + { + if(res.checkCollision(area)) + { + player.sendMessage("§cArea collides with subzone: §e" + sz); + } + } + } } areas.put(name, area); player.sendMessage("§aArea created. ID:§e " + name); } public void addSubzone(Player player, Location loc1, Location loc2, String name) { name = name.replace(".", "_"); name = name.replace(":", "_"); if(!Residence.getPermissionManager().isResidenceAdmin(player)) { if (!this.perms.hasResidencePermission(player, true)) { if(!this.perms.playerHas(player.getName(), "subzone", false)) { player.sendMessage("§cYou dont have permission to do this."); return; } } if (!(this.containsLoc(loc1) && this.containsLoc(loc2))) { player.sendMessage("§cBoth selection points must be inside the residence."); return; } if (subzones.containsKey(name)) { player.sendMessage("§cSubzone name already exists."); return; } PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(this.getZoneDepth()>=group.getMaxSubzoneDepth()) { player.sendMessage("§cYou've reached the max allowed subzone depth."); return; } } CuboidArea newArea = new CuboidArea(loc1, loc2); Set<Entry<String, ClaimedResidence>> set = subzones.entrySet(); synchronized (subzones) { for (Entry<String, ClaimedResidence> resEntry : set) { ClaimedResidence res = resEntry.getValue(); if (res.checkCollision(newArea)) { player.sendMessage("§cSubzone collides with subzone: §e" + resEntry.getKey()); return; } } } ClaimedResidence newres = new ClaimedResidence(player.getName(), perms.getWorld(), this); newres.addArea(player, newArea, name); if(newres.getAreaCount()!=0) { newres.getPermissions().applyDefaultFlags(); PermissionGroup group = Residence.getPermissionManager().getGroup(player); newres.setEnterMessage(group.getDefaultEnterMessage()); newres.setLeaveMessage(group.getDefaultLeaveMessage()); subzones.put(name, newres); player.sendMessage("§aCreated subzone: §e" + name); } else { player.sendMessage("§cUnable to create subzone..."); } } public String getSubzoneNameByLoc(Location loc) { Set<Entry<String, ClaimedResidence>> set = subzones.entrySet(); ClaimedResidence res = null; String key = null; for (Entry<String, ClaimedResidence> entry : set) { res = entry.getValue(); if (res.containsLoc(loc)) { key = entry.getKey(); break; } } if (key == null) { return null; } String subname = res.getSubzoneNameByLoc(loc); if (subname != null) { return key + "." + subname; } return key; } public ClaimedResidence getSubzoneByLoc(Location loc) { Set<Entry<String, ClaimedResidence>> set = subzones.entrySet(); boolean found = false; ClaimedResidence res = null; synchronized (subzones) { for (Entry<String, ClaimedResidence> entry : set) { res = entry.getValue(); if (res.containsLoc(loc)) { found = true; break; } } } if (!found) { return null; } ClaimedResidence subrez = res.getSubzoneByLoc(loc); if (subrez == null) { return res; } return subrez; } public ClaimedResidence getSubzone(String subzonename) { if (!subzonename.contains(".")) { return subzones.get(subzonename); } String split[] = subzonename.split("\\."); ClaimedResidence get = subzones.get(split[0]); for (int i = 1; i < split.length; i++) { if (get == null) { return null; } get = get.getSubzone(split[i]); } return get; } public String[] getSubzoneList() { ArrayList zones = new ArrayList<String>(); Set<String> set = subzones.keySet(); synchronized (subzones) { for (String key : set) { if (key != null) { zones.add(key); } } } return (String[]) zones.toArray(); } public boolean checkCollision(CuboidArea area) { Set<String> set = areas.keySet(); for (String key : set) { CuboidArea checkarea = areas.get(key); if (checkarea != null) { if (checkarea.checkCollision(area)) { return true; } } } return false; } public boolean containsLoc(Location loc) { Collection<CuboidArea> keys = areas.values(); for (CuboidArea key : keys) { if (key.containsLoc(loc)) { if(parent!=null) return parent.containsLoc(loc); return true; } } return false; } public ClaimedResidence getParent() { return parent; } public ClaimedResidence getTopParent() { if(parent==null) return this; return parent.getTopParent(); } public void removeSubzone(Player player, String name) { ClaimedResidence res = subzones.get(name); if (!res.perms.hasResidencePermission(player, true)) { player.sendMessage("§cYou dont have permission to do this."); return; } subzones.remove(name); player.sendMessage("§aSubzone removed."); } public void removeSubzone(String name) { subzones.remove(name); } public long getTotalSize() { Collection<CuboidArea> set = areas.values(); long size = 0; synchronized (areas) { for (CuboidArea entry : set) { size = size + entry.getSize(); } } return size; } public CuboidArea[] getAreaArray() { CuboidArea[] temp = new CuboidArea[areas.size()]; int i=0; for(CuboidArea area : areas.values()) { temp[i] = area; i++; } return temp; } public ResidencePermissions getPermissions() { return perms; } public String getEnterMessage() { return enterMessage; } public String getLeaveMessage() { return leaveMessage; } public void setEnterMessage(String message) { enterMessage = message; } public void setLeaveMessage(String message) { leaveMessage = message; } public void setEnterLeaveMessage(Player player, String message, boolean enter) { if(message!=null) if(message.equals("")) message = null; boolean resadmin = Residence.getPermissionManager().isResidenceAdmin(player); PermissionGroup group = Residence.getPermissionManager().getGroup(perms.getOwner(), perms.getWorld()); if(!group.canSetEnterLeaveMessages() && !resadmin) { player.sendMessage("§cOwner is not allowed to change enter / leave messages."); return; } if(!perms.hasResidencePermission(player, false) && !resadmin) { player.sendMessage("§cYou dont have permission to do this."); return; } if(enter) this.setEnterMessage(message); else this.setLeaveMessage(message); player.sendMessage("§aMessage set..."); } public Location getOutsideFreeLoc(Location insideLoc) { int maxIt = 100; CuboidArea area = this.getAreaByLoc(insideLoc); if(area==null) return insideLoc; Location highLoc = area.getHighLoc(); Location newLoc = new Location(highLoc.getWorld(), highLoc.getBlockX(), highLoc.getBlockY(), highLoc.getBlockZ()); boolean found = false; int it = 0; while (!found && it < maxIt) { it++; Location lowLoc; newLoc.setX(newLoc.getBlockX() + 1); newLoc.setZ(newLoc.getBlockZ() + 1); lowLoc = new Location(newLoc.getWorld(), newLoc.getBlockX(), 126, newLoc.getBlockZ()); newLoc.setY(127); while ((newLoc.getBlock().getTypeId() != 0 || lowLoc.getBlock().getTypeId() == 0) && lowLoc.getBlockY() > -126) { newLoc.setY(newLoc.getY() - 1); lowLoc.setY(lowLoc.getY() - 1); } if (newLoc.getBlock().getTypeId() == 0 && lowLoc.getBlock().getTypeId() != 0) { found = true; } } if(found) return newLoc; else { World world = Residence.getServ().getWorld(perms.getWorld()); if(world!=null) return world.getSpawnLocation(); return insideLoc; } } protected CuboidArea getAreaByLoc(Location loc) { synchronized(areas) { for(CuboidArea thisarea : areas.values()) { if(thisarea.containsLoc(loc)) return thisarea; } } return null; } public String CSVSubzoneList() { String list = ""; synchronized(subzones) { for(String res : subzones.keySet()) { if(list.equals("")) list = res; else list = list + ", " + res; } } return list; } public String[] listSubzones() { String list[] = new String[subzones.size()]; int i = 0; synchronized(subzones) { for(String res : subzones.keySet()) { list[i] = res; i++; } } return list; } public String getFormattedAreaList() { StringBuilder s = new StringBuilder(); for(Entry<String, CuboidArea> entry : areas.entrySet()) { CuboidArea a = entry.getValue(); Location h = a.getHighLoc(); Location l = a.getLowLoc(); s.append("§a{§eID:§c").append(entry.getKey()).append(" §eP1:§c(").append(h.getBlockX()).append(",").append(h.getBlockY()).append(",").append(h.getBlockZ()).append(") §eP2:§c(").append(l.getBlockX()).append(",").append(l.getBlockY()).append(",").append(l.getBlockZ()+") §e(Size:§c" + a.getSize() + "§e)§a} "); } return s.toString(); } public int getZoneDepth() { int count = 0; ClaimedResidence res = parent; while(res!=null) { count++; res = res.getParent(); } return count; } public void setTpLoc(Player player) { if(!this.perms.hasResidencePermission(player, false)) { player.sendMessage("§cYou dont have permission to set the teleport location."); return; } if(!this.containsLoc(player.getLocation())) { player.sendMessage("§cYou are not in the residence."); return; } tpLoc = player.getLocation(); player.sendMessage("§aTeleport Location Set..."); } public void tpToResidence(Player reqPlayer, Player targetPlayer) { if (!Residence.getPermissionManager().isResidenceAdmin(reqPlayer)) { PermissionGroup group = Residence.getPermissionManager().getGroup(reqPlayer); if (!group.hasTpAccess()) { reqPlayer.sendMessage("§cYou dont have teleport access."); return; } if (!reqPlayer.equals(targetPlayer)) { reqPlayer.sendMessage("§cOnly admins can teleport other players."); return; } if (!this.perms.playerHas(reqPlayer.getName(), "tp", true)) { reqPlayer.sendMessage("§cThe owner has not allowed you to teleport to this residence."); return; } } if(tpLoc!=null) { targetPlayer.teleport(tpLoc); targetPlayer.sendMessage("§aTeleported!"); } else { CuboidArea area = areas.values().iterator().next(); if(area==null) { reqPlayer.sendMessage("Could not find area to teleport to..."); return; } targetPlayer.teleport(this.getOutsideFreeLoc(area.getHighLoc())); targetPlayer.sendMessage("§eTeleported to near residence."); } } public String getAreaIDbyLoc(Location loc) { for(Entry<String, CuboidArea> area : areas.entrySet()) { if(area.getValue().containsLoc(loc)) return area.getKey(); } return null; } public void removeArea(String id) { areas.remove(id); } public void removeArea(Player player, String id) { if(this.getPermissions().hasResidencePermission(player, true)) { if(!areas.containsKey(id)) { player.sendMessage("§cInvalid Area ID"); return; } if(areas.size()==1 && !Residence.getConfig().allowEmptyResidences()) { player.sendMessage("§cCannot remove the residence's last area, use '/res remove' instead..."); return; } removeArea(id); player.sendMessage("§aArea ID §e" + id + "§a removed..."); } else player.sendMessage("§cYou dont have permission..."); } public Map<String, Object> save() { Map<String, Object> root = new HashMap<String,Object>(); Map<String,Object> areamap = new HashMap<String,Object>(); root.put("EnterMessage", enterMessage); root.put("LeaveMessage", leaveMessage); for(Entry<String, CuboidArea> entry : areas.entrySet()) { areamap.put(entry.getKey(), entry.getValue().save()); } root.put("Areas", areamap); Map<String,Object> subzonemap = new HashMap<String,Object>(); for(Entry<String, ClaimedResidence> sz : subzones.entrySet()) { subzonemap.put(sz.getKey(), sz.getValue().save()); } root.put("Subzones", subzonemap); root.put("Permissions", perms.save()); if(tpLoc!=null) { Map<String,Object> tpmap = new HashMap<String,Object>(); tpmap.put("X", tpLoc.getBlockX()); tpmap.put("Y", tpLoc.getBlockY()); tpmap.put("Z", tpLoc.getBlockZ()); root.put("TPLoc", tpmap); } return root; } public static ClaimedResidence load(Map<String,Object> root, ClaimedResidence parent) throws Exception { ClaimedResidence res = new ClaimedResidence(); if(root == null) throw new Exception("Invalid residence..."); res.enterMessage = (String) root.get("EnterMessage"); res.leaveMessage = (String) root.get("LeaveMessage"); Map<String,Object> areamap = (Map<String, Object>) root.get("Areas"); res.perms = ResidencePermissions.load(res,(Map<String, Object>) root.get("Permissions")); World world = Residence.getServ().getWorld(res.perms.getWorld()); if(world==null) throw new Exception("Can't find world:" + res.perms.getWorld()); for(Entry<String, Object> map : areamap.entrySet()) { res.areas.put(map.getKey(), CuboidArea.load((Map<String, Object>) map.getValue(),world)); } Map<String,Object> subzonemap = (Map<String, Object>) root.get("Subzones"); for(Entry<String, Object> map : subzonemap.entrySet()) { res.subzones.put(map.getKey(), ClaimedResidence.load((Map<String, Object>) map.getValue(), res)); } res.parent = parent; Map<String,Object> tploc = (Map<String, Object>) root.get("TPLoc"); if(tploc != null) { res.tpLoc = new Location(world,(Integer)tploc.get("X"),(Integer)tploc.get("Y"),(Integer)tploc.get("Z")); } return res; } public int getAreaCount() { return areas.size(); } public void renameSubzone(Player player, String oldName, String newName) { newName = newName.replace(".", "_"); newName = newName.replace(":", "_"); ClaimedResidence res = subzones.get(oldName); if(res==null) { player.sendMessage("§cInvalid Subzone..."); return; } if(!res.getPermissions().hasResidencePermission(player, true)) { player.sendMessage("§cYou dont have permission..."); return; } if(subzones.containsKey(newName)) { player.sendMessage("§cNew subzone name already exists..."); return; } subzones.put(newName, res); subzones.remove(oldName); player.sendMessage("§aRenamed " + oldName + " to " + newName + "..."); } public void renameArea(Player player, String oldName, String newName) { newName = newName.replace(".", "_"); newName = newName.replace(":", "_"); if(perms.hasResidencePermission(player, true)) { if(areas.containsKey(newName)) { player.sendMessage("§cArea name already exists..."); return; } CuboidArea area = areas.get(oldName); if(area == null) { player.sendMessage("§cInvalid Area Name..."); return; } areas.put(newName, area); areas.remove(oldName); player.sendMessage("§aRenamed area " + oldName + " to " + newName); } } public CuboidArea getArea(String name) { return areas.get(name); } }
false
true
public void addArea(Player player, CuboidArea area, String name) { name = name.replace(".", "_"); name = name.replace(":", "_"); if(areas.containsKey(name)) { player.sendMessage("§cArea name already exists."); return; } if (!area.getWorld().getName().equalsIgnoreCase(perms.getWorld())) { player.sendMessage("§cArea is in a different world from residence."); return; } if(area.getSize()==0) { player.sendMessage("§cError, 0 sized area."); return; } if(!Residence.getPermissionManager().isResidenceAdmin(player)) { if (!this.perms.hasResidencePermission(player, true)) { player.sendMessage("§cYou dont have permission to do this."); return; } if (parent != null) { if (!parent.containsLoc(area.getHighLoc()) || !parent.containsLoc(area.getLowLoc())) { player.sendMessage("§cArea is not within parent area."); return; } if(!parent.getPermissions().hasResidencePermission(player, true) && !parent.getPermissions().playerHas(player.getName(),"subzone", true)) { player.sendMessage("§cYou dont have permission to make changes to the parent area."); return; } } PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(!group.canCreateResidences() && !Residence.getPermissionManager().hasAuthority(player, "residence.create", false)) { player.sendMessage("You dont have permission to create residences."); return; } if(areas.size()>=group.getMaxPhysicalPerResidence()) { player.sendMessage("§cYou've reached the max physical areas allowed for your residence."); return; } if(!group.inLimits(area)) { player.sendMessage("§cArea size is not within your allowed limits."); return; } if(group.getMinHeight()>area.getLowLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this deep, minimum height:" + group.getMinHeight()); return; } if(group.getMaxHeight()<area.getHighLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this high up, maximum height:" + group.getMaxHeight()); return; } if(parent==null && Residence.getConfig().enableEconomy()) { int chargeamount = (int) Math.ceil((double)area.getSize() * group.getCostPerBlock()); if(!TransactionManager.chargeEconomyMoney(player, chargeamount, "new residence area")) { return; } } } String collideResidence = Residence.getResidenceManger().checkAreaCollision(area, this); if(collideResidence!=null) { player.sendMessage("§cArea collides with residence: §e" + collideResidence); return; } areas.put(name, area); player.sendMessage("§aArea created. ID:§e " + name); }
public void addArea(Player player, CuboidArea area, String name) { name = name.replace(".", "_"); name = name.replace(":", "_"); if(areas.containsKey(name)) { player.sendMessage("§cArea name already exists."); return; } if (!area.getWorld().getName().equalsIgnoreCase(perms.getWorld())) { player.sendMessage("§cArea is in a different world from residence."); return; } if(area.getSize()==0) { player.sendMessage("§cError, 0 sized area."); return; } if(!Residence.getPermissionManager().isResidenceAdmin(player)) { if (!this.perms.hasResidencePermission(player, true)) { player.sendMessage("§cYou dont have permission to do this."); return; } if (parent != null) { if (!parent.containsLoc(area.getHighLoc()) || !parent.containsLoc(area.getLowLoc())) { player.sendMessage("§cArea is not within parent area."); return; } if(!parent.getPermissions().hasResidencePermission(player, true) && !parent.getPermissions().playerHas(player.getName(),"subzone", true)) { player.sendMessage("§cYou dont have permission to make changes to the parent area."); return; } } PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(!group.canCreateResidences() && !Residence.getPermissionManager().hasAuthority(player, "residence.create", false)) { player.sendMessage("You dont have permission to create residences."); return; } if(areas.size()>=group.getMaxPhysicalPerResidence()) { player.sendMessage("§cYou've reached the max physical areas allowed for your residence."); return; } if(!group.inLimits(area)) { player.sendMessage("§cArea size is not within your allowed limits."); return; } if(group.getMinHeight()>area.getLowLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this deep, minimum height:" + group.getMinHeight()); return; } if(group.getMaxHeight()<area.getHighLoc().getBlockY()) { player.sendMessage("You are not allowed to protect this high up, maximum height:" + group.getMaxHeight()); return; } if(parent==null && Residence.getConfig().enableEconomy()) { int chargeamount = (int) Math.ceil((double)area.getSize() * group.getCostPerBlock()); if(!TransactionManager.chargeEconomyMoney(player, chargeamount, "new residence area")) { return; } } } if(parent==null) { String collideResidence = Residence.getResidenceManger().checkAreaCollision(area, this); if(collideResidence!=null) { player.sendMessage("§cArea collides with residence: §e" + collideResidence); return; } } else { String[] subzones = parent.listSubzones(); for(String sz : subzones) { ClaimedResidence res = parent.getSubzone(sz); if(res!=null) { if(res.checkCollision(area)) { player.sendMessage("§cArea collides with subzone: §e" + sz); } } } } areas.put(name, area); player.sendMessage("§aArea created. ID:§e " + name); }
diff --git a/src/com/android/exchange/adapter/ProvisionParser.java b/src/com/android/exchange/adapter/ProvisionParser.java index 057ffaf..5ba43e4 100644 --- a/src/com/android/exchange/adapter/ProvisionParser.java +++ b/src/com/android/exchange/adapter/ProvisionParser.java @@ -1,450 +1,446 @@ /* 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.exchange.adapter; import com.android.email.SecurityPolicy; import com.android.email.SecurityPolicy.PolicySet; import com.android.exchange.EasSyncService; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Parse the result of the Provision command * * Assuming a successful parse, we store the PolicySet and the policy key */ public class ProvisionParser extends Parser { private EasSyncService mService; PolicySet mPolicySet = null; String mPolicyKey = null; boolean mRemoteWipe = false; boolean mIsSupportable = true; public ProvisionParser(InputStream in, EasSyncService service) throws IOException { super(in); mService = service; } public PolicySet getPolicySet() { return mPolicySet; } public String getPolicyKey() { return mPolicyKey; } public boolean getRemoteWipe() { return mRemoteWipe; } public boolean hasSupportablePolicySet() { return (mPolicySet != null) && mIsSupportable; } private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; - // Complex character setting is only used if we're in "strong" (alphanumeric) mode + // Complex characters are supported case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); - if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && - (passwordComplexChars > 0)) { - tagIsSupported = false; - } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); } /** * Return whether or not either of the application list tags specifies any applications * @param endTag the tag whose children we're walking through * @return whether any applications were specified (by name or by hash) * @throws IOException */ private boolean specifiesApplications(int endTag) throws IOException { boolean specifiesApplications = false; while (nextTag(endTag) != END) { switch (tag) { case Tags.PROVISION_APPLICATION_NAME: case Tags.PROVISION_HASH: specifiesApplications = true; break; default: skipTag(); } } return specifiesApplications; } class ShadowPolicySet { int mMinPasswordLength = 0; int mPasswordMode = PolicySet.PASSWORD_MODE_NONE; int mMaxPasswordFails = 0; int mMaxScreenLockTime = 0; int mPasswordExpiration = 0; int mPasswordHistory = 0; int mPasswordComplexChars = 0; } /*package*/ void parseProvisionDocXml(String doc) throws IOException { ShadowPolicySet sps = new ShadowPolicySet(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8"); int type = parser.getEventType(); if (type == XmlPullParser.START_DOCUMENT) { type = parser.next(); if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("wap-provisioningdoc")) { parseWapProvisioningDoc(parser, sps); } } } } catch (XmlPullParserException e) { throw new IOException(); } mPolicySet = new PolicySet(sps.mMinPasswordLength, sps.mPasswordMode, sps.mMaxPasswordFails, sps.mMaxScreenLockTime, true, sps.mPasswordExpiration, sps.mPasswordHistory, sps.mPasswordComplexChars); } /** * Return true if password is required; otherwise false. */ private boolean parseSecurityPolicy(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean passwordRequired = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("parm")) { String name = parser.getAttributeValue(null, "name"); if (name.equals("4131")) { String value = parser.getAttributeValue(null, "value"); if (value.equals("1")) { passwordRequired = false; } } } } } return passwordRequired; } private void parseCharacteristic(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean enforceInactivityTimer = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { if (parser.getName().equals("parm")) { String name = parser.getAttributeValue(null, "name"); String value = parser.getAttributeValue(null, "value"); if (name.equals("AEFrequencyValue")) { if (enforceInactivityTimer) { if (value.equals("0")) { sps.mMaxScreenLockTime = 1; } else { sps.mMaxScreenLockTime = 60*Integer.parseInt(value); } } } else if (name.equals("AEFrequencyType")) { // "0" here means we don't enforce an inactivity timeout if (value.equals("0")) { enforceInactivityTimer = false; } } else if (name.equals("DeviceWipeThreshold")) { sps.mMaxPasswordFails = Integer.parseInt(value); } else if (name.equals("CodewordFrequency")) { // Ignore; has no meaning for us } else if (name.equals("MinimumPasswordLength")) { sps.mMinPasswordLength = Integer.parseInt(value); } else if (name.equals("PasswordComplexity")) { if (value.equals("0")) { sps.mPasswordMode = PolicySet.PASSWORD_MODE_STRONG; } else { sps.mPasswordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } } } } } private void parseRegistry(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { parseCharacteristic(parser, sps); } } } } private void parseWapProvisioningDoc(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { String atype = parser.getAttributeValue(null, "type"); if (atype.equals("SecurityPolicy")) { // If a password isn't required, stop here if (!parseSecurityPolicy(parser, sps)) { return; } } else if (atype.equals("Registry")) { parseRegistry(parser, sps); return; } } } } } private void parseProvisionData() throws IOException { while (nextTag(Tags.PROVISION_DATA) != END) { if (tag == Tags.PROVISION_EAS_PROVISION_DOC) { parseProvisionDocWbxml(); } else { skipTag(); } } } private void parsePolicy() throws IOException { String policyType = null; while (nextTag(Tags.PROVISION_POLICY) != END) { switch (tag) { case Tags.PROVISION_POLICY_TYPE: policyType = getValue(); mService.userLog("Policy type: ", policyType); break; case Tags.PROVISION_POLICY_KEY: mPolicyKey = getValue(); break; case Tags.PROVISION_STATUS: mService.userLog("Policy status: ", getValue()); break; case Tags.PROVISION_DATA: if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) { // Parse the old style XML document parseProvisionDocXml(getValue()); } else { // Parse the newer WBXML data parseProvisionData(); } break; default: skipTag(); } } } private void parsePolicies() throws IOException { while (nextTag(Tags.PROVISION_POLICIES) != END) { if (tag == Tags.PROVISION_POLICY) { parsePolicy(); } else { skipTag(); } } } @Override public boolean parse() throws IOException { boolean res = false; if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) { throw new IOException(); } while (nextTag(START_DOCUMENT) != END_DOCUMENT) { switch (tag) { case Tags.PROVISION_STATUS: int status = getValueInt(); mService.userLog("Provision status: ", status); res = (status == 1); break; case Tags.PROVISION_POLICIES: parsePolicies(); break; case Tags.PROVISION_REMOTE_WIPE: // Indicate remote wipe command received mRemoteWipe = true; break; default: skipTag(); } } return res; } }
false
true
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; // Complex character setting is only used if we're in "strong" (alphanumeric) mode case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && (passwordComplexChars > 0)) { tagIsSupported = false; } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; // Complex characters are supported case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
diff --git a/gwt-client/src/main/java/org/mule/galaxy/web/client/ui/ExternalHyperlink.java b/gwt-client/src/main/java/org/mule/galaxy/web/client/ui/ExternalHyperlink.java index c5486e68..593b4b3c 100644 --- a/gwt-client/src/main/java/org/mule/galaxy/web/client/ui/ExternalHyperlink.java +++ b/gwt-client/src/main/java/org/mule/galaxy/web/client/ui/ExternalHyperlink.java @@ -1,82 +1,82 @@ /* * $Id$ * -------------------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.mule.galaxy.web.client.ui; import com.extjs.gxt.ui.client.widget.Component; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; /** * This is an adapted version of GWanTed's ExternalHyperlink (original class under * LGPL). */ public class ExternalHyperlink extends Component { private final Element anchorElem; public ExternalHyperlink(final String text, final String link) { this.anchorElem = getAnchorElement(text, link, null); } public ExternalHyperlink(final String text, final String link, final String target) { this.anchorElem = getAnchorElement(text, link, target); } private Element getAnchorElement(final String text, final String link, final String target) { setElement(DOM.createDiv()); - final Element anchorElem = DOM.createAnchor(); - DOM.appendChild(getElement(), this.anchorElem); + final Element anchorElement = DOM.createAnchor(); + DOM.appendChild(getElement(), anchorElement); setLink(link); setText(text); if (target != null) { setTarget(target); } - return anchorElem; + return anchorElement; } public final void setId(String id) { anchorElem.setId(id); } public final void setText(final String text) { DOM.setInnerHTML(this.anchorElem, text); } public final void setLink(final String link) { DOM.setAttribute(this.anchorElem, "href", link); } public final String getText() { return DOM.getInnerHTML(this.anchorElem); } public final String getLink() { return DOM.getAttribute(this.anchorElem, "href"); } public final String getTarget() { return DOM.getAttribute(this.anchorElem, "target"); } public final void setTarget(final String target) { DOM.setAttribute(this.anchorElem, "target", target); } }
false
true
private Element getAnchorElement(final String text, final String link, final String target) { setElement(DOM.createDiv()); final Element anchorElem = DOM.createAnchor(); DOM.appendChild(getElement(), this.anchorElem); setLink(link); setText(text); if (target != null) { setTarget(target); } return anchorElem; }
private Element getAnchorElement(final String text, final String link, final String target) { setElement(DOM.createDiv()); final Element anchorElement = DOM.createAnchor(); DOM.appendChild(getElement(), anchorElement); setLink(link); setText(text); if (target != null) { setTarget(target); } return anchorElement; }
diff --git a/src/main/java/com/github/ucchyocean/ct/command/CTeamingCommand.java b/src/main/java/com/github/ucchyocean/ct/command/CTeamingCommand.java index ff463d3..ee897df 100644 --- a/src/main/java/com/github/ucchyocean/ct/command/CTeamingCommand.java +++ b/src/main/java/com/github/ucchyocean/ct/command/CTeamingCommand.java @@ -1,432 +1,429 @@ /* * Copyright ucchy 2013 */ package com.github.ucchyocean.ct.command; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.github.ucchyocean.ct.ColorTeaming; import com.github.ucchyocean.ct.ColorTeamingAPI; import com.github.ucchyocean.ct.ColorTeamingConfig; import com.github.ucchyocean.ct.Utility; import com.github.ucchyocean.ct.event.ColorTeamingPlayerLeaveEvent.Reason; import com.github.ucchyocean.ct.scoreboard.CustomScoreInterface; import com.github.ucchyocean.ct.scoreboard.PlayerCriteria; import com.github.ucchyocean.ct.scoreboard.SidebarCriteria; /** * colorteaming(ct)コマンドの実行クラス * @author ucchy */ public class CTeamingCommand implements CommandExecutor { private static final String PREERR = ChatColor.RED.toString(); private static final String PREINFO = ChatColor.GRAY.toString(); private ColorTeaming plugin; public CTeamingCommand(ColorTeaming plugin) { this.plugin = plugin; } /** * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length < 1 ) { return false; } if ( args[0].equalsIgnoreCase("reload") ) { plugin.reloadCTConfig(); sender.sendMessage("config.ymlの再読み込みを行いました。"); return true; } else if ( args[0].equalsIgnoreCase("removeall") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); for ( String group : members.keySet() ) { for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); } api.removeTeam(group); } // サイドバー削除、タブキーリスト更新 api.removeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "全てのグループが解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("remove") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); String group = args[1]; if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は存在しません。"); return true; } for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); p.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); } api.removeTeam(group); // サイドバー再作成、タブキーリスト更新 api.makeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("trophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct trophy コマンドには、マイナス値を指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数達成時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数達成時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("reachTrophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct reachTrophy コマンドには、マイナス値を指定できません。"); return true; } else if ( plugin.getCTConfig().getKillTrophy() < amount ) { sender.sendMessage(PREERR + "killTrophyの設定値より大きな値は指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillReachTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinAny") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinRandom") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 3 && args[0].equalsIgnoreCase("add") ) { String group = args[1]; if ( !Utility.isValidColor(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は設定できないグループ名です。"); return true; } Player player = Bukkit.getPlayerExact(args[2]); if ( player == null ) { sender.sendMessage(PREERR + "プレイヤー " + args[2] + " は存在しません。"); return true; } ColorTeamingAPI api = plugin.getAPI(); boolean isNewGroup = !api.getAllTeamMembers().containsKey(group); api.addPlayerTeam(player, group); // メンバー情報をlastdataに保存する api.getCTSaveDataHandler().save("lastdata"); // サイドバーの更新 グループが増える場合は、再生成する if ( isNewGroup ) { api.makeSidebarScore(); } api.refreshSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "プレイヤー " + player.getName() + " をグループ " + group + " に追加しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("side") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getSideCriteria() == SidebarCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { - config.setSideCriteria(SidebarCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } - config.setListCriteria(PlayerCriteria.CUSTOM); - config.setListCustomSlot(slot); + config.setSideCriteria(SidebarCriteria.CUSTOM); + config.setSideCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } if ( args[1].equalsIgnoreCase("kill") ) { config.setSideCriteria(SidebarCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setSideCriteria(SidebarCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setSideCriteria(SidebarCriteria.POINT); } else if ( args[1].equalsIgnoreCase("rest") ) { config.setSideCriteria(SidebarCriteria.REST_PLAYER); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setSideCriteria(SidebarCriteria.NONE); } else { return false; } config.saveConfig(); // サイドバーの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeSidebarScore(); String criteria = config.getSideCriteria().toString(); sender.sendMessage(PREINFO + "サイドバーの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("list") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getListCriteria() == PlayerCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { - config.setListCriteria(PlayerCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setListCriteria(PlayerCriteria.CUSTOM); config.setListCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setListCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setListCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setListCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setListCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setListCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); String criteria = config.getListCriteria().toString(); sender.sendMessage(PREINFO + "リストの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("below") ) { ColorTeamingConfig config = plugin.getCTConfig(); // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { - config.setListCriteria(PlayerCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setBelowCriteria(PlayerCriteria.CUSTOM); config.setBelowCustomSlot(slot); config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setBelowCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setBelowCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setBelowCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setBelowCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setBelowCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); // 設定の保存 String criteria = config.getBelowCriteria().toString(); sender.sendMessage(PREINFO + "名前欄のスコア表示を" + criteria + "にしました。"); return true; } return false; } }
false
true
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length < 1 ) { return false; } if ( args[0].equalsIgnoreCase("reload") ) { plugin.reloadCTConfig(); sender.sendMessage("config.ymlの再読み込みを行いました。"); return true; } else if ( args[0].equalsIgnoreCase("removeall") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); for ( String group : members.keySet() ) { for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); } api.removeTeam(group); } // サイドバー削除、タブキーリスト更新 api.removeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "全てのグループが解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("remove") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); String group = args[1]; if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は存在しません。"); return true; } for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); p.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); } api.removeTeam(group); // サイドバー再作成、タブキーリスト更新 api.makeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("trophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct trophy コマンドには、マイナス値を指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数達成時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数達成時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("reachTrophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct reachTrophy コマンドには、マイナス値を指定できません。"); return true; } else if ( plugin.getCTConfig().getKillTrophy() < amount ) { sender.sendMessage(PREERR + "killTrophyの設定値より大きな値は指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillReachTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinAny") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinRandom") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 3 && args[0].equalsIgnoreCase("add") ) { String group = args[1]; if ( !Utility.isValidColor(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は設定できないグループ名です。"); return true; } Player player = Bukkit.getPlayerExact(args[2]); if ( player == null ) { sender.sendMessage(PREERR + "プレイヤー " + args[2] + " は存在しません。"); return true; } ColorTeamingAPI api = plugin.getAPI(); boolean isNewGroup = !api.getAllTeamMembers().containsKey(group); api.addPlayerTeam(player, group); // メンバー情報をlastdataに保存する api.getCTSaveDataHandler().save("lastdata"); // サイドバーの更新 グループが増える場合は、再生成する if ( isNewGroup ) { api.makeSidebarScore(); } api.refreshSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "プレイヤー " + player.getName() + " をグループ " + group + " に追加しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("side") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getSideCriteria() == SidebarCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { config.setSideCriteria(SidebarCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setListCriteria(PlayerCriteria.CUSTOM); config.setListCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } if ( args[1].equalsIgnoreCase("kill") ) { config.setSideCriteria(SidebarCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setSideCriteria(SidebarCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setSideCriteria(SidebarCriteria.POINT); } else if ( args[1].equalsIgnoreCase("rest") ) { config.setSideCriteria(SidebarCriteria.REST_PLAYER); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setSideCriteria(SidebarCriteria.NONE); } else { return false; } config.saveConfig(); // サイドバーの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeSidebarScore(); String criteria = config.getSideCriteria().toString(); sender.sendMessage(PREINFO + "サイドバーの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("list") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getListCriteria() == PlayerCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { config.setListCriteria(PlayerCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setListCriteria(PlayerCriteria.CUSTOM); config.setListCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setListCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setListCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setListCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setListCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setListCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); String criteria = config.getListCriteria().toString(); sender.sendMessage(PREINFO + "リストの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("below") ) { ColorTeamingConfig config = plugin.getCTConfig(); // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { config.setListCriteria(PlayerCriteria.CUSTOM); int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setBelowCriteria(PlayerCriteria.CUSTOM); config.setBelowCustomSlot(slot); config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setBelowCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setBelowCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setBelowCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setBelowCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setBelowCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); // 設定の保存 String criteria = config.getBelowCriteria().toString(); sender.sendMessage(PREINFO + "名前欄のスコア表示を" + criteria + "にしました。"); return true; } return false; }
public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if ( args.length < 1 ) { return false; } if ( args[0].equalsIgnoreCase("reload") ) { plugin.reloadCTConfig(); sender.sendMessage("config.ymlの再読み込みを行いました。"); return true; } else if ( args[0].equalsIgnoreCase("removeall") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); for ( String group : members.keySet() ) { for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); } api.removeTeam(group); } // サイドバー削除、タブキーリスト更新 api.removeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "全てのグループが解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("remove") ) { ColorTeamingAPI api = plugin.getAPI(); HashMap<String, ArrayList<Player>> members = api.getAllTeamMembers(); String group = args[1]; if ( !members.containsKey(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は存在しません。"); return true; } for ( Player p : members.get(group) ) { api.leavePlayerTeam(p, Reason.TEAM_REMOVED); p.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); } api.removeTeam(group); // サイドバー再作成、タブキーリスト更新 api.makeSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "グループ " + group + " が解散しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("trophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct trophy コマンドには、マイナス値を指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数達成時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数達成時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("reachTrophy") ) { if ( !Utility.tryIntParse(args[1]) && !args[1].equalsIgnoreCase("off") ) { sender.sendMessage(PREERR + "キル数 " + args[1] + " は、数値として解釈できません。"); return true; } int amount; if ( args[1].equalsIgnoreCase("off") ) { amount = 0; } else { amount = Integer.parseInt(args[1]); } if ( amount < 0 ) { sender.sendMessage(PREERR + "ct reachTrophy コマンドには、マイナス値を指定できません。"); return true; } else if ( plugin.getCTConfig().getKillTrophy() < amount ) { sender.sendMessage(PREERR + "killTrophyの設定値より大きな値は指定できません。"); return true; } ColorTeamingConfig config = plugin.getCTConfig(); config.setKillReachTrophy(amount); config.saveConfig(); if ( amount == 0 ) { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能をオフにしました。"); } else { sender.sendMessage(PREINFO + "キル数リーチ時の通知機能を、" + amount + "キル数に設定します。"); } return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinAny") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinAny(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin (group) の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("allowJoinRandom") ) { if ( args[1].equalsIgnoreCase("on") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(true); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が可能になりました。"); return true; } else if ( args[1].equalsIgnoreCase("off") ) { ColorTeamingConfig config = plugin.getCTConfig(); config.setAllowPlayerJoinRandom(false); config.saveConfig(); sender.sendMessage(ChatColor.GRAY + "一般プレイヤーの /cjoin の使用が不可になりました。"); return true; } return false; } else if ( args.length >= 3 && args[0].equalsIgnoreCase("add") ) { String group = args[1]; if ( !Utility.isValidColor(group) ) { sender.sendMessage(PREERR + "グループ " + group + " は設定できないグループ名です。"); return true; } Player player = Bukkit.getPlayerExact(args[2]); if ( player == null ) { sender.sendMessage(PREERR + "プレイヤー " + args[2] + " は存在しません。"); return true; } ColorTeamingAPI api = plugin.getAPI(); boolean isNewGroup = !api.getAllTeamMembers().containsKey(group); api.addPlayerTeam(player, group); // メンバー情報をlastdataに保存する api.getCTSaveDataHandler().save("lastdata"); // サイドバーの更新 グループが増える場合は、再生成する if ( isNewGroup ) { api.makeSidebarScore(); } api.refreshSidebarScore(); api.refreshTabkeyListScore(); api.refreshBelowNameScore(); sender.sendMessage(PREINFO + "プレイヤー " + player.getName() + " をグループ " + group + " に追加しました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("side") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getSideCriteria() == SidebarCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setSideCriteria(SidebarCriteria.CUSTOM); config.setSideCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } if ( args[1].equalsIgnoreCase("kill") ) { config.setSideCriteria(SidebarCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setSideCriteria(SidebarCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setSideCriteria(SidebarCriteria.POINT); } else if ( args[1].equalsIgnoreCase("rest") ) { config.setSideCriteria(SidebarCriteria.REST_PLAYER); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setSideCriteria(SidebarCriteria.NONE); } else { return false; } config.saveConfig(); // サイドバーの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeSidebarScore(); String criteria = config.getSideCriteria().toString(); sender.sendMessage(PREINFO + "サイドバーの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("list") ) { ColorTeamingConfig config = plugin.getCTConfig(); // 前回がカスタムだった場合、表示を終了する必要があるので、 // あらかじめカスタムを取得しておく CustomScoreInterface oldCustom = null; if ( config.getListCriteria() == PlayerCriteria.CUSTOM ) { String slot = config.getSideCustomSlot(); oldCustom = plugin.getAPI().getCustomScoreCriteria(slot); } // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setListCriteria(PlayerCriteria.CUSTOM); config.setListCustomSlot(slot); config.saveConfig(); // 開始処理と終了処理、スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setListCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setListCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setListCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setListCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setListCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 if ( oldCustom != null ) { oldCustom.displayEnd(); } plugin.getAPI().makeTabkeyListScore(); String criteria = config.getListCriteria().toString(); sender.sendMessage(PREINFO + "リストの表示を" + criteria + "にしました。"); return true; } else if ( args.length >= 2 && args[0].equalsIgnoreCase("below") ) { ColorTeamingConfig config = plugin.getCTConfig(); // カスタム指定の場合 if ( args[1].toLowerCase().startsWith("custom-") ) { int index = 7; // args[1].indexOf("-") + 1; String slot = args[1].toLowerCase().substring(index); CustomScoreInterface custom = plugin.getAPI().getCustomScoreCriteria(slot); if ( custom == null ) { sender.sendMessage(PREERR + "カスタムスコア" + slot + "が存在しません。"); return true; } config.setBelowCriteria(PlayerCriteria.CUSTOM); config.setBelowCustomSlot(slot); config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); sender.sendMessage(PREINFO + "リストの表示をカスタムスコア" + slot + "にしました。"); return true; } // その他の指定の場合 if ( args[1].equalsIgnoreCase("kill") ) { config.setBelowCriteria(PlayerCriteria.KILL_COUNT); } else if ( args[1].equalsIgnoreCase("death") ) { config.setBelowCriteria(PlayerCriteria.DEATH_COUNT); } else if ( args[1].equalsIgnoreCase("point") ) { config.setBelowCriteria(PlayerCriteria.POINT); } else if ( args[1].equalsIgnoreCase("health") ) { config.setBelowCriteria(PlayerCriteria.HEALTH); } else if ( args[1].equalsIgnoreCase("clear") || args[1].equalsIgnoreCase("none") ) { config.setBelowCriteria(PlayerCriteria.NONE); } else { return false; } config.saveConfig(); // スコアボードの更新 plugin.getAPI().makeBelowNameScore(); // 設定の保存 String criteria = config.getBelowCriteria().toString(); sender.sendMessage(PREINFO + "名前欄のスコア表示を" + criteria + "にしました。"); return true; } return false; }
diff --git a/src/java/davmail/caldav/CaldavConnection.java b/src/java/davmail/caldav/CaldavConnection.java index 8708266..e2fa6f2 100644 --- a/src/java/davmail/caldav/CaldavConnection.java +++ b/src/java/davmail/caldav/CaldavConnection.java @@ -1,766 +1,766 @@ package davmail.caldav; import davmail.AbstractConnection; import davmail.Settings; import davmail.exchange.ExchangeSession; import davmail.exchange.ExchangeSessionFactory; import davmail.tray.DavGatewayTray; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.auth.AuthenticationException; import org.apache.log4j.Logger; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.text.SimpleDateFormat; import java.util.*; /** * Handle a caldav connection. */ public class CaldavConnection extends AbstractConnection { protected Logger wireLogger = Logger.getLogger(this.getClass()); protected boolean closed = false; // Initialize the streams and start the thread public CaldavConnection(Socket clientSocket) { super("CaldavConnection", clientSocket, "UTF-8"); wireLogger.setLevel(Settings.getLoggingLevel("httpclient.wire")); } protected Map<String, String> parseHeaders() throws IOException { HashMap<String, String> headers = new HashMap<String, String>(); String line; while ((line = readClient()) != null && line.length() > 0) { int index = line.indexOf(':'); if (index <= 0) { throw new IOException("Invalid header: " + line); } headers.put(line.substring(0, index).toLowerCase(), line.substring(index + 1).trim()); } return headers; } protected String getContent(String contentLength) throws IOException { if (contentLength == null || contentLength.length() == 0) { return null; } else { int size; try { size = Integer.parseInt(contentLength); } catch (NumberFormatException e) { throw new IOException("Invalid content length: " + contentLength); } char[] buffer = new char[size]; int actualSize = in.read(buffer); if (actualSize < 0) { throw new IOException("End of stream reached reading content"); } return new String(buffer, 0, actualSize); } } protected void setSocketTimeout(String keepAliveValue) throws IOException { if (keepAliveValue != null && keepAliveValue.length() > 0) { int keepAlive; try { keepAlive = Integer.parseInt(keepAliveValue); } catch (NumberFormatException e) { throw new IOException("Invalid Keep-Alive: " + keepAliveValue); } if (keepAlive > 300) { keepAlive = 300; } client.setSoTimeout(keepAlive * 1000); DavGatewayTray.debug("Set socket timeout to " + keepAlive + " seconds"); } } public void run() { String line; StringTokenizer tokens; try { while (!closed) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new StringTokenizer(line); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); Map<String, String> headers = parseHeaders(); if (tokens.hasMoreTokens()) { String path = tokens.nextToken(); String content = getContent(headers.get("content-length")); setSocketTimeout(headers.get("keep-alive")); if ("OPTIONS".equals(command)) { sendOptions(); } else if (!headers.containsKey("authorization")) { sendUnauthorized(); } else { decodeCredentials(headers.get("authorization")); // authenticate only once if (session == null) { // first check network connectivity ExchangeSessionFactory.checkConfig(); try { session = ExchangeSessionFactory.getInstance(userName, password); } catch (AuthenticationException e) { sendErr(HttpStatus.SC_UNAUTHORIZED, e.getMessage()); } } if (session != null) { handleRequest(command, path, headers, content); } } } else { sendErr(HttpStatus.SC_NOT_IMPLEMENTED, "Invalid URI"); } } os.flush(); } } catch (SocketTimeoutException e) { DavGatewayTray.debug("Closing connection on timeout"); } catch (SocketException e) { DavGatewayTray.debug("Connection closed"); } catch (IOException e) { DavGatewayTray.error(e); try { sendErr(HttpStatus.SC_INTERNAL_SERVER_ERROR, e); } catch (IOException e2) { DavGatewayTray.debug("Exception sending error to client", e2); } } finally { close(); } DavGatewayTray.resetIcon(); } protected int getDepth(Map<String, String> headers) { int result = 0; String depthValue = headers.get("depth"); if (depthValue != null) { try { result = Integer.valueOf(depthValue); } catch (NumberFormatException e) { DavGatewayTray.warn("Invalid depth value: " + depthValue); } } return result; } public void handleRequest(String command, String path, Map<String, String> headers, String body) throws IOException { int depth = getDepth(headers); String[] paths = path.split("/"); // full debug trace if (wireLogger.isDebugEnabled()) { wireLogger.debug("Caldav command: " + command + " " + path + " depth: " + depth + "\n" + body); } CaldavRequest request = null; if ("PROPFIND".equals(command) || "REPORT".equals(command)) { request = new CaldavRequest(body); } if ("OPTIONS".equals(command)) { sendOptions(); // redirect PROPFIND on / to current user principal } else if ("PROPFIND".equals(command) && (paths.length == 0 || paths.length == 1)) { sendRoot(request); } else if ("GET".equals(command) && (paths.length == 0 || paths.length == 1)) { sendGetRoot(); // return current user calendar } else if ("calendar".equals(paths[1])) { StringBuilder message = new StringBuilder(); message.append("/calendar no longer supported, recreate calendar with /users/") .append(session.getEmail()).append("/calendar"); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } else if ("user".equals(paths[1])) { sendRedirect(headers, "/principals/users/" + session.getEmail() + "/"); // principal namespace } else if ("PROPFIND".equals(command) && "principals".equals(paths[1]) && paths.length == 4 && "users".equals(paths[2])) { sendPrincipal(request, paths[3]); // send back principal on search } else if ("REPORT".equals(command) && "principals".equals(paths[1]) && paths.length == 3 && "users".equals(paths[2])) { sendPrincipal(request, session.getEmail()); // user root } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 3) { sendUserRoot(request, depth, paths[2]); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { sendInbox(request, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { reportInbox(); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { sendOutbox(request, paths[2]); } else if ("POST".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { - sendFreeBusy(paths[2]); + sendFreeBusy(body); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3])) { sendCalendar(request, depth, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { reportCalendar(request); } else if ("PUT".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { String etag = headers.get("if-match"); int status = session.createOrUpdateEvent(paths[4], body, etag); sendHttpResponse(status, true); } else if ("DELETE".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { int status = session.deleteEvent(paths[4]); sendHttpResponse(status, true); } else if ("GET".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { ExchangeSession.Event event = session.getEvent(paths[4]); sendHttpResponse(HttpStatus.SC_OK, null, "text/calendar;charset=UTF-8", event.getICS(), true); } else { StringBuilder message = new StringBuilder(); message.append("Unsupported request: ").append(command).append(" ").append(path); message.append(" Depth: ").append(depth).append("\n").append(body); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } } protected void appendEventsResponses(StringBuilder buffer, CaldavRequest request, List<ExchangeSession.Event> events) throws IOException { int size = events.size(); int count = 0; for (ExchangeSession.Event event : events) { DavGatewayTray.debug("Retrieving event " + (++count) + "/" + size); appendEventResponse(buffer, request, event); } } protected void appendEventResponse(StringBuilder buffer, CaldavRequest request, ExchangeSession.Event event) throws IOException { String eventPath = event.getPath().replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); buffer.append("<D:response>\n"); buffer.append(" <D:href>/users/").append(session.getEmail()).append("/calendar").append(eventPath).append("</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("calendar-data")) { String ics = event.getICS(); if (ics != null && ics.length() > 0) { ics = ics.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); buffer.append(" <C:calendar-data xmlns:C=\"urn:ietf:params:xml:ns:caldav\"\n"); buffer.append(" C:content-type=\"text/calendar\" C:version=\"2.0\">"); buffer.append(ics); buffer.append("</C:calendar-data>\n"); } } if (request.hasProperty("getetag")) { buffer.append(" <D:getetag>").append(event.getEtag()).append("</D:getetag>\n"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); } public void appendCalendar(StringBuilder buffer, String principal, CaldavRequest request) throws IOException { buffer.append(" <D:response>\n"); buffer.append(" <D:href>/users/").append(principal).append("/calendar</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("resourcetype")) { buffer.append(" <D:resourcetype>\n"); buffer.append(" <D:collection/>\n"); buffer.append(" <C:calendar xmlns:C=\"urn:ietf:params:xml:ns:caldav\"/>\n"); buffer.append(" </D:resourcetype>\n"); } if (request.hasProperty("owner")) { buffer.append(" <D:owner>\n"); buffer.append(" <D:href>/principals/users/").append(principal).append("</D:href>\n"); buffer.append(" </D:owner>\n"); } if (request.hasProperty("getctag")) { buffer.append(" <CS:getctag xmlns:CS=\"http://calendarserver.org/ns/\">") .append(base64Encode(session.getCalendarEtag())) .append("</CS:getctag>\n"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); } public void appendInbox(StringBuilder buffer, String principal, CaldavRequest request) throws IOException { buffer.append(" <D:response>\n"); buffer.append(" <D:href>/users/").append(principal).append("/inbox</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("resourcetype")) { buffer.append(" <D:resourcetype>\n"); buffer.append(" <D:collection/>\n"); buffer.append(" <C:schedule-inbox xmlns:C=\"urn:ietf:params:xml:ns:caldav\"/>\n"); buffer.append(" </D:resourcetype>\n"); } if (request.hasProperty("getctag")) { buffer.append(" <CS:getctag xmlns:CS=\"http://calendarserver.org/ns/\">0</CS:getctag>\n"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); } public void appendOutbox(StringBuilder buffer, String principal, CaldavRequest request) throws IOException { buffer.append(" <D:response>\n"); buffer.append(" <D:href>/users/").append(principal).append("/outbox</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("resourcetype")) { buffer.append(" <D:resourcetype>\n"); buffer.append(" <D:collection/>\n"); buffer.append(" <C:schedule-outbox xmlns:C=\"urn:ietf:params:xml:ns:caldav\"/>\n"); buffer.append(" </D:resourcetype>\n"); } if (request.hasProperty("getctag")) { buffer.append(" <CS:getctag xmlns:CS=\"http://calendarserver.org/ns/\">0</CS:getctag>\n"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); } public void sendErr(int status, Exception e) throws IOException { String message = e.getMessage(); if (message == null) { message = e.toString(); } sendErr(status, message); } public void sendGetRoot() throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("Connected to DavMail<br/>"); buffer.append("UserName :").append(userName).append("<br/>"); buffer.append("Email :").append(session.getEmail()).append("<br/>"); sendHttpResponse(HttpStatus.SC_OK, null, "text/html;charset=UTF-8", buffer.toString(), true); } public void sendInbox(CaldavRequest request, String principal) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); appendInbox(buffer, principal, request); buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void reportInbox() throws IOException { // inbox is always empty StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<D:multistatus xmlns:D=\"DAV:\">\n"); buffer.append("</D:multistatus>"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendOutbox(CaldavRequest request, String principal) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); appendOutbox(buffer, principal, request); buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendCalendar(CaldavRequest request, int depth, String principal) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); appendCalendar(buffer, principal, request); if (depth == 1) { appendEventsResponses(buffer, request, session.getAllEvents()); } buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } protected String getEventFileNameFromPath(String path) { int index = path.indexOf("/calendar/"); if (index < 0) { return null; } else { return path.substring(index + "/calendar/".length()); } } public void reportCalendar(CaldavRequest request) throws IOException { List<ExchangeSession.Event> events; List<String> notFound = new ArrayList<String>(); if (request.isMultiGet()) { events = new ArrayList<ExchangeSession.Event>(); for (String href : request.getHrefs()) { try { String eventName = getEventFileNameFromPath(href); if (eventName == null) { notFound.add(href); } else { events.add(session.getEvent(eventName)); } } catch (HttpException e) { notFound.add(href); } } } else { events = session.getAllEvents(); } StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<D:multistatus xmlns:D=\"DAV:\">\n"); appendEventsResponses(buffer, request, events); // send not found events errors for (String href : notFound) { buffer.append(" <D:response>\n"); buffer.append(" <D:href>").append(href).append("</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:status>HTTP/1.1 404 Not Found</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); } buffer.append("</D:multistatus>"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendUserRoot(CaldavRequest request, int depth, String principal) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); buffer.append(" <D:response>\n"); buffer.append(" <D:href>/users/").append(principal).append("</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("resourcetype")) { buffer.append(" <D:resourcetype>\n"); buffer.append(" <D:collection/>\n"); buffer.append(" </D:resourcetype>\n"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); if (depth == 1) { appendInbox(buffer, principal, request); appendOutbox(buffer, principal, request); appendCalendar(buffer, principal, request); } buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendRoot(CaldavRequest request) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); buffer.append(" <D:response>\n"); buffer.append(" <D:href>/</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("principal-collection-set")) { buffer.append(" <D:principal-collection-set>\n"); buffer.append(" <D:href>/principals/users/</D:href>\n"); buffer.append(" </D:principal-collection-set>"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendPrincipal(CaldavRequest request, String principal) throws IOException { StringBuilder buffer = new StringBuilder(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); buffer.append("<D:multistatus xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n"); buffer.append(" <D:response>\n"); buffer.append(" <D:href>/principals/users/").append(principal).append("</D:href>\n"); buffer.append(" <D:propstat>\n"); buffer.append(" <D:prop>\n"); if (request.hasProperty("calendar-home-set")) { buffer.append(" <C:calendar-home-set>\n"); buffer.append(" <D:href>/users/").append(principal).append("</D:href>\n"); buffer.append(" </C:calendar-home-set>"); } if (request.hasProperty("calendar-user-address-set")) { buffer.append(" <C:calendar-user-address-set>\n"); buffer.append(" <D:href>mailto:").append(principal).append("</D:href>\n"); buffer.append(" </C:calendar-user-address-set>"); } if (request.hasProperty("schedule-inbox-URL")) { buffer.append(" <C:schedule-inbox-URL>\n"); buffer.append(" <D:href>/users/").append(principal).append("/inbox</D:href>\n"); buffer.append(" </C:schedule-inbox-URL>"); } if (request.hasProperty("schedule-outbox-URL")) { buffer.append(" <C:schedule-outbox-URL>\n"); buffer.append(" <D:href>/users/").append(principal).append("/outbox</D:href>\n"); buffer.append(" </C:schedule-outbox-URL>"); } buffer.append(" </D:prop>\n"); buffer.append(" <D:status>HTTP/1.1 200 OK</D:status>\n"); buffer.append(" </D:propstat>\n"); buffer.append(" </D:response>\n"); buffer.append("</D:multistatus>\n"); sendHttpResponse(HttpStatus.SC_MULTI_STATUS, null, "text/xml;charset=UTF-8", buffer.toString(), true); } public void sendFreeBusy(String body) throws IOException { Map<String, String> valueMap = new HashMap<String, String>(); Map<String, String> keyMap = new HashMap<String, String>(); BufferedReader reader = new BufferedReader(new StringReader(body)); String line; String key = null; while ((line = reader.readLine()) != null) { if (line.startsWith(" ") && "ATTENDEE".equals(key)) { valueMap.put(key, valueMap.get(key) + line.substring(1)); } else { int index = line.indexOf(':'); if (index <= 0) { throw new IOException("Invalid request: " + body); } String fullkey = line.substring(0, index); String value = line.substring(index + 1); int semicolonIndex = fullkey.indexOf(";"); if (semicolonIndex > 0) { key = fullkey.substring(0, semicolonIndex); } else { key = fullkey; } valueMap.put(key, value); keyMap.put(key, fullkey); } } String freeBusy = session.getFreebusy(valueMap); if (freeBusy != null) { String response = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + " <C:schedule-response xmlns:D=\"DAV:\"\n" + " xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n" + " <C:response>\n" + " <C:recipient>\n" + " <D:href>" + valueMap.get("ATTENDEE") + "</D:href>\n" + " </C:recipient>\n" + " <C:request-status>2.0;Success</C:request-status>\n" + " <C:calendar-data>BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN\n" + "METHOD:REPLY\n" + "BEGIN:VFREEBUSY\n" + "DTSTAMP:" + valueMap.get("DTSTAMP") + "\n" + "ORGANIZER:" + valueMap.get("ORGANIZER") + "\n" + "DTSTART:" + valueMap.get("DTSTART") + "\n" + "DTEND:" + valueMap.get("DTEND") + "\n" + "UID:" + valueMap.get("UID") + "\n" + keyMap.get("ATTENDEE") + ";" + valueMap.get("ATTENDEE") + "\n" + "FREEBUSY;FBTYPE=BUSY-UNAVAILABLE:" + freeBusy + "\n" + "END:VFREEBUSY\n" + "END:VCALENDAR" + "</C:calendar-data>\n" + " </C:response>\n" + " </C:schedule-response>"; sendHttpResponse(HttpStatus.SC_OK, null, "text/xml;charset=UTF-8", response, true); } else { sendHttpResponse(HttpStatus.SC_NOT_FOUND, null, "text/plain", "Unknown recipient: " + valueMap.get("ATTENDEE"), true); } } public void sendRedirect(Map<String, String> headers, String path) throws IOException { StringBuilder buffer = new StringBuilder(); if (headers.get("host") != null) { buffer.append("http://").append(headers.get("host")); } buffer.append(path); Map<String, String> responseHeaders = new HashMap<String, String>(); responseHeaders.put("Location", buffer.toString()); sendHttpResponse(HttpStatus.SC_MOVED_PERMANENTLY, responseHeaders, null, null, true); } public void sendErr(int status, String message) throws IOException { sendHttpResponse(status, null, "text/plain;charset=UTF-8", message, false); } public void sendOptions() throws IOException { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Allow", "OPTIONS, GET, PROPFIND, PUT, POST"); headers.put("DAV", "1, 2, 3, access-control, calendar-access, ticket, calendar-schedule"); sendHttpResponse(HttpStatus.SC_OK, headers, null, null, true); } public void sendUnauthorized() throws IOException { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("WWW-Authenticate", "Basic realm=\"" + Settings.getProperty("davmail.url") + "\""); sendHttpResponse(HttpStatus.SC_UNAUTHORIZED, headers, null, null, true); } public void sendHttpResponse(int status, boolean keepAlive) throws IOException { sendHttpResponse(status, null, null, null, keepAlive); } public void sendHttpResponse(int status, Map<String, String> headers, String contentType, String content, boolean keepAlive) throws IOException { sendClient("HTTP/1.1 " + status + " " + HttpStatus.getStatusText(status)); sendClient("Server: DavMail Gateway"); SimpleDateFormat formatter = new java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH); sendClient("Date: " + formatter.format(new java.util.Date())); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { sendClient(header.getKey() + ": " + header.getValue()); } } if (contentType != null) { sendClient("Content-Type: " + contentType); } sendClient("Connection: " + (keepAlive ? "keep-alive" : "close")); closed = !keepAlive; if (content != null && content.length() > 0) { sendClient("Content-Length: " + content.getBytes("UTF-8").length); } else { sendClient("Content-Length: 0"); } sendClient(""); if (content != null && content.length() > 0) { // full debug trace if (wireLogger.isDebugEnabled()) { wireLogger.debug("> " + content); } sendClient(content.getBytes("UTF-8")); } } /** * Decode HTTP credentials * * @param authorization http authorization header value * @throws java.io.IOException if invalid credentials */ protected void decodeCredentials(String authorization) throws IOException { int index = authorization.indexOf(' '); if (index > 0) { String mode = authorization.substring(0, index).toLowerCase(); if (!"basic".equals(mode)) { throw new IOException("Unsupported authorization mode: " + mode); } String encodedCredentials = authorization.substring(index + 1); String decodedCredentials = base64Decode(encodedCredentials); index = decodedCredentials.indexOf(':'); if (index > 0) { userName = decodedCredentials.substring(0, index); password = decodedCredentials.substring(index + 1); } else { throw new IOException("Invalid credentials"); } } else { throw new IOException("Invalid credentials"); } } protected class CaldavRequest { protected HashSet<String> properties = new HashSet<String>(); protected HashSet<String> hrefs; protected boolean isMultiGet; public CaldavRequest(String body) throws IOException { // parse body XMLStreamReader streamReader = null; try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); streamReader = inputFactory.createXMLStreamReader(new StringReader(body)); boolean inElement = false; boolean inProperties = false; String currentElement = null; while (streamReader.hasNext()) { int event = streamReader.next(); if (event == XMLStreamConstants.START_ELEMENT) { inElement = true; currentElement = streamReader.getLocalName(); if ("prop".equals(currentElement)) { inProperties = true; } else if ("calendar-multiget".equals(currentElement)) { isMultiGet = true; } else if (inProperties) { properties.add(currentElement); } } else if (event == XMLStreamConstants.END_ELEMENT) { if ("prop".equals(currentElement)) { inProperties = false; } } else if (event == XMLStreamConstants.CHARACTERS && inElement) { if ("href".equals(currentElement)) { if (hrefs == null) { hrefs = new HashSet<String>(); } hrefs.add(streamReader.getText()); } inElement = false; } } } catch (XMLStreamException e) { throw new IOException(e.getMessage()); } finally { try { if (streamReader != null) { streamReader.close(); } } catch (XMLStreamException e) { DavGatewayTray.error(e); } } } public boolean hasProperty(String propertyName) { return properties.contains(propertyName); } public boolean isMultiGet() { return isMultiGet && hrefs != null; } public Set<String> getHrefs() { return hrefs; } } }
true
true
public void handleRequest(String command, String path, Map<String, String> headers, String body) throws IOException { int depth = getDepth(headers); String[] paths = path.split("/"); // full debug trace if (wireLogger.isDebugEnabled()) { wireLogger.debug("Caldav command: " + command + " " + path + " depth: " + depth + "\n" + body); } CaldavRequest request = null; if ("PROPFIND".equals(command) || "REPORT".equals(command)) { request = new CaldavRequest(body); } if ("OPTIONS".equals(command)) { sendOptions(); // redirect PROPFIND on / to current user principal } else if ("PROPFIND".equals(command) && (paths.length == 0 || paths.length == 1)) { sendRoot(request); } else if ("GET".equals(command) && (paths.length == 0 || paths.length == 1)) { sendGetRoot(); // return current user calendar } else if ("calendar".equals(paths[1])) { StringBuilder message = new StringBuilder(); message.append("/calendar no longer supported, recreate calendar with /users/") .append(session.getEmail()).append("/calendar"); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } else if ("user".equals(paths[1])) { sendRedirect(headers, "/principals/users/" + session.getEmail() + "/"); // principal namespace } else if ("PROPFIND".equals(command) && "principals".equals(paths[1]) && paths.length == 4 && "users".equals(paths[2])) { sendPrincipal(request, paths[3]); // send back principal on search } else if ("REPORT".equals(command) && "principals".equals(paths[1]) && paths.length == 3 && "users".equals(paths[2])) { sendPrincipal(request, session.getEmail()); // user root } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 3) { sendUserRoot(request, depth, paths[2]); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { sendInbox(request, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { reportInbox(); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { sendOutbox(request, paths[2]); } else if ("POST".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { sendFreeBusy(paths[2]); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3])) { sendCalendar(request, depth, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { reportCalendar(request); } else if ("PUT".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { String etag = headers.get("if-match"); int status = session.createOrUpdateEvent(paths[4], body, etag); sendHttpResponse(status, true); } else if ("DELETE".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { int status = session.deleteEvent(paths[4]); sendHttpResponse(status, true); } else if ("GET".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { ExchangeSession.Event event = session.getEvent(paths[4]); sendHttpResponse(HttpStatus.SC_OK, null, "text/calendar;charset=UTF-8", event.getICS(), true); } else { StringBuilder message = new StringBuilder(); message.append("Unsupported request: ").append(command).append(" ").append(path); message.append(" Depth: ").append(depth).append("\n").append(body); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } }
public void handleRequest(String command, String path, Map<String, String> headers, String body) throws IOException { int depth = getDepth(headers); String[] paths = path.split("/"); // full debug trace if (wireLogger.isDebugEnabled()) { wireLogger.debug("Caldav command: " + command + " " + path + " depth: " + depth + "\n" + body); } CaldavRequest request = null; if ("PROPFIND".equals(command) || "REPORT".equals(command)) { request = new CaldavRequest(body); } if ("OPTIONS".equals(command)) { sendOptions(); // redirect PROPFIND on / to current user principal } else if ("PROPFIND".equals(command) && (paths.length == 0 || paths.length == 1)) { sendRoot(request); } else if ("GET".equals(command) && (paths.length == 0 || paths.length == 1)) { sendGetRoot(); // return current user calendar } else if ("calendar".equals(paths[1])) { StringBuilder message = new StringBuilder(); message.append("/calendar no longer supported, recreate calendar with /users/") .append(session.getEmail()).append("/calendar"); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } else if ("user".equals(paths[1])) { sendRedirect(headers, "/principals/users/" + session.getEmail() + "/"); // principal namespace } else if ("PROPFIND".equals(command) && "principals".equals(paths[1]) && paths.length == 4 && "users".equals(paths[2])) { sendPrincipal(request, paths[3]); // send back principal on search } else if ("REPORT".equals(command) && "principals".equals(paths[1]) && paths.length == 3 && "users".equals(paths[2])) { sendPrincipal(request, session.getEmail()); // user root } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 3) { sendUserRoot(request, depth, paths[2]); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { sendInbox(request, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "inbox".equals(paths[3])) { reportInbox(); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { sendOutbox(request, paths[2]); } else if ("POST".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "outbox".equals(paths[3])) { sendFreeBusy(body); } else if ("PROPFIND".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3])) { sendCalendar(request, depth, paths[2]); } else if ("REPORT".equals(command) && "users".equals(paths[1]) && paths.length == 4 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { reportCalendar(request); } else if ("PUT".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { String etag = headers.get("if-match"); int status = session.createOrUpdateEvent(paths[4], body, etag); sendHttpResponse(status, true); } else if ("DELETE".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { int status = session.deleteEvent(paths[4]); sendHttpResponse(status, true); } else if ("GET".equals(command) && "users".equals(paths[1]) && paths.length == 5 && "calendar".equals(paths[3]) // only current user for now && session.getEmail().equals(paths[2])) { ExchangeSession.Event event = session.getEvent(paths[4]); sendHttpResponse(HttpStatus.SC_OK, null, "text/calendar;charset=UTF-8", event.getICS(), true); } else { StringBuilder message = new StringBuilder(); message.append("Unsupported request: ").append(command).append(" ").append(path); message.append(" Depth: ").append(depth).append("\n").append(body); DavGatewayTray.error(message.toString()); sendErr(HttpStatus.SC_BAD_REQUEST, message.toString()); } }
diff --git a/src/com/monstersfromtheid/imready/service/CheckMeetingsService.java b/src/com/monstersfromtheid/imready/service/CheckMeetingsService.java index c19e219..34e8780 100644 --- a/src/com/monstersfromtheid/imready/service/CheckMeetingsService.java +++ b/src/com/monstersfromtheid/imready/service/CheckMeetingsService.java @@ -1,212 +1,213 @@ package com.monstersfromtheid.imready.service; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONArray; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.PowerManager; import com.monstersfromtheid.imready.IMReady; import com.monstersfromtheid.imready.IMeetingChangeReceiver; import com.monstersfromtheid.imready.MyMeetings; import com.monstersfromtheid.imready.R; import com.monstersfromtheid.imready.client.Meeting; import com.monstersfromtheid.imready.client.ServerAPI; import com.monstersfromtheid.imready.client.ServerAPICallFailedException; public class CheckMeetingsService extends IntentService { private static PowerManager.WakeLock lock = null; public static final String LOCK_NAME = "com.monstersfromtheid.imready.service.CheckMeetingsService"; private static ServerAPI api; private static String userName; public CheckMeetingsService(String name) { super(name); } public CheckMeetingsService() { this("CheckMeetingsService"); } @Override public void onCreate() { super.onCreate(); if( IMReady.isAccountDefined(this) ){ userName = IMReady.getUserName(this); api = new ServerAPI(userName); } } /** * Compare the provided JSON with the last seen JSON. Use any differences (and the * current notification level) to generate notifications of the changes * * @param latestJSON */ protected void generateNotifications(Intent intent){ - if( api == null && IMReady.isAccountDefined(this) ){ + if ( !IMReady.isAccountDefined(this) ) return; + if( api == null ){ userName = IMReady.getUserName(this); api = new ServerAPI(userName); } JSONArray latestJSON = new JSONArray(); try { latestJSON = api.userMeetings(api.getRequestingUserId()); } catch (ServerAPICallFailedException e) { // Silently ignore failures to get meetings. return; } int notificationLevel = IMReady.getNotificationLevel(this); ArrayList<Meeting> latestMeetings = IMReady.toMeetingList(latestJSON); // Want to know numbers for: // New - A meeting that is previously unknown to the user. // Ready - Meeting a user was aware of that has become ready. Note there can't be a "New" meeting // that is ready as the user would have had to mark it ready, and thus be aware of it. // Changed - Meetings that the user is aware of that have seen some change since they were last aware // of it. // If anything has changed, send a broadcast. // If notification level is sufficient, create a notification ArrayList<Meeting> newMeetingList = IMReady.rollupMeetingLists(latestMeetings, this); int newM = 0; int readyM = 0; int changeM = 0; Iterator<Meeting> newMeetingListIter = newMeetingList.iterator(); while(newMeetingListIter.hasNext()){ Meeting m = newMeetingListIter.next(); if( m.isNewToUser() ) { newM++; } if( m.isChangedToUser() ) { if( m.getState() == 1 ){ readyM++; } else { changeM++; } } } // Broadcast to any registered receivers that we've got the new latest info. // There may or may not be changes, but they should redraw Intent broadcastIntent = new Intent(); broadcastIntent.setAction(IMeetingChangeReceiver.ACTION_RESP); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(broadcastIntent); // Assume the notification lasts until it is acted on by the user. // This means that I only create a new notification if I saw something change since I last looked. // There is a special case: New meeting X, delete meeting X. In this case, I delete the notification. // Otherwise I try to list number of meetings that are: if (notificationLevel == 0) { return; } // Now we know what's changed, it's time to generate a notification // [(n) new[,] ][(r) ready[ and] ][(c) changed] String notificationMessage = ""; NotificationManager notMgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); if( newM > 0 ){ if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + newM + ") new, (" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new and (" + readyM + ") ready"; } } else { if( changeM > 0 ){ notificationMessage = "(" + newM + ") new and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new"; } } } else { if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + readyM + ") ready"; } } else { if( changeM > 0 ){ // Add a preferences check to see if we should display this. notificationMessage = "(" + changeM + ") changed"; } else { // There is nothing to report return; } } } Notification notification = new Notification(R.drawable.notification, "IMReady Meetings", System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledOnMS = 300; notification.ledOffMS = 1100; CharSequence notificationTitle = getString( R.string.app_name ); Context context = getApplicationContext(); Intent notificationIntent = new Intent(this, MyMeetings.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); notification.setLatestEventInfo(context, notificationTitle, notificationMessage, pendingIntent); notMgr.notify(IMReady.NOTIFICATION_ID, notification); } protected void onHandleIntent(Intent intent) { try { setNextWakeup(intent); // QUESTION - does this checking work? // If background data settings is off then do nothing. ConnectivityManager cmgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); if( cmgr.getBackgroundDataSetting() ) { // For ICE_CREAM_SANDWICH, cmgr.getBackgroundDataSetting() always returns true... // But the code bellow, won't soding work! //if( cmgr.getActiveNetworkInfo() == null || !cmgr.getActiveNetworkInfo().isAvailable() || !cmgr.getActiveNetworkInfo().isConnected() ) { // return; //} generateNotifications( intent ); } } finally { getLock(this).release(); } } protected void setNextWakeup(Intent intent) { // If we're polling in dynamic mode, then set the next poll alarm. if( IMReady.getPollingInterval(this) == 2 ){ IMReady.setNextAlarm(this); } } synchronized private static PowerManager.WakeLock getLock(Context context) { if (lock == null) { PowerManager pmgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE); lock = pmgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME); lock.setReferenceCounted(true); } return (lock); } public static void acquireLock(Context context) { getLock(context).acquire(); } }
true
true
protected void generateNotifications(Intent intent){ if( api == null && IMReady.isAccountDefined(this) ){ userName = IMReady.getUserName(this); api = new ServerAPI(userName); } JSONArray latestJSON = new JSONArray(); try { latestJSON = api.userMeetings(api.getRequestingUserId()); } catch (ServerAPICallFailedException e) { // Silently ignore failures to get meetings. return; } int notificationLevel = IMReady.getNotificationLevel(this); ArrayList<Meeting> latestMeetings = IMReady.toMeetingList(latestJSON); // Want to know numbers for: // New - A meeting that is previously unknown to the user. // Ready - Meeting a user was aware of that has become ready. Note there can't be a "New" meeting // that is ready as the user would have had to mark it ready, and thus be aware of it. // Changed - Meetings that the user is aware of that have seen some change since they were last aware // of it. // If anything has changed, send a broadcast. // If notification level is sufficient, create a notification ArrayList<Meeting> newMeetingList = IMReady.rollupMeetingLists(latestMeetings, this); int newM = 0; int readyM = 0; int changeM = 0; Iterator<Meeting> newMeetingListIter = newMeetingList.iterator(); while(newMeetingListIter.hasNext()){ Meeting m = newMeetingListIter.next(); if( m.isNewToUser() ) { newM++; } if( m.isChangedToUser() ) { if( m.getState() == 1 ){ readyM++; } else { changeM++; } } } // Broadcast to any registered receivers that we've got the new latest info. // There may or may not be changes, but they should redraw Intent broadcastIntent = new Intent(); broadcastIntent.setAction(IMeetingChangeReceiver.ACTION_RESP); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(broadcastIntent); // Assume the notification lasts until it is acted on by the user. // This means that I only create a new notification if I saw something change since I last looked. // There is a special case: New meeting X, delete meeting X. In this case, I delete the notification. // Otherwise I try to list number of meetings that are: if (notificationLevel == 0) { return; } // Now we know what's changed, it's time to generate a notification // [(n) new[,] ][(r) ready[ and] ][(c) changed] String notificationMessage = ""; NotificationManager notMgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); if( newM > 0 ){ if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + newM + ") new, (" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new and (" + readyM + ") ready"; } } else { if( changeM > 0 ){ notificationMessage = "(" + newM + ") new and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new"; } } } else { if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + readyM + ") ready"; } } else { if( changeM > 0 ){ // Add a preferences check to see if we should display this. notificationMessage = "(" + changeM + ") changed"; } else { // There is nothing to report return; } } } Notification notification = new Notification(R.drawable.notification, "IMReady Meetings", System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledOnMS = 300; notification.ledOffMS = 1100; CharSequence notificationTitle = getString( R.string.app_name ); Context context = getApplicationContext(); Intent notificationIntent = new Intent(this, MyMeetings.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); notification.setLatestEventInfo(context, notificationTitle, notificationMessage, pendingIntent); notMgr.notify(IMReady.NOTIFICATION_ID, notification); }
protected void generateNotifications(Intent intent){ if ( !IMReady.isAccountDefined(this) ) return; if( api == null ){ userName = IMReady.getUserName(this); api = new ServerAPI(userName); } JSONArray latestJSON = new JSONArray(); try { latestJSON = api.userMeetings(api.getRequestingUserId()); } catch (ServerAPICallFailedException e) { // Silently ignore failures to get meetings. return; } int notificationLevel = IMReady.getNotificationLevel(this); ArrayList<Meeting> latestMeetings = IMReady.toMeetingList(latestJSON); // Want to know numbers for: // New - A meeting that is previously unknown to the user. // Ready - Meeting a user was aware of that has become ready. Note there can't be a "New" meeting // that is ready as the user would have had to mark it ready, and thus be aware of it. // Changed - Meetings that the user is aware of that have seen some change since they were last aware // of it. // If anything has changed, send a broadcast. // If notification level is sufficient, create a notification ArrayList<Meeting> newMeetingList = IMReady.rollupMeetingLists(latestMeetings, this); int newM = 0; int readyM = 0; int changeM = 0; Iterator<Meeting> newMeetingListIter = newMeetingList.iterator(); while(newMeetingListIter.hasNext()){ Meeting m = newMeetingListIter.next(); if( m.isNewToUser() ) { newM++; } if( m.isChangedToUser() ) { if( m.getState() == 1 ){ readyM++; } else { changeM++; } } } // Broadcast to any registered receivers that we've got the new latest info. // There may or may not be changes, but they should redraw Intent broadcastIntent = new Intent(); broadcastIntent.setAction(IMeetingChangeReceiver.ACTION_RESP); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); sendBroadcast(broadcastIntent); // Assume the notification lasts until it is acted on by the user. // This means that I only create a new notification if I saw something change since I last looked. // There is a special case: New meeting X, delete meeting X. In this case, I delete the notification. // Otherwise I try to list number of meetings that are: if (notificationLevel == 0) { return; } // Now we know what's changed, it's time to generate a notification // [(n) new[,] ][(r) ready[ and] ][(c) changed] String notificationMessage = ""; NotificationManager notMgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); if( newM > 0 ){ if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + newM + ") new, (" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new and (" + readyM + ") ready"; } } else { if( changeM > 0 ){ notificationMessage = "(" + newM + ") new and (" + changeM + ") changed"; } else { notificationMessage = "(" + newM + ") new"; } } } else { if( readyM > 0 ){ if( changeM > 0 ){ notificationMessage = "(" + readyM + ") ready and (" + changeM + ") changed"; } else { notificationMessage = "(" + readyM + ") ready"; } } else { if( changeM > 0 ){ // Add a preferences check to see if we should display this. notificationMessage = "(" + changeM + ") changed"; } else { // There is nothing to report return; } } } Notification notification = new Notification(R.drawable.notification, "IMReady Meetings", System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.ledOnMS = 300; notification.ledOffMS = 1100; CharSequence notificationTitle = getString( R.string.app_name ); Context context = getApplicationContext(); Intent notificationIntent = new Intent(this, MyMeetings.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); notification.setLatestEventInfo(context, notificationTitle, notificationMessage, pendingIntent); notMgr.notify(IMReady.NOTIFICATION_ID, notification); }
diff --git a/lib-core/src/main/java/com/silverpeas/form/fieldDisplayer/WysiwygFCKFieldDisplayer.java b/lib-core/src/main/java/com/silverpeas/form/fieldDisplayer/WysiwygFCKFieldDisplayer.java index 328655acb3..fb6fdba230 100644 --- a/lib-core/src/main/java/com/silverpeas/form/fieldDisplayer/WysiwygFCKFieldDisplayer.java +++ b/lib-core/src/main/java/com/silverpeas/form/fieldDisplayer/WysiwygFCKFieldDisplayer.java @@ -1,582 +1,585 @@ /** * 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 received 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/>. */ package com.silverpeas.form.fieldDisplayer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import au.id.jericho.lib.html.Source; import com.silverpeas.form.Field; import com.silverpeas.form.FieldDisplayer; import com.silverpeas.form.FieldTemplate; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.GalleryHelper; import com.silverpeas.form.PagesContext; import com.silverpeas.form.Util; import com.silverpeas.form.fieldType.TextField; import com.silverpeas.util.i18n.I18NHelper; import com.silverpeas.wysiwyg.dynamicvalue.control.DynamicValueReplacement; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.util.SilverpeasSettings; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.beans.admin.ComponentInstLight; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.FileServerUtils; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.exception.UtilException; import com.stratelia.webactiv.util.fileFolder.FileFolderManager; import com.stratelia.webactiv.util.indexEngine.model.FullIndexEntry; /** * A WysiwygFieldDisplayer is an object which can display a TextFiel in HTML the content of a * TextFiel to a end user and can retrieve via HTTP any updated value. * @see Field * @see FieldTemplate * @see Form * @see FieldDisplayer */ public class WysiwygFCKFieldDisplayer extends AbstractFieldDisplayer { public static final String dbKey = "xmlWysiwygField_"; public static final String dir = "xmlWysiwyg"; private static final ResourceLocator settings = new ResourceLocator( "com.stratelia.silverpeas.wysiwyg.settings.wysiwygSettings", ""); /** * Constructeur */ public WysiwygFCKFieldDisplayer() { } /** * Returns the name of the managed types. */ public String[] getManagedTypes() { String[] s = new String[0]; s[0] = TextField.TYPE; return s; } /** * Prints the javascripts which will be used to control the new value given to the named field. * The error messages may be adapted to a local language. The FieldTemplate gives the field type * and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but * log a silvertrace and writes an empty string when : * <UL> * <LI>the fieldName is unknown by the template. * <LI>the field type is not a managed type. * </UL> */ public void displayScripts(PrintWriter out, FieldTemplate template, PagesContext PagesContext) throws java.io.IOException { String fieldName = template.getFieldName(); String language = PagesContext.getLanguage(); if (!template.getTypeName().equals(TextField.TYPE)) { SilverTrace.info("form", "WysiwygFCKFieldDisplayer.displayScripts", "form.INFO_NOT_CORRECT_TYPE", TextField.TYPE); } out.println("var oEditor;"); out.println("oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("var thecode = oEditor.GetHTML();"); if (template.isMandatory() && PagesContext.useMandatory()) { out .println(" if (isWhitespace(stripInitialWhitespace(thecode)) || thecode == \"<P>&nbsp;</P>\") {"); out.println(" errorMsg+=\" - '" + template.getLabel(language) + "' " + Util.getString("GML.MustBeFilled", language) + "\\n \";"); out.println(" errorNb++;"); out.println(" }"); } Util.getJavascriptChecker(template.getFieldName(), PagesContext, out); } /** * Prints the HTML value of the field. The displayed value must be updatable by the end user. The * value format may be adapted to a local language. The fieldName must be used to name the html * form input. Never throws an Exception but log a silvertrace and writes an empty string when : * <UL> * <LI>the field type is not a managed type. * </UL> */ public void display(PrintWriter out, Field field, FieldTemplate template, PagesContext pageContext) throws FormException { String code = ""; String fieldName = template.getFieldName(); Map<String, String> parameters = template.getParameters(pageContext.getLanguage()); if (!field.getTypeName().equals(TextField.TYPE)) { SilverTrace.info("form", "WysiwygFCKFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE", TextField.TYPE); } if (!field.isNull()) { code = field.getValue(pageContext.getLanguage()); } String contentLanguage = I18NHelper.checkLanguage(pageContext.getContentLanguage()); code = getContent(pageContext.getComponentId(), pageContext.getObjectId(), template.getFieldName(), code, contentLanguage); if (template.isDisabled() || template.isReadOnly()) { // dynamic value functionality if (DynamicValueReplacement.isActivate()) { DynamicValueReplacement replacement = new DynamicValueReplacement(); code = replacement.replaceKeyByValue(code); } out.println(code); } else { out.println("<table>"); // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("<tr class=\"TB_Expand\"> <td class=\"TB_Expand\" align=\"center\">"); out.println(DynamicValueReplacement.buildHTMLSelect(pageContext.getLanguage(), fieldName)); out.println("</td></tr>"); } ResourceLocator resources = new ResourceLocator( "com.stratelia.silverpeas.wysiwyg.multilang.wysiwygBundle", contentLanguage); // storage file : HTML select building List<ComponentInstLight> fileStorage = WysiwygController.getStorageFile(pageContext.getUserId()); if (!fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"storageFile_" + fieldName + "\" name=\"componentId\" onchange=\"openStorageFilemanager" + FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')) + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( resources.getString("storageFile.select.title")).append("</option>"); for (ComponentInstLight component : fileStorage) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } // Gallery file : HTML select building List<ComponentInstLight> galleries = WysiwygController.getGalleries(); String fieldNameFunction = FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')); if (galleries != null && !galleries.isEmpty()) { if (fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"galleryFile_" + fieldName + "\" name=\"componentId\" onchange=\"openGalleryFileManager" + fieldNameFunction + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( Util.getString("GML.galleries", contentLanguage)) .append("</option>"); for (ComponentInstLight component : galleries) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } if (!fileStorage.isEmpty() || (galleries != null && !galleries.isEmpty())) { out.println("</td></tr>"); } out.println("<tr>"); // looks for size parameters int editorWitdh = 500; int editorHeight = 300; if (parameters.containsKey("width")) { editorWitdh = Integer.parseInt(parameters.get("width")); } if (parameters.containsKey("height")) { editorHeight = Integer.parseInt(parameters.get("height")); } out.println("<td valign=\"top\">"); out.println("<textarea id=\"" + fieldName + "\" name=\"" + fieldName + "\" rows=\"10\" cols=\"10\">" + code + "</textarea>"); out.println("<script type=\"text/javascript\">"); out.println("var oFCKeditor = new FCKeditor('" + fieldName + "');"); out.println("oFCKeditor.Width = \"" + editorWitdh + "\";"); out.println("oFCKeditor.Height = \"" + editorHeight + "\";"); out.println("oFCKeditor.BasePath = \"" + Util.getPath() + "/wysiwyg/jsp/FCKeditor/\" ;"); out.println("oFCKeditor.DisplayErrors = true;"); out .println("oFCKeditor.Config[\"DefaultLanguage\"] = \"" + pageContext.getLanguage() + "\";"); String configFile = SilverpeasSettings.readString(settings, "configFile", Util.getPath() + "/wysiwyg/jsp/javaScript/myconfig.js"); out.println("oFCKeditor.Config[\"CustomConfigurationsPath\"] = \"" + configFile + "\";"); out.println("oFCKeditor.ToolbarSet = 'XMLForm';"); out.println("oFCKeditor.Config[\"ToolbarStartExpanded\"] = false;"); + out.println("oFCKeditor.Config[\"ImageBrowserURL\"] = '" + Util.getPath() + + "/wysiwyg/jsp/uploadFile.jsp?ComponentId=" + pageContext.getComponentId() + "&ObjectId=" + + pageContext.getObjectId() + "&Context=" + fieldName + "';"); out.println("oFCKeditor.ReplaceTextarea();"); // field name used to generate a javascript function name // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("function chooseDynamicValues" + fieldNameFunction + "(){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("index = document.getElementById(\"dynamicValues_" + fieldName + "\").selectedIndex;"); out.println("var str = document.getElementById(\"dynamicValues_" + fieldName + "\").options[index].value;"); out.println("if (index != 0 && str != null){"); out.println("oEditor.InsertHtml('(%'+str+'%)');"); out.println("} }"); } // storage file : javascript functions out.println("var storageFileWindow=window;"); out.println("function openStorageFilemanager" + fieldNameFunction + "(){"); out.println("index = document.getElementById(\"storageFile_" + fieldName + "\").selectedIndex;"); out.println("var componentId = document.getElementById(\"storageFile_" + fieldName + "\").options[index].value;"); out.println("if (index != 0){ "); out .println("url = \"" + URLManager.getApplicationURL() + "/kmelia/jsp/attachmentLinkManagement.jsp?key=\"+componentId+\"&ntype=COMPONENT&fieldname=" + fieldNameFunction + "\";"); out.println("windowName = \"StorageFileWindow\";"); out.println("width = \"750\";"); out.println("height = \"580\";"); out .println("windowParams = \"scrollbars=1,directories=0,menubar=0,toolbar=0, alwaysRaised\";"); out.println("if (!storageFileWindow.closed && storageFileWindow.name==windowName)"); out.println("storageFileWindow.close();"); out .println("storageFileWindow = SP_openWindow(url, windowName, width, height, windowParams);"); out.println("}}"); out.println("function insertAttachmentLink" + fieldNameFunction + "(url,img,label){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out .println("oEditor.InsertHtml('<a href=\"'+url+'\"> <img src=\"'+img+'\" width=\"20\" border=\"0\" alt=\"\"/> '+label+'</a> ');"); out.println("}"); // Gallery files exists; javascript functions if (galleries != null && !galleries.isEmpty()) { GalleryHelper.getJavaScript(fieldNameFunction, fieldName, contentLanguage, out); out.println("function choixImageInGallery" + fieldNameFunction + "(url){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("oEditor.InsertHtml('<img src=\"'+url+'\" border=\"0\" alt=\"\"/>');"); out.println("}"); } out.println("</script>"); if (template.isMandatory() && pageContext.useMandatory()) { out.println(Util.getMandatorySnippet()); } out.println("</td>"); out.println("</tr>"); out.println("</table>"); } } /** * Updates the value of the field. The fieldName must be used to retrieve the HTTP parameter from * the request. * @throw FormException if the field type is not a managed type. * @throw FormException if the field doesn't accept the new value. */ @Override public List<String> update(String newValue, Field field, FieldTemplate template, PagesContext pageContext) throws FormException { if (!field.getTypeName().equals(TextField.TYPE)) { throw new FormException("WysiwygFCKFieldDisplayer.update", "form.EX_NOT_CORRECT_TYPE", TextField.TYPE); } if (field.acceptValue(newValue, pageContext.getLanguage())) { // field.setValue(newValue, PagesContext.getLanguage()); try { String contentLanguage = I18NHelper.checkLanguage(pageContext.getContentLanguage()); String fileName = setContentIntoFile(pageContext.getComponentId(), pageContext.getObjectId(), template. getFieldName(), newValue, contentLanguage); field.setValue(dbKey + fileName, pageContext.getLanguage()); } catch (Exception e) { throw new FormException("WysiwygFCKFieldDisplayer.update", "form.EX_NOT_CORRECT_VALUE", e); } } else { throw new FormException("WysiwygFCKFieldDisplayer.update", "form.EX_NOT_CORRECT_VALUE", TextField.TYPE); } return new ArrayList<String>(); } public boolean isDisplayedMandatory() { return true; } public int getNbHtmlObjectsDisplayed(FieldTemplate template, PagesContext pagesContext) { return 2; } @Override public void index(FullIndexEntry indexEntry, String key, String fieldName, Field field, String language) { String fieldValue = field.getValue(); String fieldValueIndex = ""; if (fieldValue != null && fieldValue.trim().length() > 0) { if (fieldValue.startsWith(dbKey)) { String file = WysiwygFCKFieldDisplayer.getFile(indexEntry.getComponent(), indexEntry.getObjectId(), fieldName, language); try { Source source = new Source(new FileInputStream(file)); if (source != null) { fieldValueIndex = source.getTextExtractor().toString(); } } catch (IOException ioex) { SilverTrace.warn("form", "WysiwygFCKFieldDisplayer.index", "form.incorrect_data", "File not found " + file + " " + ioex.getMessage(), ioex); } indexEntry.addTextContent(fieldValueIndex, language); } else { indexEntry.addTextContent(fieldValue.trim(), language); fieldValueIndex = fieldValue.trim().replaceAll("##", " "); } indexEntry.addField(key, fieldValueIndex, language); } } public void duplicateContent(Field field, FieldTemplate template, PagesContext pageContext, String newObjectId) throws FormException { String contentLanguage = I18NHelper.checkLanguage(pageContext.getContentLanguage()); String code = field.getStringValue(); code = getContent(pageContext.getComponentId(), pageContext.getObjectId(), template.getFieldName(), code, contentLanguage); String fileName = setContentIntoFile(pageContext.getComponentId(), newObjectId, template.getFieldName(), code, contentLanguage); field.setValue(dbKey + fileName, pageContext.getLanguage()); } private String getContent(String componentId, String objectId, String fieldName, String code, String language) throws FormException { if (!code.startsWith(dbKey)) { setContentIntoFile(componentId, objectId, fieldName, code, language); } else { try { code = getContentFromFile(componentId, objectId, fieldName, language); } catch (UtilException e) { throw new FormException("WysiwygFCKFieldDisplayer.getContent", e.getMessage(), e); } } return code; } private String setContentIntoFile(String componentId, String objectId, String fieldName, String code, String language) { try { FileRepositoryManager.createAbsolutePath(componentId, dir); } catch (Exception e) { } String[] dirs = new String[1]; dirs[0] = dir; String path = FileRepositoryManager.getAbsolutePath(componentId, dirs); String fileName = getFileName(fieldName, objectId, language); try { FileFolderManager.createFile(path, fileName, code); } catch (UtilException e) { // do nothinf } return fileName; } public static String getContentFromFile(String componentId, String objectId, String fieldName) throws UtilException { return getContentFromFile(componentId, objectId, fieldName, null); } public static String getContentFromFile(String componentId, String objectId, String fieldName, String language) throws UtilException { String fileName = getFileName(fieldName, objectId, language); String[] dirs = new String[1]; dirs[0] = dir; String path = FileRepositoryManager.getAbsolutePath(componentId, dirs); return FileFolderManager.getCode(path, fileName); } private static String getFileName(String fieldName, String objectId) { return getFileName(fieldName, objectId, null); } private static String getFileName(String fieldName, String objectId, String language) { if (language == null || I18NHelper.isDefaultLanguage(language)) { return objectId + "_" + fieldName; } else { return objectId + "_" + language + "_" + fieldName; } } public void cloneContents(String componentIdFrom, String objectIdFrom, String componentIdTo, String objectIdTo) throws UtilException, IOException { String[] dirs = new String[1]; dirs[0] = dir; String fromPath = FileRepositoryManager.getAbsolutePath(componentIdFrom, dirs); String toPath = FileRepositoryManager.getAbsolutePath(componentIdTo, dirs); File from = new File(fromPath); if (from != null && from.exists()) { try { FileRepositoryManager.createAbsolutePath(componentIdTo, dir); } catch (Exception e) { throw new IOException(e.getMessage()); } List<File> files = (List<File>) FileFolderManager.getAllFile(fromPath); for (int f = 0; f < files.size(); f++) { File file = files.get(f); String fileName = file.getName(); if (fileName.startsWith(objectIdFrom + "_")) { String fieldName = fileName.substring(objectIdFrom.length() + 1); FileRepositoryManager.copyFile(fromPath + file.getName(), toPath + getFileName(fieldName, objectIdTo)); Iterator<String> languages = I18NHelper.getLanguages(); while (languages.hasNext()) { String language = languages.next(); if (fieldName.startsWith(language + "_")) { fieldName = fieldName.substring(3); // skip en_ FileRepositoryManager.copyFile(fromPath + file.getName(), toPath + getFileName(fieldName, objectIdTo, language)); } } } } } } public void mergeContents(String componentIdFrom, String objectIdFrom, String componentIdTo, String objectIdTo) throws UtilException, IOException { String[] dirs = new String[1]; dirs[0] = dir; String fromPath = FileRepositoryManager.getAbsolutePath(componentIdFrom, dirs); File from = new File(fromPath); if (from != null && from.exists()) { // Verifie si le repertoire de destination existe try { FileRepositoryManager.createAbsolutePath(componentIdTo, dir); } catch (Exception e) { throw new IOException(e.getMessage()); } // Copier/coller de tous les fichiers wysiwyg de objectIdFrom vers objectIdTo List<File> files = (List<File>) FileFolderManager.getAllFile(fromPath); for (int f = 0; f < files.size(); f++) { File file = files.get(f); String fileName = file.getName(); if (fileName.startsWith(objectIdFrom + "_")) { String fieldName = fileName.substring(objectIdFrom.length() + 1); String fieldContent = getContentFromFile(componentIdFrom, objectIdFrom, fieldName); setContentIntoFile(componentIdTo, objectIdTo, fieldName, fieldContent, null); // paste translations Iterator<String> languages = I18NHelper.getLanguages(); while (languages.hasNext()) { String language = languages.next(); if (fieldName.startsWith(language + "_")) { fieldName = fieldName.substring(3); // skip en_ fieldContent = getContentFromFile(componentIdFrom, objectIdFrom, fieldName, language); setContentIntoFile(componentIdTo, objectIdTo, fieldName, fieldContent, language); } } } } // Delete merged files for (int f = 0; f < files.size(); f++) { File file = files.get(f); String fileName = file.getName(); if (fileName.startsWith(objectIdFrom + "_")) { file.delete(); } } } } public static String getFile(String componentId, String objectId, String fieldName, String language) { String[] dirs = new String[1]; dirs[0] = dir; String path = FileRepositoryManager.getAbsolutePath(componentId, dirs); return path + getFileName(fieldName, objectId, language); } }
true
true
public void display(PrintWriter out, Field field, FieldTemplate template, PagesContext pageContext) throws FormException { String code = ""; String fieldName = template.getFieldName(); Map<String, String> parameters = template.getParameters(pageContext.getLanguage()); if (!field.getTypeName().equals(TextField.TYPE)) { SilverTrace.info("form", "WysiwygFCKFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE", TextField.TYPE); } if (!field.isNull()) { code = field.getValue(pageContext.getLanguage()); } String contentLanguage = I18NHelper.checkLanguage(pageContext.getContentLanguage()); code = getContent(pageContext.getComponentId(), pageContext.getObjectId(), template.getFieldName(), code, contentLanguage); if (template.isDisabled() || template.isReadOnly()) { // dynamic value functionality if (DynamicValueReplacement.isActivate()) { DynamicValueReplacement replacement = new DynamicValueReplacement(); code = replacement.replaceKeyByValue(code); } out.println(code); } else { out.println("<table>"); // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("<tr class=\"TB_Expand\"> <td class=\"TB_Expand\" align=\"center\">"); out.println(DynamicValueReplacement.buildHTMLSelect(pageContext.getLanguage(), fieldName)); out.println("</td></tr>"); } ResourceLocator resources = new ResourceLocator( "com.stratelia.silverpeas.wysiwyg.multilang.wysiwygBundle", contentLanguage); // storage file : HTML select building List<ComponentInstLight> fileStorage = WysiwygController.getStorageFile(pageContext.getUserId()); if (!fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"storageFile_" + fieldName + "\" name=\"componentId\" onchange=\"openStorageFilemanager" + FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')) + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( resources.getString("storageFile.select.title")).append("</option>"); for (ComponentInstLight component : fileStorage) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } // Gallery file : HTML select building List<ComponentInstLight> galleries = WysiwygController.getGalleries(); String fieldNameFunction = FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')); if (galleries != null && !galleries.isEmpty()) { if (fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"galleryFile_" + fieldName + "\" name=\"componentId\" onchange=\"openGalleryFileManager" + fieldNameFunction + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( Util.getString("GML.galleries", contentLanguage)) .append("</option>"); for (ComponentInstLight component : galleries) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } if (!fileStorage.isEmpty() || (galleries != null && !galleries.isEmpty())) { out.println("</td></tr>"); } out.println("<tr>"); // looks for size parameters int editorWitdh = 500; int editorHeight = 300; if (parameters.containsKey("width")) { editorWitdh = Integer.parseInt(parameters.get("width")); } if (parameters.containsKey("height")) { editorHeight = Integer.parseInt(parameters.get("height")); } out.println("<td valign=\"top\">"); out.println("<textarea id=\"" + fieldName + "\" name=\"" + fieldName + "\" rows=\"10\" cols=\"10\">" + code + "</textarea>"); out.println("<script type=\"text/javascript\">"); out.println("var oFCKeditor = new FCKeditor('" + fieldName + "');"); out.println("oFCKeditor.Width = \"" + editorWitdh + "\";"); out.println("oFCKeditor.Height = \"" + editorHeight + "\";"); out.println("oFCKeditor.BasePath = \"" + Util.getPath() + "/wysiwyg/jsp/FCKeditor/\" ;"); out.println("oFCKeditor.DisplayErrors = true;"); out .println("oFCKeditor.Config[\"DefaultLanguage\"] = \"" + pageContext.getLanguage() + "\";"); String configFile = SilverpeasSettings.readString(settings, "configFile", Util.getPath() + "/wysiwyg/jsp/javaScript/myconfig.js"); out.println("oFCKeditor.Config[\"CustomConfigurationsPath\"] = \"" + configFile + "\";"); out.println("oFCKeditor.ToolbarSet = 'XMLForm';"); out.println("oFCKeditor.Config[\"ToolbarStartExpanded\"] = false;"); out.println("oFCKeditor.ReplaceTextarea();"); // field name used to generate a javascript function name // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("function chooseDynamicValues" + fieldNameFunction + "(){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("index = document.getElementById(\"dynamicValues_" + fieldName + "\").selectedIndex;"); out.println("var str = document.getElementById(\"dynamicValues_" + fieldName + "\").options[index].value;"); out.println("if (index != 0 && str != null){"); out.println("oEditor.InsertHtml('(%'+str+'%)');"); out.println("} }"); } // storage file : javascript functions out.println("var storageFileWindow=window;"); out.println("function openStorageFilemanager" + fieldNameFunction + "(){"); out.println("index = document.getElementById(\"storageFile_" + fieldName + "\").selectedIndex;"); out.println("var componentId = document.getElementById(\"storageFile_" + fieldName + "\").options[index].value;"); out.println("if (index != 0){ "); out .println("url = \"" + URLManager.getApplicationURL() + "/kmelia/jsp/attachmentLinkManagement.jsp?key=\"+componentId+\"&ntype=COMPONENT&fieldname=" + fieldNameFunction + "\";"); out.println("windowName = \"StorageFileWindow\";"); out.println("width = \"750\";"); out.println("height = \"580\";"); out .println("windowParams = \"scrollbars=1,directories=0,menubar=0,toolbar=0, alwaysRaised\";"); out.println("if (!storageFileWindow.closed && storageFileWindow.name==windowName)"); out.println("storageFileWindow.close();"); out .println("storageFileWindow = SP_openWindow(url, windowName, width, height, windowParams);"); out.println("}}"); out.println("function insertAttachmentLink" + fieldNameFunction + "(url,img,label){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out .println("oEditor.InsertHtml('<a href=\"'+url+'\"> <img src=\"'+img+'\" width=\"20\" border=\"0\" alt=\"\"/> '+label+'</a> ');"); out.println("}"); // Gallery files exists; javascript functions if (galleries != null && !galleries.isEmpty()) { GalleryHelper.getJavaScript(fieldNameFunction, fieldName, contentLanguage, out); out.println("function choixImageInGallery" + fieldNameFunction + "(url){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("oEditor.InsertHtml('<img src=\"'+url+'\" border=\"0\" alt=\"\"/>');"); out.println("}"); } out.println("</script>"); if (template.isMandatory() && pageContext.useMandatory()) { out.println(Util.getMandatorySnippet()); } out.println("</td>"); out.println("</tr>"); out.println("</table>"); } }
public void display(PrintWriter out, Field field, FieldTemplate template, PagesContext pageContext) throws FormException { String code = ""; String fieldName = template.getFieldName(); Map<String, String> parameters = template.getParameters(pageContext.getLanguage()); if (!field.getTypeName().equals(TextField.TYPE)) { SilverTrace.info("form", "WysiwygFCKFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE", TextField.TYPE); } if (!field.isNull()) { code = field.getValue(pageContext.getLanguage()); } String contentLanguage = I18NHelper.checkLanguage(pageContext.getContentLanguage()); code = getContent(pageContext.getComponentId(), pageContext.getObjectId(), template.getFieldName(), code, contentLanguage); if (template.isDisabled() || template.isReadOnly()) { // dynamic value functionality if (DynamicValueReplacement.isActivate()) { DynamicValueReplacement replacement = new DynamicValueReplacement(); code = replacement.replaceKeyByValue(code); } out.println(code); } else { out.println("<table>"); // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("<tr class=\"TB_Expand\"> <td class=\"TB_Expand\" align=\"center\">"); out.println(DynamicValueReplacement.buildHTMLSelect(pageContext.getLanguage(), fieldName)); out.println("</td></tr>"); } ResourceLocator resources = new ResourceLocator( "com.stratelia.silverpeas.wysiwyg.multilang.wysiwygBundle", contentLanguage); // storage file : HTML select building List<ComponentInstLight> fileStorage = WysiwygController.getStorageFile(pageContext.getUserId()); if (!fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"storageFile_" + fieldName + "\" name=\"componentId\" onchange=\"openStorageFilemanager" + FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')) + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( resources.getString("storageFile.select.title")).append("</option>"); for (ComponentInstLight component : fileStorage) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } // Gallery file : HTML select building List<ComponentInstLight> galleries = WysiwygController.getGalleries(); String fieldNameFunction = FileServerUtils.replaceAccentChars(fieldName.replace(' ', '_')); if (galleries != null && !galleries.isEmpty()) { if (fileStorage.isEmpty()) { out.println("<tr class=\"TB_Expand\"><td class=\"TB_Expand\">"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<select id=\"galleryFile_" + fieldName + "\" name=\"componentId\" onchange=\"openGalleryFileManager" + fieldNameFunction + "();this.selectedIndex=0\">"); stringBuilder.append("<option value=\"\">").append( Util.getString("GML.galleries", contentLanguage)) .append("</option>"); for (ComponentInstLight component : galleries) { stringBuilder.append("<option value=\"").append(component.getId()).append("\">").append( component.getLabel(contentLanguage)).append("</option>"); } stringBuilder.append("</select>"); out.println(stringBuilder.toString()); } if (!fileStorage.isEmpty() || (galleries != null && !galleries.isEmpty())) { out.println("</td></tr>"); } out.println("<tr>"); // looks for size parameters int editorWitdh = 500; int editorHeight = 300; if (parameters.containsKey("width")) { editorWitdh = Integer.parseInt(parameters.get("width")); } if (parameters.containsKey("height")) { editorHeight = Integer.parseInt(parameters.get("height")); } out.println("<td valign=\"top\">"); out.println("<textarea id=\"" + fieldName + "\" name=\"" + fieldName + "\" rows=\"10\" cols=\"10\">" + code + "</textarea>"); out.println("<script type=\"text/javascript\">"); out.println("var oFCKeditor = new FCKeditor('" + fieldName + "');"); out.println("oFCKeditor.Width = \"" + editorWitdh + "\";"); out.println("oFCKeditor.Height = \"" + editorHeight + "\";"); out.println("oFCKeditor.BasePath = \"" + Util.getPath() + "/wysiwyg/jsp/FCKeditor/\" ;"); out.println("oFCKeditor.DisplayErrors = true;"); out .println("oFCKeditor.Config[\"DefaultLanguage\"] = \"" + pageContext.getLanguage() + "\";"); String configFile = SilverpeasSettings.readString(settings, "configFile", Util.getPath() + "/wysiwyg/jsp/javaScript/myconfig.js"); out.println("oFCKeditor.Config[\"CustomConfigurationsPath\"] = \"" + configFile + "\";"); out.println("oFCKeditor.ToolbarSet = 'XMLForm';"); out.println("oFCKeditor.Config[\"ToolbarStartExpanded\"] = false;"); out.println("oFCKeditor.Config[\"ImageBrowserURL\"] = '" + Util.getPath() + "/wysiwyg/jsp/uploadFile.jsp?ComponentId=" + pageContext.getComponentId() + "&ObjectId=" + pageContext.getObjectId() + "&Context=" + fieldName + "';"); out.println("oFCKeditor.ReplaceTextarea();"); // field name used to generate a javascript function name // dynamic value functionality if (DynamicValueReplacement.isActivate()) { out.println("function chooseDynamicValues" + fieldNameFunction + "(){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("index = document.getElementById(\"dynamicValues_" + fieldName + "\").selectedIndex;"); out.println("var str = document.getElementById(\"dynamicValues_" + fieldName + "\").options[index].value;"); out.println("if (index != 0 && str != null){"); out.println("oEditor.InsertHtml('(%'+str+'%)');"); out.println("} }"); } // storage file : javascript functions out.println("var storageFileWindow=window;"); out.println("function openStorageFilemanager" + fieldNameFunction + "(){"); out.println("index = document.getElementById(\"storageFile_" + fieldName + "\").selectedIndex;"); out.println("var componentId = document.getElementById(\"storageFile_" + fieldName + "\").options[index].value;"); out.println("if (index != 0){ "); out .println("url = \"" + URLManager.getApplicationURL() + "/kmelia/jsp/attachmentLinkManagement.jsp?key=\"+componentId+\"&ntype=COMPONENT&fieldname=" + fieldNameFunction + "\";"); out.println("windowName = \"StorageFileWindow\";"); out.println("width = \"750\";"); out.println("height = \"580\";"); out .println("windowParams = \"scrollbars=1,directories=0,menubar=0,toolbar=0, alwaysRaised\";"); out.println("if (!storageFileWindow.closed && storageFileWindow.name==windowName)"); out.println("storageFileWindow.close();"); out .println("storageFileWindow = SP_openWindow(url, windowName, width, height, windowParams);"); out.println("}}"); out.println("function insertAttachmentLink" + fieldNameFunction + "(url,img,label){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out .println("oEditor.InsertHtml('<a href=\"'+url+'\"> <img src=\"'+img+'\" width=\"20\" border=\"0\" alt=\"\"/> '+label+'</a> ');"); out.println("}"); // Gallery files exists; javascript functions if (galleries != null && !galleries.isEmpty()) { GalleryHelper.getJavaScript(fieldNameFunction, fieldName, contentLanguage, out); out.println("function choixImageInGallery" + fieldNameFunction + "(url){"); out.println(" var oEditor = FCKeditorAPI.GetInstance('" + fieldName + "');"); out.println("oEditor.Focus();"); out.println("oEditor.InsertHtml('<img src=\"'+url+'\" border=\"0\" alt=\"\"/>');"); out.println("}"); } out.println("</script>"); if (template.isMandatory() && pageContext.useMandatory()) { out.println(Util.getMandatorySnippet()); } out.println("</td>"); out.println("</tr>"); out.println("</table>"); } }
diff --git a/TicTac.java b/TicTac.java index 1b1e27b..f94ac5a 100644 --- a/TicTac.java +++ b/TicTac.java @@ -1,169 +1,169 @@ /** * @author MpoMp * @version 1.4 * @since 14-12-2011 * * Tic-Tac-Toe game */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** Notes and tasks: * * TODO: add table lines display * TODO: new game prompt (victory/loss message) */ public class TicTac { public static void main(String args[]) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(isr); String ttt[][] = new String[3][3]; //the tic-tac-toe table and variables final String x = "X"; final String o = "O"; boolean win = false; byte empt = 9; //empty positions left int l, r; //l, r variables for reading the user input //Table initialized for (byte i=0; i<3; i++) for (byte j=0; j<3; j++) ttt[i][j] = "-"; display(ttt); //Table display //Two initial turns for each player //No winning moves available yet for (byte i=1; i<=2; i++) { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) - System.out.println("Out of bounds \n"); + System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) - System.out.println("Not an empty position \n"); + System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) - System.out.println("Out of bounds \n"); + System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) - System.out.println("Not an empty position \n"); + System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display } //Winning moves available //Checking for victory after each move do { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) - System.out.println("Out of bounds \n"); + System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) - System.out.println("Not an empty position \n"); + System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display win = check(ttt, x, l-1, r-1); if (win || empt == 0) break; //While X plays first, he will also be the last to play if the game ends up to a draw do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) - System.out.println("Out of bounds \n"); + System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) - System.out.println("Not an empty position \n"); + System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display win = check(ttt, o, l-1, r-1); }while(!win); if (empt == 0 && win == false) System.out.println("\nDraw"); } //"check" function checks if the last move is a winning move //variable "lm" holds the last move symbol private static boolean check(String t[][], String lm, int l, int r) { boolean ret = false; //check if the row where the last move was made is complete if ((t[0][r].compareToIgnoreCase(t[1][r]) == 0 && (t[0][r].compareToIgnoreCase(t[2][r]) == 0 ))) { ret = true; } //check if the line where the last move was made is complete else if ((t[l][0].compareToIgnoreCase(t[l][1]) == 0 && (t[l][0].compareToIgnoreCase(t[l][2]) == 0 ))) { ret = true; } //check the first diagonal else if ((t[0][0].compareToIgnoreCase(t[1][1]) == 0 && (t[0][0].compareToIgnoreCase(t[2][2]) == 0))) { ret = true; } //check the second diagonal else if ((t[2][0].compareToIgnoreCase(t[1][1]) == 0 && (t[2][0].compareToIgnoreCase(t[0][2]) == 0 ))) { ret = true; } if(ret) System.out.println("Player " + lm + " wins!"); return ret; } //displays the table private static void display(String t[][]) { System.out.println("\n"); for (byte i=0; i<3; i++) { System.out.println("\n"); for (byte j=0; j<3; j++) System.out.print(" " + t[i][j]); } System.out.println("\n"); } }
false
true
public static void main(String args[]) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(isr); String ttt[][] = new String[3][3]; //the tic-tac-toe table and variables final String x = "X"; final String o = "O"; boolean win = false; byte empt = 9; //empty positions left int l, r; //l, r variables for reading the user input //Table initialized for (byte i=0; i<3; i++) for (byte j=0; j<3; j++) ttt[i][j] = "-"; display(ttt); //Table display //Two initial turns for each player //No winning moves available yet for (byte i=1; i<=2; i++) { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.out.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.out.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.out.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.out.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display } //Winning moves available //Checking for victory after each move do { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.out.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.out.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display win = check(ttt, x, l-1, r-1); if (win || empt == 0) break; //While X plays first, he will also be the last to play if the game ends up to a draw do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.out.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.out.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display win = check(ttt, o, l-1, r-1); }while(!win); if (empt == 0 && win == false) System.out.println("\nDraw"); }
public static void main(String args[]) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader input = new BufferedReader(isr); String ttt[][] = new String[3][3]; //the tic-tac-toe table and variables final String x = "X"; final String o = "O"; boolean win = false; byte empt = 9; //empty positions left int l, r; //l, r variables for reading the user input //Table initialized for (byte i=0; i<3; i++) for (byte j=0; j<3; j++) ttt[i][j] = "-"; display(ttt); //Table display //Two initial turns for each player //No winning moves available yet for (byte i=1; i<=2; i++) { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display } //Winning moves available //Checking for victory after each move do { do { System.out.println("X player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("X player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = x; empt--; display(ttt); //Table display win = check(ttt, x, l-1, r-1); if (win || empt == 0) break; //While X plays first, he will also be the last to play if the game ends up to a draw do { System.out.println("O player: Give a LINE number: "); l = Integer.parseInt(input.readLine()); System.out.println("O player: Give a ROW number: "); r = Integer.parseInt(input.readLine()); if ((r < 1 || r > 3) || (l < 1 || l > 3)) System.err.println("Out of bounds \n"); if (ttt[l-1][r-1].compareToIgnoreCase("-") != 0) System.err.println("Not an empty position \n"); } while ((r < 1 || r > 3) || (l < 1 || l > 3) || (ttt[l-1][r-1].compareToIgnoreCase("-") != 0)); ttt[l-1][r-1] = o; empt--; display(ttt); //Table display win = check(ttt, o, l-1, r-1); }while(!win); if (empt == 0 && win == false) System.out.println("\nDraw"); }
diff --git a/src/main/java/org/mongolink/domain/mapper/MapMapper.java b/src/main/java/org/mongolink/domain/mapper/MapMapper.java index 67536a2..a1b1465 100644 --- a/src/main/java/org/mongolink/domain/mapper/MapMapper.java +++ b/src/main/java/org/mongolink/domain/mapper/MapMapper.java @@ -1,66 +1,68 @@ /* * MongoLink, Object Document Mapper for Java and MongoDB * * Copyright (c) 2012, Arpinum or third-party contributors as * indicated by the @author tags * * MongoLink is free software: you can redistribute it and/or modify * it under the terms of the Lesser GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MongoLink 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 * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public License * along with MongoLink. If not, see <http://www.gnu.org/licenses/>. * */ package org.mongolink.domain.mapper; import com.mongodb.*; import org.apache.log4j.Logger; import org.mongolink.utils.*; import java.lang.reflect.*; import java.util.Map; public class MapMapper implements Mapper { public MapMapper(MethodContainer methodContainer) { this.name = methodContainer.shortName(); this.method = methodContainer.getMethod(); } @Override public void save(final Object instance, final DBObject into) { try { Map map = (Map) method.invoke(instance); into.put(name, new BasicDBObject(map)); } catch (Exception e) { LOGGER.error("Can't saveInto collection " + name, e); } } @Override public void populate(final Object instance, final DBObject from) { try { Field field = ReflectionUtils.findPrivateField(instance.getClass(), name); field.setAccessible(true); - Map map = (Map) field.get(instance); - //noinspection unchecked - map.putAll((Map) from.get(name)); + Map dbMap = (Map) from.get(name); + if (dbMap != null) { + Map map = (Map) field.get(instance); + map.putAll(dbMap); + } field.setAccessible(false); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } private final Method method; private final String name; private static final Logger LOGGER = Logger.getLogger(CollectionMapper.class); }
true
true
public void populate(final Object instance, final DBObject from) { try { Field field = ReflectionUtils.findPrivateField(instance.getClass(), name); field.setAccessible(true); Map map = (Map) field.get(instance); //noinspection unchecked map.putAll((Map) from.get(name)); field.setAccessible(false); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
public void populate(final Object instance, final DBObject from) { try { Field field = ReflectionUtils.findPrivateField(instance.getClass(), name); field.setAccessible(true); Map dbMap = (Map) from.get(name); if (dbMap != null) { Map map = (Map) field.get(instance); map.putAll(dbMap); } field.setAccessible(false); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
diff --git a/src/com/redhat/qe/sm/base/SubscriptionManagerCLITestScript.java b/src/com/redhat/qe/sm/base/SubscriptionManagerCLITestScript.java index 6257543e..abce7397 100644 --- a/src/com/redhat/qe/sm/base/SubscriptionManagerCLITestScript.java +++ b/src/com/redhat/qe/sm/base/SubscriptionManagerCLITestScript.java @@ -1,573 +1,573 @@ package com.redhat.qe.sm.base; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; import com.redhat.qe.auto.testng.Assert; import com.redhat.qe.auto.testng.TestNGUtils; import com.redhat.qe.sm.cli.tasks.CandlepinTasks; import com.redhat.qe.sm.cli.tasks.SubscriptionManagerTasks; import com.redhat.qe.sm.data.EntitlementCert; import com.redhat.qe.sm.data.ProductSubscription; import com.redhat.qe.sm.data.SubscriptionPool; import com.redhat.qe.tools.RemoteFileTasks; import com.redhat.qe.tools.SSHCommandResult; import com.redhat.qe.tools.SSHCommandRunner; /** * @author ssalevan * @author jsefler * */ public class SubscriptionManagerCLITestScript extends SubscriptionManagerBaseTestScript{ public static Connection dbConnection = null; protected static SubscriptionManagerTasks clienttasks = null; protected static SubscriptionManagerTasks client1tasks = null; // client1 subscription manager tasks protected static SubscriptionManagerTasks client2tasks = null; // client2 subscription manager tasks protected Random randomGenerator = new Random(System.currentTimeMillis()); public SubscriptionManagerCLITestScript() { super(); // TODO Auto-generated constructor stub } // Configuration Methods *********************************************************************** @BeforeSuite(groups={"setup"},description="subscription manager set up") public void setupBeforeSuite() throws IOException { client = new SSHCommandRunner(clienthostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); clienttasks = new SubscriptionManagerTasks(client); client1 = client; client1tasks = clienttasks; File serverCaCertFile = null; List<File> generatedProductCertFiles = new ArrayList<File>(); // will we be connecting to the candlepin server? if (!serverHostname.equals("") && isServerOnPremises) { server = new SSHCommandRunner(serverHostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(server,serverInstallDir,isServerOnPremises); } else { log.info("Assuming the server is already setup and running."); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(null,null,isServerOnPremises); } // will we be testing multiple clients? if (!( client2hostname.equals("") /*|| client2username.equals("") || client2password.equals("")*/ )) { client2 = new SSHCommandRunner(client2hostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); client2tasks = new SubscriptionManagerTasks(client2); } else { log.info("Multi-client testing will be skipped."); } // setup the server if (server!=null && servertasks.isOnPremises) { // NOTE: After updating the candlepin.conf file, the server needs to be restarted, therefore this will not work against the Hosted IT server which we don't want to restart or deploy // I suggest manually setting this on hosted and asking calfanso to restart servertasks.updateConfigFileParameter("pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule","0 0\\/2 * * * ?"); // every 2 minutes servertasks.cleanOutCRL(); servertasks.deploy(serverHostname, serverImportDir,serverBranch); // also connect to the candlepin server database dbConnection = connectToDatabase(); // do this after the call to deploy since it will restart postgresql // fetch the candlepin CA Cert log.info("Fetching Candlepin CA cert..."); serverCaCertFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); RemoteFileTasks.getFile(server.getConnection(), serverCaCertFile.getParent(),servertasks.candlepinCACertFile.getPath()); // fetch the generated Product Certs log.info("Fetching the generated product certs..."); SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { File remoteFile = new File(remoteFileAsString); File localFile = new File("/tmp/"+remoteFile.getName()); RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); generatedProductCertFiles.add(localFile); } } // if clients are already registered from a prior run, unregister them unregisterClientsAfterSuite(); // setup the client(s) for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { if (smt==null) continue; smt.installSubscriptionManagerRPMs(rpmUrls,enableRepoForDeps); // rhsm.conf [server] configurations if (!serverHostname.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "hostname", serverHostname); else serverHostname = smt.getConfFileParameter(smt.rhsmConfFile, "hostname"); if (!serverPrefix.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "prefix", serverPrefix); else serverPrefix = smt.getConfFileParameter(smt.rhsmConfFile, "prefix"); if (!serverPort.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "port", serverPort); else serverPort = smt.getConfFileParameter(smt.rhsmConfFile, "port"); if (!serverInsecure.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "insecure", serverInsecure); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverSslVerifyDepth.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ssl_verify_depth", serverSslVerifyDepth); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverCaCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ca_cert_dir", serverCaCertDir); else serverCaCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "ca_cert_dir"); // rhsm.conf [rhsm] configurations if (!rhsmBaseUrl.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "baseurl", rhsmBaseUrl); else rhsmBaseUrl = smt.getConfFileParameter(smt.rhsmConfFile, "baseurl"); if (!rhsmRepoCaCert.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "repo_ca_cert", rhsmRepoCaCert); else rhsmRepoCaCert = smt.getConfFileParameter(smt.rhsmConfFile, "repo_ca_cert"); //if (!rhsmShowIncompatiblePools.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools", rhsmShowIncompatiblePools); else rhsmShowIncompatiblePools = smt.getConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools"); if (!rhsmProductCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "productCertDir", rhsmProductCertDir); else rhsmProductCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "productCertDir"); if (!rhsmEntitlementCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "entitlementCertDir", rhsmEntitlementCertDir); else rhsmEntitlementCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "entitlementCertDir"); if (!rhsmConsumerCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "consumerCertDir", rhsmConsumerCertDir); else rhsmConsumerCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "consumerCertDir"); // rhsm.conf [rhsmcertd] configurations if (!rhsmcertdCertFrequency.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "certFrequency", rhsmcertdCertFrequency); else rhsmcertdCertFrequency = smt.getConfFileParameter(smt.rhsmConfFile, "certFrequency"); smt.initializeFieldsFromConfigFile(); smt.removeAllCerts(true,true); smt.installRepoCaCerts(repoCaCertUrls); // transfer a copy of the candlepin CA Cert from the candlepin server to the clients so we can test in secure mode log.info("Copying Candlepin cert onto client to enable certificate validation..."); - smt.installRepoCaCert(serverCaCertFile, serverHostname.split("\\.")[0]+"-"+servertasks.candlepinCACertFile.getName()); + smt.installRepoCaCert(serverCaCertFile, serverHostname.split("\\.")[0]+"-"+servertasks.candlepinCACertFile.getName().split("\\.")[0]+".pem"); // transfer copies of all the generated product certs from the candlepin server to the clients log.info("Copying Candlepin generated product certs onto client to simulate installed products..."); smt.installProductCerts(generatedProductCertFiles); } // // transfer a copy of the CA Cert from the candlepin server to the clients so we can test in secure mode // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin cert onto clients to enable certificate validation..."); // File localFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),servertasks.candlepinCACertFile.getPath()); // // for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { // if (smt==null) continue; // smt.installRepoCaCert(localFile, serverHostname); // } // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.getConfFileParameter(client1tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // client1tasks.updateConfFileParameter(client1tasks.rhsmConfFile, "insecure", "0"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.getConfFileParameter(client2tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // if (client2!=null) client2tasks.updateConfFileParameter(client2tasks.rhsmConfFile, "insecure", "0"); // } // // transfer a copy of the generated product certs from the candlepin server to the clients so we can test // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin generated product certs onto clients to simulate installed products..."); // SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); // for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { // File remoteFile = new File(remoteFileAsString); // File localFile = new File("/tmp/"+remoteFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.productCertDir+"/", "0644"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.productCertDir+"/", "0644"); // } // } log.info("Installed version of candlepin..."); try { JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(serverHostname,serverPort,serverPrefix,"anybody","password","/status")); // seems to work no matter what credentials are passed log.info("Candlepin server '"+serverHostname+"' is running version: "+jsonStatus.get("version")); } catch (Exception e) { log.warning("Candlepin server '"+serverHostname+"' is running version: UNKNOWN"); } log.info("Installed version of subscription-manager..."); log.info("Subscription manager client '"+client1hostname+"' is running version: "+client1.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 if (client2!=null) log.info("Subscription manager client '"+client2hostname+"' is running version: "+client2.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 isSetupBeforeSuiteComplete = true; } protected static boolean isSetupBeforeSuiteComplete = false; @AfterSuite(groups={"setup", "cleanup"},description="subscription manager tear down") public void unregisterClientsAfterSuite() { if (client2tasks!=null) client2tasks.unregister_(null, null, null); // release the entitlements consumed by the current registration if (client1tasks!=null) client1tasks.unregister_(null, null, null); // release the entitlements consumed by the current registration } @AfterSuite(groups={"setup", "cleanup"},description="subscription manager tear down") public void disconnectDatabaseAfterSuite() { // close the candlepin database connection if (dbConnection!=null) { try { dbConnection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // close the connection to the database } } // Protected Methods *********************************************************************** protected Connection connectToDatabase() { Connection dbConnection = null; try { // Load the JDBC driver Class.forName(dbSqlDriver); // "org.postgresql.Driver" or "oracle.jdbc.driver.OracleDriver" // Create a connection to the database String url = dbSqlDriver.contains("postgres")? "jdbc:postgresql://" + dbHostname + ":" + dbPort + "/" + dbName : "jdbc:oracle:thin:@" + dbHostname + ":" + dbPort + ":" + dbName ; log.info(String.format("Attempting to connect to database with url and credentials: url=%s username=%s password=%s",url,dbUsername,dbPassword)); dbConnection = DriverManager.getConnection(url, dbUsername, dbPassword); //log.finer("default dbConnection.getAutoCommit()= "+dbConnection.getAutoCommit()); dbConnection.setAutoCommit(true); DatabaseMetaData dbmd = dbConnection.getMetaData(); //get MetaData to confirm connection log.fine("Connection to "+dbmd.getDatabaseProductName()+" "+dbmd.getDatabaseProductVersion()+" successful.\n"); } catch (ClassNotFoundException e) { log.warning("JDBC driver not found!:\n" + e.getMessage()); } catch (SQLException e) { log.warning("Could not connect to backend database:\n" + e.getMessage()); } return dbConnection; } /* DELETEME OLD CODE FROM ssalevan public void getSalesToEngineeringProductBindings(){ try { String products = itDBConnection.nativeSQL("select * from butt;"); } catch (SQLException e) { // TODO Auto-generated catch block log.info("Database query for Sales-to-Engineering product bindings failed! Traceback:\n"+e.getMessage()); } } */ public static void sleep(long milliseconds) { log.info("Sleeping for "+milliseconds+" milliseconds..."); try { Thread.sleep(milliseconds); } catch (InterruptedException e) { log.info("Sleep interrupted!"); } } protected int getRandInt(){ return Math.abs(randomGenerator.nextInt()); } // public void runRHSMCallAsLang(SSHCommandRunner sshCommandRunner, String lang,String rhsmCall){ // sshCommandRunner.runCommandAndWait("export LANG="+lang+"; " + rhsmCall); // } // // public void setLanguage(SSHCommandRunner sshCommandRunner, String lang){ // sshCommandRunner.runCommandAndWait("export LANG="+lang); // } // Protected Inner Data Class *********************************************************************** protected class RegistrationData { public String username=null; public String password=null; public String ownerKey=null; public SSHCommandResult registerResult=null; public List<SubscriptionPool> allAvailableSubscriptionPools=null;/*new ArrayList<SubscriptionPool>();*/ public RegistrationData() { super(); } public RegistrationData(String username, String password, String ownerKey, SSHCommandResult registerResult, List<SubscriptionPool> allAvailableSubscriptionPools) { super(); this.username = username; this.password = password; this.ownerKey = ownerKey; this.registerResult = registerResult; this.allAvailableSubscriptionPools = allAvailableSubscriptionPools; } public String toString() { String string = ""; if (username != null) string += String.format(" %s='%s'", "username",username); if (password != null) string += String.format(" %s='%s'", "password",password); if (ownerKey != null) string += String.format(" %s='%s'", "ownerKey",ownerKey); if (registerResult != null) string += String.format(" %s=[%s]", "registerResult",registerResult); for (SubscriptionPool subscriptionPool : allAvailableSubscriptionPools) { string += String.format(" %s=[%s]", "availableSubscriptionPool",subscriptionPool); } return string.trim(); } } // this list will be populated by subclass ResisterTests.RegisterWithUsernameAndPassword_Test protected static List<RegistrationData> registrationDataList = new ArrayList<RegistrationData>(); /** * Useful when trying to find a username that belongs to a different owner/org than the current username you are testing with. * @param key * @return null when no match is found * @throws JSONException */ protected RegistrationData findRegistrationDataNotMatchingOwnerKey(String key) throws JSONException { Assert.assertTrue (!registrationDataList.isEmpty(), "The RegisterWithUsernameAndPassword_Test has been executed thereby populating the registrationDataList with content for testing."); for (RegistrationData registration : registrationDataList) { if (registration.ownerKey!=null) { if (!registration.ownerKey.equals(key)) { return registration; } } } return null; } /** * Useful when trying to find a username that belongs to the same owner/org as the current username you are testing with. * @param key * @param username * @return null when no match is found * @throws JSONException */ protected RegistrationData findRegistrationDataMatchingOwnerKeyButNotMatchingUsername(String key, String username) throws JSONException { Assert.assertTrue (!registrationDataList.isEmpty(), "The RegisterWithUsernameAndPassword_Test has been executed thereby populating the registrationDataList with content for testing."); for (RegistrationData registration : registrationDataList) { if (registration.ownerKey!=null) { if (registration.ownerKey.equals(key)) { if (!registration.username.equals(username)) { return registration; } } } } return null; } /** * Useful when trying to find registration data results from a prior registration by a given username. * @param key * @param username * @return null when no match is found * @throws JSONException */ protected RegistrationData findRegistrationDataMatchingUsername(String username) throws JSONException { Assert.assertTrue (!registrationDataList.isEmpty(), "The RegisterWithUsernameAndPassword_Test has been executed thereby populating the registrationDataList with content for testing."); for (RegistrationData registration : registrationDataList) { if (registration.username.equals(username)) { return registration; } } return null; } /** * This can be called by Tests that depend on it in a BeforeClass method to insure that registrationDataList has been populated. * @throws IOException */ protected void RegisterWithUsernameAndPassword_Test() throws IOException { if (registrationDataList.isEmpty()) { for (List<Object> UsernameAndPassword : getUsernameAndPasswordDataAsListOfLists()) { com.redhat.qe.sm.cli.tests.RegisterTests registerTests = new com.redhat.qe.sm.cli.tests.RegisterTests(); registerTests.setupBeforeSuite(); registerTests.RegisterWithUsernameAndPassword_Test((String)UsernameAndPassword.get(0), (String)UsernameAndPassword.get(1)); } } } // Data Providers *********************************************************************** @DataProvider(name="getGoodRegistrationData") public Object[][] getGoodRegistrationDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getGoodRegistrationDataAsListOfLists()); } protected List<List<Object>> getGoodRegistrationDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); // for (List<Object> registrationDataList : getBogusRegistrationDataAsListOfLists()) { // // pull out all of the valid registration data (indicated by an Integer exitCode of 0) // if (registrationDataList.contains(Integer.valueOf(0))) { // // String username, String password, String type, String consumerId // ll.add(registrationDataList.subList(0, 4)); // } // // } // changing to registrationDataList to get all the valid registeredConsumer for (RegistrationData registeredConsumer : registrationDataList) { if (registeredConsumer.registerResult.getExitCode().intValue()==0) { ll.add(Arrays.asList(new Object[]{registeredConsumer.username, registeredConsumer.password})); // minimize the number of dataProvided rows (useful during automated testcase development) if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize","false"))) break; } } return ll; } @DataProvider(name="getAvailableSubscriptionPoolsData") public Object[][] getAvailableSubscriptionPoolsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getAvailableSubscriptionPoolsDataAsListOfLists()); } protected List<List<Object>> getAvailableSubscriptionPoolsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (clienttasks==null) return ll; // assure we are registered clienttasks.unregister(null, null, null); clienttasks.register(clientusername, clientpassword, null, null, null, null, null, null, null, null); if (client2tasks!=null) { client2tasks.unregister(null, null, null); client2tasks.register(client2username, client2password, null, null, null, null, null, null, null, null); } // unsubscribe from all consumed product subscriptions and then assemble a list of all SubscriptionPools clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions(); if (client2tasks!=null) { client2tasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions(); } // populate a list of all available SubscriptionPools for (SubscriptionPool pool : clienttasks.getCurrentlyAvailableSubscriptionPools()) { ll.add(Arrays.asList(new Object[]{pool})); // minimize the number of dataProvided rows (useful during automated testcase development) if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize","false"))) break; } // manually reorder the pools so that the base "Red Hat Enterprise Linux*" pool is first in the list // This is a workaround for InstallAndRemovePackageAfterSubscribingToPool_Test so as to avoid installing // a package from a repo that has a package dependency from a repo that is not yet entitled. int i=0; for (List<Object> list : ll) { if (((SubscriptionPool)(list.get(0))).subscriptionName.startsWith("Red Hat Enterprise Linux")) { ll.remove(i); ll.add(0, list); break; } i++; } return ll; } @DataProvider(name="getSystemSubscriptionPoolProductData") public Object[][] getSystemSubscriptionPoolProductDataAs2dArray() throws JSONException { return TestNGUtils.convertListOfListsTo2dArray(getSystemSubscriptionPoolProductDataAsListOfLists()); } protected List<List<Object>> getSystemSubscriptionPoolProductDataAsListOfLists() throws JSONException { List<List<Object>> ll = new ArrayList<List<Object>>(); for (int j=0; j<systemSubscriptionPoolProductData.length(); j++) { JSONObject poolProductDataAsJSONObject = (JSONObject) systemSubscriptionPoolProductData.get(j); String systemProductId = poolProductDataAsJSONObject.getString("systemProductId"); JSONArray bundledProductDataAsJSONArray = poolProductDataAsJSONObject.getJSONArray("bundledProductData"); // String systemProductId, JSONArray bundledProductDataAsJSONArray ll.add(Arrays.asList(new Object[]{systemProductId, bundledProductDataAsJSONArray})); // minimize the number of dataProvided rows (useful during automated testcase development) if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize","false"))) break; } return ll; } @DataProvider(name="getUsernameAndPasswordData") public Object[][] getUsernameAndPasswordDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getUsernameAndPasswordDataAsListOfLists()); } protected List<List<Object>> getUsernameAndPasswordDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String[] usernames = clientUsernames.split(","); String[] passwords = clientPasswords.split(","); String password = passwords[0].trim(); for (int i = 0; i < usernames.length; i++) { String username = usernames[i].trim(); // when there is not a 1:1 relationship between usernames and passwords, the last password is repeated // this allows one to specify only one password when all the usernames share the same password if (i<passwords.length) password = passwords[i].trim(); ll.add(Arrays.asList(new Object[]{username,password})); } return ll; } @DataProvider(name="getAllConsumedProductSubscriptionsData") public Object[][] getAllConsumedProductSubscriptionsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getAllConsumedProductSubscriptionsDataAsListOfLists()); } protected List<List<Object>> getAllConsumedProductSubscriptionsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (clienttasks==null) return ll; // first make sure we are subscribed to all pools clienttasks.unregister(null, null, null); clienttasks.register(clientusername,clientpassword,null,null,null,null, null, null, null, null); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(null); // then assemble a list of all consumed ProductSubscriptions for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) { ll.add(Arrays.asList(new Object[]{productSubscription})); // minimize the number of dataProvided rows (useful during automated testcase development) if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize","false"))) break; } return ll; } @DataProvider(name="getAllEntitlementCertsData") public Object[][] getAllEntitlementCertsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getAllEntitlementCertsDataAsListOfLists()); } protected List<List<Object>> getAllEntitlementCertsDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (clienttasks==null) return ll; // first make sure we are subscribed to all pools clienttasks.unregister(null, null, null); clienttasks.register(clientusername,clientpassword,null,null,null,null, null, null, null, null); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(null); // then assemble a list of all consumed ProductSubscriptions for (EntitlementCert entitlementCert : clienttasks.getCurrentEntitlementCerts()) { ll.add(Arrays.asList(new Object[]{entitlementCert})); // minimize the number of dataProvided rows (useful during automated testcase development) if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize","false"))) break; } return ll; } }
true
true
public void setupBeforeSuite() throws IOException { client = new SSHCommandRunner(clienthostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); clienttasks = new SubscriptionManagerTasks(client); client1 = client; client1tasks = clienttasks; File serverCaCertFile = null; List<File> generatedProductCertFiles = new ArrayList<File>(); // will we be connecting to the candlepin server? if (!serverHostname.equals("") && isServerOnPremises) { server = new SSHCommandRunner(serverHostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(server,serverInstallDir,isServerOnPremises); } else { log.info("Assuming the server is already setup and running."); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(null,null,isServerOnPremises); } // will we be testing multiple clients? if (!( client2hostname.equals("") /*|| client2username.equals("") || client2password.equals("")*/ )) { client2 = new SSHCommandRunner(client2hostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); client2tasks = new SubscriptionManagerTasks(client2); } else { log.info("Multi-client testing will be skipped."); } // setup the server if (server!=null && servertasks.isOnPremises) { // NOTE: After updating the candlepin.conf file, the server needs to be restarted, therefore this will not work against the Hosted IT server which we don't want to restart or deploy // I suggest manually setting this on hosted and asking calfanso to restart servertasks.updateConfigFileParameter("pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule","0 0\\/2 * * * ?"); // every 2 minutes servertasks.cleanOutCRL(); servertasks.deploy(serverHostname, serverImportDir,serverBranch); // also connect to the candlepin server database dbConnection = connectToDatabase(); // do this after the call to deploy since it will restart postgresql // fetch the candlepin CA Cert log.info("Fetching Candlepin CA cert..."); serverCaCertFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); RemoteFileTasks.getFile(server.getConnection(), serverCaCertFile.getParent(),servertasks.candlepinCACertFile.getPath()); // fetch the generated Product Certs log.info("Fetching the generated product certs..."); SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { File remoteFile = new File(remoteFileAsString); File localFile = new File("/tmp/"+remoteFile.getName()); RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); generatedProductCertFiles.add(localFile); } } // if clients are already registered from a prior run, unregister them unregisterClientsAfterSuite(); // setup the client(s) for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { if (smt==null) continue; smt.installSubscriptionManagerRPMs(rpmUrls,enableRepoForDeps); // rhsm.conf [server] configurations if (!serverHostname.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "hostname", serverHostname); else serverHostname = smt.getConfFileParameter(smt.rhsmConfFile, "hostname"); if (!serverPrefix.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "prefix", serverPrefix); else serverPrefix = smt.getConfFileParameter(smt.rhsmConfFile, "prefix"); if (!serverPort.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "port", serverPort); else serverPort = smt.getConfFileParameter(smt.rhsmConfFile, "port"); if (!serverInsecure.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "insecure", serverInsecure); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverSslVerifyDepth.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ssl_verify_depth", serverSslVerifyDepth); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverCaCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ca_cert_dir", serverCaCertDir); else serverCaCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "ca_cert_dir"); // rhsm.conf [rhsm] configurations if (!rhsmBaseUrl.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "baseurl", rhsmBaseUrl); else rhsmBaseUrl = smt.getConfFileParameter(smt.rhsmConfFile, "baseurl"); if (!rhsmRepoCaCert.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "repo_ca_cert", rhsmRepoCaCert); else rhsmRepoCaCert = smt.getConfFileParameter(smt.rhsmConfFile, "repo_ca_cert"); //if (!rhsmShowIncompatiblePools.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools", rhsmShowIncompatiblePools); else rhsmShowIncompatiblePools = smt.getConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools"); if (!rhsmProductCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "productCertDir", rhsmProductCertDir); else rhsmProductCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "productCertDir"); if (!rhsmEntitlementCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "entitlementCertDir", rhsmEntitlementCertDir); else rhsmEntitlementCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "entitlementCertDir"); if (!rhsmConsumerCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "consumerCertDir", rhsmConsumerCertDir); else rhsmConsumerCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "consumerCertDir"); // rhsm.conf [rhsmcertd] configurations if (!rhsmcertdCertFrequency.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "certFrequency", rhsmcertdCertFrequency); else rhsmcertdCertFrequency = smt.getConfFileParameter(smt.rhsmConfFile, "certFrequency"); smt.initializeFieldsFromConfigFile(); smt.removeAllCerts(true,true); smt.installRepoCaCerts(repoCaCertUrls); // transfer a copy of the candlepin CA Cert from the candlepin server to the clients so we can test in secure mode log.info("Copying Candlepin cert onto client to enable certificate validation..."); smt.installRepoCaCert(serverCaCertFile, serverHostname.split("\\.")[0]+"-"+servertasks.candlepinCACertFile.getName()); // transfer copies of all the generated product certs from the candlepin server to the clients log.info("Copying Candlepin generated product certs onto client to simulate installed products..."); smt.installProductCerts(generatedProductCertFiles); } // // transfer a copy of the CA Cert from the candlepin server to the clients so we can test in secure mode // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin cert onto clients to enable certificate validation..."); // File localFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),servertasks.candlepinCACertFile.getPath()); // // for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { // if (smt==null) continue; // smt.installRepoCaCert(localFile, serverHostname); // } // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.getConfFileParameter(client1tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // client1tasks.updateConfFileParameter(client1tasks.rhsmConfFile, "insecure", "0"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.getConfFileParameter(client2tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // if (client2!=null) client2tasks.updateConfFileParameter(client2tasks.rhsmConfFile, "insecure", "0"); // } // // transfer a copy of the generated product certs from the candlepin server to the clients so we can test // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin generated product certs onto clients to simulate installed products..."); // SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); // for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { // File remoteFile = new File(remoteFileAsString); // File localFile = new File("/tmp/"+remoteFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.productCertDir+"/", "0644"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.productCertDir+"/", "0644"); // } // } log.info("Installed version of candlepin..."); try { JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(serverHostname,serverPort,serverPrefix,"anybody","password","/status")); // seems to work no matter what credentials are passed log.info("Candlepin server '"+serverHostname+"' is running version: "+jsonStatus.get("version")); } catch (Exception e) { log.warning("Candlepin server '"+serverHostname+"' is running version: UNKNOWN"); } log.info("Installed version of subscription-manager..."); log.info("Subscription manager client '"+client1hostname+"' is running version: "+client1.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 if (client2!=null) log.info("Subscription manager client '"+client2hostname+"' is running version: "+client2.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 isSetupBeforeSuiteComplete = true; }
public void setupBeforeSuite() throws IOException { client = new SSHCommandRunner(clienthostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); clienttasks = new SubscriptionManagerTasks(client); client1 = client; client1tasks = clienttasks; File serverCaCertFile = null; List<File> generatedProductCertFiles = new ArrayList<File>(); // will we be connecting to the candlepin server? if (!serverHostname.equals("") && isServerOnPremises) { server = new SSHCommandRunner(serverHostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(server,serverInstallDir,isServerOnPremises); } else { log.info("Assuming the server is already setup and running."); servertasks = new com.redhat.qe.sm.cli.tasks.CandlepinTasks(null,null,isServerOnPremises); } // will we be testing multiple clients? if (!( client2hostname.equals("") /*|| client2username.equals("") || client2password.equals("")*/ )) { client2 = new SSHCommandRunner(client2hostname, sshUser, sshKeyPrivate, sshkeyPassphrase, null); client2tasks = new SubscriptionManagerTasks(client2); } else { log.info("Multi-client testing will be skipped."); } // setup the server if (server!=null && servertasks.isOnPremises) { // NOTE: After updating the candlepin.conf file, the server needs to be restarted, therefore this will not work against the Hosted IT server which we don't want to restart or deploy // I suggest manually setting this on hosted and asking calfanso to restart servertasks.updateConfigFileParameter("pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule","0 0\\/2 * * * ?"); // every 2 minutes servertasks.cleanOutCRL(); servertasks.deploy(serverHostname, serverImportDir,serverBranch); // also connect to the candlepin server database dbConnection = connectToDatabase(); // do this after the call to deploy since it will restart postgresql // fetch the candlepin CA Cert log.info("Fetching Candlepin CA cert..."); serverCaCertFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); RemoteFileTasks.getFile(server.getConnection(), serverCaCertFile.getParent(),servertasks.candlepinCACertFile.getPath()); // fetch the generated Product Certs log.info("Fetching the generated product certs..."); SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { File remoteFile = new File(remoteFileAsString); File localFile = new File("/tmp/"+remoteFile.getName()); RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); generatedProductCertFiles.add(localFile); } } // if clients are already registered from a prior run, unregister them unregisterClientsAfterSuite(); // setup the client(s) for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { if (smt==null) continue; smt.installSubscriptionManagerRPMs(rpmUrls,enableRepoForDeps); // rhsm.conf [server] configurations if (!serverHostname.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "hostname", serverHostname); else serverHostname = smt.getConfFileParameter(smt.rhsmConfFile, "hostname"); if (!serverPrefix.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "prefix", serverPrefix); else serverPrefix = smt.getConfFileParameter(smt.rhsmConfFile, "prefix"); if (!serverPort.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "port", serverPort); else serverPort = smt.getConfFileParameter(smt.rhsmConfFile, "port"); if (!serverInsecure.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "insecure", serverInsecure); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverSslVerifyDepth.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ssl_verify_depth", serverSslVerifyDepth); else serverInsecure = smt.getConfFileParameter(smt.rhsmConfFile, "insecure"); if (!serverCaCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "ca_cert_dir", serverCaCertDir); else serverCaCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "ca_cert_dir"); // rhsm.conf [rhsm] configurations if (!rhsmBaseUrl.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "baseurl", rhsmBaseUrl); else rhsmBaseUrl = smt.getConfFileParameter(smt.rhsmConfFile, "baseurl"); if (!rhsmRepoCaCert.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "repo_ca_cert", rhsmRepoCaCert); else rhsmRepoCaCert = smt.getConfFileParameter(smt.rhsmConfFile, "repo_ca_cert"); //if (!rhsmShowIncompatiblePools.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools", rhsmShowIncompatiblePools); else rhsmShowIncompatiblePools = smt.getConfFileParameter(smt.rhsmConfFile, "showIncompatiblePools"); if (!rhsmProductCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "productCertDir", rhsmProductCertDir); else rhsmProductCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "productCertDir"); if (!rhsmEntitlementCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "entitlementCertDir", rhsmEntitlementCertDir); else rhsmEntitlementCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "entitlementCertDir"); if (!rhsmConsumerCertDir.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "consumerCertDir", rhsmConsumerCertDir); else rhsmConsumerCertDir = smt.getConfFileParameter(smt.rhsmConfFile, "consumerCertDir"); // rhsm.conf [rhsmcertd] configurations if (!rhsmcertdCertFrequency.equals("")) smt.updateConfFileParameter(smt.rhsmConfFile, "certFrequency", rhsmcertdCertFrequency); else rhsmcertdCertFrequency = smt.getConfFileParameter(smt.rhsmConfFile, "certFrequency"); smt.initializeFieldsFromConfigFile(); smt.removeAllCerts(true,true); smt.installRepoCaCerts(repoCaCertUrls); // transfer a copy of the candlepin CA Cert from the candlepin server to the clients so we can test in secure mode log.info("Copying Candlepin cert onto client to enable certificate validation..."); smt.installRepoCaCert(serverCaCertFile, serverHostname.split("\\.")[0]+"-"+servertasks.candlepinCACertFile.getName().split("\\.")[0]+".pem"); // transfer copies of all the generated product certs from the candlepin server to the clients log.info("Copying Candlepin generated product certs onto client to simulate installed products..."); smt.installProductCerts(generatedProductCertFiles); } // // transfer a copy of the CA Cert from the candlepin server to the clients so we can test in secure mode // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin cert onto clients to enable certificate validation..."); // File localFile = new File("/tmp/"+servertasks.candlepinCACertFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),servertasks.candlepinCACertFile.getPath()); // // for (SubscriptionManagerTasks smt : new SubscriptionManagerTasks[]{client2tasks, client1tasks}) { // if (smt==null) continue; // smt.installRepoCaCert(localFile, serverHostname); // } // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.getConfFileParameter(client1tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // client1tasks.updateConfFileParameter(client1tasks.rhsmConfFile, "insecure", "0"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.getConfFileParameter(client2tasks.rhsmConfFile,"ca_cert_dir").trim().replaceFirst("/$", "")+"/"+serverHostname.split("\\.")[0]+"-candlepin-ca.pem", "0644"); // if (client2!=null) client2tasks.updateConfFileParameter(client2tasks.rhsmConfFile, "insecure", "0"); // } // // transfer a copy of the generated product certs from the candlepin server to the clients so we can test // if (server!=null && servertasks.isOnPremises) { // log.info("Copying Candlepin generated product certs onto clients to simulate installed products..."); // SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(server, "find "+serverInstallDir+servertasks.generatedProductsDir+" -name '*.pem'", 0); // for (String remoteFileAsString : result.getStdout().trim().split("\\n")) { // File remoteFile = new File(remoteFileAsString); // File localFile = new File("/tmp/"+remoteFile.getName()); // RemoteFileTasks.getFile(server.getConnection(), localFile.getParent(),remoteFile.getPath()); // // RemoteFileTasks.putFile(client1.getConnection(), localFile.getPath(), client1tasks.productCertDir+"/", "0644"); // if (client2!=null) RemoteFileTasks.putFile(client2.getConnection(), localFile.getPath(), client2tasks.productCertDir+"/", "0644"); // } // } log.info("Installed version of candlepin..."); try { JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(serverHostname,serverPort,serverPrefix,"anybody","password","/status")); // seems to work no matter what credentials are passed log.info("Candlepin server '"+serverHostname+"' is running version: "+jsonStatus.get("version")); } catch (Exception e) { log.warning("Candlepin server '"+serverHostname+"' is running version: UNKNOWN"); } log.info("Installed version of subscription-manager..."); log.info("Subscription manager client '"+client1hostname+"' is running version: "+client1.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 if (client2!=null) log.info("Subscription manager client '"+client2hostname+"' is running version: "+client2.runCommandAndWait("rpm -q subscription-manager").getStdout()); // subscription-manager-0.63-1.el6.i686 isSetupBeforeSuiteComplete = true; }
diff --git a/src/main/java/net/pms/encoders/FFmpegWebVideo.java b/src/main/java/net/pms/encoders/FFmpegWebVideo.java index 959d93afc..fbc27a7af 100644 --- a/src/main/java/net/pms/encoders/FFmpegWebVideo.java +++ b/src/main/java/net/pms/encoders/FFmpegWebVideo.java @@ -1,430 +1,430 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008-2012 A.Brochard * * 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; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import com.sun.jna.Platform; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JComponent; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; import net.pms.external.ExternalFactory; import net.pms.external.URLResolver.URLResult; import net.pms.io.OutputParams; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.util.PlayerUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FFmpegWebVideo extends FFMpegVideo { private static final Logger LOGGER = LoggerFactory.getLogger(FFmpegWebVideo.class); private static List<String> protocols; public static PatternMap<Object> excludes = new PatternMap<>(); public static PatternMap<ArrayList> autoOptions = new PatternMap<ArrayList>() { private static final long serialVersionUID = 5225786297932747007L; @Override public ArrayList add(String key, Object value) { return put(key, (ArrayList) parseOptions((String) value)); } }; public static PatternMap<String> replacements = new PatternMap<>(); private static boolean init = false; // FIXME we have an id() accessor for this; no need for the field to be public @Deprecated public static final String ID = "ffmpegwebvideo"; @Override public JComponent config() { return null; } @Override public String id() { return ID; } @Override public int purpose() { return VIDEO_WEBSTREAM_PLAYER; } @Override public boolean isTimeSeekable() { return false; } @Deprecated public FFmpegWebVideo(PmsConfiguration configuration) { super(configuration); if (!init) { readWebFilters(configuration.getProfileDirectory() + File.separator + "ffmpeg.webfilters"); protocols = FFmpegOptions.getSupportedProtocols(configuration); // see XXX workaround below protocols.add("mms"); protocols.add("https"); LOGGER.debug("FFmpeg supported protocols: " + protocols); init = true; } } public FFmpegWebVideo() { if (!init) { readWebFilters(configuration.getProfileDirectory() + File.separator + "ffmpeg.webfilters"); protocols = FFmpegOptions.getSupportedProtocols(configuration); // see XXX workaround below protocols.add("mms"); protocols.add("https"); LOGGER.debug("FFmpeg supported protocols: " + protocols); init = true; } } @Override public synchronized ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; RendererConfiguration renderer = params.mediaRenderer; String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); // XXX work around an ffmpeg bug: http://ffmpeg.org/trac/ffmpeg/ticket/998 if (filename.startsWith("mms:")) { filename = "mmsh:" + filename.substring(4); } // check if we have modifier for this url String r = replacements.match(filename); if (r != null) { filename = filename.replaceAll(r, replacements.get(r)); LOGGER.debug("modified url: " + filename); } FFmpegOptions customOptions = new FFmpegOptions(); // Gather custom options from various sources in ascending priority: // - automatic options String match = autoOptions.match(filename); if (match != null) { List<String> opts = autoOptions.get(match); if (opts != null) { customOptions.addAll(opts); } } // - (http) header options if (params.header != null && params.header.length > 0) { String hdr = new String(params.header); customOptions.addAll(parseOptions(hdr)); } // - attached options String attached = (String) dlna.getAttachment(ID); if (attached != null) { customOptions.addAll(parseOptions(attached)); } // - renderer options if (StringUtils.isNotEmpty(renderer.getCustomFFmpegOptions())) { customOptions.addAll(parseOptions(renderer.getCustomFFmpegOptions())); } // basename of the named pipe: // ffmpeg -loglevel warning -threads nThreads -i URL -threads nThreads -transcode-video-options /path/to/fifoName String fifoName = String.format( "ffmpegwebvideo_%d_%d", Thread.currentThread().getId(), System.currentTimeMillis() ); // This process wraps the command that creates the named pipe PipeProcess pipe = new PipeProcess(fifoName); pipe.deleteLater(); // delete the named pipe later; harmless if it isn't created ProcessWrapper mkfifo_process = pipe.getPipeProcess(); /** * It can take a long time for Windows to create a named pipe (and * mkfifo can be slow if /tmp isn't memory-mapped), so run this in * the current thread. */ mkfifo_process.runInSameThread(); params.input_pipes[0] = pipe; // Build the command line List<String> cmdList = new ArrayList<>(); if (!dlna.isURLResolved()) { URLResult r1 = ExternalFactory.resolveURL(filename); if (r1 != null) { if (r1.precoder != null) { filename = "-"; if (Platform.isWindows()) { cmdList.add("cmd.exe"); cmdList.add("/C"); } cmdList.addAll(r1.precoder); cmdList.add("|"); } else { if (StringUtils.isNotEmpty(r1.url)) { filename = r1.url; } } if (r1.args != null && r1.args.size() > 0) { customOptions.addAll(r1.args); } } } - cmdList.add(executable().replace("/", "\\\\")); + cmdList.add(executable()); // XXX squashed bug - without this, ffmpeg hangs waiting for a confirmation // that it can write to a file that already exists i.e. the named pipe cmdList.add("-y"); cmdList.add("-loglevel"); if (LOGGER.isTraceEnabled()) { // Set -loglevel in accordance with LOGGER setting cmdList.add("info"); // Could be changed to "verbose" or "debug" if "info" level is not enough } else { cmdList.add("warning"); } int nThreads = configuration.getNumberOfCpuCores(); // Decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add global and input-file custom options, if any if (!customOptions.isEmpty()) { customOptions.transferGlobals(cmdList); customOptions.transferInputFileOptions(cmdList); } if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + (int) params.timeseek); } cmdList.add("-i"); cmdList.add(filename); cmdList.addAll(getVideoFilterOptions(dlna, media, params)); // Encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add the output options (-f, -c:a, -c:v, etc.) cmdList.addAll(getVideoTranscodeOptions(dlna, media, params)); // Add video bitrate options cmdList.addAll(getVideoBitrateOptions(dlna, media, params)); // Add audio bitrate options cmdList.addAll(getAudioBitrateOptions(dlna, media, params)); // Add any remaining custom options if (!customOptions.isEmpty()) { customOptions.transferAll(cmdList); } // Output file cmdList.add(pipe.getInputPipe()); // Convert the command list to an array String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); // Hook to allow plugins to customize this command line cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); // Now launch FFmpeg ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(mkfifo_process); // Clean up the mkfifo process when the transcode ends // Give the mkfifo process a little time try { Thread.sleep(300); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for named pipe to be created", e); } // Launch the transcode command... pw.runInNewThread(); // ...and wait briefly to allow it to start try { Thread.sleep(200); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for transcode to start", e); } return pw; } @Override public String name() { return "FFmpeg Web Video"; } // TODO remove this when it's removed from Player @Deprecated @Override public String[] args() { return null; } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { if (PlayerUtil.isWebVideo(resource)) { String url = resource.getSystemName(); return protocols.contains(url.split(":")[0]) && excludes.match(url) == null; } return false; } public boolean readWebFilters(String filename) { PatternMap filter = null; String line; try { LineIterator it = FileUtils.lineIterator(new File(filename)); try { while (it.hasNext()) { line = it.nextLine().trim(); if (line.isEmpty() || line.startsWith("#")) { // continue } else if (line.equals("EXCLUDE")) { filter = excludes; } else if (line.equals("OPTIONS")) { filter = autoOptions; } else if (line.equals("REPLACE")) { filter = replacements; } else if (filter != null) { String[] var = line.split(" \\| ", 2); filter.add(var[0], var.length > 1 ? var[1] : null); } } return true; } finally { it.close(); } } catch (Exception e) { LOGGER.debug("Error reading ffmpeg web filters: " + e.getLocalizedMessage()); } return false; } } // A self-combining map of regexes that recompiles if modified class PatternMap<T> extends modAwareHashMap<String, T> { private static final long serialVersionUID = 3096452459003158959L; Matcher combo; List<String> groupmap = new ArrayList<>(); public T add(String key, Object value) { return put(key, (T) value); } // Returns the first matching regex String match(String str) { if (!isEmpty()) { if (modified) { compile(); } if (combo.reset(str).find()) { for (int i = 0; i < combo.groupCount(); i++) { if (combo.group(i + 1) != null) { return groupmap.get(i); } } } } return null; } void compile() { String joined = ""; groupmap.clear(); for (String regex : this.keySet()) { // add each regex as a capture group joined += "|(" + regex + ")"; // map all subgroups to the parent for (int i = 0; i < Pattern.compile(regex).matcher("").groupCount() + 1; i++) { groupmap.add(regex); } } // compile the combined regex combo = Pattern.compile(joined.substring(1)).matcher(""); modified = false; } } // A HashMap that reports whether it's been modified // (necessary because 'modCount' isn't accessible outside java.util) class modAwareHashMap<K, V> extends HashMap<K, V> { private static final long serialVersionUID = -5334451082377480129L; public boolean modified = false; @Override public void clear() { modified = true; super.clear(); } @Override public V put(K key, V value) { modified = true; return super.put(key, value); } @Override public V remove(Object key) { modified = true; return super.remove(key); } }
true
true
public synchronized ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; RendererConfiguration renderer = params.mediaRenderer; String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); // XXX work around an ffmpeg bug: http://ffmpeg.org/trac/ffmpeg/ticket/998 if (filename.startsWith("mms:")) { filename = "mmsh:" + filename.substring(4); } // check if we have modifier for this url String r = replacements.match(filename); if (r != null) { filename = filename.replaceAll(r, replacements.get(r)); LOGGER.debug("modified url: " + filename); } FFmpegOptions customOptions = new FFmpegOptions(); // Gather custom options from various sources in ascending priority: // - automatic options String match = autoOptions.match(filename); if (match != null) { List<String> opts = autoOptions.get(match); if (opts != null) { customOptions.addAll(opts); } } // - (http) header options if (params.header != null && params.header.length > 0) { String hdr = new String(params.header); customOptions.addAll(parseOptions(hdr)); } // - attached options String attached = (String) dlna.getAttachment(ID); if (attached != null) { customOptions.addAll(parseOptions(attached)); } // - renderer options if (StringUtils.isNotEmpty(renderer.getCustomFFmpegOptions())) { customOptions.addAll(parseOptions(renderer.getCustomFFmpegOptions())); } // basename of the named pipe: // ffmpeg -loglevel warning -threads nThreads -i URL -threads nThreads -transcode-video-options /path/to/fifoName String fifoName = String.format( "ffmpegwebvideo_%d_%d", Thread.currentThread().getId(), System.currentTimeMillis() ); // This process wraps the command that creates the named pipe PipeProcess pipe = new PipeProcess(fifoName); pipe.deleteLater(); // delete the named pipe later; harmless if it isn't created ProcessWrapper mkfifo_process = pipe.getPipeProcess(); /** * It can take a long time for Windows to create a named pipe (and * mkfifo can be slow if /tmp isn't memory-mapped), so run this in * the current thread. */ mkfifo_process.runInSameThread(); params.input_pipes[0] = pipe; // Build the command line List<String> cmdList = new ArrayList<>(); if (!dlna.isURLResolved()) { URLResult r1 = ExternalFactory.resolveURL(filename); if (r1 != null) { if (r1.precoder != null) { filename = "-"; if (Platform.isWindows()) { cmdList.add("cmd.exe"); cmdList.add("/C"); } cmdList.addAll(r1.precoder); cmdList.add("|"); } else { if (StringUtils.isNotEmpty(r1.url)) { filename = r1.url; } } if (r1.args != null && r1.args.size() > 0) { customOptions.addAll(r1.args); } } } cmdList.add(executable().replace("/", "\\\\")); // XXX squashed bug - without this, ffmpeg hangs waiting for a confirmation // that it can write to a file that already exists i.e. the named pipe cmdList.add("-y"); cmdList.add("-loglevel"); if (LOGGER.isTraceEnabled()) { // Set -loglevel in accordance with LOGGER setting cmdList.add("info"); // Could be changed to "verbose" or "debug" if "info" level is not enough } else { cmdList.add("warning"); } int nThreads = configuration.getNumberOfCpuCores(); // Decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add global and input-file custom options, if any if (!customOptions.isEmpty()) { customOptions.transferGlobals(cmdList); customOptions.transferInputFileOptions(cmdList); } if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + (int) params.timeseek); } cmdList.add("-i"); cmdList.add(filename); cmdList.addAll(getVideoFilterOptions(dlna, media, params)); // Encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add the output options (-f, -c:a, -c:v, etc.) cmdList.addAll(getVideoTranscodeOptions(dlna, media, params)); // Add video bitrate options cmdList.addAll(getVideoBitrateOptions(dlna, media, params)); // Add audio bitrate options cmdList.addAll(getAudioBitrateOptions(dlna, media, params)); // Add any remaining custom options if (!customOptions.isEmpty()) { customOptions.transferAll(cmdList); } // Output file cmdList.add(pipe.getInputPipe()); // Convert the command list to an array String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); // Hook to allow plugins to customize this command line cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); // Now launch FFmpeg ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(mkfifo_process); // Clean up the mkfifo process when the transcode ends // Give the mkfifo process a little time try { Thread.sleep(300); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for named pipe to be created", e); } // Launch the transcode command... pw.runInNewThread(); // ...and wait briefly to allow it to start try { Thread.sleep(200); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for transcode to start", e); } return pw; }
public synchronized ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { params.minBufferSize = params.minFileSize; params.secondread_minsize = 100000; RendererConfiguration renderer = params.mediaRenderer; String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); // XXX work around an ffmpeg bug: http://ffmpeg.org/trac/ffmpeg/ticket/998 if (filename.startsWith("mms:")) { filename = "mmsh:" + filename.substring(4); } // check if we have modifier for this url String r = replacements.match(filename); if (r != null) { filename = filename.replaceAll(r, replacements.get(r)); LOGGER.debug("modified url: " + filename); } FFmpegOptions customOptions = new FFmpegOptions(); // Gather custom options from various sources in ascending priority: // - automatic options String match = autoOptions.match(filename); if (match != null) { List<String> opts = autoOptions.get(match); if (opts != null) { customOptions.addAll(opts); } } // - (http) header options if (params.header != null && params.header.length > 0) { String hdr = new String(params.header); customOptions.addAll(parseOptions(hdr)); } // - attached options String attached = (String) dlna.getAttachment(ID); if (attached != null) { customOptions.addAll(parseOptions(attached)); } // - renderer options if (StringUtils.isNotEmpty(renderer.getCustomFFmpegOptions())) { customOptions.addAll(parseOptions(renderer.getCustomFFmpegOptions())); } // basename of the named pipe: // ffmpeg -loglevel warning -threads nThreads -i URL -threads nThreads -transcode-video-options /path/to/fifoName String fifoName = String.format( "ffmpegwebvideo_%d_%d", Thread.currentThread().getId(), System.currentTimeMillis() ); // This process wraps the command that creates the named pipe PipeProcess pipe = new PipeProcess(fifoName); pipe.deleteLater(); // delete the named pipe later; harmless if it isn't created ProcessWrapper mkfifo_process = pipe.getPipeProcess(); /** * It can take a long time for Windows to create a named pipe (and * mkfifo can be slow if /tmp isn't memory-mapped), so run this in * the current thread. */ mkfifo_process.runInSameThread(); params.input_pipes[0] = pipe; // Build the command line List<String> cmdList = new ArrayList<>(); if (!dlna.isURLResolved()) { URLResult r1 = ExternalFactory.resolveURL(filename); if (r1 != null) { if (r1.precoder != null) { filename = "-"; if (Platform.isWindows()) { cmdList.add("cmd.exe"); cmdList.add("/C"); } cmdList.addAll(r1.precoder); cmdList.add("|"); } else { if (StringUtils.isNotEmpty(r1.url)) { filename = r1.url; } } if (r1.args != null && r1.args.size() > 0) { customOptions.addAll(r1.args); } } } cmdList.add(executable()); // XXX squashed bug - without this, ffmpeg hangs waiting for a confirmation // that it can write to a file that already exists i.e. the named pipe cmdList.add("-y"); cmdList.add("-loglevel"); if (LOGGER.isTraceEnabled()) { // Set -loglevel in accordance with LOGGER setting cmdList.add("info"); // Could be changed to "verbose" or "debug" if "info" level is not enough } else { cmdList.add("warning"); } int nThreads = configuration.getNumberOfCpuCores(); // Decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add global and input-file custom options, if any if (!customOptions.isEmpty()) { customOptions.transferGlobals(cmdList); customOptions.transferInputFileOptions(cmdList); } if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + (int) params.timeseek); } cmdList.add("-i"); cmdList.add(filename); cmdList.addAll(getVideoFilterOptions(dlna, media, params)); // Encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); // Add the output options (-f, -c:a, -c:v, etc.) cmdList.addAll(getVideoTranscodeOptions(dlna, media, params)); // Add video bitrate options cmdList.addAll(getVideoBitrateOptions(dlna, media, params)); // Add audio bitrate options cmdList.addAll(getAudioBitrateOptions(dlna, media, params)); // Add any remaining custom options if (!customOptions.isEmpty()) { customOptions.transferAll(cmdList); } // Output file cmdList.add(pipe.getInputPipe()); // Convert the command list to an array String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); // Hook to allow plugins to customize this command line cmdArray = finalizeTranscoderArgs( filename, dlna, media, params, cmdArray ); // Now launch FFmpeg ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); pw.attachProcess(mkfifo_process); // Clean up the mkfifo process when the transcode ends // Give the mkfifo process a little time try { Thread.sleep(300); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for named pipe to be created", e); } // Launch the transcode command... pw.runInNewThread(); // ...and wait briefly to allow it to start try { Thread.sleep(200); } catch (InterruptedException e) { LOGGER.error("Thread interrupted while waiting for transcode to start", e); } return pw; }
diff --git a/ZKDLComponentsHibernateExt/src/main/java/cz/datalite/zk/components/list/filter/compilers/BooleanCriterionCompiler.java b/ZKDLComponentsHibernateExt/src/main/java/cz/datalite/zk/components/list/filter/compilers/BooleanCriterionCompiler.java index eb33db4..f1f2849 100644 --- a/ZKDLComponentsHibernateExt/src/main/java/cz/datalite/zk/components/list/filter/compilers/BooleanCriterionCompiler.java +++ b/ZKDLComponentsHibernateExt/src/main/java/cz/datalite/zk/components/list/filter/compilers/BooleanCriterionCompiler.java @@ -1,78 +1,78 @@ /** * Copyright 19.3.11 (c) DataLite, spol. s r.o. All rights reserved. * Web: http://www.datalite.cz Mail: [email protected] */ package cz.datalite.zk.components.list.filter.compilers; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; /** * Default implementation for boolean compiler. * * For boolean values it behavies as expected. * For String values (from QuickFilter): * for a, ano, y, yes, true it compiles true condition * for n, ne, no, false it compiles false condition * @author Jiri Bubnik <bubnik at datalite cz> */ public class BooleanCriterionCompiler extends FilterCriterionCompiler { @Override protected Criterion compileOperatorEqual( final String key, final Object... values ) { final Object value = values[0]; if ( value != null && value instanceof String ) { // input from Quick Filter final String val = ( String ) value; if ( val.equalsIgnoreCase("a") || val.equalsIgnoreCase("ano") || val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("true")) { return compile( key, true ); } else if ( val.equalsIgnoreCase("n") || val.equalsIgnoreCase("ne") || val.equalsIgnoreCase("no") || val.equalsIgnoreCase("false")) { - return Restrictions.sqlRestriction( "1=1" ); + return Restrictions.sqlRestriction( "1=0" ); } else { - return Restrictions.sqlRestriction( "1=0" ); + return Restrictions.sqlRestriction( "1=1" ); } } else if ( (value instanceof Boolean) || (Boolean.TYPE.equals( value.getClass() )) ) { // input from checkbox return compile( key, ( Boolean ) value ); } else { return Restrictions.sqlRestriction( "1=0" ); } } @Override protected Criterion compileOperatorNotEqual( final String key, final Object... values ) { return compile( key, !( Boolean ) values[0] ); } protected Criterion compile( final String key, final boolean value ) { return Restrictions.eq( key, value ); // Special class needs to be created if mapped by character // if ( value ) { // return Restrictions.or( Restrictions.eq( key, "Y"), Restrictions.eq( key, "A")); // } else { // return Restrictions.not ( Restrictions.or( Restrictions.eq( key, "Y"), Restrictions.eq( key, "A")) ); // } } /** * Boolena compiler can work with boolean value or a String (for quick filter). * * @param value the value for filter * @return true if null, String or boolean */ public boolean validateValue(Object value) { if (value == null) return true; else if (value instanceof String) return true; else if ( (value instanceof Boolean) || (Boolean.TYPE.equals( value.getClass() )) ) return true; else return false; } }
false
true
protected Criterion compileOperatorEqual( final String key, final Object... values ) { final Object value = values[0]; if ( value != null && value instanceof String ) { // input from Quick Filter final String val = ( String ) value; if ( val.equalsIgnoreCase("a") || val.equalsIgnoreCase("ano") || val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("true")) { return compile( key, true ); } else if ( val.equalsIgnoreCase("n") || val.equalsIgnoreCase("ne") || val.equalsIgnoreCase("no") || val.equalsIgnoreCase("false")) { return Restrictions.sqlRestriction( "1=1" ); } else { return Restrictions.sqlRestriction( "1=0" ); } } else if ( (value instanceof Boolean) || (Boolean.TYPE.equals( value.getClass() )) ) { // input from checkbox return compile( key, ( Boolean ) value ); } else { return Restrictions.sqlRestriction( "1=0" ); } }
protected Criterion compileOperatorEqual( final String key, final Object... values ) { final Object value = values[0]; if ( value != null && value instanceof String ) { // input from Quick Filter final String val = ( String ) value; if ( val.equalsIgnoreCase("a") || val.equalsIgnoreCase("ano") || val.equalsIgnoreCase("y") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("true")) { return compile( key, true ); } else if ( val.equalsIgnoreCase("n") || val.equalsIgnoreCase("ne") || val.equalsIgnoreCase("no") || val.equalsIgnoreCase("false")) { return Restrictions.sqlRestriction( "1=0" ); } else { return Restrictions.sqlRestriction( "1=1" ); } } else if ( (value instanceof Boolean) || (Boolean.TYPE.equals( value.getClass() )) ) { // input from checkbox return compile( key, ( Boolean ) value ); } else { return Restrictions.sqlRestriction( "1=0" ); } }
diff --git a/jsword/java/jsword/org/crosswire/jsword/book/search/parse/CustomTokenizer.java b/jsword/java/jsword/org/crosswire/jsword/book/search/parse/CustomTokenizer.java index 143059d0..10bf21e9 100644 --- a/jsword/java/jsword/org/crosswire/jsword/book/search/parse/CustomTokenizer.java +++ b/jsword/java/jsword/org/crosswire/jsword/book/search/parse/CustomTokenizer.java @@ -1,211 +1,211 @@ package org.crosswire.jsword.book.search.parse; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.crosswire.jsword.book.BookException; /** * Our command line parsing is a little specialized, so StringTokenizer is not * up to the job. The specific problem is that there is sometimes no separator * between parts of the command, and since this is specialized we also leave the * results in a Vector of SearchWords. * * <p><table border='1' cellPadding='3' cellSpacing='0'> * <tr><td bgColor='white' class='TableRowColor'><font size='-7'> * * Distribution Licence:<br /> * JSword is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License, * version 2 as published by the Free Software Foundation.<br /> * 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.<br /> * The License is available on the internet * <a href='http://www.gnu.org/copyleft/gpl.html'>here</a>, or by writing to: * Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA<br /> * The copyright to this program is held by it's authors. * </font></td></tr></table> * @see gnu.gpl.Licence * @author Joe Walker [joe at eireneh dot com] * @version $Id$ */ public class CustomTokenizer { /** * Prevent Instansiation */ private CustomTokenizer() { } /** * Convenience method to generate a Vector of SearchWords * @param sought The text to parse * @param commands The Hashtable of SearchWords to select from * @return A List of selected SearchWords */ public static List tokenize(String sought, Map commands) throws BookException { List output = new ArrayList(); String commandChars = getSingleCharWords(commands); char firstChar = sought.charAt(0); int currentType = charType(firstChar, commandChars); int startIndex = 0; // If the first character is a [ or : then we have a problem because // the loop starts with the second character because it needs // something to compare with - so if we do start with a [ or : then // we make sure that we prepend with a " " if (sought.length() > 0 && (firstChar == '[' || firstChar == ':')) { sought = ' ' + sought; } // Loop, comparing each character with the previous one for (int i = 1; i <= sought.length(); i++) { // An escaped section if (i != sought.length() && sought.charAt(i) == '[') { int end = sought.indexOf(']', i); if (end == -1) { throw new BookException(Msg.UNMATCHED_ESCAPE); } addWord(output, commands, "["); //$NON-NLS-1$ addWord(output, commands, sought.substring(i + 1, end)); addWord(output, commands, "]"); //$NON-NLS-1$ currentType = CHAR_SPACE; i = end + 1; } // Pass through everything between pairs of :: e.g. ::bread:: // as a single word. If there is no trailing :: take it // to the end of the line - if (i < sought.length() - 4 && sought.indexOf("::", i) == i) //$NON-NLS-1$ + if (i != sought.length() && sought.indexOf("::", i) == i) //$NON-NLS-1$ { int end = sought.indexOf("::", i + 2); //$NON-NLS-1$ if (end == -1) { addWord(output, commands, sought.substring(i + 2)); i = sought.length(); } else { - addWord(output, commands, sought.substring(i + 1, end)); + addWord(output, commands, sought.substring(i + 2, end)); i = end + 2; } currentType = CHAR_SPACE; } // If this is the last word then so long as this letter is not // a space (in which case it has been added already) then add all // the word in if (i == sought.length()) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex)); } } else { // If this is the start of a new section of the command // then add the word in int new_type = charType(sought.charAt(i), commandChars); if (currentType != new_type || new_type == CHAR_COMMAND) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex, i)); } startIndex = i; currentType = charType(sought.charAt(i), commandChars); } } } return output; } /** * What class of character is this? * @param sought The string to be searched for * @return The chatacter class */ private static final int charType(char sought, String commands) { if (Character.isWhitespace(sought)) { return CHAR_SPACE; } if (commands.indexOf(sought) != -1) { return CHAR_COMMAND; } return CHAR_PARAM; } /** * Convenience function to add a Word to the Vector being created. * @param output The Vector to alter * @param commands The Word source * @param word The trigger to look for */ private static void addWord(List output, Map commands, String word) { Object wordObj = commands.get(word); if (wordObj == null) { wordObj = new DefaultWord(word); } output.add(wordObj); } /** * Convenience function to add a Word to the Vector being created. * @param commands The Word source */ private static String getSingleCharWords(Map commands) { Iterator it = commands.keySet().iterator(); StringBuffer buf = new StringBuffer(); while (it.hasNext()) { String cmd = (String) it.next(); if (cmd.length() == 1) { buf.append(cmd); } } return buf.toString(); } /** * The type of character (see charType) */ private static final int CHAR_PARAM = 0; /** * The type of character (see charType) */ private static final int CHAR_COMMAND = 1; /** * The type of character (see charType) */ private static final int CHAR_SPACE = 2; }
false
true
public static List tokenize(String sought, Map commands) throws BookException { List output = new ArrayList(); String commandChars = getSingleCharWords(commands); char firstChar = sought.charAt(0); int currentType = charType(firstChar, commandChars); int startIndex = 0; // If the first character is a [ or : then we have a problem because // the loop starts with the second character because it needs // something to compare with - so if we do start with a [ or : then // we make sure that we prepend with a " " if (sought.length() > 0 && (firstChar == '[' || firstChar == ':')) { sought = ' ' + sought; } // Loop, comparing each character with the previous one for (int i = 1; i <= sought.length(); i++) { // An escaped section if (i != sought.length() && sought.charAt(i) == '[') { int end = sought.indexOf(']', i); if (end == -1) { throw new BookException(Msg.UNMATCHED_ESCAPE); } addWord(output, commands, "["); //$NON-NLS-1$ addWord(output, commands, sought.substring(i + 1, end)); addWord(output, commands, "]"); //$NON-NLS-1$ currentType = CHAR_SPACE; i = end + 1; } // Pass through everything between pairs of :: e.g. ::bread:: // as a single word. If there is no trailing :: take it // to the end of the line if (i < sought.length() - 4 && sought.indexOf("::", i) == i) //$NON-NLS-1$ { int end = sought.indexOf("::", i + 2); //$NON-NLS-1$ if (end == -1) { addWord(output, commands, sought.substring(i + 2)); i = sought.length(); } else { addWord(output, commands, sought.substring(i + 1, end)); i = end + 2; } currentType = CHAR_SPACE; } // If this is the last word then so long as this letter is not // a space (in which case it has been added already) then add all // the word in if (i == sought.length()) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex)); } } else { // If this is the start of a new section of the command // then add the word in int new_type = charType(sought.charAt(i), commandChars); if (currentType != new_type || new_type == CHAR_COMMAND) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex, i)); } startIndex = i; currentType = charType(sought.charAt(i), commandChars); } } } return output; }
public static List tokenize(String sought, Map commands) throws BookException { List output = new ArrayList(); String commandChars = getSingleCharWords(commands); char firstChar = sought.charAt(0); int currentType = charType(firstChar, commandChars); int startIndex = 0; // If the first character is a [ or : then we have a problem because // the loop starts with the second character because it needs // something to compare with - so if we do start with a [ or : then // we make sure that we prepend with a " " if (sought.length() > 0 && (firstChar == '[' || firstChar == ':')) { sought = ' ' + sought; } // Loop, comparing each character with the previous one for (int i = 1; i <= sought.length(); i++) { // An escaped section if (i != sought.length() && sought.charAt(i) == '[') { int end = sought.indexOf(']', i); if (end == -1) { throw new BookException(Msg.UNMATCHED_ESCAPE); } addWord(output, commands, "["); //$NON-NLS-1$ addWord(output, commands, sought.substring(i + 1, end)); addWord(output, commands, "]"); //$NON-NLS-1$ currentType = CHAR_SPACE; i = end + 1; } // Pass through everything between pairs of :: e.g. ::bread:: // as a single word. If there is no trailing :: take it // to the end of the line if (i != sought.length() && sought.indexOf("::", i) == i) //$NON-NLS-1$ { int end = sought.indexOf("::", i + 2); //$NON-NLS-1$ if (end == -1) { addWord(output, commands, sought.substring(i + 2)); i = sought.length(); } else { addWord(output, commands, sought.substring(i + 2, end)); i = end + 2; } currentType = CHAR_SPACE; } // If this is the last word then so long as this letter is not // a space (in which case it has been added already) then add all // the word in if (i == sought.length()) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex)); } } else { // If this is the start of a new section of the command // then add the word in int new_type = charType(sought.charAt(i), commandChars); if (currentType != new_type || new_type == CHAR_COMMAND) { if (currentType != CHAR_SPACE) { addWord(output, commands, sought.substring(startIndex, i)); } startIndex = i; currentType = charType(sought.charAt(i), commandChars); } } } return output; }
diff --git a/src/simple/home/jtbuaa/simpleHome.java b/src/simple/home/jtbuaa/simpleHome.java index a2993a4..00f8cd8 100644 --- a/src/simple/home/jtbuaa/simpleHome.java +++ b/src/simple/home/jtbuaa/simpleHome.java @@ -1,1687 +1,1691 @@ package simple.home.jtbuaa; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Random; import easy.lib.util; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.CallLog.Calls; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.telephony.TelephonyManager; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; class wrapWallpaperManager { Object mInstance; public static void checkAvailable() {} static Method getWallpaperManagerMethod = null; static Method setWallpaperOffsetsMethod = null; static Method setBitmapMethod = null; static Method suggestDesiredDimensionsMethod = null; static { try { Class c = Class.forName("android.app.WallpaperManager"); getWallpaperManagerMethod = c.getMethod("getInstance", new Class[] { Context.class });// api 5 setWallpaperOffsetsMethod = c.getMethod("setWallpaperOffsets", new Class[] { IBinder.class, float.class, float.class });// api 5 setBitmapMethod = c.getMethod("setBitmap", new Class[] { Bitmap.class });//api 5 suggestDesiredDimensionsMethod = c.getMethod("suggestDesiredDimensions", new Class[] { int.class, int.class });//api 5 } catch (Exception ex) { throw new RuntimeException(ex); } } void getInstance(Context context) { if (getWallpaperManagerMethod != null) try {mInstance = getWallpaperManagerMethod.invoke(context, context);} catch (Exception e) {mInstance = null;} } void setWallpaperOffsets(IBinder token, float x, float y) { if (setWallpaperOffsetsMethod != null) try {setWallpaperOffsetsMethod.invoke(mInstance, token, x, y);} catch (Exception e) {} } void setBitmap(Bitmap bitmap) { if (setBitmapMethod != null) try {setBitmapMethod.invoke(mInstance, bitmap);} catch (Exception e) {} } void suggestDesiredDimensions(int x, int y) { if (suggestDesiredDimensionsMethod != null) try {suggestDesiredDimensionsMethod.invoke(mInstance, x, y);} catch (Exception e) {} } } public class simpleHome extends Activity implements SensorEventListener, sizedRelativeLayout.OnResizeChangeListener { int homeTab = 1; boolean paid;//paid or not AlertDialog restartDialog = null; AlertDialog hintDialog = null; //wall paper related String downloadPath; SensorManager sensorMgr; Sensor mSensor; float last_x, last_y, last_z; long lastUpdate, lastSet; ArrayList<String> picList, picList_selected; boolean shakeWallpaper = false; boolean busy; SharedPreferences perferences; String wallpaperFile = ""; AppAlphaList sysAlphaList, userAlphaList; PkgAlphaList packageAlphaList; //alpha list related TextView radioText; RadioGroup radioGroup; //app list related private List<View> mListViews; GridView favoAppList; ListView sysAppList, userAppList, shortAppList; ImageView homeBar, shortBar; String version, myPackageName; ViewPager mainlayout; MyPagerAdapter myPagerAdapter; RelativeLayout home; ResolveInfo appDetail; List<ResolveInfo> mAllApps, mFavoApps, mSysApps, mUserApps, mShortApps; PackageManager pm; favoAppAdapter favoAdapter; shortAppAdapter shortAdapter; ResolveInfo ri_phone, ri_sms, ri_contact; CallObserver callObserver; SmsChangeObserver smsObserver; ImageView shortcut_phone, shortcut_sms, shortcut_contact; sizedRelativeLayout base; RelativeLayout apps; RelativeLayout shortcutBar_center; appHandler mAppHandler = new appHandler(); final static int UPDATE_RI_PHONE = 0, UPDATE_RI_SMS = 1, UPDATE_RI_CONTACT = 2, UPDATE_USER = 3, UPDATE_SPLASH = 4, UPDATE_PACKAGE = 5; ContextMenu mMenu; ricase selected_case; boolean canRoot; DisplayMetrics dm; IBinder token; //package size related HashMap<String, Object> packagesSize; Method getPackageSizeInfo; IPackageStatsObserver sizeObserver; static int sizeM = 1024*1024; static public com.android.internal.telephony.ITelephony getITelephony(TelephonyManager telMgr) throws Exception { Method getITelephonyMethod = telMgr.getClass().getDeclaredMethod("getITelephony"); getITelephonyMethod.setAccessible(true);//私有化函数也能使用 return (com.android.internal.telephony.ITelephony)getITelephonyMethod.invoke(telMgr); } wrapWallpaperManager mWallpaperManager; static boolean wallpaperManagerAvaiable; static { try { wrapWallpaperManager.checkAvailable(); wallpaperManagerAvaiable = true; } catch (Throwable t) { wallpaperManagerAvaiable = false; } } Context mContext; static Method overridePendingTransitionMethod = null; static { try {//API 5 overridePendingTransitionMethod = Activity.class.getMethod("overridePendingTransition", new Class[] { int.class, int.class });//api 5 } catch (Exception e) {} } void invokeOverridePendingTransition() { if (overridePendingTransitionMethod != null) try {overridePendingTransitionMethod.invoke(mContext, 0, 0);} catch (Exception e) {} } class MyPagerAdapter extends PagerAdapter{ @Override public void destroyItem(View collection, int arg1, Object view) { ((ViewPager) collection).removeView((View) view); } @Override public void finishUpdate(View arg0) { } @Override public int getCount() { return mListViews.size(); } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(mListViews.get(arg1), 0); return mListViews.get(arg1); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0==(arg1); } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } @Override public int getItemPosition(Object object) { return POSITION_NONE; } } @Override protected void onResume() { if (sysAlphaList.appToDel != null) { String apkToDel = sysAlphaList.appToDel.activityInfo.applicationInfo.sourceDir; String res = ShellInterface.doExec(new String[] {"ls /data/data/" + sysAlphaList.appToDel.activityInfo.packageName}, true); if (res.contains("No such file or directory")) {//uninstalled String[] cmds = { "rm " + apkToDel + ".bak", "rm " + apkToDel.replace(".apk", ".odex")}; ShellInterface.doExec(cmds); } else ShellInterface.doExec(new String[] {"mv " + apkToDel + ".bak " + apkToDel}); sysAlphaList.appToDel = null; } shakeWallpaper = perferences.getBoolean("shake", false); if (shakeWallpaper) { sensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI); busy = false; } else { sensorMgr.unregisterListener(this); } super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, 0, 0, R.string.wallpaper).setIcon(android.R.drawable.ic_menu_gallery).setAlphabeticShortcut('W'); menu.add(0, 1, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences) .setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS)); menu.add(0, 2, 0, R.string.help).setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('H'); return true; } public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case 0://wallpaper final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); util.startActivity(Intent.createChooser(pickWallpaper, getString(R.string.wallpaper)), true, getBaseContext()); break; case 1://settings return super.onOptionsItemSelected(item); case 2://help dialog Intent intent = new Intent("simple.home.jtbuaa.about"); intent.putExtra("version", version); intent.putExtra("filename", wallpaperFile); util.startActivity(intent, false, getBaseContext()); break; } return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); selected_case = (ricase) v.getTag(); switch (selected_case.mCase) { case 0://on home menu.add(0, 0, 0, getString(R.string.removeFromFavo)); break; case 1://on shortcut menu.add(0, 1, 0, getString(R.string.removeFromShort)); break; case 2://on app list if (mainlayout.getCurrentItem() == sysAlphaList.index) { if (sysAlphaList.mIsGrid) menu.add(0, 8, 0, getString(R.string.list_view)); else menu.add(0, 8, 0, getString(R.string.grid_view)); } else if (mainlayout.getCurrentItem() == userAlphaList.index) { if (userAlphaList.mIsGrid) menu.add(0, 8, 0, getString(R.string.list_view)); else menu.add(0, 8, 0, getString(R.string.grid_view)); } menu.add(0, 7, 0, getString(R.string.hideapp)); menu.add(0, 4, 0, getString(R.string.appdetail)); menu.add(0, 5, 0, getString(R.string.addtoFavo)); menu.add(0, 6, 0, getString(R.string.addtoShort)); mMenu = menu; break; case 3://on package list if (paid) { if (packageAlphaList.mIsGrid) menu.add(0, 8, 0, getString(R.string.list_view)); else menu.add(0, 8, 0, getString(R.string.grid_view)); } menu.add(0, 10, 0, getString(R.string.hidepage)); menu.add(0, 9, 0, getString(R.string.appdetail)); } } void writeFile(String name) { try { FileOutputStream fo = this.openFileOutput(name, 0); ObjectOutputStream oos = new ObjectOutputStream(fo); if (name.equals("short")) { for (int i = 0; i < mShortApps.size(); i++) oos.writeObject(((ResolveInfo)mShortApps.get(i)).activityInfo.name); } else if (name.equals("favo")) { for (int i = 0; i < mFavoApps.size(); i++) oos.writeObject(((ResolveInfo)mFavoApps.get(i)).activityInfo.name); } oos.flush(); oos.close(); fo.close(); } catch (Exception e) {} } boolean backup(String sourceDir) {//copy file to sdcard String apk = sourceDir.split("/")[sourceDir.split("/").length-1]; FileOutputStream fos; FileInputStream fis; String filename = downloadPath + "apk/" + apk; try { File target = new File(filename); fos = new FileOutputStream(target, false); fis = new FileInputStream(sourceDir); byte buf[] = new byte[10240]; int readLength = 0; while((readLength = fis.read(buf))>0){ fos.write(buf, 0, readLength); } fos.close(); fis.close(); } catch (Exception e) { hintDialog.setMessage(e.toString()); hintDialog.show(); return false; } return true; } public boolean onContextItemSelected(MenuItem item){ super.onContextItemSelected(item); ResolveInfo info = null; if (item.getItemId() < 8) info = (ResolveInfo) selected_case.mRi; switch (item.getItemId()) { case 0://remove from home favoAdapter.remove(info); writeFile("favo"); break; case 1://remove from shortcut shortAdapter.remove(info); writeFile("short"); //save shortcut to file break; case 4://get app detail info showDetail(info.activityInfo.applicationInfo.sourceDir, info.activityInfo.packageName, info.loadLabel(pm), info.loadIcon(pm)); break; case 5://add to home if (favoAdapter.getPosition(info) < 0) { favoAdapter.add(info); writeFile("favo"); } break; case 6://add to shortcut if (shortAdapter.getPosition(info) < 0) { shortAdapter.insert(info, 0); writeFile("short"); //save shortcut to file } break; case 7://hide the ri if (mainlayout.getCurrentItem() == sysAlphaList.index) { sysAlphaList.remove(info.activityInfo.packageName); } else { userAlphaList.remove(info.activityInfo.packageName); } refreshRadioButton(); break; case 8://switch view restartDialog.show(); return true;//break can't finish on some device? case 9://get package detail info PackageInfo pi = (PackageInfo) selected_case.mRi; showDetail(pi.applicationInfo.sourceDir, pi.packageName, pi.applicationInfo.loadLabel(pm), pi.applicationInfo.loadIcon(pm)); break; case 10://hide current page if (mainlayout.getCurrentItem() == sysAlphaList.index) sysAlphaList.mApps.clear(); else if (mainlayout.getCurrentItem() == userAlphaList.index) userAlphaList.mApps.clear(); else if (mainlayout.getCurrentItem() == packageAlphaList.index) packageAlphaList.mApps.clear(); refreshRadioButton(); break; } return false; } void showDetail(final String sourceDir, final String packageName, final CharSequence label, Drawable icon) { AlertDialog detailDlg = new AlertDialog.Builder(this). setTitle(label). setIcon(icon). setMessage(packageName + "\n\n" + sourceDir). setPositiveButton(R.string.share, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, R.string.share); String text = label + getString(R.string.app_share_text) + "http://bpc.borqs.com/market.html?id=" + packageName; intent.putExtra(Intent.EXTRA_TEXT, text); util.startActivity(Intent.createChooser(intent, getString(R.string.sharemode)), true, getBaseContext()); } }).setNeutralButton(R.string.backapp, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String apk = sourceDir.split("/")[sourceDir.split("/").length-1]; if (backup(sourceDir)) { String odex = sourceDir.replace(".apk", ".odex"); File target = new File(odex); boolean backupOdex = true; if (target.exists()) if (!backup(odex)) backupOdex = false;//backup odex if any if (backupOdex) { hintDialog.setMessage(getString(R.string.backapp) + " " + label + " to " + downloadPath + "apk/" + apk); hintDialog.show(); } } } }). setNegativeButton(R.string.more, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { Intent intent; if (appDetail != null) { intent = new Intent(Intent.ACTION_VIEW); intent.setClassName(appDetail.activityInfo.packageName, appDetail.activityInfo.name); intent.putExtra("pkg", packageName); intent.putExtra("com.android.settings.ApplicationPkgName", packageName); } else {//2.6 tahiti change the action. intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", Uri.fromParts("package", packageName, null)); } util.startActivity(intent, true, getBaseContext()); } }).create(); boolean canBackup = !downloadPath.startsWith(getFilesDir().getPath()); detailDlg.show(); detailDlg.getButton(DialogInterface.BUTTON_NEUTRAL).setEnabled(canBackup);//not backup if no SDcard. } @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*//splash screen Thread splashTimer=new Thread() { public void run(){ try{ long curTime = System.currentTimeMillis(); while (System.currentTimeMillis() - curTime < 3000) { sleep(1000);//wait for 1000ms } Message msg = mAppHandler.obtainMessage(); msg.what = UPDATE_SPLASH; mAppHandler.sendMessage(msg);//inform UI thread to update UI. } catch(Exception ex){ } } }; splashTimer.start();*/ paid = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("paid", false); myPackageName = this.getPackageName(); pm = getPackageManager(); version = util.getVersion(this); try { getPackageSizeInfo = PackageManager.class.getMethod( "getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class}); } catch (Exception e) { e.printStackTrace(); } sizeObserver = new IPackageStatsObserver.Stub() { @Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException { long size = pStats.codeSize; String ssize = new String(); if (size > 10 * sizeM) ssize = size / sizeM + "M"; else if (size > 10 * 1024) ssize = size / 1024 + "K"; else if (size > 0) ssize = size + "B"; else ssize = ""; packagesSize.put(pStats.packageName, ssize); } }; packagesSize = new HashMap<String, Object>(); sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); perferences = PreferenceManager.getDefaultSharedPreferences(this); dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); //1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively. //int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; //if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen. //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout setContentView(R.layout.ads); home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null); //favorite app tab favoAppList = (GridView) home.findViewById(R.id.favos); favoAppList.setVerticalScrollBarEnabled(false); favoAppList.inflate(this, R.layout.app_list, null); favoAppList.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { shortAppList.setVisibility(View.INVISIBLE); return false; } }); shortAppList = (ListView) home.findViewById(R.id.business); shortAppList.bringToFront(); shortAppList.setVisibility(View.INVISIBLE); boolean isGrid = perferences.getBoolean("system", true); sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); isGrid = perferences.getBoolean("user", false); userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); if (paid) { isGrid = perferences.getBoolean("package", true); packageAlphaList = new PkgAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);//package tab } mListViews = new ArrayList<View>(); mListViews.add(sysAlphaList.view); sysAlphaList.index = 0; mListViews.add(home); mListViews.add(userAlphaList.view); userAlphaList.index = 2; if (paid) { mListViews.add(packageAlphaList.view); packageAlphaList.index = 3; } radioText = (TextView) findViewById(R.id.radio_text); radioGroup = (RadioGroup) findViewById(R.id.radio_hint); if (!paid) radioGroup.removeViewAt(0); if (wallpaperManagerAvaiable) { mWallpaperManager = new wrapWallpaperManager(); mWallpaperManager.getInstance(mContext); } mainlayout = (ViewPager)findViewById(R.id.mainFrame); mainlayout.setLongClickable(true); myPagerAdapter = new MyPagerAdapter(); mainlayout.setAdapter(myPagerAdapter); mainlayout.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_SETTLING) { refreshRadioButton(); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok mWallpaperManager.setWallpaperOffsets(token, //when slide from home to systems or from systems to home, the "position" is 0, //when slide from home to users or from users to home, it is 1. //positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0. //so we can unify it to (0, 1) by (positionOffset+position)/2 (positionOffset+position)/(mListViews.size()-1), 0); } } @Override public void onPageSelected(int arg0) { } }); mainlayout.setCurrentItem(homeTab); mSysApps = new ArrayList<ResolveInfo>(); mUserApps = new ArrayList<ResolveInfo>(); mFavoApps = new ArrayList<ResolveInfo>(); mShortApps = new ArrayList<ResolveInfo>(); favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps); favoAppList.setAdapter(favoAdapter); base = (sizedRelativeLayout) home.findViewById(R.id.base); base.setResizeListener(this); shortcutBar_center = (RelativeLayout) home.findViewById(R.id.shortcut_bar_center); homeBar = (ImageView) home.findViewById(R.id.home_bar); homeBar.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("harley.browsers", "easy.lib.SimpleBrowser"); if (!util.startActivity(intent, false, getBaseContext())) { - intent.setClassName(myPackageName, "easy.lib.SimpleBrowser"); - util.startActivity(intent, true, getBaseContext()); + intent.setClassName("easy.browser", "easy.lib.SimpleBrowser"); + if (!util.startActivity(intent, false, getBaseContext())) { + intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers")); + //intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field + util.startActivity(intent, true, getBaseContext()); + } } } }); shortBar = (ImageView) home.findViewById(R.id.business_bar); shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout @Override public void onClick(View arg0) { if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty()) shortAppList.setVisibility(View.VISIBLE); else shortAppList.setVisibility(View.INVISIBLE); } }); setLayout(dm.widthPixels); shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone); shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms); //shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact); //for package add/remove IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); registerReceiver(packageReceiver, filter); //for wall paper changed filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED); registerReceiver(wallpaperReceiver, filter); filter = new IntentFilter("simpleHome.action.HOME_CHANGED"); registerReceiver(homeChangeReceiver, filter); filter = new IntentFilter("simpleHome.action.PIC_ADDED"); registerReceiver(picAddReceiver, filter); filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP"); registerReceiver(deskShareReceiver, filter); filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addDataScheme("file"); registerReceiver(sdcardListener, filter); apps = (RelativeLayout) findViewById(R.id.apps); //mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer? //TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE); //getITelephony(tm).getActivePhoneType(); ContentResolver cr = getContentResolver(); callObserver = new CallObserver(cr, mAppHandler); smsObserver = new SmsChangeObserver(cr, mAppHandler); getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver); cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver); //task for init, such as load webview, load package list InitTask initTask = new InitTask(); initTask.execute(""); Context mContext = this; restartDialog = new AlertDialog.Builder(this). setTitle(R.string.app_name). setIcon(R.drawable.icon). setMessage(R.string.restart). setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //save the layout SharedPreferences.Editor editor = perferences.edit(); if (mainlayout.getCurrentItem() == sysAlphaList.index) editor.putBoolean("system", !sysAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == userAlphaList.index) editor.putBoolean("user", !userAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == packageAlphaList.index) editor.putBoolean("package", !packageAlphaList.mIsGrid); editor.commit(); //restart the activity. note if set singleinstance or singletask of activity, below will not work on some device. Intent intent = getIntent(); invokeOverridePendingTransition(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); finish(); invokeOverridePendingTransition(); startActivity(intent); } }). setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); hintDialog = new AlertDialog.Builder(this). setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); } @Override protected void onDestroy() { unregisterReceiver(packageReceiver); unregisterReceiver(wallpaperReceiver); unregisterReceiver(picAddReceiver); unregisterReceiver(deskShareReceiver); unregisterReceiver(homeChangeReceiver); unregisterReceiver(sdcardListener); super.onDestroy(); } BroadcastReceiver sdcardListener = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(Intent.ACTION_MEDIA_MOUNTED.equals(action) || Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action) || Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action) ){// SD卡成功挂载 if (downloadPath != null) downloadPath = Environment.getExternalStorageDirectory() + "/simpleHome/"; if (mMenu != null) mMenu.getItem(3).setEnabled(true); } else if(Intent.ACTION_MEDIA_REMOVED.equals(action) || Intent.ACTION_MEDIA_UNMOUNTED.equals(action) || Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action) ){// SD卡挂载失败 if (downloadPath != null) downloadPath = getFilesDir().getPath() + "/"; if (mMenu != null) mMenu.getItem(3).setEnabled(false); } } }; BroadcastReceiver wallpaperReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { apps.setBackgroundColor(0);//set back ground to transparent to show wallpaper wallpaperFile = ""; } }; BroadcastReceiver picAddReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String picName = intent.getStringExtra("picFile"); picList.add(picName);//add to picture list SharedPreferences.Editor editor = perferences.edit(); editor.putBoolean("shake_enabled", true); editor.commit(); } }; BroadcastReceiver deskShareReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String snap = downloadPath + "snap/snap.png"; FileOutputStream fos; try {//prepare for share desktop fos = new FileOutputStream(snap); apps.setDrawingCacheEnabled(true); Bitmap bmp = apps.getDrawingCache(); bmp.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); apps.destroyDrawingCache(); } catch (Exception e) { } Intent intentSend = new Intent(Intent.ACTION_SEND); intentSend.setType("image/*"); intentSend.putExtra(Intent.EXTRA_SUBJECT, R.string.share); intentSend.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(downloadPath + "snap/snap.png"))); util.startActivity(Intent.createChooser(intentSend, getString(R.string.sharemode)), true, getBaseContext()); } }; BroadcastReceiver homeChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String homeName = intent.getStringExtra("old_home"); if(homeName.equals(myPackageName)) finish(); } }; void refreshRadioButton() { int count = sysAlphaList.getCount(); if (count == 0) { if (sysAlphaList.index > -1) {//should hide it if it is visiable mListViews.remove(sysAlphaList.index); sysAlphaList.index = -1; if (userAlphaList.index > -1) userAlphaList.index -= 1; if ((paid) && (packageAlphaList.index > -1)) packageAlphaList.index -= 1; } } else if (sysAlphaList.index == -1) {//show it if it was hided. sysAlphaList.index = 0; mListViews.add(sysAlphaList.index, sysAlphaList.view); if (userAlphaList.index > -1) userAlphaList.index += 1; if ((paid) && (packageAlphaList.index > -1)) packageAlphaList.index += 1; } count = userAlphaList.getCount(); if (count == 0) { if (userAlphaList.index > -1) {//should hide it if it is visiable mListViews.remove(userAlphaList.index); userAlphaList.index = -1; if ((paid) && (packageAlphaList.index > -1)) packageAlphaList.index -= 1; } } else if (userAlphaList.index == -1) {//show it if it was hided. userAlphaList.index = 2+sysAlphaList.index; mListViews.add(userAlphaList.index, userAlphaList.view); if ((paid) && (packageAlphaList.index > -1)) packageAlphaList.index += 1; } if (paid) { count = packageAlphaList.getCount(); if (count == 0) { if (packageAlphaList.index > -1) {//should hide it if it is visiable mListViews.remove(packageAlphaList.index); packageAlphaList.index = -1; } } else if (packageAlphaList.index == -1) {//show it if it was hided. int tmp = 0; if (userAlphaList.index < 0) tmp += userAlphaList.index; packageAlphaList.index = 3 + sysAlphaList.index + tmp; mListViews.add(packageAlphaList.index, packageAlphaList.view); } } //myPagerAdapter.notifyDataSetChanged();//this will flash the screen? if (sysAlphaList.index > -1) homeTab = 1; else homeTab = 0; while (radioGroup.getChildCount() < myPagerAdapter.getCount()+1) { RadioButton view = new RadioButton(getBaseContext()); view.setButtonDrawable(R.drawable.radio); view.setChecked(false); radioGroup.addView(view, 0); } while (radioGroup.getChildCount() > myPagerAdapter.getCount()+1) radioGroup.removeViewAt(0); int current = mainlayout.getCurrentItem(); radioGroup.clearCheck(); if (current < radioGroup.getChildCount()) ((RadioButton) radioGroup.getChildAt(current)).setChecked(true);// crash once for ClassCastException. if (current == sysAlphaList.index) radioText.setText(getString(R.string.systemapps) + "(" + sysAlphaList.getCount() + ")"); else if (current == userAlphaList.index) radioText.setText(getString(R.string.userapps) + "(" + userAlphaList.getCount() + ")"); else if ((paid) && (current == packageAlphaList.index)) radioText.setText("service/provider (" + packageAlphaList.getCount() + ")"); else radioText.setText("Home"); } BroadcastReceiver packageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); String packageName = intent.getDataString().split(":")[1];//it always in the format of package:x.y.z if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { ResolveInfo info = userAlphaList.remove(packageName); if (info == null) info = sysAlphaList.remove(packageName); refreshRadioButton(); if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {//not remove shortcut if it is just replace for (int i = 0; i < favoAdapter.getCount(); i++) { info = favoAdapter.getItem(i); if (info.activityInfo.packageName.equals(packageName)) { favoAdapter.remove(info); writeFile("favo"); break; } } for (int i = 0; i < shortAdapter.getCount(); i++) { info = shortAdapter.getItem(i); if (info.activityInfo.packageName.equals(packageName)) { shortAdapter.remove(info); writeFile("short"); break; } } } } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) { try {//get size of new installed package getPackageSizeInfo.invoke(pm, packageName, sizeObserver); } catch (Exception e) { e.printStackTrace(); } Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mainIntent.setPackage(packageName); List<ResolveInfo> targetApps = pm.queryIntentActivities(mainIntent, 0); for (int i = 0; i < targetApps.size(); i++) { if (targetApps.get(i).activityInfo.packageName.equals(packageName) ) {//the new package may not support Launcher category, we will omit it. ResolveInfo ri = targetApps.get(i); CharSequence sa = ri.loadLabel(pm); if (sa == null) sa = ri.activityInfo.name; ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label. String tmp = ri.activityInfo.applicationInfo.dataDir.substring(0, 1); if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) { sysAlphaList.add(ri); break; } else { userAlphaList.add(ri); break; } } } refreshRadioButton(); } } }; private class favoAppAdapter extends ArrayAdapter<ResolveInfo> { ArrayList<ResolveInfo> localApplist; public favoAppAdapter(Context context, List<ResolveInfo> apps) { super(context, 0, apps); localApplist = (ArrayList<ResolveInfo>) apps; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ResolveInfo info = (ResolveInfo) localApplist.get(position); if (convertView == null) { final LayoutInflater inflater = getLayoutInflater(); convertView = inflater.inflate(R.layout.favo_list, parent, false); } convertView.setBackgroundColor(0); final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon); btnIcon.setImageDrawable(info.loadIcon(pm)); btnIcon.setOnClickListener(new OnClickListener() {//start app @Override public void onClick(View arg0) { util.startApp(info, getBaseContext()); } }); btnIcon.setTag(new ricase(info, 0)); registerForContextMenu(btnIcon); return convertView; } } private class shortAppAdapter extends ArrayAdapter<ResolveInfo> { ArrayList<ResolveInfo> localApplist; public shortAppAdapter(Context context, List<ResolveInfo> apps) { super(context, 0, apps); localApplist = (ArrayList<ResolveInfo>) apps; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ResolveInfo info = (ResolveInfo) localApplist.get(position); if (convertView == null) { final LayoutInflater inflater = getLayoutInflater(); convertView = inflater.inflate(R.layout.favo_list, parent, false); } final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon); btnIcon.setImageDrawable(info.loadIcon(pm)); TextView appname = (TextView) convertView.findViewById(R.id.favoappname); appname.setText(info.loadLabel(pm)); convertView.setOnClickListener(new OnClickListener() {//launch app @Override public void onClick(View arg0) { util.startApp(info, getBaseContext()); shortAppList.setVisibility(View.INVISIBLE); } }); convertView.setTag(new ricase(info, 1)); registerForContextMenu(convertView); return convertView; } } void readFile(String name) { FileInputStream fi = null; ObjectInputStream ois = null; try {//read favorite or shortcut data fi = openFileInput(name); ois = new ObjectInputStream(fi); String activityName; while ((activityName = (String) ois.readObject()) != null) { for (int i = 0; i < mAllApps.size(); i++) if (mAllApps.get(i).activityInfo.name.equals(activityName)) { if (name.equals("favo")) mFavoApps.add(mAllApps.get(i)); else if (name.equals("short")) mShortApps.add(mAllApps.get(i)); break; } } } catch (EOFException e) {//only when read eof need send out msg. try { ois.close(); fi.close(); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } public String getToken(CharSequence sa) { String sa1 = sa.toString().trim(); String sa2 = sa1; if (sa1.length() > 0) { try {//this is to fix a bug report by market sa2 = easy.lib.HanziToPinyin.getInstance().getToken(sa1.charAt(0)).target.trim(); if (sa2.length() > 1) sa2 = sa2.substring(0, 1); } catch(Exception e) { e.printStackTrace(); } } sa2 = sa2.toUpperCase(); if ((sa2.compareTo("A") < 0) || (sa2.compareTo("Z") > 0)) sa2 = "#";//for space or number, we change to # return sa2; } class InitTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) {//do all time consuming work here canRoot = false; String res = ShellInterface.doExec(new String[] {"id"}, true); if (res.contains("root")) { res = ShellInterface.doExec(new String[] {"mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system"}, true); if (res.contains("Error")) canRoot = false; else canRoot = true; } Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mAllApps = pm.queryIntentActivities(mainIntent, 0); readFile("favo"); readFile("short"); boolean shortEmpty = mShortApps.isEmpty(); if (paid) { getHidePackages(); Message msgPkg = mAppHandler.obtainMessage(); msgPkg.what = UPDATE_PACKAGE; mAppHandler.sendMessage(msgPkg);//inform UI thread to update UI. } //read all resolveinfo String label_sms = "簡訊 Messaging Messages メッセージ 信息 消息 短信 메시지 Mensajes Messaggi Berichten SMS a MMS SMS/MMS"; //use label name to get short cut String label_phone = "電話 Phone 电话 电话和联系人 拨号键盘 키패드 Telefon Teléfono Téléphone Telefono Telefoon Телефон 휴대전화 Dialer"; String label_contact = "聯絡人 联系人 Contacts People 連絡先 通讯录 전화번호부 Kontakty Kontakte Contactos Contatti Contacten Контакты 주소록"; int match = 0; for (int i = 0; i < mAllApps.size(); i++) { ResolveInfo ri = mAllApps.get(i); CharSequence sa = ri.loadLabel(pm); if (sa == null) sa = ri.activityInfo.name; ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label. if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) { sysAlphaList.add(ri, false, false); if (match < 3) {//only find 3 match: sms, phone, contact String name = sa.toString() ; //Log.d("===============", name); if (label_phone.contains(name)) { if (ri_phone == null) { ri_phone = ri; Message msgphone = mAppHandler.obtainMessage(); msgphone.what = UPDATE_RI_PHONE; mAppHandler.sendMessage(msgphone);//inform UI thread to update UI. match += 1; } } else if (label_sms.contains(name)) { if ((ri_sms == null) && (!name.equals("MM"))) { ri_sms = ri; Message msgsms = mAppHandler.obtainMessage(); msgsms.what = UPDATE_RI_SMS; mAppHandler.sendMessage(msgsms);//inform UI thread to update UI. match += 1; } } else if ((shortEmpty) && label_contact.contains(name)) {//only add contact to shortcut if shortcut is empty. if (ri_contact == null) { mShortApps.add(ri); /*ri_contact = ri; Message msgcontact = mAppHandler.obtainMessage(); msgcontact.what = UPDATE_RI_CONTACT; mAppHandler.sendMessage(msgcontact);//inform UI thread to update UI.*/ match += 1; } } } } else userAlphaList.add(ri, false, false); try { getPackageSizeInfo.invoke(pm, ri.activityInfo.packageName, sizeObserver); } catch (Exception e) { e.printStackTrace(); } } sysAlphaList.sortAlpha(); userAlphaList.sortAlpha(); Message msguser = mAppHandler.obtainMessage(); msguser.what = UPDATE_USER; mAppHandler.sendMessage(msguser);//inform UI thread to update UI. downloadPath = util.preparePath(getBaseContext()); picList = new ArrayList(); picList_selected = new ArrayList(); new File(downloadPath).list(new OnlyPic()); if (picList.size() > 0) { SharedPreferences.Editor editor = perferences.edit(); editor.putBoolean("shake_enabled", true); editor.commit(); } mainIntent = new Intent(Intent.ACTION_VIEW, null); mainIntent.addCategory(Intent.CATEGORY_DEFAULT); List<ResolveInfo> viewApps = pm.queryIntentActivities(mainIntent, 0); appDetail = null; for (int i = 0; i < viewApps.size(); i++) { if (viewApps.get(i).activityInfo.name.contains("InstalledAppDetails")) { appDetail = viewApps.get(i);//get the activity for app detail setting break; } } return null; } } void getHidePackages() { List<PackageInfo> mPackages = pm.getInstalledPackages(0); int i = 0; while (i < mPackages.size()) { boolean found = false; for (int j = 0; j < mAllApps.size(); j++) { if (mAllApps.get(j).activityInfo.packageName.equals(mPackages.get(i).packageName)) { mPackages.remove(i);//remove duplicate package if already in app list found = true; break; } } if (!found) i += 1; } i = 0; while (i < mPackages.size()) { Intent intent = new Intent(); intent.setPackage(mPackages.get(i).packageName); List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); if (list.size() > 0) { //mAllApps.addAll(list); mAllApps.add(list.get(list.size()-1)); mPackages.remove(i); } else i += 1; } i = 0; while (i < mPackages.size()) { PackageInfo pi = mPackages.get(i); try {//get package size getPackageSizeInfo.invoke(pm, pi.packageName, sizeObserver); } catch (Exception e) { e.printStackTrace(); } if (pi.applicationInfo != null) { CharSequence sa = pi.applicationInfo.loadLabel(pm); if (sa == null) sa = pi.packageName; mPackages.get(i).sharedUserId = getToken(sa);//use sharedUserId to store alpha index } else mPackages.get(i).sharedUserId = pi.packageName; i += 1; } Collections.sort(mPackages, new PackageComparator());//sort by name packageAlphaList.mApps.addAll(mPackages); packageAlphaList.sortAlpha(); } class OnlyPic implements FilenameFilter { public boolean accept(File dir, String s) { String name = s.toLowerCase(); if (s.endsWith(".png") || s.endsWith(".jpg")) { picList.add(s); return true; } else return false; } } class appHandler extends Handler { public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_USER: sysAlphaList.setAdapter(); userAlphaList.setAdapter(); refreshRadioButton();//this will update the radio button with correct app number. only for very slow phone shortAdapter = new shortAppAdapter(getBaseContext(), mShortApps); shortAppList.setAdapter(shortAdapter); break; case UPDATE_PACKAGE: packageAlphaList.setAdapter(); break; case UPDATE_RI_PHONE: int missCallCount = callObserver.countUnread(); if (missCallCount > 0) { Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.phone); shortcut_phone.setImageBitmap(util.generatorCountIcon(bm, missCallCount, 1, getBaseContext())); } else shortcut_phone.setImageResource(R.drawable.phone); shortcut_phone.setOnClickListener(new OnClickListener() {//start app @Override public void onClick(View arg0) { util.startApp(ri_phone, getBaseContext()); } }); break; case UPDATE_RI_SMS: int unreadCount = smsObserver.countUnread(); if (unreadCount > 0) { Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.sms); shortcut_sms.setImageBitmap(util.generatorCountIcon(bm, unreadCount, 1, getBaseContext())); } else shortcut_sms.setImageResource(R.drawable.sms); shortcut_sms.setOnClickListener(new OnClickListener() {//start app @Override public void onClick(View arg0) { util.startApp(ri_sms, getBaseContext()); } }); break; case UPDATE_RI_CONTACT: shortcut_contact.setImageDrawable(ri_contact.loadIcon(pm)); shortcut_contact.setOnClickListener(new OnClickListener() {//start app @Override public void onClick(View arg0) { util.startApp(ri_contact, getBaseContext()); } }); break; /*case UPDATE_SPLASH: ImageView splash = (ImageView) findViewById(R.id.splash); splash.setVisibility(View.INVISIBLE); apps.setVisibility(View.VISIBLE); apps.bringToFront(); break;*/ } } }; @Override protected void onNewIntent(Intent intent) {//go back to home if press Home key. if ((intent.getAction().equals(Intent.ACTION_MAIN)) && (intent.hasCategory(Intent.CATEGORY_HOME))) { if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab); else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick(); } super.onNewIntent(intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getRepeatCount() == 0) { if (keyCode == KeyEvent.KEYCODE_BACK) {//press Back key in webview will go backword. if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab); else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick(); else this.openOptionsMenu(); return true; } } return false; } void setLayout(int width) { if (width < 100) return;//can't work on so small screen. LayoutParams lp = shortcutBar_center.getLayoutParams(); if (width > 600) lp.width = width/2-100; else if (width > 320) lp.width = width/2-25; else lp.width = width/2-15; lp = shortAppList.getLayoutParams(); if (width/2 - 140 > 200) lp.width = width/2 - 140; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); //not restart activity each time screen orientation changes getWindowManager().getDefaultDisplay().getMetrics(dm); setLayout(dm.widthPixels); if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { } @Override public void onSensorChanged(SensorEvent arg0) { if (arg0.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { long curTime = System.currentTimeMillis(); // 每100毫秒检测一次 if ((curTime - lastUpdate) > 100) { long timeInterval = (curTime - lastUpdate); lastUpdate = curTime; float x = arg0.values[SensorManager.DATA_X]; float y = arg0.values[SensorManager.DATA_Y]; float z = arg0.values[SensorManager.DATA_Z]; float deltaX = x - last_x; float deltaY = y - last_y; float deltaZ = z - last_z; double speed = Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ)/timeInterval * 100; //condition to change wallpaper: speed is enough; frequency is not too high; picList is not empty. if ((!busy) && (speed > 8) && (curTime - lastSet > 500) && (picList != null) && (picList.size() > 0)) { busy = true; Random random = new Random(); int id = random.nextInt(picList.size()); try { wallpaperFile = downloadPath + picList.get(id); BitmapDrawable bd = (BitmapDrawable) BitmapDrawable.createFromPath(wallpaperFile); double factor = 1.0 * bd.getIntrinsicWidth() / bd.getIntrinsicHeight(); if (factor >= 1.2) {//if too wide, we want use setWallpaperOffsets to move it, so we need set it to wallpaper int tmpWidth = (int) (dm.heightPixels * factor); mWallpaperManager.setBitmap(Bitmap.createScaledBitmap(bd.getBitmap(), tmpWidth, dm.heightPixels, false)); mWallpaperManager.suggestDesiredDimensions(tmpWidth, dm.heightPixels); sensorMgr.unregisterListener(this); SharedPreferences.Editor editor = perferences.edit(); shakeWallpaper = false; editor.putBoolean("shake", false); editor.commit(); } else {//otherwise just change the background is ok. ClippedDrawable cd = new ClippedDrawable(bd, apps.getWidth(), apps.getHeight()); apps.setBackgroundDrawable(cd); } picList_selected.add(picList.get(id)); picList.remove(id);//prevent it be selected again before a full cycle lastSet = System.currentTimeMillis(); } catch (Exception e) { e.printStackTrace(); picList.remove(id); wallpaperFile = ""; } if (picList.isEmpty()) { if (picList_selected.isEmpty()) { sensorMgr.unregisterListener(this); SharedPreferences.Editor editor = perferences.edit(); editor.putBoolean("shake_enabled", false); shakeWallpaper = false; editor.putBoolean("shake", false); editor.commit(); } else { picList = (ArrayList<String>) picList_selected.clone(); picList_selected.clear(); } } busy = false; } last_x = x; last_y = y; last_z = z; } } } @Override public void onSizeChanged(int w, int h, int oldW, int oldH) { //setLayout(oldW); } } /** from Android Home sample * When a drawable is attached to a View, the View gives the Drawable its dimensions * by calling Drawable.setBounds(). In this application, the View that draws the * wallpaper has the same size as the screen. However, the wallpaper might be larger * that the screen which means it will be automatically stretched. Because stretching * a bitmap while drawing it is very expensive, we use a ClippedDrawable instead. * This drawable simply draws another wallpaper but makes sure it is not stretched * by always giving it its intrinsic dimensions. If the wallpaper is larger than the * screen, it will simply get clipped but it won't impact performance. */ class ClippedDrawable extends Drawable { private final Drawable mWallpaper; int screenWidth, screenHeight; boolean tooWide = false; public ClippedDrawable(Drawable wallpaper, int sw, int sh) { mWallpaper = wallpaper; screenWidth = sw; screenHeight = sh; } @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); // Ensure the wallpaper is as large as it really is, to avoid stretching it at drawing time int tmpHeight = mWallpaper.getIntrinsicHeight() * screenWidth / mWallpaper.getIntrinsicWidth(); int tmpWidth = mWallpaper.getIntrinsicWidth() * screenHeight / mWallpaper.getIntrinsicHeight(); if (tmpHeight >= screenHeight) { top -= (tmpHeight - screenHeight)/2; mWallpaper.setBounds(left, top, left + screenWidth, top + tmpHeight); } else {//if the pic width is wider than screen width, then we need show part of the pic. tooWide = true; left -= (tmpWidth - screenWidth)/2; mWallpaper.setBounds(left, top, left + tmpWidth, top + screenHeight); } } public void draw(Canvas canvas) { mWallpaper.draw(canvas); } public void setAlpha(int alpha) { mWallpaper.setAlpha(alpha); } public void setColorFilter(ColorFilter cf) { mWallpaper.setColorFilter(cf); } public int getOpacity() { return mWallpaper.getOpacity(); } } class sizedRelativeLayout extends RelativeLayout { public sizedRelativeLayout(Context context) { super(context); } public sizedRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } private OnResizeChangeListener mOnResizeChangeListener; protected void onSizeChanged(int w, int h, int oldW, int oldH) { if(mOnResizeChangeListener!=null){ mOnResizeChangeListener.onSizeChanged(w,h,oldW,oldH); } super.onSizeChanged(w,h,oldW,oldH); } public void setResizeListener(OnResizeChangeListener l) { mOnResizeChangeListener = l; } public interface OnResizeChangeListener{ void onSizeChanged(int w,int h,int oldW,int oldH); } } class SmsChangeObserver extends ContentObserver { ContentResolver mCR; Handler mHandler; public SmsChangeObserver(ContentResolver cr, Handler handler) { super(handler); mCR = cr; mHandler = handler; } public int countUnread() { //get sms unread count int ret = 0; Cursor csr = mCR.query(Uri.parse("content://sms"), new String[] {"thread_id"}, "read=0", null, null); if (csr != null) ret = csr.getCount(); //get mms unread count csr = mCR.query(Uri.parse("content://mms"), new String[] {"thread_id"}, "read=0", null, null); if (csr != null) ret += csr.getCount(); return ret; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Message msgsms = mHandler.obtainMessage(); msgsms.what = 1;//UPDATE_RI_SMS; mHandler.sendMessage(msgsms);//inform UI thread to update UI. } } class CallObserver extends ContentObserver { ContentResolver mCR; Handler mHandler; public CallObserver(ContentResolver cr, Handler handler) { super(handler); mHandler = handler; mCR = cr; } public int countUnread() { //get missed call number Cursor csr = mCR.query(Calls.CONTENT_URI, new String[] {Calls.NUMBER, Calls.TYPE, Calls.NEW}, Calls.TYPE + "=" + Calls.MISSED_TYPE + " AND " + Calls.NEW + "=1", null, Calls.DEFAULT_SORT_ORDER); if (csr != null) return csr.getCount(); else return 0; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Message msgphone = mHandler.obtainMessage(); msgphone.what = 0;//UPDATE_RI_PHONE; mHandler.sendMessage(msgphone);//inform UI thread to update UI. } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*//splash screen Thread splashTimer=new Thread() { public void run(){ try{ long curTime = System.currentTimeMillis(); while (System.currentTimeMillis() - curTime < 3000) { sleep(1000);//wait for 1000ms } Message msg = mAppHandler.obtainMessage(); msg.what = UPDATE_SPLASH; mAppHandler.sendMessage(msg);//inform UI thread to update UI. } catch(Exception ex){ } } }; splashTimer.start();*/ paid = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("paid", false); myPackageName = this.getPackageName(); pm = getPackageManager(); version = util.getVersion(this); try { getPackageSizeInfo = PackageManager.class.getMethod( "getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class}); } catch (Exception e) { e.printStackTrace(); } sizeObserver = new IPackageStatsObserver.Stub() { @Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException { long size = pStats.codeSize; String ssize = new String(); if (size > 10 * sizeM) ssize = size / sizeM + "M"; else if (size > 10 * 1024) ssize = size / 1024 + "K"; else if (size > 0) ssize = size + "B"; else ssize = ""; packagesSize.put(pStats.packageName, ssize); } }; packagesSize = new HashMap<String, Object>(); sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); perferences = PreferenceManager.getDefaultSharedPreferences(this); dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); //1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively. //int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; //if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen. //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout setContentView(R.layout.ads); home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null); //favorite app tab favoAppList = (GridView) home.findViewById(R.id.favos); favoAppList.setVerticalScrollBarEnabled(false); favoAppList.inflate(this, R.layout.app_list, null); favoAppList.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { shortAppList.setVisibility(View.INVISIBLE); return false; } }); shortAppList = (ListView) home.findViewById(R.id.business); shortAppList.bringToFront(); shortAppList.setVisibility(View.INVISIBLE); boolean isGrid = perferences.getBoolean("system", true); sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); isGrid = perferences.getBoolean("user", false); userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); if (paid) { isGrid = perferences.getBoolean("package", true); packageAlphaList = new PkgAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);//package tab } mListViews = new ArrayList<View>(); mListViews.add(sysAlphaList.view); sysAlphaList.index = 0; mListViews.add(home); mListViews.add(userAlphaList.view); userAlphaList.index = 2; if (paid) { mListViews.add(packageAlphaList.view); packageAlphaList.index = 3; } radioText = (TextView) findViewById(R.id.radio_text); radioGroup = (RadioGroup) findViewById(R.id.radio_hint); if (!paid) radioGroup.removeViewAt(0); if (wallpaperManagerAvaiable) { mWallpaperManager = new wrapWallpaperManager(); mWallpaperManager.getInstance(mContext); } mainlayout = (ViewPager)findViewById(R.id.mainFrame); mainlayout.setLongClickable(true); myPagerAdapter = new MyPagerAdapter(); mainlayout.setAdapter(myPagerAdapter); mainlayout.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_SETTLING) { refreshRadioButton(); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok mWallpaperManager.setWallpaperOffsets(token, //when slide from home to systems or from systems to home, the "position" is 0, //when slide from home to users or from users to home, it is 1. //positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0. //so we can unify it to (0, 1) by (positionOffset+position)/2 (positionOffset+position)/(mListViews.size()-1), 0); } } @Override public void onPageSelected(int arg0) { } }); mainlayout.setCurrentItem(homeTab); mSysApps = new ArrayList<ResolveInfo>(); mUserApps = new ArrayList<ResolveInfo>(); mFavoApps = new ArrayList<ResolveInfo>(); mShortApps = new ArrayList<ResolveInfo>(); favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps); favoAppList.setAdapter(favoAdapter); base = (sizedRelativeLayout) home.findViewById(R.id.base); base.setResizeListener(this); shortcutBar_center = (RelativeLayout) home.findViewById(R.id.shortcut_bar_center); homeBar = (ImageView) home.findViewById(R.id.home_bar); homeBar.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("harley.browsers", "easy.lib.SimpleBrowser"); if (!util.startActivity(intent, false, getBaseContext())) { intent.setClassName(myPackageName, "easy.lib.SimpleBrowser"); util.startActivity(intent, true, getBaseContext()); } } }); shortBar = (ImageView) home.findViewById(R.id.business_bar); shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout @Override public void onClick(View arg0) { if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty()) shortAppList.setVisibility(View.VISIBLE); else shortAppList.setVisibility(View.INVISIBLE); } }); setLayout(dm.widthPixels); shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone); shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms); //shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact); //for package add/remove IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); registerReceiver(packageReceiver, filter); //for wall paper changed filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED); registerReceiver(wallpaperReceiver, filter); filter = new IntentFilter("simpleHome.action.HOME_CHANGED"); registerReceiver(homeChangeReceiver, filter); filter = new IntentFilter("simpleHome.action.PIC_ADDED"); registerReceiver(picAddReceiver, filter); filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP"); registerReceiver(deskShareReceiver, filter); filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addDataScheme("file"); registerReceiver(sdcardListener, filter); apps = (RelativeLayout) findViewById(R.id.apps); //mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer? //TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE); //getITelephony(tm).getActivePhoneType(); ContentResolver cr = getContentResolver(); callObserver = new CallObserver(cr, mAppHandler); smsObserver = new SmsChangeObserver(cr, mAppHandler); getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver); cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver); //task for init, such as load webview, load package list InitTask initTask = new InitTask(); initTask.execute(""); Context mContext = this; restartDialog = new AlertDialog.Builder(this). setTitle(R.string.app_name). setIcon(R.drawable.icon). setMessage(R.string.restart). setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //save the layout SharedPreferences.Editor editor = perferences.edit(); if (mainlayout.getCurrentItem() == sysAlphaList.index) editor.putBoolean("system", !sysAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == userAlphaList.index) editor.putBoolean("user", !userAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == packageAlphaList.index) editor.putBoolean("package", !packageAlphaList.mIsGrid); editor.commit(); //restart the activity. note if set singleinstance or singletask of activity, below will not work on some device. Intent intent = getIntent(); invokeOverridePendingTransition(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); finish(); invokeOverridePendingTransition(); startActivity(intent); } }). setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); hintDialog = new AlertDialog.Builder(this). setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*//splash screen Thread splashTimer=new Thread() { public void run(){ try{ long curTime = System.currentTimeMillis(); while (System.currentTimeMillis() - curTime < 3000) { sleep(1000);//wait for 1000ms } Message msg = mAppHandler.obtainMessage(); msg.what = UPDATE_SPLASH; mAppHandler.sendMessage(msg);//inform UI thread to update UI. } catch(Exception ex){ } } }; splashTimer.start();*/ paid = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("paid", false); myPackageName = this.getPackageName(); pm = getPackageManager(); version = util.getVersion(this); try { getPackageSizeInfo = PackageManager.class.getMethod( "getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class}); } catch (Exception e) { e.printStackTrace(); } sizeObserver = new IPackageStatsObserver.Stub() { @Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException { long size = pStats.codeSize; String ssize = new String(); if (size > 10 * sizeM) ssize = size / sizeM + "M"; else if (size > 10 * 1024) ssize = size / 1024 + "K"; else if (size > 0) ssize = size + "B"; else ssize = ""; packagesSize.put(pStats.packageName, ssize); } }; packagesSize = new HashMap<String, Object>(); sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); perferences = PreferenceManager.getDefaultSharedPreferences(this); dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); //1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively. //int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; //if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen. //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout setContentView(R.layout.ads); home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null); //favorite app tab favoAppList = (GridView) home.findViewById(R.id.favos); favoAppList.setVerticalScrollBarEnabled(false); favoAppList.inflate(this, R.layout.app_list, null); favoAppList.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { shortAppList.setVisibility(View.INVISIBLE); return false; } }); shortAppList = (ListView) home.findViewById(R.id.business); shortAppList.bringToFront(); shortAppList.setVisibility(View.INVISIBLE); boolean isGrid = perferences.getBoolean("system", true); sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); isGrid = perferences.getBoolean("user", false); userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480); if (paid) { isGrid = perferences.getBoolean("package", true); packageAlphaList = new PkgAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);//package tab } mListViews = new ArrayList<View>(); mListViews.add(sysAlphaList.view); sysAlphaList.index = 0; mListViews.add(home); mListViews.add(userAlphaList.view); userAlphaList.index = 2; if (paid) { mListViews.add(packageAlphaList.view); packageAlphaList.index = 3; } radioText = (TextView) findViewById(R.id.radio_text); radioGroup = (RadioGroup) findViewById(R.id.radio_hint); if (!paid) radioGroup.removeViewAt(0); if (wallpaperManagerAvaiable) { mWallpaperManager = new wrapWallpaperManager(); mWallpaperManager.getInstance(mContext); } mainlayout = (ViewPager)findViewById(R.id.mainFrame); mainlayout.setLongClickable(true); myPagerAdapter = new MyPagerAdapter(); mainlayout.setAdapter(myPagerAdapter); mainlayout.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_SETTLING) { refreshRadioButton(); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok mWallpaperManager.setWallpaperOffsets(token, //when slide from home to systems or from systems to home, the "position" is 0, //when slide from home to users or from users to home, it is 1. //positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0. //so we can unify it to (0, 1) by (positionOffset+position)/2 (positionOffset+position)/(mListViews.size()-1), 0); } } @Override public void onPageSelected(int arg0) { } }); mainlayout.setCurrentItem(homeTab); mSysApps = new ArrayList<ResolveInfo>(); mUserApps = new ArrayList<ResolveInfo>(); mFavoApps = new ArrayList<ResolveInfo>(); mShortApps = new ArrayList<ResolveInfo>(); favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps); favoAppList.setAdapter(favoAdapter); base = (sizedRelativeLayout) home.findViewById(R.id.base); base.setResizeListener(this); shortcutBar_center = (RelativeLayout) home.findViewById(R.id.shortcut_bar_center); homeBar = (ImageView) home.findViewById(R.id.home_bar); homeBar.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("harley.browsers", "easy.lib.SimpleBrowser"); if (!util.startActivity(intent, false, getBaseContext())) { intent.setClassName("easy.browser", "easy.lib.SimpleBrowser"); if (!util.startActivity(intent, false, getBaseContext())) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers")); //intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field util.startActivity(intent, true, getBaseContext()); } } } }); shortBar = (ImageView) home.findViewById(R.id.business_bar); shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout @Override public void onClick(View arg0) { if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty()) shortAppList.setVisibility(View.VISIBLE); else shortAppList.setVisibility(View.INVISIBLE); } }); setLayout(dm.widthPixels); shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone); shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms); //shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact); //for package add/remove IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); registerReceiver(packageReceiver, filter); //for wall paper changed filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED); registerReceiver(wallpaperReceiver, filter); filter = new IntentFilter("simpleHome.action.HOME_CHANGED"); registerReceiver(homeChangeReceiver, filter); filter = new IntentFilter("simpleHome.action.PIC_ADDED"); registerReceiver(picAddReceiver, filter); filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP"); registerReceiver(deskShareReceiver, filter); filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addDataScheme("file"); registerReceiver(sdcardListener, filter); apps = (RelativeLayout) findViewById(R.id.apps); //mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer? //TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE); //getITelephony(tm).getActivePhoneType(); ContentResolver cr = getContentResolver(); callObserver = new CallObserver(cr, mAppHandler); smsObserver = new SmsChangeObserver(cr, mAppHandler); getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver); cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver); //task for init, such as load webview, load package list InitTask initTask = new InitTask(); initTask.execute(""); Context mContext = this; restartDialog = new AlertDialog.Builder(this). setTitle(R.string.app_name). setIcon(R.drawable.icon). setMessage(R.string.restart). setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //save the layout SharedPreferences.Editor editor = perferences.edit(); if (mainlayout.getCurrentItem() == sysAlphaList.index) editor.putBoolean("system", !sysAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == userAlphaList.index) editor.putBoolean("user", !userAlphaList.mIsGrid); else if (mainlayout.getCurrentItem() == packageAlphaList.index) editor.putBoolean("package", !packageAlphaList.mIsGrid); editor.commit(); //restart the activity. note if set singleinstance or singletask of activity, below will not work on some device. Intent intent = getIntent(); invokeOverridePendingTransition(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); finish(); invokeOverridePendingTransition(); startActivity(intent); } }). setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); hintDialog = new AlertDialog.Builder(this). setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).create(); }
diff --git a/android/src/com/facebook/flw/RedirectActivity.java b/android/src/com/facebook/flw/RedirectActivity.java index 856586b..f4dba4d 100644 --- a/android/src/com/facebook/flw/RedirectActivity.java +++ b/android/src/com/facebook/flw/RedirectActivity.java @@ -1,23 +1,24 @@ package com.facebook.flw; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * Created with IntelliJ IDEA. * User: ostrulovich * Date: 9/26/13 * Time: 11:13 PM * To change this template use File | Settings | File Templates. */ public class RedirectActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); Intent intent = new Intent(this, PickRestaurantActivity.class); Log.i(FreeLunchWednesdayApplication.TAG, "Lets redirect"); startActivity(intent); } }
true
true
protected void onCreate(Bundle savedInstanceState) { Intent intent = new Intent(this, PickRestaurantActivity.class); Log.i(FreeLunchWednesdayApplication.TAG, "Lets redirect"); startActivity(intent); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(this, PickRestaurantActivity.class); Log.i(FreeLunchWednesdayApplication.TAG, "Lets redirect"); startActivity(intent); }
diff --git a/src/com/webb/androidmosaic/TakePhotoActivity.java b/src/com/webb/androidmosaic/TakePhotoActivity.java index 1e1eeb4..6c1e491 100644 --- a/src/com/webb/androidmosaic/TakePhotoActivity.java +++ b/src/com/webb/androidmosaic/TakePhotoActivity.java @@ -1,160 +1,165 @@ package com.webb.androidmosaic; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import android.app.Activity; import android.content.Intent; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.webb.androidmosaic.generation.AnalyzedImage; import com.webb.androidmosaic.generation.Configuration; import com.webb.androidmosaic.generation.NewStateListener; import com.webb.androidmosaic.generation.generator.Generator; import com.webb.androidmosaic.generation.generator.GeneratorFactory; import com.webb.androidmosaic.util.MosaicUtil; public class TakePhotoActivity extends Activity { private static final int CAMERA_REQUEST = 1888; private ImageView imageView; private Button makeMosaicButton; private Bitmap image; private Generator generator; @SuppressWarnings("unused") private Configuration cfg; private List<AnalyzedImage> solution; private String MosaicGeneratorTag = "Mosaic Generation"; private int count = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.imageview); this.imageView = (ImageView) this.findViewById(R.id.imageView1); Button photoButton = (Button) this.findViewById(R.id.button1); photoButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } }); makeMosaicButton = (Button) this.findViewById(R.id.makeMosaic); makeMosaicButton.setEnabled(false); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { Bitmap photo = null; if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { photo = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(photo); image = photo; } makeMosaicButton.setEnabled(true); makeMosaicButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.i(MosaicGeneratorTag, "Now creating mosaic"); createPhotoMosaic(image); } }); } private void createPhotoMosaic(Bitmap image) { AndroidMosaicApp app = (AndroidMosaicApp) getApplicationContext(); generator = GeneratorFactory.getGenerator(app.getCfg()); generator.setTargetImage(image); NewStateListener generatorStateListener = new NewStateListener() { public void handle(List<AnalyzedImage> state, float currentFitness) { Log.d(MosaicGeneratorTag, "got state"); if(count >= 100) { generator.pause(); solution = generator.getSolutionTiles(); if(saveMosaic(generator.getNumTilesPerRowInSolution(), generator.getNumTilesPerColumnInSolution(), generator.getWidthOfTileInPixels())) { Log.d(MosaicGeneratorTag, "Image saved"); } } else { count++; } // TODO code for animating mosaic change } }; generator.registerNewStateListener(generatorStateListener); Log.i(MosaicGeneratorTag, "Listener attached"); generator.start(); if(generator.getSolutionTiles() != null) { solution = generator.getSolutionTiles(); } //Code could follow here to add image to screen } - private boolean saveMosaic(int numOfRows, int numOfColums, int widthOfTile) { - Bitmap mosaicBitmap = Bitmap.createBitmap(numOfRows*widthOfTile, numOfColums*widthOfTile, Bitmap.Config.ARGB_8888); + private boolean saveMosaic(int numOfRows, int numOfColumns, int widthOfTile) { + int width = numOfColumns*widthOfTile; + int height = numOfRows*widthOfTile; + Bitmap mosaicBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas mosaic = new Canvas(mosaicBitmap); boolean success = false; FileInputStream file = null; int x = 0; int y = 0; int columnsCurrentlyWritten = 0; for(AnalyzedImage analyzedImage: solution) { String fileName = ((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory() + "/" + analyzedImage.getFile(); File directory = getDir(((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory(), MODE_WORLD_READABLE); try { file = new FileInputStream(directory+ "/" + analyzedImage.getFile()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bitmap image = BitmapFactory.decodeStream(file); if(image != null) { Bitmap croppedImage = MosaicUtil.cropBitMapToSquare(image); image = Bitmap.createScaledBitmap(croppedImage, widthOfTile, widthOfTile, false); - if(columnsCurrentlyWritten == numOfColums) { - y = y+15; + if(columnsCurrentlyWritten == numOfColumns-1) { + mosaic.drawBitmap(image, x, y, null); + y = y+widthOfTile; x = 0; + columnsCurrentlyWritten = 0; } else { mosaic.drawBitmap(image, x, y, null); - x = x+15; + x = x+widthOfTile; + columnsCurrentlyWritten++; } } } try { File sdDir = Environment.getExternalStorageDirectory(); mosaicBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(sdDir+"/image.jpg")); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); success = true; } catch(IOException e) { Log.e(MosaicGeneratorTag, "Unable to save the mosaic"); e.printStackTrace(); } return success; } }
false
true
private boolean saveMosaic(int numOfRows, int numOfColums, int widthOfTile) { Bitmap mosaicBitmap = Bitmap.createBitmap(numOfRows*widthOfTile, numOfColums*widthOfTile, Bitmap.Config.ARGB_8888); Canvas mosaic = new Canvas(mosaicBitmap); boolean success = false; FileInputStream file = null; int x = 0; int y = 0; int columnsCurrentlyWritten = 0; for(AnalyzedImage analyzedImage: solution) { String fileName = ((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory() + "/" + analyzedImage.getFile(); File directory = getDir(((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory(), MODE_WORLD_READABLE); try { file = new FileInputStream(directory+ "/" + analyzedImage.getFile()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bitmap image = BitmapFactory.decodeStream(file); if(image != null) { Bitmap croppedImage = MosaicUtil.cropBitMapToSquare(image); image = Bitmap.createScaledBitmap(croppedImage, widthOfTile, widthOfTile, false); if(columnsCurrentlyWritten == numOfColums) { y = y+15; x = 0; } else { mosaic.drawBitmap(image, x, y, null); x = x+15; } } } try { File sdDir = Environment.getExternalStorageDirectory(); mosaicBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(sdDir+"/image.jpg")); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); success = true; } catch(IOException e) { Log.e(MosaicGeneratorTag, "Unable to save the mosaic"); e.printStackTrace(); } return success; }
private boolean saveMosaic(int numOfRows, int numOfColumns, int widthOfTile) { int width = numOfColumns*widthOfTile; int height = numOfRows*widthOfTile; Bitmap mosaicBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas mosaic = new Canvas(mosaicBitmap); boolean success = false; FileInputStream file = null; int x = 0; int y = 0; int columnsCurrentlyWritten = 0; for(AnalyzedImage analyzedImage: solution) { String fileName = ((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory() + "/" + analyzedImage.getFile(); File directory = getDir(((AndroidMosaicApp) getApplicationContext()).getBitmapDirectory(), MODE_WORLD_READABLE); try { file = new FileInputStream(directory+ "/" + analyzedImage.getFile()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bitmap image = BitmapFactory.decodeStream(file); if(image != null) { Bitmap croppedImage = MosaicUtil.cropBitMapToSquare(image); image = Bitmap.createScaledBitmap(croppedImage, widthOfTile, widthOfTile, false); if(columnsCurrentlyWritten == numOfColumns-1) { mosaic.drawBitmap(image, x, y, null); y = y+widthOfTile; x = 0; columnsCurrentlyWritten = 0; } else { mosaic.drawBitmap(image, x, y, null); x = x+widthOfTile; columnsCurrentlyWritten++; } } } try { File sdDir = Environment.getExternalStorageDirectory(); mosaicBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(sdDir+"/image.jpg")); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); success = true; } catch(IOException e) { Log.e(MosaicGeneratorTag, "Unable to save the mosaic"); e.printStackTrace(); } return success; }
diff --git a/schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchViewLabelProvider.java b/schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchViewLabelProvider.java index d43ea350d..c6193af11 100644 --- a/schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchViewLabelProvider.java +++ b/schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/SearchViewLabelProvider.java @@ -1,291 +1,291 @@ /* * 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.directory.studio.schemaeditor.view.views; import org.apache.directory.shared.ldap.schema.SchemaObject; import org.apache.directory.studio.schemaeditor.Activator; import org.apache.directory.studio.schemaeditor.PluginConstants; import org.apache.directory.studio.schemaeditor.model.AttributeTypeImpl; import org.apache.directory.studio.schemaeditor.model.ObjectClassImpl; import org.apache.directory.studio.schemaeditor.view.ViewUtils; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** * This class implements the LabelProvider for the SearchView. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class SearchViewLabelProvider extends LabelProvider { /** The preferences store */ private IPreferenceStore store; /** * Creates a new instance of DifferencesWidgetSchemaLabelProvider. */ public SearchViewLabelProvider() { store = Activator.getDefault().getPreferenceStore(); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) */ public String getText( Object element ) { String label = ""; //$NON-NLS-1$ int labelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_LABEL ); boolean abbreviate = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE ); int abbreviateMaxLength = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE_MAX_LENGTH ); boolean secondaryLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_DISPLAY ); int secondaryLabelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL ); boolean secondaryLabelAbbreviate = store .getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE ); int secondaryLabelAbbreviateMaxLength = store .getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE_MAX_LENGTH ); boolean schemaLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SCHEMA_LABEL_DISPLAY ); if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = at.getOid(); } else // Default { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = oc.getOid(); } else // Default { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } // Secondary Label if ( secondaryLabelDisplay ) { String secondaryLabel = ""; //$NON-NLS-1$ if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = at.getOid(); } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = oc.getOid(); } } if ( secondaryLabelAbbreviate && ( secondaryLabelAbbreviateMaxLength < secondaryLabel.length() ) ) { secondaryLabel = secondaryLabel.substring( 0, secondaryLabelAbbreviateMaxLength ) + "..."; //$NON-NLS-1$ } label += " [" + secondaryLabel + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } // Schema Label if ( schemaLabelDisplay ) { if ( element instanceof SchemaObject ) { SchemaObject object = ( SchemaObject ) element; - label += " from schema \"" + object.getSchema() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ + label += " " + Messages.getString( "SearchViewLabelProvider.FromSchema" ) + "\"" + object.getSchema() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ } } return label; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) */ public Image getImage( Object element ) { if ( element instanceof AttributeTypeImpl ) { return Activator.getDefault().getImage( PluginConstants.IMG_ATTRIBUTE_TYPE ); } else if ( element instanceof ObjectClassImpl ) { return Activator.getDefault().getImage( PluginConstants.IMG_OBJECT_CLASS ); } // Default return null; } }
true
true
public String getText( Object element ) { String label = ""; //$NON-NLS-1$ int labelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_LABEL ); boolean abbreviate = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE ); int abbreviateMaxLength = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE_MAX_LENGTH ); boolean secondaryLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_DISPLAY ); int secondaryLabelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL ); boolean secondaryLabelAbbreviate = store .getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE ); int secondaryLabelAbbreviateMaxLength = store .getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE_MAX_LENGTH ); boolean schemaLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SCHEMA_LABEL_DISPLAY ); if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = at.getOid(); } else // Default { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = oc.getOid(); } else // Default { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } // Secondary Label if ( secondaryLabelDisplay ) { String secondaryLabel = ""; //$NON-NLS-1$ if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = at.getOid(); } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = oc.getOid(); } } if ( secondaryLabelAbbreviate && ( secondaryLabelAbbreviateMaxLength < secondaryLabel.length() ) ) { secondaryLabel = secondaryLabel.substring( 0, secondaryLabelAbbreviateMaxLength ) + "..."; //$NON-NLS-1$ } label += " [" + secondaryLabel + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } // Schema Label if ( schemaLabelDisplay ) { if ( element instanceof SchemaObject ) { SchemaObject object = ( SchemaObject ) element; label += " from schema \"" + object.getSchema() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ } } return label; }
public String getText( Object element ) { String label = ""; //$NON-NLS-1$ int labelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_LABEL ); boolean abbreviate = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE ); int abbreviateMaxLength = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_ABBREVIATE_MAX_LENGTH ); boolean secondaryLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_DISPLAY ); int secondaryLabelValue = store.getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL ); boolean secondaryLabelAbbreviate = store .getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE ); int secondaryLabelAbbreviateMaxLength = store .getInt( PluginConstants.PREFS_SEARCH_VIEW_SECONDARY_LABEL_ABBREVIATE_MAX_LENGTH ); boolean schemaLabelDisplay = store.getBoolean( PluginConstants.PREFS_SEARCH_VIEW_SCHEMA_LABEL_DISPLAY ); if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = at.getOid(); } else // Default { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; // Label if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = ViewUtils.concateAliases( names ); } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( labelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { label = oc.getOid(); } else // Default { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { label = names[0]; } else { label = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } // Abbreviate if ( abbreviate && ( abbreviateMaxLength < label.length() ) ) { label = label.substring( 0, abbreviateMaxLength ) + "..."; //$NON-NLS-1$ } } // Secondary Label if ( secondaryLabelDisplay ) { String secondaryLabel = ""; //$NON-NLS-1$ if ( element instanceof AttributeTypeImpl ) { AttributeTypeImpl at = ( AttributeTypeImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = at.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = at.getOid(); } } else if ( element instanceof ObjectClassImpl ) { ObjectClassImpl oc = ( ObjectClassImpl ) element; if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_FIRST_NAME ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = names[0]; } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_ALL_ALIASES ) { String[] names = oc.getNamesRef(); if ( ( names != null ) && ( names.length > 0 ) ) { secondaryLabel = ViewUtils.concateAliases( names ); } else { secondaryLabel = Messages.getString( "SearchViewLabelProvider.None" ); //$NON-NLS-1$ } } else if ( secondaryLabelValue == PluginConstants.PREFS_SEARCH_VIEW_LABEL_OID ) { secondaryLabel = oc.getOid(); } } if ( secondaryLabelAbbreviate && ( secondaryLabelAbbreviateMaxLength < secondaryLabel.length() ) ) { secondaryLabel = secondaryLabel.substring( 0, secondaryLabelAbbreviateMaxLength ) + "..."; //$NON-NLS-1$ } label += " [" + secondaryLabel + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } // Schema Label if ( schemaLabelDisplay ) { if ( element instanceof SchemaObject ) { SchemaObject object = ( SchemaObject ) element; label += " " + Messages.getString( "SearchViewLabelProvider.FromSchema" ) + "\"" + object.getSchema() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ } } return label; }
diff --git a/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java b/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java index b4caa35..dfc4e28 100644 --- a/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java +++ b/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java @@ -1,506 +1,506 @@ package chalmers.dax021308.ecosystem.view; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLEventListener; import javax.swing.JFrame; import com.sun.opengl.util.FPSAnimator; import chalmers.dax021308.ecosystem.model.agent.IAgent; import chalmers.dax021308.ecosystem.model.environment.EcoWorld; import chalmers.dax021308.ecosystem.model.environment.EllipticalObstacle; import chalmers.dax021308.ecosystem.model.environment.IModel; import chalmers.dax021308.ecosystem.model.environment.IObstacle; import chalmers.dax021308.ecosystem.model.environment.RectangularObstacle; import chalmers.dax021308.ecosystem.model.population.AbstractPopulation; import chalmers.dax021308.ecosystem.model.population.IPopulation; import chalmers.dax021308.ecosystem.model.util.CircleShape; import chalmers.dax021308.ecosystem.model.util.IShape; import chalmers.dax021308.ecosystem.model.util.Log; import chalmers.dax021308.ecosystem.model.util.Position; import chalmers.dax021308.ecosystem.model.util.SquareShape; import chalmers.dax021308.ecosystem.model.util.TriangleShape; import chalmers.dax021308.ecosystem.model.util.Vector; /** * OpenGL version of SimulationView. * <p> * Uses JOGL library. * <p> * Install instructions: * <p> * Download: http://download.java.net/media/jogl/builds/archive/jsr-231-1.1.1a/ * Select the version of your choice, i.e. windows-amd64.zip * Extract the files to a folder. * Add the extracted files jogl.jar and gluegen-rt.jar to build-path. * Add path to jogl library to VM-argument in Run Configurations * <p> * For Javadoc add the Jogl Javadoc jar as Javadoc refernce to the selected JOGL jar. * <p> * @author Erik Ramqvist * */ public class OpenGLSimulationView extends GLCanvas /*/ (GLCanvas extends Java.AWT.Component) */ implements IView { private static final long serialVersionUID = 1585638837620985591L; private List<IPopulation> newPops = new ArrayList<IPopulation>(); private List<IObstacle> newObs = new ArrayList<IObstacle>(); private Timer fpsTimer; private int updates; private int lastFps; private boolean showFPS; private int newFps; private Object fpsSync = new Object(); private Dimension size; private JOGLListener glListener; //private GLCanvas canvas; private IShape shape; /** * Create the panel. */ public OpenGLSimulationView(IModel model, Dimension size, boolean showFPS) { this.size = size; model.addObserver(this); //setVisible(true); //setSize(size); //canvas = new GLCanvas(); //canvas.setSize(size); //canvas.addGLEventListener(new JOGLListener()); glListener = new JOGLListener(); addGLEventListener(glListener); FPSAnimator animator = new FPSAnimator(this, 60); animator.start(); //add(); this.showFPS = showFPS; if(showFPS) { fpsTimer = new Timer(); fpsTimer.schedule(new TimerTask() { @Override public void run() { int fps = getUpdate(); /*if(fps + lastFps != 0) { fps = ( fps + lastFps ) / 2; } */ setNewFps(fps); lastFps = fps; setUpdateValue(0); } }, 1000, 1000); } } private int getUpdate() { synchronized (OpenGLSimulationView.class) { return updates; } } private void setUpdateValue(int newValue) { synchronized (OpenGLSimulationView.class) { updates = newValue; } } private int getNewFps() { synchronized (fpsSync) { return newFps; } } private void setNewFps(int newValue) { synchronized (fpsSync) { newFps = newValue; } } private void increaseUpdateValue() { synchronized (OpenGLSimulationView.class) { updates++; } } @Override public void propertyChange(PropertyChangeEvent event) { String eventName = event.getPropertyName(); if(eventName == EcoWorld.EVENT_TICK) { //Tick notification recived from model. Do something with the data. if(event.getNewValue() instanceof List<?>) { this.newPops = (List<IPopulation>) event.getNewValue(); } if(event.getOldValue() instanceof List<?>) { this.newObs = (List<IObstacle>) event.getOldValue(); } //repaint(); //display(); //removeAll(); //repaint(); } else if(eventName == EcoWorld.EVENT_STOP) { //Model has stopped. Maybe hide view? //frame.setVisible(false); } else if(eventName == EcoWorld.EVENT_DIMENSIONCHANGED) { Object o = event.getNewValue(); if(o instanceof Dimension) { this.size = (Dimension) o; } } else if(eventName == EcoWorld.EVENT_SHAPE_CHANGED) { Object o = event.getNewValue(); if(o instanceof IShape) { this.shape = (IShape) o; } } } /** * Sets the FPS counter visible or not visible * * @param visible */ public void setFPSCounterVisible(boolean visible) { if(showFPS && !visible) { fpsTimer.cancel(); showFPS = visible; } else if(!showFPS && visible) { fpsTimer = new Timer(); fpsTimer.schedule(new TimerTask() { @Override public void run() { newFps = getUpdate(); int temp = newFps; if(newFps + lastFps != 0) { newFps = ( newFps + lastFps ) / 2; } lastFps = temp; setUpdateValue(0); } }, 1000, 1000); showFPS = true; } } /** * JOGL Listener, listenes to commands from the GLCanvas. * * @author Erik * */ private class JOGLListener implements GLEventListener { //Number of edges in each created circle. private final float COLOR_FACTOR = (1.0f/255); /** * Called each frame to redraw all the 3D elements. * */ @Override public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); increaseUpdateValue(); long start = System.currentTimeMillis(); double frameHeight = (double)getHeight(); double frameWidth = (double)getWidth(); double scaleX = frameWidth / size.width; double scaleY = frameHeight / size.height; gl.glColor3d(0.9, 0.9, 0.9); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(frameWidth, 0); gl.glEnd(); if(shape != null && shape instanceof CircleShape) { double increment = 2.0*Math.PI/50.0; double cx = frameWidth / 2.0; double cy = frameHeight/ 2.0; gl.glColor3d(0.545098, 0.270588, 0.0745098); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(cx*(1+Math.cos(angle)), cy*(1+Math.sin(angle))); gl.glVertex2d(cx*(1+Math.cos(angle+increment)), cy*(1+Math.sin(angle+increment))); gl.glEnd(); } } else if (shape != null && shape instanceof TriangleShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth/2.0, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth/2.0, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } else if (shape != null && shape instanceof SquareShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(frameWidth, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } /* * Draw Obstacles */ for(IObstacle o: newObs){ if(o != null && o instanceof EllipticalObstacle){ double increment = 2.0*Math.PI/50.0; double w = frameWidth*o.getWidth()/size.width; double h = frameHeight*o.getHeight()/size.height; double x = frameWidth*o.getPosition().getX()/size.width; double y = frameHeight*o.getPosition().getY()/size.height; gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glVertex2d(x + w*Math.cos(angle),frameHeight - (y + h*Math.sin(angle))); } gl.glEnd(); } else if (o != null && o instanceof RectangularObstacle){ double x = o.getPosition().getX(); double y = o.getPosition().getY(); double w = o.getWidth(); double h = o.getHeight(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, - frameHeight*(o.getPosition().getY()-h)/size.height); + frameHeight - frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, - frameHeight*(o.getPosition().getY()-h)/size.height); + frameHeight - frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, - frameHeight*(o.getPosition().getY()+h)/size.height); + frameHeight - frameHeight*(o.getPosition().getY()+h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, - frameHeight*(o.getPosition().getY()+h)/size.height); + frameHeight - frameHeight*(o.getPosition().getY()+h)/size.height); gl.glEnd(); } } int popSize = newPops.size(); for(int i = 0; i < popSize; i ++) { List<IAgent> agents = newPops.get(i).getAgents(); int size = agents.size(); IAgent a; for(int j = 0; j < size; j++) { a = agents.get(j); Color c = a.getColor(); gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha()); Position p = a.getPosition(); /*double cx = p.getX(); double cy = getHeight() - p.getY(); double radius = a.getWidth()/2 + 5;*/ double height = (double)a.getHeight(); double width = (double)a.getWidth(); double originalX = a.getVelocity().x; double originalY = a.getVelocity().y; double originalNorm = getNorm(originalX, originalY); //if(v.getX() != 0 && v.getY() != 0) { gl.glBegin(GL.GL_TRIANGLES); double x = originalX * 2.0*height/(3.0*originalNorm); double y = originalY * 2.0*height/(3.0*originalNorm); //Vector bodyCenter = new Vector(p.getX(), p.getY()); double xBodyCenter = p.getX(); double yBodyCenter = p.getY(); //Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter); double noseX = x+xBodyCenter; double noseY = y+yBodyCenter; double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter; double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ; //Vector legLengthVector = new Vector(-originalY/originalX,1); double legLengthX1 = -originalY/originalX; double legLengthY1 = 1; double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 )); //legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); legLengthX1 = legLengthX1 * legLenthVectorNorm2; legLengthY1 = legLengthY1 * legLenthVectorNorm2; //Vector rightLeg = legLengthVector; double rightLegX = legLengthX1 + bottomX; double rightLegY = legLengthY1 + bottomY; //v = new Vector(a.getVelocity()); double legLengthX2 = originalY/originalX * legLenthVectorNorm2; double legLengthY2 = -1 * legLenthVectorNorm2; //legLengthVector = new Vector(originalY/originalX,-1); // legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); //Vector leftLeg = legLengthVector.add(bottom); //Vector leftLeg = legLengthVector; double leftLegX = legLengthX2 + bottomX; double leftLegY = legLengthY2 + bottomY; gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY); gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY); gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY); gl.glEnd(); /*} else { for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){ gl.glBegin(GL.GL_TRIANGLES); gl.glVertex2d(cx, cy); gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius); gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius); gl.glEnd(); } }*/ } } // // /* Information print, comment out to increase performance. */ // Long totalTime = System.currentTimeMillis() - start; // StringBuffer sb = new StringBuffer("OpenGL Redraw! Fps: "); // sb.append(getNewFps()); // //sb.append(" Rendertime in ms: "); // //sb.append(totalTime); // System.out.println(sb.toString()); /* End Information print. */ } public double getNorm(double x, double y){ return Math.sqrt((x*x)+(y*y)); } @Override public void init(GLAutoDrawable drawable) { GL gl = drawable.getGL(); // System.out.println("INIT CALLED"); } /** * Called by the drawable during the first repaint after the component has been resized. The * client can update the viewport and view volume of the window appropriately, for example by a * call to GL.glViewport(int, int, int, int); note that for convenience the component has * already called GL.glViewport(int, int, int, int)(x, y, width, height) when this method is * called, so the client may not have to do anything in this method. * * @param gLDrawable The GLDrawable object. * @param x The X Coordinate of the viewport rectangle. * @param y The Y coordinate of the viewport rectanble. * @param width The new width of the window. * @param height The new height of the window. */ @Override public void reshape(GLAutoDrawable drawable, int arg1, int arg2, int arg3, int arg4) { //System.out.println("RESHAPE CALLED Frame size:" + getSize().toString()); //Projection mode is for setting camera GL gl = drawable.getGL(); gl.glMatrixMode(GL.GL_PROJECTION); //This will set the camera for orthographic projection and allow 2D view //Our projection will be on 400 X 400 screen gl.glLoadIdentity(); // Log.v("getWidth(): " + getWidth()); // Log.v("getHeight(): " + getHeight()); // Log.v("size.width: " + size.width); // Log.v("size.height: " + size.height); gl.glOrtho(0, getWidth(), getHeight(), 0, 0, 1); //Modelview is for drawing gl.glMatrixMode(GL.GL_MODELVIEW); //Depth is disabled because we are drawing in 2D gl.glDisable(GL.GL_DEPTH_TEST); //Setting the clear color (in this case black) //and clearing the buffer with this set clear color gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL.GL_COLOR_BUFFER_BIT); //This defines how to blend when a transparent graphics //is placed over another (here we have blended colors of //two consecutively overlapping graphic objects) gl.glBlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable (GL.GL_BLEND); gl.glLoadIdentity(); //After this we start the drawing of object //We want to draw a triangle which is a type of polygon } @Override public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) { } } @Override public void init() { // TODO Auto-generated method stub } @Override public void addController(ActionListener controller) { // TODO Auto-generated method stub } @Override public void onTick() { // TODO Auto-generated method stub } @Override public void release() { // TODO Auto-generated method stub } }
false
true
public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); increaseUpdateValue(); long start = System.currentTimeMillis(); double frameHeight = (double)getHeight(); double frameWidth = (double)getWidth(); double scaleX = frameWidth / size.width; double scaleY = frameHeight / size.height; gl.glColor3d(0.9, 0.9, 0.9); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(frameWidth, 0); gl.glEnd(); if(shape != null && shape instanceof CircleShape) { double increment = 2.0*Math.PI/50.0; double cx = frameWidth / 2.0; double cy = frameHeight/ 2.0; gl.glColor3d(0.545098, 0.270588, 0.0745098); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(cx*(1+Math.cos(angle)), cy*(1+Math.sin(angle))); gl.glVertex2d(cx*(1+Math.cos(angle+increment)), cy*(1+Math.sin(angle+increment))); gl.glEnd(); } } else if (shape != null && shape instanceof TriangleShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth/2.0, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth/2.0, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } else if (shape != null && shape instanceof SquareShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(frameWidth, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } /* * Draw Obstacles */ for(IObstacle o: newObs){ if(o != null && o instanceof EllipticalObstacle){ double increment = 2.0*Math.PI/50.0; double w = frameWidth*o.getWidth()/size.width; double h = frameHeight*o.getHeight()/size.height; double x = frameWidth*o.getPosition().getX()/size.width; double y = frameHeight*o.getPosition().getY()/size.height; gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glVertex2d(x + w*Math.cos(angle),frameHeight - (y + h*Math.sin(angle))); } gl.glEnd(); } else if (o != null && o instanceof RectangularObstacle){ double x = o.getPosition().getX(); double y = o.getPosition().getY(); double w = o.getWidth(); double h = o.getHeight(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, frameHeight*(o.getPosition().getY()+h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, frameHeight*(o.getPosition().getY()+h)/size.height); gl.glEnd(); } } int popSize = newPops.size(); for(int i = 0; i < popSize; i ++) { List<IAgent> agents = newPops.get(i).getAgents(); int size = agents.size(); IAgent a; for(int j = 0; j < size; j++) { a = agents.get(j); Color c = a.getColor(); gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha()); Position p = a.getPosition(); /*double cx = p.getX(); double cy = getHeight() - p.getY(); double radius = a.getWidth()/2 + 5;*/ double height = (double)a.getHeight(); double width = (double)a.getWidth(); double originalX = a.getVelocity().x; double originalY = a.getVelocity().y; double originalNorm = getNorm(originalX, originalY); //if(v.getX() != 0 && v.getY() != 0) { gl.glBegin(GL.GL_TRIANGLES); double x = originalX * 2.0*height/(3.0*originalNorm); double y = originalY * 2.0*height/(3.0*originalNorm); //Vector bodyCenter = new Vector(p.getX(), p.getY()); double xBodyCenter = p.getX(); double yBodyCenter = p.getY(); //Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter); double noseX = x+xBodyCenter; double noseY = y+yBodyCenter; double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter; double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ; //Vector legLengthVector = new Vector(-originalY/originalX,1); double legLengthX1 = -originalY/originalX; double legLengthY1 = 1; double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 )); //legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); legLengthX1 = legLengthX1 * legLenthVectorNorm2; legLengthY1 = legLengthY1 * legLenthVectorNorm2; //Vector rightLeg = legLengthVector; double rightLegX = legLengthX1 + bottomX; double rightLegY = legLengthY1 + bottomY; //v = new Vector(a.getVelocity()); double legLengthX2 = originalY/originalX * legLenthVectorNorm2; double legLengthY2 = -1 * legLenthVectorNorm2; //legLengthVector = new Vector(originalY/originalX,-1); // legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); //Vector leftLeg = legLengthVector.add(bottom); //Vector leftLeg = legLengthVector; double leftLegX = legLengthX2 + bottomX; double leftLegY = legLengthY2 + bottomY; gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY); gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY); gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY); gl.glEnd(); /*} else { for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){ gl.glBegin(GL.GL_TRIANGLES); gl.glVertex2d(cx, cy); gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius); gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius); gl.glEnd(); } }*/ } }
public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); increaseUpdateValue(); long start = System.currentTimeMillis(); double frameHeight = (double)getHeight(); double frameWidth = (double)getWidth(); double scaleX = frameWidth / size.width; double scaleY = frameHeight / size.height; gl.glColor3d(0.9, 0.9, 0.9); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(frameWidth, 0); gl.glEnd(); if(shape != null && shape instanceof CircleShape) { double increment = 2.0*Math.PI/50.0; double cx = frameWidth / 2.0; double cy = frameHeight/ 2.0; gl.glColor3d(0.545098, 0.270588, 0.0745098); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(cx*(1+Math.cos(angle)), cy*(1+Math.sin(angle))); gl.glVertex2d(cx*(1+Math.cos(angle+increment)), cy*(1+Math.sin(angle+increment))); gl.glEnd(); } } else if (shape != null && shape instanceof TriangleShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, frameHeight); gl.glVertex2d(frameWidth/2.0, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth/2.0, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } else if (shape != null && shape instanceof SquareShape){ gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(frameWidth, 0); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(0, 0); gl.glVertex2d(0, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, 0); gl.glVertex2d(frameWidth, frameHeight); gl.glEnd(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_LINES); gl.glVertex2d(frameWidth, frameHeight); gl.glVertex2d(0, frameHeight); gl.glEnd(); } /* * Draw Obstacles */ for(IObstacle o: newObs){ if(o != null && o instanceof EllipticalObstacle){ double increment = 2.0*Math.PI/50.0; double w = frameWidth*o.getWidth()/size.width; double h = frameHeight*o.getHeight()/size.height; double x = frameWidth*o.getPosition().getX()/size.width; double y = frameHeight*o.getPosition().getY()/size.height; gl.glColor3d(0.545098, 0.270588, 0.0745098); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){ gl.glVertex2d(x + w*Math.cos(angle),frameHeight - (y + h*Math.sin(angle))); } gl.glEnd(); } else if (o != null && o instanceof RectangularObstacle){ double x = o.getPosition().getX(); double y = o.getPosition().getY(); double w = o.getWidth(); double h = o.getHeight(); gl.glLineWidth(2.5F); gl.glBegin(GL.GL_POLYGON); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, frameHeight - frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, frameHeight - frameHeight*(o.getPosition().getY()-h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()+w)/size.width, frameHeight - frameHeight*(o.getPosition().getY()+h)/size.height); gl.glVertex2d(frameWidth*(o.getPosition().getX()-w)/size.width, frameHeight - frameHeight*(o.getPosition().getY()+h)/size.height); gl.glEnd(); } } int popSize = newPops.size(); for(int i = 0; i < popSize; i ++) { List<IAgent> agents = newPops.get(i).getAgents(); int size = agents.size(); IAgent a; for(int j = 0; j < size; j++) { a = agents.get(j); Color c = a.getColor(); gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha()); Position p = a.getPosition(); /*double cx = p.getX(); double cy = getHeight() - p.getY(); double radius = a.getWidth()/2 + 5;*/ double height = (double)a.getHeight(); double width = (double)a.getWidth(); double originalX = a.getVelocity().x; double originalY = a.getVelocity().y; double originalNorm = getNorm(originalX, originalY); //if(v.getX() != 0 && v.getY() != 0) { gl.glBegin(GL.GL_TRIANGLES); double x = originalX * 2.0*height/(3.0*originalNorm); double y = originalY * 2.0*height/(3.0*originalNorm); //Vector bodyCenter = new Vector(p.getX(), p.getY()); double xBodyCenter = p.getX(); double yBodyCenter = p.getY(); //Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter); double noseX = x+xBodyCenter; double noseY = y+yBodyCenter; double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter; double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ; //Vector legLengthVector = new Vector(-originalY/originalX,1); double legLengthX1 = -originalY/originalX; double legLengthY1 = 1; double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 )); //legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); legLengthX1 = legLengthX1 * legLenthVectorNorm2; legLengthY1 = legLengthY1 * legLenthVectorNorm2; //Vector rightLeg = legLengthVector; double rightLegX = legLengthX1 + bottomX; double rightLegY = legLengthY1 + bottomY; //v = new Vector(a.getVelocity()); double legLengthX2 = originalY/originalX * legLenthVectorNorm2; double legLengthY2 = -1 * legLenthVectorNorm2; //legLengthVector = new Vector(originalY/originalX,-1); // legLengthVector = legLengthVector.multiply(legLenthVectorNorm2); //Vector leftLeg = legLengthVector.add(bottom); //Vector leftLeg = legLengthVector; double leftLegX = legLengthX2 + bottomX; double leftLegY = legLengthY2 + bottomY; gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY); gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY); gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY); gl.glEnd(); /*} else { for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){ gl.glBegin(GL.GL_TRIANGLES); gl.glVertex2d(cx, cy); gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius); gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius); gl.glEnd(); } }*/ } }
diff --git a/src/main/java/com/yellowbkpk/geo/xapi/servlet/XapiServlet.java b/src/main/java/com/yellowbkpk/geo/xapi/servlet/XapiServlet.java index 3deb425..3314bc0 100644 --- a/src/main/java/com/yellowbkpk/geo/xapi/servlet/XapiServlet.java +++ b/src/main/java/com/yellowbkpk/geo/xapi/servlet/XapiServlet.java @@ -1,193 +1,194 @@ package com.yellowbkpk.geo.xapi.servlet; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URLDecoder; import java.util.logging.Logger; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openstreetmap.osmosis.core.OsmosisRuntimeException; import org.openstreetmap.osmosis.core.container.v0_6.EntityContainer; import org.openstreetmap.osmosis.core.database.DatabaseLoginCredentials; import org.openstreetmap.osmosis.core.database.DatabasePreferences; import org.openstreetmap.osmosis.core.lifecycle.ReleasableIterator; import org.openstreetmap.osmosis.core.task.v0_6.Sink; import com.yellowbkpk.geo.xapi.admin.XapiQueryStats; import com.yellowbkpk.geo.xapi.db.PostgreSqlDatasetContext; import com.yellowbkpk.geo.xapi.db.Selector; import com.yellowbkpk.geo.xapi.db.Selector.BoundingBox; import com.yellowbkpk.geo.xapi.query.XAPIParseException; import com.yellowbkpk.geo.xapi.query.XAPIQueryInfo; public class XapiServlet extends HttpServlet { private static final DatabasePreferences preferences = new DatabasePreferences(false, false); private static Logger log = Logger.getLogger("XAPI"); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String host = getServletContext().getInitParameter("xapi.db.host"); String database = getServletContext().getInitParameter("xapi.db.database"); String user = getServletContext().getInitParameter("xapi.db.username"); String password = getServletContext().getInitParameter("xapi.db.password"); DatabaseLoginCredentials loginCredentials = new DatabaseLoginCredentials(host, database, user, password, true, false, null); float maxBboxArea = Float.parseFloat(getServletContext().getInitParameter("xapi.max_bbox_area")); XapiQueryStats tracker = XapiQueryStats.beginTracking(Thread.currentThread()); try { // Parse URL XAPIQueryInfo info = null; Filetype filetype = Filetype.xml; try { StringBuffer urlBuffer = request.getRequestURL(); if (request.getQueryString() != null) { urlBuffer.append("?").append(request.getQueryString()); } String reqUrl = urlBuffer.toString(); String query = reqUrl.substring(reqUrl.lastIndexOf('/') + 1); query = URLDecoder.decode(query, "UTF-8"); if(XapiQueryStats.isQueryAlreadyRunning(query, request.getRemoteHost())) { response.sendError(500, "Ignoring a duplicate request from this address. Be patient!"); tracker.receivedUrl(query, request.getRemoteHost()); tracker.error(); return; } tracker.receivedUrl(query, request.getRemoteHost()); log.info("Query " + query); info = XAPIQueryInfo.fromString(query); if (info.getFiletype() != null) { filetype = info.getFiletype(); } } catch (XAPIParseException e) { tracker.error(e); response.sendError(500, "Could not parse query: " + e.getMessage()); return; } if(!filetype.isSinkInstalled()) { response.sendError(500, "I don't know how to serialize that."); return; } if(info.getBboxSelectors().size() + info.getTagSelectors().size() < 1) { tracker.error(); response.sendError(500, "Must have at least one selector."); return; } double totalArea = 0; for (BoundingBox bbox : info.getBboxSelectors()) { totalArea += bbox.area(); } if(totalArea > maxBboxArea) { tracker.error(); response.sendError(500, "Maximum bounding box area is " + maxBboxArea + " square degrees."); return; } // Query DB PostgreSqlDatasetContext datasetReader = null; ReleasableIterator<EntityContainer> bboxData = null; long elements = 0; long middle; try { tracker.startDbQuery(); long start = System.currentTimeMillis(); datasetReader = new PostgreSqlDatasetContext(loginCredentials, preferences); bboxData = makeRequestIterator(datasetReader, info); if (bboxData == null) { response.sendError(500, "Unsupported operation."); + tracker.error(); return; } tracker.startSerialization(); middle = System.currentTimeMillis(); log.info("Query complete: " + (middle - start) + "ms"); // Build up a writer connected to the response output stream response.setContentType(filetype.getContentTypeString()); OutputStream outputStream = response.getOutputStream(); String acceptEncodingHeader = request.getHeader("Accept-Encoding"); if(acceptEncodingHeader != null && acceptEncodingHeader.contains("gzip")) { outputStream = new GZIPOutputStream(outputStream); response.setHeader("Content-Encoding", "gzip"); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream)); // Serialize to the client Sink sink = filetype.getSink(out); while (bboxData.hasNext()) { elements++; sink.process(bboxData.next()); } sink.complete(); out.flush(); out.close(); } finally { bboxData.release(); datasetReader.complete(); tracker.elementsSerialized(elements); } long end = System.currentTimeMillis(); log.info("Serialization complete: " + (end - middle) + "ms"); tracker.complete(); } catch(OsmosisRuntimeException e) { tracker.error(e); throw e; } catch(IOException e) { tracker.error(e); throw e; } catch(RuntimeException e) { tracker.error(e); throw e; } } /** * Creates an Osmosis releasable iterator over all the elements which are selected by the query. * * @param datasetReader The database context to use when executing queries. * @param info Object encapsulating the query information. * @return An iterator over all the entities which match the query, or null if the query could not be executed. */ public static ReleasableIterator<EntityContainer> makeRequestIterator(PostgreSqlDatasetContext datasetReader, XAPIQueryInfo info) { ReleasableIterator<EntityContainer> bboxData = null; if(XAPIQueryInfo.RequestType.NODE.equals(info.getKind())) { bboxData = datasetReader.iterateSelectedNodes(info.getBboxSelectors(), info.getTagSelectors()); } else if(XAPIQueryInfo.RequestType.WAY.equals(info.getKind())) { bboxData = datasetReader.iterateSelectedWays(info.getBboxSelectors(), info.getTagSelectors()); } else if(XAPIQueryInfo.RequestType.RELATION.equals(info.getKind())) { bboxData = datasetReader.iterateSelectedRelations(info.getBboxSelectors(), info.getTagSelectors()); } else if(XAPIQueryInfo.RequestType.ALL.equals(info.getKind())) { bboxData = datasetReader.iterateSelectedPrimitives(info.getBboxSelectors(), info.getTagSelectors()); } else if(XAPIQueryInfo.RequestType.MAP.equals(info.getKind())) { Selector.BoundingBox boundingBox = info.getBboxSelectors().get(0); bboxData = datasetReader.iterateBoundingBox(boundingBox.getLeft(), boundingBox.getRight(), boundingBox.getTop(), boundingBox.getBottom(), true); } return bboxData; } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String host = getServletContext().getInitParameter("xapi.db.host"); String database = getServletContext().getInitParameter("xapi.db.database"); String user = getServletContext().getInitParameter("xapi.db.username"); String password = getServletContext().getInitParameter("xapi.db.password"); DatabaseLoginCredentials loginCredentials = new DatabaseLoginCredentials(host, database, user, password, true, false, null); float maxBboxArea = Float.parseFloat(getServletContext().getInitParameter("xapi.max_bbox_area")); XapiQueryStats tracker = XapiQueryStats.beginTracking(Thread.currentThread()); try { // Parse URL XAPIQueryInfo info = null; Filetype filetype = Filetype.xml; try { StringBuffer urlBuffer = request.getRequestURL(); if (request.getQueryString() != null) { urlBuffer.append("?").append(request.getQueryString()); } String reqUrl = urlBuffer.toString(); String query = reqUrl.substring(reqUrl.lastIndexOf('/') + 1); query = URLDecoder.decode(query, "UTF-8"); if(XapiQueryStats.isQueryAlreadyRunning(query, request.getRemoteHost())) { response.sendError(500, "Ignoring a duplicate request from this address. Be patient!"); tracker.receivedUrl(query, request.getRemoteHost()); tracker.error(); return; } tracker.receivedUrl(query, request.getRemoteHost()); log.info("Query " + query); info = XAPIQueryInfo.fromString(query); if (info.getFiletype() != null) { filetype = info.getFiletype(); } } catch (XAPIParseException e) { tracker.error(e); response.sendError(500, "Could not parse query: " + e.getMessage()); return; } if(!filetype.isSinkInstalled()) { response.sendError(500, "I don't know how to serialize that."); return; } if(info.getBboxSelectors().size() + info.getTagSelectors().size() < 1) { tracker.error(); response.sendError(500, "Must have at least one selector."); return; } double totalArea = 0; for (BoundingBox bbox : info.getBboxSelectors()) { totalArea += bbox.area(); } if(totalArea > maxBboxArea) { tracker.error(); response.sendError(500, "Maximum bounding box area is " + maxBboxArea + " square degrees."); return; } // Query DB PostgreSqlDatasetContext datasetReader = null; ReleasableIterator<EntityContainer> bboxData = null; long elements = 0; long middle; try { tracker.startDbQuery(); long start = System.currentTimeMillis(); datasetReader = new PostgreSqlDatasetContext(loginCredentials, preferences); bboxData = makeRequestIterator(datasetReader, info); if (bboxData == null) { response.sendError(500, "Unsupported operation."); return; } tracker.startSerialization(); middle = System.currentTimeMillis(); log.info("Query complete: " + (middle - start) + "ms"); // Build up a writer connected to the response output stream response.setContentType(filetype.getContentTypeString()); OutputStream outputStream = response.getOutputStream(); String acceptEncodingHeader = request.getHeader("Accept-Encoding"); if(acceptEncodingHeader != null && acceptEncodingHeader.contains("gzip")) { outputStream = new GZIPOutputStream(outputStream); response.setHeader("Content-Encoding", "gzip"); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream)); // Serialize to the client Sink sink = filetype.getSink(out); while (bboxData.hasNext()) { elements++; sink.process(bboxData.next()); } sink.complete(); out.flush(); out.close(); } finally { bboxData.release(); datasetReader.complete(); tracker.elementsSerialized(elements); } long end = System.currentTimeMillis(); log.info("Serialization complete: " + (end - middle) + "ms"); tracker.complete(); } catch(OsmosisRuntimeException e) { tracker.error(e); throw e; } catch(IOException e) { tracker.error(e); throw e; } catch(RuntimeException e) { tracker.error(e); throw e; } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String host = getServletContext().getInitParameter("xapi.db.host"); String database = getServletContext().getInitParameter("xapi.db.database"); String user = getServletContext().getInitParameter("xapi.db.username"); String password = getServletContext().getInitParameter("xapi.db.password"); DatabaseLoginCredentials loginCredentials = new DatabaseLoginCredentials(host, database, user, password, true, false, null); float maxBboxArea = Float.parseFloat(getServletContext().getInitParameter("xapi.max_bbox_area")); XapiQueryStats tracker = XapiQueryStats.beginTracking(Thread.currentThread()); try { // Parse URL XAPIQueryInfo info = null; Filetype filetype = Filetype.xml; try { StringBuffer urlBuffer = request.getRequestURL(); if (request.getQueryString() != null) { urlBuffer.append("?").append(request.getQueryString()); } String reqUrl = urlBuffer.toString(); String query = reqUrl.substring(reqUrl.lastIndexOf('/') + 1); query = URLDecoder.decode(query, "UTF-8"); if(XapiQueryStats.isQueryAlreadyRunning(query, request.getRemoteHost())) { response.sendError(500, "Ignoring a duplicate request from this address. Be patient!"); tracker.receivedUrl(query, request.getRemoteHost()); tracker.error(); return; } tracker.receivedUrl(query, request.getRemoteHost()); log.info("Query " + query); info = XAPIQueryInfo.fromString(query); if (info.getFiletype() != null) { filetype = info.getFiletype(); } } catch (XAPIParseException e) { tracker.error(e); response.sendError(500, "Could not parse query: " + e.getMessage()); return; } if(!filetype.isSinkInstalled()) { response.sendError(500, "I don't know how to serialize that."); return; } if(info.getBboxSelectors().size() + info.getTagSelectors().size() < 1) { tracker.error(); response.sendError(500, "Must have at least one selector."); return; } double totalArea = 0; for (BoundingBox bbox : info.getBboxSelectors()) { totalArea += bbox.area(); } if(totalArea > maxBboxArea) { tracker.error(); response.sendError(500, "Maximum bounding box area is " + maxBboxArea + " square degrees."); return; } // Query DB PostgreSqlDatasetContext datasetReader = null; ReleasableIterator<EntityContainer> bboxData = null; long elements = 0; long middle; try { tracker.startDbQuery(); long start = System.currentTimeMillis(); datasetReader = new PostgreSqlDatasetContext(loginCredentials, preferences); bboxData = makeRequestIterator(datasetReader, info); if (bboxData == null) { response.sendError(500, "Unsupported operation."); tracker.error(); return; } tracker.startSerialization(); middle = System.currentTimeMillis(); log.info("Query complete: " + (middle - start) + "ms"); // Build up a writer connected to the response output stream response.setContentType(filetype.getContentTypeString()); OutputStream outputStream = response.getOutputStream(); String acceptEncodingHeader = request.getHeader("Accept-Encoding"); if(acceptEncodingHeader != null && acceptEncodingHeader.contains("gzip")) { outputStream = new GZIPOutputStream(outputStream); response.setHeader("Content-Encoding", "gzip"); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outputStream)); // Serialize to the client Sink sink = filetype.getSink(out); while (bboxData.hasNext()) { elements++; sink.process(bboxData.next()); } sink.complete(); out.flush(); out.close(); } finally { bboxData.release(); datasetReader.complete(); tracker.elementsSerialized(elements); } long end = System.currentTimeMillis(); log.info("Serialization complete: " + (end - middle) + "ms"); tracker.complete(); } catch(OsmosisRuntimeException e) { tracker.error(e); throw e; } catch(IOException e) { tracker.error(e); throw e; } catch(RuntimeException e) { tracker.error(e); throw e; } }
diff --git a/luni/src/main/java/java/lang/ref/FinalizerReference.java b/luni/src/main/java/java/lang/ref/FinalizerReference.java index a3f90248d..2d5cef20b 100644 --- a/luni/src/main/java/java/lang/ref/FinalizerReference.java +++ b/luni/src/main/java/java/lang/ref/FinalizerReference.java @@ -1,76 +1,76 @@ /* * Copyright (C) 2011 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 java.lang.ref; import java.lang.FinalizerThread; /** * @hide */ public final class FinalizerReference<T> extends Reference<T> { private static FinalizerReference head = null; private T zombie; private FinalizerReference prev; private FinalizerReference next; public FinalizerReference(T r, ReferenceQueue<? super T> q) { super(r, q); } @Override public T get() { return zombie; } @Override public void clear() { zombie = null; } static void add(Object referent) { ReferenceQueue<Object> queue = FinalizerThread.queue; FinalizerReference<?> reference = new FinalizerReference<Object>(referent, queue); synchronized (FinalizerReference.class) { reference.prev = null; reference.next = head; if (head != null) { head.prev = reference; } head = reference; } } public static void remove(FinalizerReference reference) { synchronized (FinalizerReference.class) { FinalizerReference next = reference.next; FinalizerReference prev = reference.prev; reference.next = null; reference.prev = null; if (prev != null) { prev.next = next; } else { - head = reference; + head = next; } if (next != null) { next.prev = prev; } } } }
true
true
public static void remove(FinalizerReference reference) { synchronized (FinalizerReference.class) { FinalizerReference next = reference.next; FinalizerReference prev = reference.prev; reference.next = null; reference.prev = null; if (prev != null) { prev.next = next; } else { head = reference; } if (next != null) { next.prev = prev; } } }
public static void remove(FinalizerReference reference) { synchronized (FinalizerReference.class) { FinalizerReference next = reference.next; FinalizerReference prev = reference.prev; reference.next = null; reference.prev = null; if (prev != null) { prev.next = next; } else { head = next; } if (next != null) { next.prev = prev; } } }
diff --git a/src/joshua/util/ExtractTopCand.java b/src/joshua/util/ExtractTopCand.java index e4fb0f4e..a9b64999 100644 --- a/src/joshua/util/ExtractTopCand.java +++ b/src/joshua/util/ExtractTopCand.java @@ -1,187 +1,187 @@ /* This file is part of the Joshua Machine Translation System. * * Joshua 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 joshua.util; import joshua.util.io.LineReader; import joshua.util.io.IndexedReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.FileOutputStream; import java.io.IOException; /** * This program extracts the 1-best output translations from the * n-best output translations generated by * {@link joshua.decoder.JoshuaDecoder}. * * @author wren ng thornton <[email protected]> * @version $LastChangedDate: 2009-03-26 15:06:57 -0400 (Thu, 26 Mar 2009) $ */ /* TODO: This class should be renamed, something like ExtractBestCandidates * or ExtractBestTranslations. Saying "top" implies more than one * (the top how many?) and "cand" is unnecessary abbreviation (also, * who cares about candidacy?). Once we rename this, the * ./example2/decode_example2.sh script will need updating (as will * the end-to-end code) */ public class ExtractTopCand { /** * Usage: <code>java ExtractTopCand nbestInputFile 1bestOutputFile</code>. * <p> * If the input file name is "-" then input is read from * <code>System.in</code>. If the output file name is "-" * then output is directed to <code>System.out</code>. If * a file already exists with the output file name, it is * truncated before writing. The bulk of this program is * implemented by * {@link #extractOneBest(IndexedReader,BufferedWriter)}. */ public static void main(String[] args) { String inFile = "-"; String outFile = "-"; if (args.length == 1) { inFile = args[0]; } else if (args.length == 2) { inFile = args[0]; outFile = args[1]; } else { System.err.println("Usage: ExtractTopCand [nbestInputFile [1bestOutputFile]]\n (default to stdin/stdout)"); System.exit(1); } try { // TODO: see documentation for extractOneBest // regarding using an n-best SegmentFileParser. IndexedReader<String> nbestReader = new IndexedReader<String>("line", "-".equals(inFile) ? new LineReader(System.in) - : new LineReader(inFile)); + : new LineReader(inFile)); /* TODO: This duplicates FileUtility.getWriteFileStream * but with the addition of defaulting to System.out; * should fix that (without breaking other clients * of that method). We ultimately want something which * autochecks for errors (like Writer); has a newLine * method (like BufferedWriter); can wrap System.out; * can autoflush; and it'd be handy to have the * print/println methods of PrintStream/PrintWriter * to boot. PrintWriter *almost* gives us all this, * but it swallows errors and gives no way to * retrieve them >:( */ BufferedWriter onebestWriter = new BufferedWriter( new OutputStreamWriter( ("-".equals(outFile) ? System.out : new FileOutputStream(outFile, false) ), "UTF-8")); extractOneBest(nbestReader, onebestWriter); } catch (IOException ioe) { // NOTE: if our onebest was System.out, then that // will already have been closed by the finally // block. Printing to a closed PrintStream generates // no exceptions. We should be printing to System.err // anyways, but this something subtle to be aware of. System.err.println("There was an error: " + ioe.getMessage()); } } /** * Prints the one-best translation for each segment ID from * the reader as a line on the writer, and closes both * before exiting. The translations for a segment are printed * in the order of the first occurance of the segment ID. * Any information about the segment other than the translation * (including segment ID) is not printed to the writer. * * <h4>Developer Notes</h4> * This implementation assumes: * <ol> * <li>all translations for a segment are contiguous</li> * <li>the 1-best translation is the first one encountered.</li> * </ol> * We will need to alter the implementation if these * assumptions no longer hold for the output of JoshuaDecoder * (or any sensible n-best format passed to this method). * <p> * We should switch to using an n-best * {@link joshua.decoder.segment_file.SegmentFileParser} * to ensure future compatibility with being able to configure * the output format of the decoder. The MERT code needs * such a SegmentFileParser anyways, so that will reduce * the code duplication between these two classes. */ protected static void extractOneBest( IndexedReader<String> nbestReader, BufferedWriter onebestWriter) throws IOException { try { String prevID = null; for (String line : nbestReader) { String[] columns = Regex.threeBarsWithSpace.split(line); // We allow non-integer segment IDs because the // Segment interface does, and we have no reason // to add new restrictions. String newID = columns[0].trim(); // We want to give the same error message // regardless of whether there's a leading space // or not. And, we don't want to accidentally // accept lines with lots and lots of columns. if ("".equals(newID) || newID.startsWith("|||")) { throw nbestReader.wrapIOException( new IOException("Malformed line, missing segment ID:\n" + line)); } // Make sure there's a translation there too // TODO: good error message for when the second // "|||" doesn't have a following field, m/\|{3}\s*$/ if (3 > columns.length) { throw nbestReader.wrapIOException( new IOException("Malformed line, should have at least two \" ||| \":\n" + line)); } if (null == prevID || ! prevID.equals(newID)) { onebestWriter.write(columns[1], 0, columns[1].length()); onebestWriter.newLine(); onebestWriter.flush(); prevID = newID; } } } finally { try { nbestReader.close(); } finally { onebestWriter.close(); } } } }
true
true
public static void main(String[] args) { String inFile = "-"; String outFile = "-"; if (args.length == 1) { inFile = args[0]; } else if (args.length == 2) { inFile = args[0]; outFile = args[1]; } else { System.err.println("Usage: ExtractTopCand [nbestInputFile [1bestOutputFile]]\n (default to stdin/stdout)"); System.exit(1); } try { // TODO: see documentation for extractOneBest // regarding using an n-best SegmentFileParser. IndexedReader<String> nbestReader = new IndexedReader<String>("line", "-".equals(inFile) ? new LineReader(System.in) : new LineReader(inFile)); /* TODO: This duplicates FileUtility.getWriteFileStream * but with the addition of defaulting to System.out; * should fix that (without breaking other clients * of that method). We ultimately want something which * autochecks for errors (like Writer); has a newLine * method (like BufferedWriter); can wrap System.out; * can autoflush; and it'd be handy to have the * print/println methods of PrintStream/PrintWriter * to boot. PrintWriter *almost* gives us all this, * but it swallows errors and gives no way to * retrieve them >:( */ BufferedWriter onebestWriter = new BufferedWriter( new OutputStreamWriter( ("-".equals(outFile) ? System.out : new FileOutputStream(outFile, false) ), "UTF-8")); extractOneBest(nbestReader, onebestWriter); } catch (IOException ioe) { // NOTE: if our onebest was System.out, then that // will already have been closed by the finally // block. Printing to a closed PrintStream generates // no exceptions. We should be printing to System.err // anyways, but this something subtle to be aware of. System.err.println("There was an error: " + ioe.getMessage()); } }
public static void main(String[] args) { String inFile = "-"; String outFile = "-"; if (args.length == 1) { inFile = args[0]; } else if (args.length == 2) { inFile = args[0]; outFile = args[1]; } else { System.err.println("Usage: ExtractTopCand [nbestInputFile [1bestOutputFile]]\n (default to stdin/stdout)"); System.exit(1); } try { // TODO: see documentation for extractOneBest // regarding using an n-best SegmentFileParser. IndexedReader<String> nbestReader = new IndexedReader<String>("line", "-".equals(inFile) ? new LineReader(System.in) : new LineReader(inFile)); /* TODO: This duplicates FileUtility.getWriteFileStream * but with the addition of defaulting to System.out; * should fix that (without breaking other clients * of that method). We ultimately want something which * autochecks for errors (like Writer); has a newLine * method (like BufferedWriter); can wrap System.out; * can autoflush; and it'd be handy to have the * print/println methods of PrintStream/PrintWriter * to boot. PrintWriter *almost* gives us all this, * but it swallows errors and gives no way to * retrieve them >:( */ BufferedWriter onebestWriter = new BufferedWriter( new OutputStreamWriter( ("-".equals(outFile) ? System.out : new FileOutputStream(outFile, false) ), "UTF-8")); extractOneBest(nbestReader, onebestWriter); } catch (IOException ioe) { // NOTE: if our onebest was System.out, then that // will already have been closed by the finally // block. Printing to a closed PrintStream generates // no exceptions. We should be printing to System.err // anyways, but this something subtle to be aware of. System.err.println("There was an error: " + ioe.getMessage()); } }
diff --git a/core/src/visad/trunk/Contour2D.java b/core/src/visad/trunk/Contour2D.java index 177558a72..dd23241a8 100644 --- a/core/src/visad/trunk/Contour2D.java +++ b/core/src/visad/trunk/Contour2D.java @@ -1,4623 +1,4625 @@ // // Contour2D.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2006 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.util.HashMap; /** Contour2D is a class equipped with a 2-D contouring function.<P> */ public class Contour2D { // Applet variables protected Contour2D con; protected int whichlabels = 0; protected boolean showgrid; protected int rows, cols, scale; protected int[] num1, num2, num3, num4; protected float[][] vx1, vy1, vx2, vy2, vx3, vy3, vx4, vy4; public static final int EASY = 0; public static final int HARD = 1; public static final int DIFFICULTY_THRESHOLD = 7000; public static final float DIMENSION_THRESHOLD = 5.0E5f; /** * Compute contour lines for a 2-D array. If the interval is negative, * then contour lines less than base will be drawn as dashed lines. * The contour lines will be computed for all V such that:<br> * lowlimit <= V <= highlimit<br> * and V = base + n*interval for some integer n<br> * Note that the input array, g, should be in column-major (FORTRAN) order. * * @param g the 2-D array to contour. * @param nr size of 2-D array in rows * @param nc size of 2-D array in columns. * @param interval contour interval * @param lowlimit the lower limit on values to contour. * @param highlimit the upper limit on values to contour. * @param base base value to start contouring at. * @param vx1 array to put contour line vertices (x value) * @param vy1 array to put contour line vertices (y value) * @param maxv1 size of vx1, vy1 arrays * @param numv1 pointer to int to return number of vertices in vx1,vy1 * @param vx2 array to put 'hidden' contour line vertices (x value) * @param vy2 array to put 'hidden' contour line vertices (y value) * @param maxv2 size of vx2, vy2 arrays * @param numv2 pointer to int to return number of vertices in vx2,vy2 * @param vx3 array to put contour label vertices (x value) * @param vy3 array to put contour label vertices (y value) * @param maxv3 size of vx3, vy3 arrays * @param numv3 pointer to int to return number of vertices in vx3,vy3 * @param vx4 array to put contour label vertices, inverted (x value) * @param vy4 array to put contour label vertices, inverted (y value) * <br>** see note for VxB and VyB in PlotDigits.java ** * @param maxv4 size of vx4, vy4 arrays * @param numv4 pointer to int to return number of vertices in vx4,vy4 */ public static void contour( float g[], int nr, int nc, float interval, float lowlimit, float highlimit, float base, float vx1[][], float vy1[][], float[][] vz1, int maxv1, int[] numv1, float vx2[][], float vy2[][], float[][] vz2, int maxv2, int[] numv2, float vx3[][], float vy3[][], float[][] vz3, int maxv3, int[] numv3, float vx4[][], float vy4[][], float[][] vz4, int maxv4, int[] numv4, byte[][] auxValues, byte[][] auxLevels1, byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap, boolean fill, float[][] tri, byte[][] tri_color, float[][][] grd_normals, float[][] tri_normals, byte[][] interval_colors, float[][][][] lbl_vv, byte[][][][] lbl_cc, float[][][] lbl_loc, double scale_ratio, double label_size, byte[] labelColor, Gridded3DSet spatial_set) throws VisADException { boolean[] dashes = {false}; float[] intervals = intervalToLevels(interval, lowlimit, highlimit, base, dashes); boolean dash = dashes[0]; contour( g, nr, nc, intervals, lowlimit, highlimit, base, dash, vx1, vy1, vz1, maxv1, numv1, vx2, vy2, vz2, maxv2, numv2, vx3, vy3, vz3, maxv3, numv3, vx4, vy4, vz4, maxv4, numv4, auxValues, auxLevels1, auxLevels2, auxLevels3, swap, fill, tri, tri_color, grd_normals, tri_normals, interval_colors, lbl_vv, lbl_cc, lbl_loc, scale_ratio, label_size, labelColor, spatial_set); } /** * Returns an array of contour values and an indication on whether to use * dashed lines below the base value. * * @param interval The contouring interval. Must be non-zero. * If the interval is negative, then contour lines * less than the base will be drawn as dashed * lines. Must not be NaN. * @param low The minimum contour value. The returned array * will not contain a value below this. Must not * be NaN. * @param high The maximum contour value. The returned array * will not contain a value above this. Must not * be NaN. * @param ba The base contour value. The returned values * will be integer multiples of the interval * away from this this value. Must not be NaN. * dash Whether or not contour lines less than the base * should be drawn as dashed lines. This is a * computed and returned value. * @throws VisADException The contour interval is zero or too small. */ public static float[] intervalToLevels(float interval, float low, float high, float ba, boolean[] dash) throws VisADException { float[] levs = null; if (interval == 0.0) { throw new VisADException("Contour interval cannot be zero"); } dash[0] = false; if (interval < 0) { dash[0] = true; interval = -interval; } // compute list of contours // compute nlo and nhi, for low and high contour values in the box long nlo = Math.round((Math.ceil((low - ba) / Math.abs(interval)))); long nhi = Math.round((Math.floor((high - ba) / Math.abs(interval)))); // how many contour lines are needed. int numc = (int) (nhi - nlo) + 1; if (numc < 1) return levs; if (numc > 4000) { throw new VisADException("Contour interval " + interval + " too small for range " + low + "," + high ); } try { levs = new float[numc]; } catch (OutOfMemoryError e) { throw new VisADException("Contour interval too small"); } for(int i = 0; i < numc; i++) { levs[i] = ba + (nlo + i) * interval; } return levs; } /** * Compute contour lines for a 2-D array. If the interval is negative, * then contour lines less than base will be drawn as dashed lines. * The contour lines will be computed for all V such that:<br> * lowlimit <= V <= highlimit<br> * and V = base + n*interval for some integer n<br> * Note that the input array, g, should be in column-major (FORTRAN) order. * * @param g the 2-D array to contour. * @param nr size of 2-D array in rows * @param nc size of 2-D array in columns. * @param values the values to be plotted * @param lowlimit the lower limit on values to contour. * @param highlimit the upper limit on values to contour. * @param base base value to start contouring at. * @param dash boolean to dash contours below base or not * @param vx1 array to put contour line vertices (x value) * @param vy1 array to put contour line vertices (y value) * @param vz1 * @param maxv1 size of vx1, vy1 arrays * @param numv1 pointer to int to return number of vertices in vx1,vy1 * @param vx2 array to put 'hidden' contour line vertices (x value) * @param vy2 array to put 'hidden' contour line vertices (y value) * @param vz2 * @param maxv2 size of vx2, vy2 arrays * @param numv2 pointer to int to return number of vertices in vx2,vy2 * @param vx3 array to put contour label vertices (x value) * @param vy3 array to put contour label vertices (y value) * @param vz3 * @param maxv3 size of vx3, vy3 arrays * @param numv3 pointer to int to return number of vertices in vx3,vy3 * @param vx4 array to put contour label vertices, inverted (x value) * @param vy4 array to put contour label vertices, inverted (y value) * <br>** see note for VxB and VyB in PlotDigits.java ** * @param vz4 * @param maxv4 size of vx4, vy4 arrays * @param numv4 pointer to int to return number of vertices in vx4,vy4 * @param auxValues * @param auxLevels1 * @param auxLevels2 * @param auxLevels3 * @param swap * @param fill * @param tri * @param tri_color * @param grd_normals * @param tri_normals * @param interval_colors * @param lbl_vv * @param lbl_cc * @param lbl_loc * @param scale_ratio * @param label_size * @param labelColor RGB label color byte array * @param spatial_set * @throws VisADException */ public static void contour( float g[], int nr, int nc, float[] values, float lowlimit, float highlimit, float base, boolean dash, float vx1[][], float vy1[][], float[][] vz1, int maxv1, int[] numv1, float vx2[][], float vy2[][], float[][] vz2, int maxv2, int[] numv2, float vx3[][], float vy3[][], float[][] vz3, int maxv3, int[] numv3, float vx4[][], float vy4[][], float[][] vz4, int maxv4, int[] numv4, byte[][] auxValues, byte[][] auxLevels1, byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap, boolean fill, float[][] tri, byte[][] tri_color, float[][][] grd_normals, float[][] tri_normals, byte[][] interval_colors, float[][][][] lbl_vv, byte[][][][] lbl_cc, float[][][] lbl_loc, double scale_ratio, double label_size, byte[] labelColor, Gridded3DSet spatial_set) throws VisADException { /* System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit + " highlimit = " + highlimit + " base = " + base); boolean any = false; boolean anymissing = false; boolean anynotmissing = false; */ //System.out.println("contour: swap = " + swap[0] + " " + swap[1] + " " + swap[2]); dash = (fill == true) ? false : dash; PlotDigits plot = new PlotDigits(); int ir, ic; int nrm, ncm; int numc, il; int lr, lc, lc2, lrr, lr2, lcc; float xd, yd ,xx, yy; float xdd, ydd; // float clow, chi; float gg; int maxsize = maxv1+maxv2; float[] vx = new float[maxsize]; float[] vy = new float[maxsize]; // WLH 21 April 2000 // int[] ipnt = new int[2*maxsize]; int[] ipnt = new int[nr*nc+4]; int nump, ip; int numv; /* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */ float[] myvals = null; if (values != null) { myvals = (float[]) values.clone(); java.util.Arrays.sort(myvals); } // flags for each level indicating dashed rendering boolean[] dashFlags = new boolean[myvals.length]; int low; int hi; int t; byte[][] auxLevels = null; int naux = (auxValues != null) ? auxValues.length : 0; byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { if (auxLevels1 == null || auxLevels1.length != naux || auxLevels2 == null || auxLevels2.length != naux || auxLevels3 == null || auxLevels3.length != naux) { throw new SetException("Contour2D.contour: " +"auxLevels length doesn't match"); } for (int i=0; i<naux; i++) { if (auxValues[i].length != g.length) { throw new SetException("Contour2D.contour: " +"auxValues lengths don't match"); } } auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; auxLevels = new byte[naux][maxsize]; } else { if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) { throw new SetException("Contour2D.contour: " +"auxValues null but auxLevels not null"); } } // initialize vertex counts numv1[0] = 0; numv2[0] = 0; numv3[0] = 0; numv4[0] = 0; if (values == null) return; // WLH 24 Aug 99 /* DRM: 1999-05-19 - Not needed since dash is a boolean // check for bad contour interval if (interval==0.0) { throw new DisplayException("Contour2D.contour: interval cannot be 0"); } if (!dash) { // draw negative contour lines as dashed lines interval = -interval; idash = 1; } else { idash = 0; } */ nrm = nr-1; ncm = nc-1; xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0 ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0 /**-TDR xd = xdd - 0.0001f; yd = ydd - 0.0001f; gap too big **/ xd = xdd - 0.00002f; yd = ydd - 0.00002f; /* * set up mark array * mark= 0 if avail for label center, * 2 if in label, and * 1 if not available and not in label * * lr and lc give label size in grid boxes * lrr and lcc give unavailable radius */ if (swap[0]) { lr = 1+(nr-2)/10; lc = 1+(nc-2)/50; } else { lr = 1+(nr-2)/50; lc = 1+(nc-2)/10; } lc2 = lc/2; lr2 = lr/2; lrr = 1+(nr-2)/8; lcc = 1+(nc-2)/8; // allocate mark array char[] mark = new char[nr * nc]; // initialize mark array to zeros for (int i=0; i<nr * nc; i++) mark[i] = 0; // set top and bottom rows to 1 float max_g = -Float.MAX_VALUE; float min_g = Float.MAX_VALUE; for (ic=0;ic<nc;ic++) { for (ir=0;ir<lr;ir++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (ic) * nr + (nr-ir-2) ] = 1; float val = g[(ic) * nr + (ir)]; if (val > max_g) max_g = val; if (val < min_g) min_g = val; } } // set left and right columns to 1 for (ir=0;ir<nr;ir++) { for (ic=0;ic<lc;ic++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (nc-ic-2) * nr + (ir) ] = 1; } } numv = nump = 0; //- color fill arrays byte[][] color_bin = null; byte[][][] o_flags = null; short[][] n_lines = null; short[][] ctrLow = null; if (fill) { color_bin = interval_colors; o_flags = new byte[nrm][ncm][]; n_lines = new short[nrm][ncm]; ctrLow = new short[nrm][ncm]; } //- estimate contour difficutly int ctr_lo = 0; int ctr_hi = myvals.length-1; for (int k=0; k<myvals.length; k++) { if (min_g >= myvals[k]) ctr_lo = k; if (max_g >= myvals[k]) ctr_hi = k; } - float ctr_int = myvals[1] - myvals[0]; int switch_cnt = 0; - float[] last_diff = new float[(ctr_hi-ctr_lo)+1]; - for (ir=2; ir<nrm-2; ir+=1) { - for (int k=0; k<last_diff.length;k++) { - last_diff[k] = g[ir] - myvals[ctr_lo+k]; - for (ic=2; ic<ncm-2; ic+=1) { - float diff = g[ic*nr + ir] - myvals[ctr_lo+k]; - if ((diff*last_diff[k] < 0) && ((diff > 0.005*ctr_int) || (diff < -0.005*ctr_int)) ) { - switch_cnt++; + if (myvals.length > 1) { + float ctr_int = myvals[1] - myvals[0]; + float[] last_diff = new float[(ctr_hi-ctr_lo)+1]; + for (ir=2; ir<nrm-2; ir+=1) { + for (int k=0; k<last_diff.length;k++) { + last_diff[k] = g[ir] - myvals[ctr_lo+k]; + for (ic=2; ic<ncm-2; ic+=1) { + float diff = g[ic*nr + ir] - myvals[ctr_lo+k]; + if ((diff*last_diff[k] < 0) && ((diff > 0.005*ctr_int) || (diff < -0.005*ctr_int)) ) { + switch_cnt++; + } + last_diff[k] = diff; } - last_diff[k] = diff; } } } int contourDifficulty = Contour2D.EASY; if (switch_cnt > Contour2D.DIFFICULTY_THRESHOLD) contourDifficulty = Contour2D.HARD; ContourStripSet ctrSet = new ContourStripSet(nrm, myvals, swap, scale_ratio, label_size, nr, nc, spatial_set, contourDifficulty); // compute contours for (ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; // = ir for (ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; float gv, gn, gx; float tmp1, tmp2; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } // save index of first vertex in this grid box ipnt[nump++] = numv; yy = ydd*ic+0.0f; // = ic /* ga = ( g[ (ic) * nr + (ir) ] ); gb = ( g[ (ic) * nr + (ir+1) ] ); gc = ( g[ (ic+1) * nr + (ir) ] ); gd = ( g[ (ic+1) * nr + (ir+1) ] ); boolean miss = false; if (ga != ga || gb != gb || gc != gc || gd != gd) { miss = true; System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " + ga + " " + gb + " " + gc + " " + gd); } */ /* if (ga != ga || gb != gb || gc != gc || gd != gd) { if (!anymissing) { anymissing = true; System.out.println("missing"); } } else { if (!anynotmissing) { anynotmissing = true; System.out.println("notmissing"); } } */ // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; /* DRM move outside the loop byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; */ if (naux > 0) { for (int i=0; i<naux; i++) { auxa[i] = auxValues[i][(ic) * nr + (ir)]; auxb[i] = auxValues[i][(ic) * nr + (ir+1)]; auxc[i] = auxValues[i][(ic+1) * nr + (ir)]; auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)]; } } // find average, min, and max of 4 corner values gv = (ga+gb+gc+gd)/4.0f; // gn = MIN4(ga,gb,gc,gd); tmp1 = ( (ga) < (gb) ? (ga) : (gb) ); tmp2 = ( (gc) < (gd) ? (gc) : (gd) ); gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) ); // gx = MAX4(ga,gb,gc,gd); tmp1 = ( (ga) > (gb) ? (ga) : (gb) ); tmp2 = ( (gc) > (gd) ? (gc) : (gd) ); gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) ); /* remove for new signature, replace with code below // compute clow and chi, low and high contour values in the box tmp1 = (gn-base) / interval; clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )-1); while (clow<gn) { clow += interval; } tmp1 = (gx-base) / interval; chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )+1); while (chi>gx) { chi -= interval; } // how many contour lines in the box: tmp1 = (chi-clow) / interval; numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) ); // gg is current contour line value gg = clow; */ low = 0; hi = myvals.length - 1; if (myvals[low] > gx || myvals[hi] < gn) // no contours { numc = 1; } else // some inside the box { for (int i = 0; i < myvals.length; i++) { if (i == 0 && myvals[i] >= gn) { low = i; } else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; } if (i == 0 && myvals[i] >= gx) { hi = i; } else if (myvals[i] >= gx && myvals[i-1] < gx) { hi = i; } } numc = hi - low + 1; } gg = myvals[low]; /* if (!any && numc > 0) { System.out.println("gn = " + gn + " gx = " + gx + " gv = " + gv); System.out.println("numc = " + numc + " clow = " + myvals[low] + " chi = " + myvals[hi]); any = true; } */ if (fill) { o_flags[ir][ic] = new byte[2*numc]; //- case flags n_lines[ir][ic] = 0; //- number of contour line segments ctrLow[ir][ic] = (short)hi; } for (il=0; il<numc; il++) { gg = myvals[low+il]; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } float gba, gca, gdb, gdc; int ii; // make sure gg is within contouring limits if (gg < gn) continue; if (gg > gx) break; if (gg < lowlimit) continue; if (gg > highlimit) break; // compute orientation of lines inside box ii = 0; if (gg > ga) ii = 1; if (gg > gb) ii += 2; if (gg > gc) ii += 4; if (gg > gd) ii += 8; if (ii > 7) ii = 15 - ii; if (ii <= 0) continue; if (fill) { if ((low+il) < ctrLow[ir][ic]) ctrLow[ir][ic] = (short)(low+il); } // DO LABEL HERE if (( mark[ (ic) * nr + (ir) ] )==0) { int kc, kr, mc, mr, jc, jr; float xk, yk, xm, ym, value; // Insert a label // BOX TO AVOID kc = ic-lc2-lcc; kr = ir-lr2-lrr; mc = kc+2*lcc+lc-1; mr = kr+2*lrr+lr-1; // OK here for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { if (( mark[ (jc) * nr + (jr) ] ) != 2) { mark[ (jc) * nr + (jr) ] = 1; } } } } } // BOX TO HOLD LABEL kc = ic-lc2; kr = ir-lr2; mc = kc+lc-1; mr = kr+lr-1; for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { mark[ (jc) * nr + (jr) ] = 2; } } } } xk = xdd*kr+0.0f; yk = ydd*kc+0.0f; xm = xdd*(mr+1.0f)+0.0f; ym = ydd*(mc+1.0f)+0.0f; value = gg; if (numv4[0]+1000 >= maxv4) { // allocate more space maxv4 = 2 * (numv4[0]+1000); float[][] tx = new float[][] {vx4[0]}; float[][] ty = new float[][] {vy4[0]}; vx4[0] = new float[maxv4]; vy4[0] = new float[maxv4]; System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]); System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]); tx = null; ty = null; } if (numv3[0]+1000 >= maxv3) { // allocate more space maxv3 = 2 * (numv3[0]+1000); float[][] tx = new float[][] {vx3[0]}; float[][] ty = new float[][] {vy3[0]}; vx3[0] = new float[maxv3]; vy3[0] = new float[maxv3]; System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]); System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels3; for (int i=0; i<naux; i++) { //byte[] taa = auxLevels3[i]; auxLevels3[i] = new byte[maxv3]; System.arraycopy(ta[i], 0, auxLevels3[i], 0, numv3[0]); } ta = null; } } plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap); System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts); System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts); if (naux > 0) { for (int i=0; i<naux; i++) { for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) { auxLevels3[i][j] = auxa[i]; } } } numv3[0] += plot.NumVerts; System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts); System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts); numv4[0] += plot.NumVerts; } switch (ii) { case 1: gba = gb-ga; gca = gc-ga; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratioca = (gg-ga)/gca; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) { vx[numv] = xx; } else { vx[numv] = xx+xd*(gg-ga)/gba; } vy[numv] = yy; numv++; if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) { vy[numv] = yy; } else { vy[numv] = yy+yd*(gg-ga)/gca; } vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] += 0.00001f; vy[numv-1] += 0.00001f; } break; case 2: gba = gb-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] -= 0.00001f; vy[numv-1] += 0.00001f; } break; case 3: gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 4: gca = gc-ga; gdc = gd-gc; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] += 0.00001f; vy[numv-2] -= 0.00001f; } break; case 5: gba = gb-ga; gdc = gd-gc; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 6: gba = gb-ga; gdc = gd-gc; gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; */ if ( (gg>gv) ^ (ga<gb) ) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } else { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+3] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; // here's a brain teaser if ( (gg>gv) ^ (ga<gb) ) { // (XOR) if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)1 + (byte)32; n_lines[ir][ic]++; } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)7 + (byte)32; n_lines[ir][ic]++; } numv++; } else { if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)2 + (byte)32; n_lines[ir][ic]++; } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)4 + (byte)32; n_lines[ir][ic]++; } } if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; break; case 7: gdb = gd-gb; gdc = gd-gc; if (naux > 0) { float ratiodb = (gg-gb)/gdb; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] -= 0.00001f; vy[numv-2] -= 0.00001f; } break; } // switch // If contour level is negative, make dashed line if (gg < base && dash) { /* DRM: 1999-05-19 */ // 2006-09-29 BMF -- Moved to ContourStrip.getDashedLineArray(...) // float vxa, vya, vxb, vyb; // vxa = vx[numv-2]; // vya = vy[numv-2]; // vxb = vx[numv-1]; // vyb = vy[numv-1]; // vx[numv-2] = (3.0f*vxa+vxb) * 0.25f; // vy[numv-2] = (3.0f*vya+vyb) * 0.25f; // vx[numv-1] = (vxa+3.0f*vxb) * 0.25f; // vy[numv-1] = (vya+3.0f*vyb) * 0.25f; dashFlags[low+il] = true; } /* if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) || (20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) { System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] + " ic, ir = " + ic + " " + ir); } */ if (ii == 6) { //- add last two pairs ctrSet.add(vx, vy, numv-4, numv-3, low+il, ic, ir); ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } else { ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } } // for il -- NOTE: gg incremented in for statement } // for ic } // for ir /**------------------- Color Fill -------------------------*/ if (fill) { fillGridBox(g, n_lines, vx, vy, xd, xdd, yd, ydd, nr, nrm, nc, ncm, ctrLow, tri, tri_color, o_flags, myvals, color_bin, grd_normals, tri_normals); // BMF 2006-10-04 do not return, ie. draw labels on filled contours // for now, just return because we don't need to do labels //return; } //---TDR, build Contour Strips float[][][] vvv = new float[2][][]; byte [][][] new_colors = new byte[2][][]; ctrSet.getLineColorArrays(vx, vy, auxLevels, labelColor, vvv, new_colors, lbl_vv, lbl_cc, lbl_loc, dashFlags, contourDifficulty); vx2[0] = vvv[1][0]; vy2[0] = vvv[1][1]; vz2[0] = vvv[1][2]; numv1[0] = vvv[0][0].length; numv2[0] = vvv[1][0].length; int n_lbls = lbl_vv[0].length; if (n_lbls > 0) { vx3[0] = lbl_vv[0][0][0]; vy3[0] = lbl_vv[0][0][1]; vz3[0] = lbl_vv[0][0][2]; vx4[0] = lbl_vv[1][0][0]; vy4[0] = lbl_vv[1][0][1]; vz4[0] = lbl_vv[1][0][2]; numv3[0] = lbl_vv[0][0][0].length; numv4[0] = lbl_vv[1][0][0].length; } if (auxLevels != null) { int clr_dim = auxValues.length; auxLevels1[0] = new_colors[0][0]; auxLevels1[1] = new_colors[0][1]; auxLevels1[2] = new_colors[0][2]; if (clr_dim == 4) auxLevels1[3] = new_colors[0][3]; auxLevels2[0] = new_colors[1][0]; auxLevels2[1] = new_colors[1][1]; auxLevels2[2] = new_colors[1][2]; if (clr_dim == 4) auxLevels2[3] = new_colors[1][3]; if (n_lbls > 0) { auxLevels3[0] = lbl_cc[0][0][0]; auxLevels3[1] = lbl_cc[0][0][1]; auxLevels3[2] = lbl_cc[0][0][2]; if (clr_dim == 4) auxLevels3[3] = lbl_cc[0][0][3]; } } if (contourDifficulty == Contour2D.EASY) { vx1[0] = vvv[0][0]; vy1[0] = vvv[0][1]; vz1[0] = vvv[0][2]; } else { int start = numv1[0]; float[][] vx_tmp = new float[1][]; float[][] vy_tmp = new float[1][]; float[][] vz_tmp = new float[1][]; byte[][] aux_tmp = new byte[4][]; float[] vx1_tmp = new float[numv]; float[] vy1_tmp = new float[numv]; float[] vz1_tmp = new float[numv]; byte[][] aux1_tmp = new byte[4][]; aux1_tmp[0] = new byte[numv]; aux1_tmp[1] = new byte[numv]; aux1_tmp[2] = new byte[numv]; int cnt = 0; for (int kk=0; kk<ctrSet.qSet.length;kk++) { ctrSet.qSet[kk].getArrays(vx, vy, auxLevels, vx_tmp, vy_tmp, vz_tmp, aux_tmp, spatial_set); int len = vx_tmp[0].length; System.arraycopy(vx_tmp[0], 0, vx1_tmp, cnt, len); System.arraycopy(vy_tmp[0], 0, vy1_tmp, cnt, len); System.arraycopy(vz_tmp[0], 0, vz1_tmp, cnt, len); System.arraycopy(aux_tmp[0], 0, aux1_tmp[0], cnt, len); System.arraycopy(aux_tmp[1], 0, aux1_tmp[1], cnt, len); System.arraycopy(aux_tmp[2], 0, aux1_tmp[2], cnt, len); cnt += len; } vx1[0] = new float[numv1[0]+cnt]; vy1[0] = new float[numv1[0]+cnt]; vz1[0] = new float[numv1[0]+cnt]; auxLevels1[0] = new byte[numv1[0]+cnt]; auxLevels1[1] = new byte[numv1[0]+cnt]; auxLevels1[2] = new byte[numv1[0]+cnt]; auxLevels1[3] = new byte[numv1[0]+cnt]; System.arraycopy(vvv[0][0], 0, vx1[0], 0, numv1[0]); System.arraycopy(vvv[0][1], 0, vy1[0], 0, numv1[0]); System.arraycopy(vvv[0][2], 0, vz1[0], 0, numv1[0]); System.arraycopy(new_colors[0][0], 0, auxLevels1[0], 0, numv1[0]); System.arraycopy(new_colors[0][1], 0, auxLevels1[1], 0, numv1[0]); System.arraycopy(new_colors[0][2], 0, auxLevels1[2], 0, numv1[0]); System.arraycopy(vx1_tmp, 0, vx1[0], start, cnt); System.arraycopy(vy1_tmp, 0, vy1[0], start, cnt); System.arraycopy(vz1_tmp, 0, vz1[0], start, cnt); System.arraycopy(aux1_tmp[0], 0, auxLevels1[0], start, cnt); System.arraycopy(aux1_tmp[1], 0, auxLevels1[1], start, cnt); System.arraycopy(aux1_tmp[2], 0, auxLevels1[2], start, cnt); numv1[0] += cnt; vx1_tmp = null; vy1_tmp = null; vz1_tmp = null; } } private static void fillGridBox(float[] g, short[][] n_lines, float[] vx, float[] vy, float xd, float xdd, float yd, float ydd, int nr, int nrm, int nc, int ncm, short[][] ctrLow, float[][] tri, byte[][] tri_color, byte[][][] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, float[][] tri_normals) { float xx, yy; int[] numv = new int[1]; numv[0] = 0; int n_tri = 0; for (int ir=0; ir<nrm; ir++) { for (int ic=0; ic<ncm; ic++) { if (n_lines[ir][ic] == 0) { n_tri +=2; } else { n_tri += (4 + (n_lines[ir][ic]-1)*2); } boolean any = false; if (o_flags[ir][ic] != null) { for (int k=0; k<o_flags[ir][ic].length; k++) { if (o_flags[ir][ic][k] > 32) any = true; } if (any) n_tri += 4; } } } tri[0] = new float[n_tri*3]; tri[1] = new float[n_tri*3]; for (int kk=0; kk<color_bin.length; kk++) { tri_color[kk] = new byte[n_tri*3]; } tri_normals[0] = new float[3*n_tri*3]; int[] t_idx = new int[1]; t_idx[0] = 0; int[] n_idx = new int[1]; n_idx[0] = 0; for (int ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; for (int ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; yy = ydd*ic+0.0f; // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; numv[0] += n_lines[ir][ic]*2; fillGridBox(new float[] {ga, gb, gc, gd}, n_lines[ir][ic], vx, vy, xx, yy, xd, yd, ic, ir, ctrLow[ir][ic], tri, t_idx, tri_color, numv[0], o_flags[ir][ic], values, color_bin, grd_normals, n_idx, tri_normals); } } } private static void fillGridBox(float[] corners, int numc, float[] vx, float[] vy, float xx, float yy, float xd, float yd, int nc, int nr, short ctrLow, float[][] tri, int[] t_idx, byte[][] tri_color, int numv, byte[] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, int[] n_idx, float[][] tri_normals_a) { float[] tri_normals = tri_normals_a[0]; int n_tri = 4 + (numc-1)*2; int[] cnt_tri = new int[1]; cnt_tri[0] = 0; int il = 0; int color_length = color_bin.length; float[] vec = new float[2]; float[] vec_last = new float[2]; float[] vv1 = new float[2]; float[] vv2 = new float[2]; float[] vv1_last = new float[2]; float[] vv2_last = new float[2]; float[][] vv = new float[2][2]; float[][] vv_last = new float[2][2]; float[] vv3 = new float[2]; int dir = 1; int start = numv-2; int o_start = numc-1; int x_min_idx = 0; int o_idx = 0; byte o_flag = o_flags[o_idx]; int ydir = 1; boolean special = false; int[] closed = {0}; boolean up; boolean right; float dist_sqrd = 0; int v_idx = start + dir*il*2; //-- color level at corners //------------------------------ byte[][] crnr_color = new byte[4][color_length]; boolean[] crnr_out = new boolean[] {true, true, true, true}; boolean all_out = true; for (int tt = 0; tt < corners.length; tt++) { int cc = 0; int kk = 0; for (kk = 0; kk < (values.length - 1); kk++) { if ((corners[tt] >= values[kk]) && (corners[tt] < values[kk+1])) { cc = kk; all_out = false; crnr_out[tt] = false; } } for (int ii=0; ii<color_length; ii++) { crnr_color[tt][ii] = color_bin[ii][cc]; } } int tt = t_idx[0]; //- initialize triangle vertex counter dir = 1; start = numv - numc*2; o_start = 0; v_idx = start + dir*il*2; up = false; right = false; float[] x_avg = new float[2]; float[] y_avg = new float[2]; if (numc > 1) { //-- first/next ctr line midpoints int idx = v_idx; x_avg[0] = (vx[idx] + vx[idx+1])/2; y_avg[0] = (vy[idx] + vy[idx+1])/2; idx = v_idx + 2; x_avg[1] = (vx[idx] + vx[idx+1])/2; y_avg[1] = (vy[idx] + vy[idx+1])/2; if ((x_avg[1] - x_avg[0]) > 0) up = true; if ((y_avg[1] - y_avg[0]) > 0) right = true; } else if ( numc == 1 ) { //- default values for logic below x_avg[0] = 0f; y_avg[0] = 0f; x_avg[1] = 1f; y_avg[1] = 1f; } else if ( numc == 0 ) //- empty grid box (no contour lines) { if (all_out) return; n_tri = 2; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; return; }//-- end no contour lines //--If any case 6 (saddle point), handle with special logic for (int iii=0; iii<o_flags.length; iii++) { if (o_flags[iii] > 32) { fillCaseSix(xx, yy, xd, yd, v_idx, dir, o_flags, ctrLow, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, color_bin, tri_color, color_length, grd_normals, n_idx, tri_normals, closed, cnt_tri); return; } } //-- start making triangles for color fill //--------------------------------------------- if (o_flag == 1 || o_flag == 4 || o_flag == 2 || o_flag == 7) { boolean opp = false; float dy = 0; float dx = 0; float dist_0 = 0; float dist_1 = 0; /** compare midpoints distances for first/next contour lines -------------------------------------------------*/ if (o_flag == 1) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 2) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (o_flag == 4) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 7) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (dist_1 < dist_0) opp = true; if (opp) { fillToOppCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (o_flags[o_idx] == 3) { int flag = 1; if (right) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (o_flags[o_idx] == 5) { int flag = 1; if (!up) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } byte last_o = o_flags[o_idx]; int cc_start = (dir > 0) ? (ctrLow-1) : (ctrLow+(numc-1)); //- move to next contour line //-------------------------------- il++; for ( il = 1; il < numc; il++ ) { v_idx = start + dir*il*2; o_idx = o_start + dir*il; int v_idx_last = v_idx - 2*dir; int cc = cc_start + dir*il; if (o_flags[o_idx] != last_o) //- contour line case change { byte[] side_s = new byte[2]; byte[] last_side_s = new byte[2]; byte[] b_arg = new byte[2]; boolean flip; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx, dir, o_flags[o_idx], b_arg); side_s[0] = b_arg[0]; side_s[1] = b_arg[1]; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx_last, dir, last_o, b_arg); last_side_s[0] = b_arg[0]; last_side_s[1] = b_arg[1]; if (side_s[0] == last_side_s[0]) { flip = false; } else if (side_s[0] == last_side_s[1]) { flip = true; } else if (side_s[1] == last_side_s[0]) { flip = true; } else if (side_s[1] == last_side_s[1]) { flip = false; } else { if(((side_s[0]+last_side_s[0]) & 1) == 1) { flip = false; } else { flip = true; } } if (!flip) { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv[0][0] = vx[v_idx]; vv[1][0] = vy[v_idx]; vv[0][1] = vx[v_idx+dir]; vv[1][1] = vy[v_idx+dir]; } else { vv1[0] = vx[v_idx+dir]; vv1[1] = vy[v_idx+dir]; vv2[0] = vx[v_idx]; vv2[1] = vy[v_idx]; vv[0][0] = vx[v_idx+dir]; vv[1][0] = vy[v_idx+dir]; vv[0][1] = vx[v_idx]; vv[1][1] = vy[v_idx]; } vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; vv_last[0][0] = vx[v_idx_last]; vv_last[1][0] = vy[v_idx_last]; vv_last[0][1] = vx[v_idx_last+dir]; vv_last[1][1] = vy[v_idx_last+dir]; //--- fill between contour lines fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); byte[] b_arg2 = new byte[2]; getBoxSide(vv[0], vv[1], xx, xd, yy, yd, 0, dir, o_flags[o_idx], b_arg); getBoxSide(vv_last[0], vv_last[1], xx, xd, yy, yd, 0, dir, last_o, b_arg2); for (int kk = 0; kk < 2; kk++) { //- close off corners float[] vvx = new float[2]; float[] vvy = new float[2]; byte side = 0; byte last_s = 0; side = b_arg[kk]; last_s = b_arg2[kk]; if ( side != last_s ) { if ((side == 0 && last_s == 3) || (side == 3 && last_s == 0)) { //- case 1 fillToNearCorner(xx, yy, xd, yd, 0, (byte)1, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 0 && last_s == 1) || (side == 1 && last_s == 0)) { //- case 2 fillToNearCorner(xx, yy, xd, yd, 0, (byte)2, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 3) || (side == 3 && last_s == 2)) { //- case 4 fillToNearCorner(xx, yy, xd, yd, 0, (byte)4, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 1) || (side == 1 && last_s == 2)) { //- case 7 fillToNearCorner(xx, yy, xd, yd, 0, (byte)7, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 0) || (side == 0 && last_s == 2)) { //- case 5 if (side == 0) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 1)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)5, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 1 && last_s == 3) || (side == 3 && last_s == 1)) { //- case 3 if (side == 3) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 8)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)3, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } } } else { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); } last_o = o_flags[o_idx]; }//---- contour loop /*- last or first/last contour line ------------------------------------*/ int flag_set = 0; if ((last_o == 1)||(last_o == 2)||(last_o == 4)||(last_o == 7)) { if(last_o == 1) flag_set = (closed[0] & 1); if(last_o == 2) flag_set = (closed[0] & 2); if(last_o == 4) flag_set = (closed[0] & 4); if(last_o == 7) flag_set = (closed[0] & 8); if (flag_set > 0) { fillToOppCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (last_o == 3) { int flag = -1; if (closed[0]==3) flag = 1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (last_o == 5) { int flag = 1; if (closed[0]==5) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } }//--- end fillGridBox private static void getBoxSide(float[] vx, float[] vy, float xx, float xd, float yy, float yd, int v_idx, int dir, byte o_flag, byte[] side) { /* if (vy[v_idx] == yy) side[0] = 0; // a-b if (vy[v_idx] == (yy + yd)) side[0] = 2; // c-d if (vx[v_idx] == xx) side[0] = 3; // a-c if (vx[v_idx] == (xx + xd)) side[0] = 1; // b-d */ for (int kk = 0; kk < 2; kk++) { int ii = v_idx + kk*dir; switch (o_flag) { case 1: side[kk] = 3; if (vy[ii] == yy) side[kk] = 0; break; case 2: side[kk] = 1; if (vy[ii] == yy) side[kk] = 0; break; case 4: side[kk] = 3; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 7: side[kk] = 1; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 3: side[kk] = 1; if (vx[ii] == xx) side[kk] = 3; break; case 5: side[kk] = 0; if (vy[ii] == (yy + yd)) side[kk] = 2; break; } } } private static void interpNormals(float vx, float vy, float xx, float yy, int nc, int nr, float xd, float yd, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int side = -1; float[] nn = new float[3]; if (vy == yy) side = 0; // a-b if (vy == (yy + yd)) side = 2; // c-d if (vx == xx) side = 3; // a-c if (vx == (xx + xd)) side = 1; // b-d float dx = vx - xx; float dy = vy - yy; switch (side) { case 0: nn[0] = ((grd_normals[nc][nr+1][0] - grd_normals[nc][nr][0])/xd)*dx + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc][nr+1][1] - grd_normals[nc][nr][1])/xd)*dx + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc][nr+1][2] - grd_normals[nc][nr][2])/xd)*dx + grd_normals[nc][nr][2]; break; case 3: nn[0] = ((grd_normals[nc+1][nr][0] - grd_normals[nc][nr][0])/yd)*dy + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc+1][nr][1] - grd_normals[nc][nr][1])/yd)*dy + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc+1][nr][2] - grd_normals[nc][nr][2])/yd)*dy + grd_normals[nc][nr][2]; break; case 1: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc][nr+1][0])/yd)*dy + grd_normals[nc][nr+1][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc][nr+1][1])/yd)*dy + grd_normals[nc][nr+1][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc][nr+1][2])/yd)*dy + grd_normals[nc][nr+1][2]; break; case 2: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc+1][nr][0])/xd)*dx + grd_normals[nc+1][nr][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc+1][nr][1])/xd)*dx + grd_normals[nc+1][nr][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc+1][nr][2])/xd)*dx + grd_normals[nc+1][nr][2]; break; default: System.out.println("interpNormals, bad side: "+side); } //- re-normalize float mag = (float) Math.sqrt(nn[0]*nn[0] + nn[1]*nn[1] + nn[2]*nn[2]); nn[0] /= mag; nn[1] /= mag; nn[2] /= mag; tri_normals[n_idx[0]++] = nn[0]; tri_normals[n_idx[0]++] = nn[1]; tri_normals[n_idx[0]++] = nn[2]; } private static void fillToLast(float xx, float yy, float xd, float yd, int nc, int nr, float[] vv1, float[] vv2, float[] vv1_last, float[] vv2_last, float[][] tri, int[] cnt_tri, int[] t_idx, byte[][] tri_color, byte[][] color_bin, int cc, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1[0]; tri[1][tt] = vv1[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri[0]++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2_last[0]; tri[1][tt] = vv2_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; t_idx[0] = tt; cnt_tri[0]++; } private static void fillCaseSix(float xx, float yy, float xd, float yd, int v_idx, int dir, byte[] o_flags, short ctrLow, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] color_bin, byte[][] tri_color, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed, int[] cnt_tri) { int n1 = 0; int n2 = 0; int n4 = 0; int n7 = 0; for (int kk = 0; kk < o_flags.length; kk++) { if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) n1++; if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) n2++; if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) n4++; if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) n7++; } float[][] vv1 = new float[2][n1*2]; float[][] vv2 = new float[2][n2*2]; float[][] vv4 = new float[2][n4*2]; float[][] vv7 = new float[2][n7*2]; int[] clr_idx1 = new int[n1]; int[] clr_idx2 = new int[n2]; int[] clr_idx4 = new int[n4]; int[] clr_idx7 = new int[n7]; float[] vvv1 = new float[2]; float[] vvv2 = new float[2]; float[] vvv1_last = new float[2]; float[] vvv2_last = new float[2]; n1 = 0; n2 = 0; n4 = 0; n7 = 0; int ii = v_idx; int cc = ctrLow - 1; int cnt = 0; int[] cases = {1, 2, 7, 4}; //- corner cases, clockwise around box for (int kk = 0; kk < o_flags.length; kk++) { if (o_flags[kk] > 32) cnt++; if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) { clr_idx1[n1] = cc; vv1[0][2*n1] = vx[ii]; vv1[1][2*n1] = vy[ii]; vv1[0][2*n1+1] = vx[ii+1]; vv1[1][2*n1+1] = vy[ii+1]; n1++; } else if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) { clr_idx2[n2] = cc; vv2[0][2*n2] = vx[ii]; vv2[1][2*n2] = vy[ii]; vv2[0][2*n2+1] = vx[ii+1]; vv2[1][2*n2+1] = vy[ii+1]; n2++; } else if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) { clr_idx4[n4] = cc; vv4[0][2*n4] = vx[ii]; vv4[1][2*n4] = vy[ii]; vv4[0][2*n4+1] = vx[ii+1]; vv4[1][2*n4+1] = vy[ii+1]; n4++; } else if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) { clr_idx7[n7] = cc; vv7[0][2*n7] = vx[ii]; vv7[1][2*n7] = vy[ii]; vv7[0][2*n7+1] = vx[ii+1]; vv7[1][2*n7+1] = vy[ii+1]; n7++; } if (o_flags[kk] < 32) { cc += 1; } else if (cnt == 2) { cnt = 0; cc++; } ii += 2; } int[] clr_idx = null; float[] vvx = null; float[] vvy = null; float[] x_avg = new float[2]; float[] y_avg = new float[2]; float dist_0 = 0; float dist_1 = 0; float xxx = 0; float yyy = 0; float dx = 0; float dy = 0; int nn = 0; int pt = 0; int n_pt = 0; int s_idx = 0; int ns_idx = 0; byte[] tmp = null; byte[] cntr_color = null; int cntr_clr = Integer.MIN_VALUE; float[][] edge_points = new float[2][8]; boolean[] edge_point_a_corner = {false, false, false, false, false, false, false, false}; boolean[] edge_point_out = {false, false, false, false, false, false, false, false}; boolean this_crnr_out = false; int n_crnr_out = 0; //- fill corners for (int kk = 0; kk < cases.length; kk++) { switch(cases[kk]) { case 1: nn = n1; clr_idx = clr_idx1; vvx = vv1[0]; vvy = vv1[1]; xxx = xx; yyy = yy; pt = 0; n_pt = 7; s_idx = 0; ns_idx = 1; tmp = crnr_color[0]; this_crnr_out = crnr_out[0]; break; case 2: nn = n2; clr_idx = clr_idx2; vvx = vv2[0]; vvy = vv2[1]; xxx = xx + xd; yyy = yy; pt = 1; n_pt = 2; s_idx = 0; ns_idx = 1; tmp = crnr_color[1]; this_crnr_out = crnr_out[1]; break; case 4: nn = n4; clr_idx = clr_idx4; vvx = vv4[0]; vvy = vv4[1]; xxx = xx; yyy = yy + yd; pt = 5; n_pt = 6; s_idx = 1; ns_idx = 0; tmp = crnr_color[2]; this_crnr_out = crnr_out[2]; break; case 7: nn = n7; clr_idx = clr_idx7; vvx = vv7[0]; vvy = vv7[1]; xxx = xx + xd; yyy = yy + yd; pt = 3; n_pt = 4; s_idx = 0; ns_idx = 1; tmp = crnr_color[3]; this_crnr_out = crnr_out[3]; break; } if ( nn == 0 ) { edge_points[0][pt] = xxx; edge_points[1][pt] = yyy; edge_points[0][n_pt] = xxx; edge_points[1][n_pt] = yyy; cntr_color = tmp; edge_point_a_corner[pt] = true; edge_point_a_corner[n_pt] = true; edge_point_out[pt] = this_crnr_out; edge_point_out[n_pt] = this_crnr_out; if (this_crnr_out) n_crnr_out++; } else if ( nn == 1) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } else { int il = 0; int idx = 0; x_avg[0] = (vvx[idx] + vvx[idx+1])/2; y_avg[0] = (vvy[idx] + vvy[idx+1])/2; idx = idx + 2; x_avg[1] = (vvx[idx] + vvx[idx+1])/2; y_avg[1] = (vvy[idx] + vvy[idx+1])/2; dy = (y_avg[1] - (yyy)); dx = (x_avg[1] - (xxx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yyy)); dx = (x_avg[0] - (xxx)); dist_0 = dy*dy + dx*dx; boolean cornerFirst = false; if ( dist_1 > dist_0) cornerFirst = true; if (cornerFirst) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } for (il = 1; il < nn; il++) { idx = dir*il*2; int idx_last = idx - 2*dir; vvv1[0] = vvx[idx]; vvv1[1] = vvy[idx]; vvv2[0] = vvx[idx+dir]; vvv2[1] = vvy[idx+dir]; vvv1_last[0] = vvx[idx_last]; vvv1_last[1] = vvy[idx_last]; vvv2_last[0] = vvx[idx_last+dir]; vvv2_last[1] = vvy[idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vvv1, vvv2, vvv1_last, vvv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, clr_idx[il], color_length, grd_normals, n_idx, tri_normals); if (!cornerFirst && il == (nn-1)) { fillToNearCorner(xx, yy, xd, yd, idx, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if (cornerFirst && il == (nn-1)) { edge_points[0][pt] = vvx[idx+s_idx]; edge_points[1][pt] = vvy[idx+s_idx]; edge_points[0][n_pt] = vvx[idx+ns_idx]; edge_points[1][n_pt] = vvy[idx+ns_idx]; if(clr_idx[il] > cntr_clr) cntr_clr = clr_idx[il]; } } } } //- fill remainder with tris all sharing center point //---------------------------------------------------- if (n_crnr_out == 2) { //- don't fill center region return; } if (cntr_color == null) { //- All corners were closed off cntr_color = new byte[color_length]; for (int c=0; c<color_length; c++) { cntr_color[c] = color_bin[c][cntr_clr]; } } int tt = t_idx[0]; for (int kk = 0; kk < edge_points[0].length; kk++) { pt = kk; n_pt = kk+1; if (kk == (edge_points[0].length - 1)) { pt = 0; n_pt = 7; } if (edge_point_a_corner[pt] || edge_point_a_corner[n_pt]) { if(edge_point_out[pt] || edge_point_out[n_pt]) continue; } for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][pt]; tri[1][tt] = edge_points[1][pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][n_pt]; tri[1][tt] = edge_points[1][n_pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; //- center point for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = xx + xd*0.5f; tri[1][tt] = yy + yd*0.5f; //- center normal, interpolate from corners float[] nrm = {0f, 0f, 0f}; for (int ic=0; ic<2; ic++) { for (int ir=0; ir<2; ir++) { nrm[0] += 0.25*grd_normals[nc+ic][nr+ir][0]; nrm[1] += 0.25*grd_normals[nc+ic][nr+ir][1]; nrm[2] += 0.25*grd_normals[nc+ic][nr+ir][2]; } } //- renormalize normal float mag = (float) Math.sqrt(nrm[0]*nrm[0] + nrm[1]*nrm[1] + nrm[2]*nrm[2]); nrm[0] /= mag; nrm[1] /= mag; nrm[2] /= mag; tri_normals[n_idx[0]++] = nrm[0]; tri_normals[n_idx[0]++] = nrm[1]; tri_normals[n_idx[0]++] = nrm[2]; tt++; cnt_tri[0]++; } t_idx[0] = tt; } private static void fillToNearCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx = 0; float cy = 0; int cc = 0; int color_length = crnr_color[0].length; int cnt_tri = cnt[0]; int tt = t_idx[0]; switch(o_flag) { case 1: cc = 0; closed[0] = closed[0] | 1; if (crnr_out[cc]) return; cx = xx; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; break; case 4: cc = 2; closed[0] = closed[0] | 4; if (crnr_out[cc]) return; cx = xx; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; break; case 2: cc = 1; closed[0] = closed[0] | 2; if (crnr_out[cc]) return; cx = xx + xd; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; break; case 7: cc = 3; closed[0] = closed[0] | 8; if (crnr_out[cc]) return; cx = xx + xd; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx; tri[1][tt] = cy; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToOppCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx1 = 0; float cx2 = 0; float cx3 = 0; float cy1 = 0; float cy2 = 0; float cy3 = 0; int cc = 0; int[][] grd = new int[3][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 1: closed[0] = closed[0] | 14; if (crnr_out[1] || crnr_out[2] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; cx3 = xx; cy3 = yy + yd; cc = 3; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; grd[2][0] = 0; grd[2][1] = 1; break; case 2: closed[0] = closed[0] | 13; if (crnr_out[0] || crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cx3 = xx + xd; cy3 = yy + yd; cc = 2; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; grd[2][0] = 1; grd[2][1] = 1; break; case 4: closed[0] = closed[0] | 11; if (crnr_out[0] || crnr_out[1] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cx3 = xx + xd; cy3 = yy + yd; cc = 1; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; grd[2][0] = 1; grd[2][1] = 1; break; case 7: closed[0] = closed[0] | 7; if (crnr_out[0] || crnr_out[1] || crnr_out[2]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx; cy2 = yy; cx3 = xx; cy3 = yy + yd; cc = 0; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 0; grd[2][0] = 0; grd[2][1] = 1; break; } int cnt_tri = cnt[0]; int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } else { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx3; tri[1][tt] = cy3; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToSide(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { int cnt_tri = cnt[0]; int tt = t_idx[0]; float cx1 = 0; float cy1 = 0; float cx2 = 0; float cy2 = 0; int cc = 0; int[][] grd = new int[2][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 3: switch (flag) { case 1: closed[0] = closed[0] | 12; if(crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy + yd; cx2 = xx + xd; cy2 = yy + yd; cc = 3; grd[0][0] = 0; grd[0][1] = 1; grd[1][0] = 1; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 3; if(crnr_out[0] || crnr_out[1]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; break; } break; case 5: switch (flag) { case 1: closed[0] = closed[0] | 5; if(crnr_out[0] || crnr_out[2]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 10; if(crnr_out[1] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; cc = 3; break; } break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; int i = grd[0][0]; int j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; i = grd[0][0]; j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if ( dir > 0 ) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; i = grd[1][0]; j = grd[1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } } // end class class ContourQuadSet { int nx = 1; int ny = 1; int npx; int npy; int nc; int nr; int lev_idx; int numv = 0; ContourStripSet css = null; ContourQuad[][] qarray = null; int snumv = 0; public HashMap subGridMap = new HashMap(); public HashMap subGrid2Map = new HashMap(); public HashMap markGridMap = new HashMap(); public HashMap markGrid2Map = new HashMap(); ContourQuadSet(int nr, int nc, int lev_idx, ContourStripSet css) { this.nc = nc; this.nr = nr; this.lev_idx = lev_idx; this.css = css; if (css.contourDifficulty == Contour2D.HARD) { nx = 20; ny = 20; } else { nx = 1; ny = 1; } npy = (int) (nr/ny); npx = (int) (nc/nx); qarray = new ContourQuad[ny][nx]; for (int j=0; j<ny; j++) { for (int i=0; i<nx; i++) { int lenx = npx; int leny = npy; if (j==ny-1) leny = nr - (ny-1)*npy; if (i==nx-1) lenx = nc - (nx-1)*npx; qarray[j][i] = new ContourQuad(this, j*npy, i*npx, leny, lenx); } } } public void add(int idx0, int gy, int gx) { int ix = (int) (gx/npx); int iy = (int) (gy/npy); if (ix == nx) ix -= 1; if (iy == ny) iy -= 1; qarray[iy][ix].add(idx0, gy, gx); } public void get(float[] vx, float[] vy) { numv = 0; snumv = 0; for (int j=0; j<ny; j++) { for (int i=0; i<nx; i++) { ContourStrip[] c_strps = qarray[j][i].getContourStrips(vx, vy); numv += qarray[j][i].numv; snumv += qarray[j][i].stripCnt; if (c_strps != null) { css.vecArray[lev_idx].add(c_strps[0]); } } } } public void getArrays(float[] vx, float[] vy, byte[][] auxLevels, float[][] vx1, float[][] vy1, float[][] vz1, byte[][] colors, Gridded3DSet spatial_set) throws VisADException { float[][] arrays = new float[2][2*numv]; colors[0] = new byte[2*numv]; colors[1] = new byte[2*numv]; colors[2] = new byte[2*numv]; int cnt=0; for (int j=0; j<ny; j++) { for (int i=0; i<nx; i++) { for (int k=0; k<qarray[j][i].numv; k++) { int vidx = qarray[j][i].vert_indices[k]; if (vidx >= 0) { arrays[0][cnt] = vx[vidx]; arrays[1][cnt] = vy[vidx]; colors[0][cnt] = auxLevels[0][vidx]; colors[1][cnt] = auxLevels[1][vidx]; colors[2][cnt] = auxLevels[2][vidx]; cnt++; arrays[0][cnt] = vx[vidx+1]; arrays[1][cnt] = vy[vidx+1]; colors[0][cnt] = auxLevels[0][vidx+1]; colors[1][cnt] = auxLevels[1][vidx+1]; colors[2][cnt] = auxLevels[2][vidx+1]; cnt++; } } } } float[][] tmp = new float[2][cnt]; byte[][] clr_tmp = new byte[3][cnt]; System.arraycopy(arrays[0], 0, tmp[0], 0, cnt); System.arraycopy(arrays[1], 0, tmp[1], 0, cnt); System.arraycopy(colors[0], 0, clr_tmp[0], 0, cnt); System.arraycopy(colors[1], 0, clr_tmp[1], 0, cnt); System.arraycopy(colors[2], 0, clr_tmp[2], 0, cnt); float[][] tmp3D = spatial_set.gridToValue(tmp); vx1[0] = tmp3D[0]; vy1[0] = tmp3D[1]; vz1[0] = tmp3D[2]; arrays = null; colors = null; } } class ContourQuad { int[] vert_indices; int[] vert_indices_save = null; int[] grid_indices; int maxnumv; int numv; ContourQuadSet qs; int nc; int nr; int strty; int strtx; int leny; int lenx; int lev_idx; int[][] sub_grid = null; int[][] sub_grid_2 = null; int[][] mark_grid = null; int[][] mark_grid_2 = null; ContourStripSet css = null; int[] stripVert_indices; int stripCnt = 0; ContourQuad(ContourQuadSet qs, int strty, int strtx, int leny, int lenx) { maxnumv = 100; numv = 0; vert_indices = new int[maxnumv]; //- indices into vx,vy grid_indices = new int[maxnumv]; //- location on the grid this.qs = qs; this.nc = qs.nc; this.nr = qs.nr; this.strty = strty; this.strtx = strtx; this.leny = leny; this.lenx = lenx; css = qs.css; lev_idx = qs.lev_idx; } public void add(int idx0, int gy, int gx) { if (numv < maxnumv-2) { vert_indices[numv] = idx0; grid_indices[numv] = gy*nc + gx; numv++; } else { maxnumv += 50; int[] tmpA = vert_indices; int[] tmpB = grid_indices; vert_indices = new int[maxnumv]; grid_indices = new int[maxnumv]; System.arraycopy(tmpA, 0, vert_indices, 0, numv); System.arraycopy(tmpB, 0, grid_indices, 0, numv); tmpA = null; tmpB = null; vert_indices[numv] = idx0; grid_indices[numv] = gy*nc + gx; numv++; } } public int[][][] getWorkArrays(int leny, int lenx) { Object key; java.util.Set keySet = qs.subGridMap.keySet(); key = null; for (java.util.Iterator i = keySet.iterator(); i.hasNext();) { CachedArrayDimension obj = (CachedArrayDimension) i.next(); if (obj.equals(new CachedArrayDimension(leny, lenx))) { key = obj; break; } } int[][] subgrid = null; int[][] subgrid2 = null; int[][] markgrid = null; int[][] markgrid2 = null; if (key != null) { subgrid = ((CachedArray)qs.subGridMap.get(key)).getArray(); subgrid2 = ((CachedArray)qs.subGrid2Map.get(key)).getArray(); markgrid = ((CachedArray)qs.markGridMap.get(key)).getArray(); markgrid2 = ((CachedArray)qs.markGrid2Map.get(key)).getArray(); } else { subgrid = new int[leny][lenx]; subgrid2 = new int[leny][lenx]; markgrid = new int[leny][lenx]; markgrid2 = new int[leny][lenx]; Object newKey = new CachedArrayDimension(leny,lenx); qs.subGridMap.put(newKey, new CachedArray(subgrid)); qs.subGrid2Map.put(newKey, new CachedArray(subgrid2)); qs.markGridMap.put(newKey, new CachedArray(markgrid)); qs.markGrid2Map.put(newKey, new CachedArray(markgrid2)); } return new int[][][] {subgrid, subgrid2, markgrid, markgrid2}; } public void get() { int ix_i = -1; int iy_i = -1; int[][][] workarrays = getWorkArrays(leny, lenx); sub_grid = workarrays[0]; sub_grid_2 = workarrays[1]; mark_grid = workarrays[2]; mark_grid_2 = workarrays[3]; for (int j=0; j<leny; j++) { for (int i=0; i<lenx; i++) { sub_grid[j][i] = 0; sub_grid_2[j][i] = 0; } } if (vert_indices_save == null) { vert_indices_save = new int[vert_indices.length]; System.arraycopy(vert_indices, 0, vert_indices_save, 0, vert_indices.length); } else { System.arraycopy(vert_indices_save, 0, vert_indices, 0, vert_indices.length); } for (int ii=0; ii<numv; ii++) { int kk = grid_indices[ii]; int iy = (int) kk/nc; int ix = kk - iy*nc; sub_grid[iy-strty][ix-strtx] = vert_indices[ii]; mark_grid[iy-strty][ix-strtx] = ii; if (ix_i == ix && iy_i == iy) { sub_grid_2[iy-strty][ix-strtx] = vert_indices[ii]; mark_grid_2[iy-strty][ix-strtx] = ii; } ix_i = ix; iy_i = iy; } } public void reset() { for (int j=0; j<leny; j++) { for (int i=0; i<lenx; i++) { if (sub_grid[j][i] < 0) { sub_grid[j][i] *= -1; } } } } public ContourStrip[] getContourStrips(float[] vx, float[] vy) { get(); stripVert_indices = new int[200]; int n_segs = 0; int[][] udrl = {{1,-1,0,0}, {0,0,1,-1}}; //-up/down, right/left //- find starting point int[] start = getStartPoint(); if (start == null) { return null; } int iy = start[0]; int ix = start[1]; int idx0 = sub_grid[iy][ix]; int idx1 = idx0 + 1; ContourStrip c_strp = new ContourStrip(200, lev_idx, idx0, idx1, css.plot_s[lev_idx], css); boolean foundA = true; boolean foundB = true; int idxA = idx0; int idxB = idx0; int last_idxA = idxA; int last_idxB = idxB; int idxA_2; int idxB_2; int ix_t, iy_t; int ix_a = ix; int iy_a = iy; int ix_b = ix; int iy_b = iy; int cnt = 0; stripVert_indices[cnt++] = idx0; sub_grid[iy][ix] *= -1; int test_cnt = 0; while( (n_segs < 100) && (test_cnt < 300) ) { test_cnt++; //- A for (int k=0; k<4; k++) { ix_t = ix_a+udrl[0][k]; iy_t = iy_a+udrl[1][k]; if ((iy_t >=0 && iy_t < leny) && (ix_t >=0 && ix_t < lenx)) { idxA = sub_grid[iy_t][ix_t]; idxA_2 = sub_grid_2[iy_t][ix_t]; if (idxA > 0) { if (c_strp.addPair(vx, vy, idxA, idxA+1)) { sub_grid[iy_t][ix_t] *= -1; stripVert_indices[cnt++] = idxA; ix_a = ix_t; iy_a = iy_t; vert_indices[mark_grid[iy_t][ix_t]] = -1; n_segs++; break; } } if (idxA_2 > 0) { if (c_strp.addPair(vx, vy, idxA_2, idxA_2+1)) { sub_grid_2[iy_t][ix_t] *= -1; stripVert_indices[cnt++] = idxA_2; ix_a = ix_t; iy_a = iy_t; vert_indices[mark_grid_2[iy_t][ix_t]] = -1; n_segs++; break; } } } } //- B for (int k=0; k<4; k++) { ix_t = ix_b+udrl[0][k]; iy_t = iy_b+udrl[1][k]; if ((iy_t >=0 && iy_t < leny) && (ix_t >=0 && ix_t < lenx)) { idxB = sub_grid[iy_t][ix_t]; idxB_2 = sub_grid_2[iy_t][ix_t]; if (idxB > 0) { if (c_strp.addPair(vx, vy, idxB, idxB+1)) { sub_grid[iy_t][ix_t] *= -1; stripVert_indices[cnt++] = idxB; ix_b = ix_t; iy_b = iy_t; vert_indices[mark_grid[iy_t][ix_t]] = -1; n_segs++; break; } } if (idxB_2 > 0) { if (c_strp.addPair(vx, vy, idxB_2, idxB_2+1)) { sub_grid_2[iy_t][ix_t] *= -1; stripVert_indices[cnt++] = idxB_2; ix_b = ix_t; iy_b = iy_t; vert_indices[mark_grid_2[iy_t][ix_t]] = -1; n_segs++; break; } } } } } stripCnt = cnt; sub_grid = null; sub_grid_2 = null; return new ContourStrip[] {c_strp}; } public int[] getStartPoint() { int n_trys = 20; float nn = (float) lenx*leny; java.util.Random rnd = new java.util.Random(); for (int tt=0; tt<n_trys; tt++) { int kk = (int) (nn*rnd.nextFloat()); int j = (int) kk/lenx; int i = kk - j*lenx; if (sub_grid[j][i] != 0) { return new int[] {j,i}; } } return null; } } class CachedArray { int [][] array; public CachedArray(int[][] array) { this.array = array; } int[][] getArray() { return array; } } class CachedArrayDimension { int lenx; int leny; CachedArrayDimension(int leny, int lenx) { this.leny = leny; this.lenx = lenx; } public boolean equals(CachedArrayDimension obj) { return (lenx == obj.lenx && leny == obj.leny); } } /** ContourStripSet is used internally by Contour2D */ class ContourStripSet { // value for dash algm. static final int DEFAULT_DASH_VALUE = 2; static final int DISABLE_DASH_VALUE = -1; int mxsize; float[] levels; int n_levs; int nr; int nc; Gridded3DSet spatial_set; java.util.Vector[] vecArray; java.util.Vector vec; PlotDigits[] plot_s; float[][] plot_min_max; boolean[] swap; ContourQuadSet[] qSet; int contourDifficulty = Contour2D.EASY; ContourStripSet(int size, float[] levels, boolean[] swap, double scale_ratio, double label_size, int nr, int nc, Gridded3DSet spatial_set, int contourDifficulty) throws VisADException { this.mxsize = 40*size; this.levels = levels; n_levs = levels.length; vecArray = new java.util.Vector[n_levs]; plot_s = new PlotDigits[n_levs]; plot_min_max = new float[n_levs][2]; float fac = (float) ((0.15*(1.0/scale_ratio))*label_size); this.nr = nr; this.nc = nc; this.swap = swap; this.spatial_set = spatial_set; this.contourDifficulty = contourDifficulty; for (int kk = 0; kk < n_levs; kk++) { vecArray[kk] = new java.util.Vector(); PlotDigits plot = new PlotDigits(); plot.Number = levels[kk]; plot.plotdigits(levels[kk], 0f, 0f, fac*1, fac*1, 400, new boolean[] {false, false, false}); float[][] tmp = new float[2][]; tmp[0] = plot.Vx; tmp[1] = plot.Vy; plot.Vx = tmp[1]; plot.Vy = tmp[0]; tmp[0] = plot.VxB; tmp[1] = plot.VyB; plot.VxB = tmp[1]; plot.VyB = tmp[0]; float vx_min = Float.MAX_VALUE; float vy_min = Float.MAX_VALUE; float vx_max = -Float.MAX_VALUE; float vy_max = -Float.MAX_VALUE; float vxB_min = Float.MAX_VALUE; float vyB_min = Float.MAX_VALUE; float vxB_max = -Float.MAX_VALUE; float vyB_max = -Float.MAX_VALUE; for ( int ii = 0; ii < plot.NumVerts; ii++) { if (plot.Vx[ii] < vx_min) vx_min = plot.Vx[ii]; if (plot.Vy[ii] < vy_min) vy_min = plot.Vy[ii]; if (plot.Vx[ii] > vx_max) vx_max = plot.Vx[ii]; if (plot.Vy[ii] > vy_max) vy_max = plot.Vy[ii]; if (plot.VxB[ii] < vxB_min) vxB_min = plot.VxB[ii]; if (plot.VyB[ii] < vyB_min) vyB_min = plot.VyB[ii]; if (plot.VxB[ii] > vxB_max) vxB_max = plot.VxB[ii]; if (plot.VyB[ii] > vyB_max) vyB_max = plot.VyB[ii]; } float t_x = (vx_max-vx_min)/2 + vx_min; float t_y = (vy_max-vy_min)/2 + vy_min; float t_xB = (vxB_max-vxB_min)/2 + vxB_min; float t_yB = (vyB_max-vyB_min)/2 + vyB_min; for (int ii = 0; ii < plot.NumVerts; ii++) { plot.Vx[ii] -= t_x; plot.Vy[ii] -= t_y; plot.VxB[ii] -= t_xB; plot.VyB[ii] -= t_yB; } plot_s[kk] = plot; if (swap[0] == false) { plot_min_max[kk][0] = vy_min; plot_min_max[kk][1] = vy_max; } else { plot_min_max[kk][0] = vx_min; plot_min_max[kk][1] = vx_max; } plot_min_max[kk][0] = vx_min; plot_min_max[kk][1] = vx_max; } qSet = new ContourQuadSet[n_levs]; for (int kk=0; kk<n_levs; kk++) { qSet[kk] = new ContourQuadSet(nr,nc,kk,this); } } void add(float[] vx, float[] vy, int idx0, int idx1, int lev_idx, int gx, int gy) { qSet[lev_idx].add(idx0, gy, gx); } void add(float[] vx, float[] vy, int idx0, int idx1, float level) { int lev_idx = 0; for (int kk = 0; kk < n_levs; kk++) { if (level == levels[kk]) lev_idx = kk; } add(vx, vy, idx0, idx1, lev_idx); } void add(float[] vx, float[] vy, int idx0, int idx1, int lev_idx) { vec = vecArray[lev_idx]; int n_strip = vec.size(); if (n_strip == 0) { ContourStrip c_strp = new ContourStrip(mxsize, lev_idx, idx0, idx1, plot_s[lev_idx], this); vec.addElement(c_strp); } else { int[] found_array = new int[3]; int found = 0; for (int kk = 0; kk < n_strip; kk++) { ContourStrip c_strp = (ContourStrip)vec.elementAt(kk); if (c_strp.addPair(vx, vy, idx0, idx1)) { found_array[found] = kk; found++; } } if (found==3) { ContourStrip c_strp = new ContourStrip(mxsize, lev_idx, idx0, idx1, plot_s[lev_idx], this); vec.addElement(c_strp); } else if (found==2) { ContourStrip c_strpA = (ContourStrip)vec.elementAt(found_array[0]); ContourStrip c_strpB = (ContourStrip)vec.elementAt(found_array[1]); ContourStrip c_strp = c_strpA.merge(c_strpB); vec.addElement(c_strp); vec.removeElement(c_strpA); vec.removeElement(c_strpB); } else if (found == 0) { ContourStrip c_strp = new ContourStrip(mxsize, lev_idx, idx0, idx1, plot_s[lev_idx], this); vec.addElement(c_strp); } } } void getLineColorArrays(float[] vx, float[] vy, byte[][] colors, byte[] labelColor, int lev_idx, float[][][] out_vv, byte[][][] out_bb, float[][][][] out_vvL, byte[][][][] out_bbL, float[][][] out_loc, boolean[] dashed) { int n_strips = vecArray[lev_idx].size(); float[][][][] la = new float[n_strips][2][][]; byte [][][][] ca = new byte [n_strips][2][][]; float[][][][][] laL = new float[n_strips][4][][][]; byte [][][][][] caL = new byte [n_strips][4][][][]; float[][][][] locL = new float[n_strips][3][][]; for (int kk=0; kk<n_strips; kk++) { ContourStrip cs = (ContourStrip)vecArray[lev_idx].elementAt(kk); // BMF 2006-09-29 //////////////////// // changes to dashed line algm. // add code to display labels for strips with a small number of points // do dashed redering for specified level if (dashed[lev_idx]) cs.dashed = DEFAULT_DASH_VALUE; else cs.dashed = DISABLE_DASH_VALUE; // do the standard label algorithm or the modified for short strips if((cs.hi_idx - cs.low_idx + 1) < ContourStrip.LBL_ALGM_THRESHHOLD){ cs.getInterpolatedLabeledColorArray (vx, vy, colors, labelColor, la[kk], ca[kk], laL[kk], caL[kk], locL[kk]); } else cs.getLabeledLineColorArray (vx, vy, colors, labelColor, la[kk], ca[kk], laL[kk], caL[kk], locL[kk]); // end BMF 2006-09-29 ////////////////// } //-- contour/contour label gap line arrays for (int tt = 0; tt < 2; tt++) { int len = 0; for (int mm = 0; mm < n_strips; mm++) { if (la[mm][tt] != null) { len += la[mm][tt][0].length; } } out_vv[tt] = new float[3][len]; int cnt = 0; for (int mm = 0; mm < n_strips; mm++) { if (la[mm][tt] != null) { System.arraycopy(la[mm][tt][0], 0, out_vv[tt][0], cnt, la[mm][tt][0].length); System.arraycopy(la[mm][tt][1], 0, out_vv[tt][1], cnt, la[mm][tt][1].length); System.arraycopy(la[mm][tt][2], 0, out_vv[tt][2], cnt, la[mm][tt][1].length); cnt += la[mm][tt][0].length; } } int clr_dim = 0; if (colors != null) { clr_dim = colors.length; len = 0; for (int mm = 0; mm < n_strips; mm++) { if (ca[mm][tt] != null) { len += ca[mm][tt][0].length; } } out_bb[tt] = new byte[clr_dim][len]; cnt = 0; for (int mm = 0; mm < n_strips; mm++) { if (ca[mm][tt] != null) { for (int cc = 0; cc < clr_dim; cc++) { System.arraycopy(ca[mm][tt][cc], 0, out_bb[tt][cc], cnt, ca[mm][tt][cc].length); } cnt += ca[mm][tt][0].length; } } } } //-- label, vx3/vx4, line arrays int n_lbl = 0; for (int mm = 0; mm < n_strips; mm++) { if (laL[mm][0] != null) { n_lbl += laL[mm][0].length; } } out_vvL[0] = new float[n_lbl][][]; out_vvL[1] = new float[n_lbl][][]; out_vvL[2] = new float[n_lbl][][]; out_vvL[3] = new float[n_lbl][][]; out_bbL[0] = new byte[n_lbl][][]; out_bbL[1] = new byte[n_lbl][][]; out_bbL[2] = new byte[n_lbl][][]; out_bbL[3] = new byte[n_lbl][][]; out_loc[0] = new float[n_lbl][]; out_loc[1] = new float[n_lbl][]; out_loc[2] = new float[n_lbl][]; for (int tt = 0; tt < 4; tt++) { n_lbl = 0; for (int kk = 0; kk < n_strips; kk++) { if (laL[kk][tt] != null) { for (int mm = 0; mm < laL[kk][tt].length; mm++ ) { out_vvL[tt][n_lbl] = laL[kk][tt][mm]; if (caL[kk][tt] != null) { out_bbL[tt][n_lbl] = caL[kk][tt][mm]; } n_lbl++; } } } } for (int tt = 0; tt < 3; tt++) { n_lbl = 0; for (int kk = 0; kk < n_strips; kk++) { if (locL[kk][0] != null) { for (int mm = 0; mm < locL[kk][tt].length; mm++) { out_loc[tt][n_lbl] = locL[kk][tt][mm]; n_lbl++; } } } } } /** * @param vx * @param vy * @param colors shared colors * @param labelColor RGB label color byte array * @param out_vv output vector verticie array {{ X }, { Y }} * @param out_bb * @param out_vvL * @param out_bbL * @param out_loc */ void getLineColorArrays(float[] vx, float[] vy, byte[][] colors, byte[] labelColor, float[][][] out_vv, byte[][][] out_bb, float[][][][] out_vvL, byte[][][][] out_bbL, float[][][] out_loc, boolean[] dashFlags, int contourDifficulty) { if (contourDifficulty == Contour2D.EASY) { makeContourStrips(vx, vy); } else { for (int kk=0; kk<qSet.length; kk++) { qSet[kk].get(vx, vy); } } float[][][][] tmp = new float[n_levs][2][][]; byte[][][][] btmp = new byte[n_levs][2][][]; float[][][][][] tmpL = new float[n_levs][4][][][]; byte[][][][][] btmpL = new byte[n_levs][4][][][]; float[][][][] tmpLoc = new float[n_levs][3][][]; int n_lbl = 0; for (int kk=0; kk<n_levs; kk++) { getLineColorArrays(vx, vy, colors, labelColor, kk, tmp[kk], btmp[kk], tmpL[kk], btmpL[kk], tmpLoc[kk], dashFlags); n_lbl += tmpL[kk][0].length; } for (int tt = 0; tt < 2; tt++) { int len = 0; for (int kk=0; kk<n_levs; kk++) { len += tmp[kk][tt][0].length; } out_vv[tt] = new float[3][len]; int cnt = 0; for (int kk = 0; kk < n_levs; kk++) { System.arraycopy(tmp[kk][tt][0], 0, out_vv[tt][0], cnt, tmp[kk][tt][0].length); System.arraycopy(tmp[kk][tt][1], 0, out_vv[tt][1], cnt, tmp[kk][tt][0].length); System.arraycopy(tmp[kk][tt][2], 0, out_vv[tt][2], cnt, tmp[kk][tt][0].length); cnt += tmp[kk][tt][0].length; } int clr_dim = 0; if (colors != null) { clr_dim = colors.length; len = 0; for (int kk=0; kk<n_levs; kk++) { len += btmp[kk][tt][0].length; } out_bb[tt] = new byte[clr_dim][len]; cnt = 0; for (int kk = 0; kk < n_levs; kk++) { for (int cc = 0; cc < clr_dim; cc++) { System.arraycopy(btmp[kk][tt][cc], 0, out_bb[tt][cc], cnt, btmp[kk][tt][cc].length); } cnt += btmp[kk][tt][0].length; } } } btmp = null; for (int tt = 0; tt < 4; tt++) { out_vvL[tt] = new float[n_lbl][][]; int cnt = 0; for (int kk = 0; kk<n_levs; kk++) { for ( int ll = 0; ll < tmpL[kk][tt].length; ll++) { out_vvL[tt][cnt] = tmpL[kk][tt][ll]; cnt++; } } out_bbL[tt] = new byte[n_lbl][][]; cnt = 0; for (int kk = 0; kk<n_levs; kk++) { for ( int ll = 0; ll < tmpL[kk][tt].length; ll++) { out_bbL[tt][cnt] = btmpL[kk][tt][ll]; cnt++; } } } tmpL = null; btmpL = null; for (int tt = 0; tt < 3; tt++) { out_loc[tt] = new float[n_lbl][]; int cnt = 0; for (int kk = 0; kk <n_levs; kk++) { if (tmpLoc[kk][tt] != null) { for (int ll = 0; ll < tmpLoc[kk][tt].length; ll++) { out_loc[tt][cnt] = tmpLoc[kk][tt][ll]; cnt++; } } } } } void makeContourStrips(float[] vx, float[] vy) { for (int kk=0; kk<n_levs; kk++) { int nx = qSet[kk].nx; int ny = qSet[kk].ny; for (int j=0; j<ny; j++) { for (int i=0; i<nx; i++) { int[] vert_indices = qSet[kk].qarray[j][i].vert_indices; int len = qSet[kk].qarray[j][i].numv; for (int q=0; q<len; q++) { int idx = vert_indices[q]; add(vx, vy, idx, idx+1, kk); } } } } } } /** ContourStrip is used internally by Contour2D */ class ContourStrip { /** Minimum number of points for which to perform label algm */ static final int LBL_ALGM_THRESHHOLD = 20; /** Intpereted arrays smaller than this will be interpreted again essentially resulting in a re-doubleing. */ static final int INTERP_THRESHHOLD = 5; int[] idx_array; int low_idx; int hi_idx; int lev_idx; /* BMF 2006-10-04 * dashed > 1 indicated this strip is to be dashed with * a skip equal to dashed. * @see #getDashedLineArray(float[][], int) */ int dashed = -1; PlotDigits plot; ContourStripSet css; float lbl_half; ContourStrip(int mxsize, int lev_idx, int idx0, int idx1, PlotDigits plot, ContourStripSet css) { idx_array = new int[mxsize]; this.lev_idx = lev_idx; this.plot = plot; low_idx = mxsize/2; hi_idx = low_idx + 1; idx_array[low_idx] = idx0; idx_array[hi_idx] = idx1; this.css = css; this.lbl_half = (css.plot_min_max[lev_idx][1] - css.plot_min_max[lev_idx][0])/2; this.lbl_half += this.lbl_half*0.30; } ContourStrip(int[] idx_array, int lev_idx, PlotDigits plot,ContourStripSet css) { this.lev_idx = lev_idx; int mxsize = idx_array.length + 400; this.idx_array = new int[mxsize]; this.plot = plot; low_idx = mxsize/2 - (idx_array.length)/2; hi_idx = (low_idx + idx_array.length)-1; System.arraycopy(idx_array, 0, this.idx_array, low_idx, idx_array.length); this.css = css; this.lbl_half = (css.plot_min_max[lev_idx][1] - css.plot_min_max[lev_idx][0])/2; this.lbl_half += this.lbl_half*0.30; } boolean addPair(float[] vx, float[] vy, int idx0, int idx1) { float vx0 = vx[idx0]; float vy0 = vy[idx0]; float vx1 = vx[idx1]; float vy1 = vy[idx1]; float vx_s = vx[idx_array[low_idx]]; float vy_s = vy[idx_array[low_idx]]; float dist = (vx0-vx_s)*(vx0-vx_s)+(vy0-vy_s)*(vy0-vy_s); if (dist <= 0.00001) { if (low_idx < 2) { int[] tmp = new int[idx_array.length + 200]; System.arraycopy(idx_array, 0, tmp, 100, idx_array.length); idx_array = tmp; tmp = null; low_idx += 100; hi_idx += 100; } low_idx -= 1; idx_array[low_idx] = idx0; low_idx -= 1; idx_array[low_idx] = idx1; return true; } dist = (vx1-vx_s)*(vx1-vx_s)+(vy1-vy_s)*(vy1-vy_s); if (dist <= 0.00001) { if (low_idx < 2) { int[] tmp = new int[idx_array.length + 200]; System.arraycopy(idx_array, 0, tmp, 100, idx_array.length); idx_array = tmp; tmp = null; low_idx += 100; hi_idx += 100; } low_idx -= 1; idx_array[low_idx] = idx1; low_idx -= 1; idx_array[low_idx] = idx0; return true; } vx_s = vx[idx_array[hi_idx]]; vy_s = vy[idx_array[hi_idx]]; dist = (vx0-vx_s)*(vx0-vx_s)+(vy0-vy_s)*(vy0-vy_s); if (dist <= 0.00001) { if (hi_idx > idx_array.length-2) { int[] tmp = new int[idx_array.length + 200]; System.arraycopy(idx_array, 0, tmp, 100, idx_array.length); idx_array = tmp; tmp = null; low_idx += 100; hi_idx += 100; } hi_idx += 1; idx_array[hi_idx] = idx0; hi_idx += 1; idx_array[hi_idx] = idx1; return true; } dist = (vx1-vx_s)*(vx1-vx_s)+(vy1-vy_s)*(vy1-vy_s); if (dist <= 0.00001) { if (hi_idx > idx_array.length-2) { int[] tmp = new int[idx_array.length + 200]; System.arraycopy(idx_array, 0, tmp, 100, idx_array.length); idx_array = tmp; tmp = null; low_idx += 100; hi_idx += 100; } hi_idx += 1; idx_array[hi_idx] = idx1; hi_idx += 1; idx_array[hi_idx] = idx0; return true; } return false; } void getLabeledLineColorArray(float[] vx, float[] vy, byte[][] colors, byte[] labelColor, float[][][] out_vv, byte[][][] out_colors, float[][][][] out_vvL, byte[][][][] out_colorsL, float[][][] lbl_loc) { float[][] vv = getLineArray(vx, vy); byte[][] bb = getColorArray(colors); processLineArrays(vv, bb, labelColor, out_vv, out_colors, out_vvL, out_colorsL, lbl_loc); } /* BMF 2006-10-04 * getLabeledLineColorArray() for interpolated short strips */ void getInterpolatedLabeledColorArray(float[] vx, float[] vy, byte[][] colors, byte[] labelColor, float[][][] out_vv, byte[][][] out_colors, float[][][][] out_vvL, byte[][][][] out_colorsL, float[][][] lbl_loc) { byte[][] bb = getColorArray(colors); byte[][] interp_bb = interpolateColorArray(bb); float[][] vv = getLineArray(vx, vy); float[][] interp_vv = interpolateLineArray(vv); // BMF 2006-10-04 // interpolate twice if below threshhold to // make sure there are visible labels if (vv.length < INTERP_THRESHHOLD){ interp_bb = interpolateColorArray(interp_bb); interp_vv = interpolateLineArray(interp_vv); } processLineArrays(interp_vv, interp_bb, labelColor, out_vv, out_colors, out_vvL, out_colorsL, lbl_loc); } /** * Common line array code * * @param vv_grid * @param bb * @param labelColor RGB label color byte array * @param out_vv * @param out_colors * @param out_vvL * @param out_colorsL * @param lbl_loc */ private void processLineArrays(float[][] vv_grid, byte[][] bb, byte[] labelColor, float[][][] out_vv, byte[][][] out_colors, float[][][][] out_vvL, byte[][][][] out_colorsL, float[][][] lbl_loc) { // dash lines if necessary if (this.dashed > 1){ vv_grid = getDashedLineArray(vv_grid); } float[][] vv = null; try { vv = css.spatial_set.gridToValue(vv_grid); } catch (VisADException e) { System.out.println(e.getMessage()); } int clr_dim = 0; if (bb != null) clr_dim = bb.length; int n_lbl = 1; out_vvL[0] = null; out_colorsL[0] = null; out_vvL[1] = null; out_colorsL[1] = null; lbl_loc[0] = null; out_vvL[2] = null; out_colorsL[2] = null; out_vvL[3] = null; out_colorsL[3] = null; lbl_loc[1] = null; lbl_loc[2] = null; out_vv[0] = vv; out_colors[0] = bb; out_vv[1] = null; out_colors[1] = null; if (vv[0].length > LBL_ALGM_THRESHHOLD && ((lev_idx & 1) == 1)) { int loc = (vv[0].length)/2; int start_break = 0; int stop_break = 0; int n_pairs_b = 1; int n_pairs_f = 1; boolean found = false; float ctr_dist; int pos = loc; while(!found) { pos -= 2; if (pos < 0 || pos > (vv[0].length-1)) return; float dx = vv[0][pos] - vv[0][loc]; float dy = vv[1][pos] - vv[1][loc]; float dz = vv[2][pos] - vv[2][loc]; ctr_dist = (float)Math.sqrt((double)(dx*dx + dy*dy + dz*dz)); if (ctr_dist > (float)Math.abs((double)lbl_half)) { found = true; } else { n_pairs_b++; } } pos = loc; found = false; while(!found) { pos += 2; if (pos < 0 || pos > (vv[0].length-1)) return; float dx = vv[0][pos] - vv[0][loc]; float dy = vv[1][pos] - vv[1][loc]; float dz = vv[2][pos] - vv[2][loc]; ctr_dist = (float)Math.sqrt((double)(dx*dx + dy*dy + dz*dz)); if (ctr_dist > (float)Math.abs((double)lbl_half)) { found = true; } else { n_pairs_f++; } } int n_skip = (n_pairs_b+n_pairs_f)*2; if ((loc & 1) == 1) { //- odd start_break = loc - (1+(n_pairs_b-1)*2); stop_break = loc + (2+(n_pairs_f-1)*2); } else { //-even start_break = loc - (2+(n_pairs_b-1)*2); stop_break = loc + (1+(n_pairs_f-1)*2); } float[] vx_tmp = new float[plot.NumVerts]; float[] vy_tmp = new float[plot.NumVerts]; System.arraycopy(plot.Vx, 0, vx_tmp, 0, plot.NumVerts); System.arraycopy(plot.Vy, 0, vy_tmp, 0, plot.NumVerts); float[] vxB_tmp = new float[plot.NumVerts]; float[] vyB_tmp = new float[plot.NumVerts]; System.arraycopy(plot.VxB, 0, vxB_tmp, 0, plot.NumVerts); System.arraycopy(plot.VyB, 0, vyB_tmp, 0, plot.NumVerts); byte[][] lbl_clr = null; if (bb != null) { lbl_clr = new byte[clr_dim][plot.NumVerts]; } boolean rotate = true; float[][] lbl_dcoords = null; if (rotate) { float[][] norm = null; Gridded3DSet cg3d = (Gridded3DSet) css.spatial_set; try { norm = cg3d.getNormals(new float[][] {{vv_grid[0][loc]}, {vv_grid[1][loc]}}); } catch (VisADException e) { System.out.println(e.getMessage()); } if (norm[2][0] < 0) { norm[0][0] = -norm[0][0]; norm[1][0] = -norm[1][0]; norm[2][0] = -norm[2][0]; } float del_x; float del_y; float del_z; del_z = vv[2][stop_break] - vv[2][start_break]; del_y = vv[1][stop_break] - vv[1][start_break]; del_x = vv[0][stop_break] - vv[0][start_break]; float mag = (float) Math.sqrt(del_y*del_y + del_x*del_x + del_z*del_z); float[] ctr_u = new float[] {del_x/mag, del_y/mag, del_z/mag}; if (ctr_u[0] < 0) { ctr_u[0] = -ctr_u[0]; ctr_u[1] = -ctr_u[1]; ctr_u[2] = -ctr_u[2]; } float[] norm_x_ctr = new float[] { norm[1][0]*ctr_u[2]-norm[2][0]*ctr_u[1], -(norm[0][0]*ctr_u[2]-norm[2][0]*ctr_u[0]), norm[0][0]*ctr_u[1]-norm[1][0]*ctr_u[0]}; mag = (float) Math.sqrt(norm_x_ctr[0]*norm_x_ctr[0] + norm_x_ctr[1]*norm_x_ctr[1] + norm_x_ctr[2]*norm_x_ctr[2]); norm_x_ctr[0] = norm_x_ctr[0]/mag; norm_x_ctr[1] = norm_x_ctr[1]/mag; norm_x_ctr[2] = norm_x_ctr[2]/mag; if (Math.abs((double)norm[2][0]) <= 0.00001) { if (norm_x_ctr[2] < 0 ) { norm_x_ctr[0] = -norm_x_ctr[0]; norm_x_ctr[1] = -norm_x_ctr[1]; norm_x_ctr[2] = -norm_x_ctr[2]; } } else { if (norm_x_ctr[1] < 0 ) { norm_x_ctr[0] = -norm_x_ctr[0]; norm_x_ctr[1] = -norm_x_ctr[1]; norm_x_ctr[2] = -norm_x_ctr[2]; } } lbl_dcoords = new float[3][plot.NumVerts]; for (int kk = 0; kk < plot.NumVerts; kk++) { lbl_dcoords[0][kk] = vx_tmp[kk]*ctr_u[0] + vyB_tmp[kk]*norm_x_ctr[0]; lbl_dcoords[1][kk] = vx_tmp[kk]*ctr_u[1] + vyB_tmp[kk]*norm_x_ctr[1]; lbl_dcoords[2][kk] = vx_tmp[kk]*ctr_u[2] + vyB_tmp[kk]*norm_x_ctr[2]; } for (int kk = 0; kk < plot.NumVerts; kk++) { lbl_dcoords[0][kk] += vv[0][loc]; lbl_dcoords[1][kk] += vv[1][loc]; lbl_dcoords[2][kk] += vv[2][loc]; } } //-- translate to label plot location -------------- for (int kk = 0; kk < plot.NumVerts; kk++) { vx_tmp[kk] += vv[0][loc]; vy_tmp[kk] += vv[1][loc]; vxB_tmp[kk] += vv[0][loc]; vyB_tmp[kk] += vv[1][loc]; } //-- assign color to contour labels -------------- if (labelColor != null) { for (int kk=0; kk<plot.NumVerts; kk++) { lbl_clr[0][kk] = labelColor[0]; lbl_clr[1][kk] = labelColor[1]; lbl_clr[2][kk] = labelColor[2]; } } else if (bb != null) { for (int kk=0; kk<plot.NumVerts; kk++) { lbl_clr[0][kk] = bb[0][loc]; lbl_clr[1][kk] = bb[1][loc]; lbl_clr[2][kk] = bb[2][loc]; } } out_vvL[0] = new float[n_lbl][][]; out_colorsL[0] = new byte[n_lbl][][]; out_vvL[1] = new float[n_lbl][][]; out_colorsL[1] = new byte[n_lbl][][]; lbl_loc[0] = new float[n_lbl][7]; lbl_loc[0][0][0] = vv[0][loc]; lbl_loc[0][0][1] = vv[1][loc]; lbl_loc[0][0][2] = vv[2][loc]; out_vv[0] = new float[3][vv[0].length - n_skip]; out_vv[1] = new float[3][n_skip]; if (bb != null) { out_colors[0] = new byte[clr_dim][bb[0].length - n_skip]; out_colors[1] = new byte[clr_dim][n_skip]; } int s_pos = 0; int d_pos = 0; int cnt = start_break; System.arraycopy(vv[0], s_pos, out_vv[0][0], d_pos, cnt); System.arraycopy(vv[1], s_pos, out_vv[0][1], d_pos, cnt); System.arraycopy(vv[2], s_pos, out_vv[0][2], d_pos, cnt); if (bb != null) { for (int cc=0; cc<clr_dim; cc++) { System.arraycopy(bb[cc], s_pos, out_colors[0][cc], d_pos, cnt); } } s_pos = start_break; d_pos = 0; cnt = n_skip; System.arraycopy(vv[0], s_pos, out_vv[1][0], d_pos, cnt); System.arraycopy(vv[1], s_pos, out_vv[1][1], d_pos, cnt); System.arraycopy(vv[2], s_pos, out_vv[1][2], d_pos, cnt); if (bb != null) { for (int cc=0; cc<clr_dim; cc++) { System.arraycopy(bb[cc], s_pos, out_colors[1][cc], d_pos, cnt); } } s_pos = stop_break+1; d_pos = start_break; cnt = vv[0].length - s_pos; System.arraycopy(vv[0], s_pos, out_vv[0][0], d_pos, cnt); System.arraycopy(vv[1], s_pos, out_vv[0][1], d_pos, cnt); System.arraycopy(vv[2], s_pos, out_vv[0][2], d_pos, cnt); if (bb != null) { for (int cc=0; cc<clr_dim; cc++) { System.arraycopy(bb[cc], s_pos, out_colors[0][cc], d_pos, cnt); } } //--- expanding/contracting left-right segments out_vvL[2] = new float[n_lbl][3][2]; out_vvL[3] = new float[n_lbl][3][2]; lbl_loc[1] = new float[n_lbl][3]; lbl_loc[2] = new float[n_lbl][3]; if (bb != null) { out_colorsL[2] = new byte[n_lbl][clr_dim][2]; out_colorsL[3] = new byte[n_lbl][clr_dim][2]; } //- left s_pos = start_break; d_pos = 0; cnt = 2; lbl_loc[1][0][0] = vv[0][s_pos]; lbl_loc[1][0][1] = vv[1][s_pos]; lbl_loc[1][0][2] = vv[2][s_pos]; //- unit left float dx = vv[0][loc] - vv[0][s_pos]; float dy = vv[1][loc] - vv[1][s_pos]; float dz = vv[2][loc] - vv[2][s_pos]; float dd = (float)Math.sqrt((double)(dx*dx + dy*dy + dz*dz)); dx = dx/dd; dy = dy/dd; dz = dz/dd; float mm = dd - (float)Math.abs((double)lbl_half); dx *= mm; dy *= mm; dz *= mm; out_vvL[2][0][0][0] = vv[0][s_pos]; out_vvL[2][0][1][0] = vv[1][s_pos]; out_vvL[2][0][2][0] = vv[2][s_pos]; out_vvL[2][0][0][1] = vv[0][s_pos] + dx; out_vvL[2][0][1][1] = vv[1][s_pos] + dy; out_vvL[2][0][2][1] = vv[2][s_pos] + dz; lbl_loc[0][0][3] = lbl_half; lbl_loc[0][0][4] = dd; if (bb != null) { for (int cc = 0; cc < clr_dim; cc++) { System.arraycopy(bb[cc], s_pos, out_colorsL[2][0][cc], d_pos, cnt); } } //- right s_pos = stop_break - 1; d_pos = 0; cnt = 2; lbl_loc[2][0][0] = vv[0][stop_break]; lbl_loc[2][0][1] = vv[1][stop_break]; lbl_loc[2][0][2] = vv[2][stop_break]; //- unit right dx = vv[0][loc] - vv[0][stop_break]; dy = vv[1][loc] - vv[1][stop_break]; dz = vv[2][loc] - vv[2][stop_break]; dd = (float)Math.sqrt((double)(dx*dx + dy*dy + dz*dz)); dx = dx/dd; dy = dy/dd; dz = dz/dd; mm = dd - (float)Math.abs((double)lbl_half); dx *= mm; dy *= mm; dz *= mm; out_vvL[3][0][0][0] = vv[0][stop_break]; out_vvL[3][0][1][0] = vv[1][stop_break]; out_vvL[3][0][2][0] = vv[2][stop_break]; out_vvL[3][0][0][1] = vv[0][stop_break] + dx; out_vvL[3][0][1][1] = vv[1][stop_break] + dy; out_vvL[3][0][2][1] = vv[2][stop_break] + dz; lbl_loc[0][0][5] = lbl_half; lbl_loc[0][0][6] = dd; if (bb != null) { for (int cc = 0; cc < clr_dim; cc++) { System.arraycopy(bb[cc], s_pos, out_colorsL[3][0][cc], d_pos, cnt); } } //----- end expanding/contracting line segments //--- label vertices out_vvL[0][0] = new float[3][]; out_vvL[0][0][0] = lbl_dcoords[0]; out_vvL[0][0][1] = vy_tmp; out_colorsL[0][0] = lbl_clr; out_vvL[1][0] = new float[3][]; out_vvL[1][0][0] = vxB_tmp; out_vvL[1][0][1] = lbl_dcoords[1]; out_colorsL[1][0] = lbl_clr; out_vvL[0][0][2] = lbl_dcoords[2]; out_vvL[1][0][2] = lbl_dcoords[2]; } else { //- no label out_vv[0] = vv; out_colors[0] = bb; out_vv[1] = null; out_colors[1] = null; return; } } /** * @param vx * @param vy * @return */ float[][] getLineArray(float[] vx, float[] vy) { float[] vvx = new float[(hi_idx-low_idx)+1]; float[] vvy = new float[vvx.length]; int ii = 0; for (int kk = low_idx; kk <= hi_idx; kk++) { vvx[ii] = vx[idx_array[kk]]; vvy[ii] = vy[idx_array[kk]]; ii++; } return new float[][] {vvx, vvy}; } byte[][] getColorArray(byte[][] colors) { if (colors == null) return null; int clr_dim = colors.length; int clr_len = (hi_idx-low_idx)+1; byte[][] new_colors = new byte[clr_dim][clr_len]; int ii = 0; for (int kk = low_idx; kk <= hi_idx; kk++) { for (int cc = 0; cc < clr_dim; cc++) { new_colors[cc][ii] = colors[cc][idx_array[kk]]; } ii++; } return new_colors; } // alternate dashed interpolation // /** // * Take a line array and remove <code>skip</code> sized segments to // * simulate a dashed line. No-op for <code>skip</code> <= 1. // * @param vv Line array as returned by <code>getLineArray</code>. // * @param skip Number of points to make up a dash; ie. number to skip. // * @see #getDashedColorArray(byte[][], int) // * @return A line array interpolated as a dashed line array. // */ // float[][] getDashedLineArray(float[][] vv, int skip) { // // int X = 0; // int Y = 1; // // // length of new array, Always even for line array // int len = (vv[0].length)/skip; // if( len % 2 == 1 ) len += 1; // // float[][] interp = new float[2][len]; // // //System.err.println(" vv[0].length:"+vv[0].length+" len:"+len+" skip:"+skip); // // for(int i=0, j=0; i+skip<vv[0].length; i+=2*skip, j+=2) { // interp[X][j] = vv[X][i]; // interp[Y][j] = vv[Y][i]; // // interp[X][j+1] = vv[X][i+skip]; // interp[Y][j+1] = vv[Y][i+skip]; // // } // // return interp; // // } float[][] getDashedLineArray(float[][] vv) { int X = 0; int Y = 1; // length of new array, Always even for line array int len = vv[0].length; float[][] interp = new float[2][len]; //System.err.println(" vv[0].length:"+vv[0].length+" len:"+len+" skip:"+skip); // from Contour2D.contour(...) for(int i=0; i<vv[0].length; i+=2) { float vxa, vya, vxb, vyb; vxa = vv[X][i+1]; vya = vv[Y][i+1]; vxb = vv[X][i]; vyb = vv[Y][i]; interp[X][i+1] = (3.0f*vxa+vxb) * 0.25f; interp[Y][i+1] = (3.0f*vya+vyb) * 0.25f; interp[X][i] = (vxa+3.0f*vxb) * 0.25f; interp[Y][i] = (vya+3.0f*vyb) * 0.25f; } return interp; } // alternate interpolation // /** // * Take a color array and remove <code>skip</code> sized segments to // * match a dashed line array. No-op for <code>skip</code> <= 1. // * @param vv Line array as returned by <code>getLineArray</code>. // * @param skip Number of points to make up a dash; ie. number to skip. // * @see #getDashedLineArray(float[][], int) // * @return A line array interpolated as a dashed line array. // */ // byte[][] getDashedColorArray(byte[][] colors, int skip) { // // if (colors == null) return null; // // // length of new array, Always even for line array // int len = (colors[0].length)/skip; // if( len % 2 == 1 ) len += 1; // // //System.err.println("colors[0].length:"+colors[0].length+" len:"+len+" skip:"+skip); // // byte[][] interp = new byte[colors.length][len]; // // for(int i=0, j=0; i+skip<colors[0].length; i+=2*skip, j+=2) { // for (int k=0; k<colors.length; k++) { // interp[k][j] = colors[k][i]; // interp[k][j+1] = colors[k][i+skip]; // } // } // // Make all colors white, for DEBUG'ing // for (int j=0; j<interp[0].length; j++){ // for (int i=0; i<interp.length; i++){ // interp[i][j] = (byte)255; // } // } // // return interp; // } /** BMF 2006-09-29 * Double the size of a line array by adding the computed midmoint * between existing values. * @param vv Line array as returned by getLineArray(float[], float[]) * @return An interpolated line array */ float[][] interpolateLineArray(float[][] vv) { int X = 0; int Y = 1; int len = vv[0].length*2; float[][] interp = new float[2][len]; for(int i=0, j=0; i<vv[0].length; i+=2, j+=4) { interp[X][j] = vv[X][i]; interp[Y][j] = vv[Y][i]; interp[X][j+1] = vv[X][i] + 0.5f*(vv[X][i+1] - vv[X][i]); interp[Y][j+1] = vv[Y][i] + 0.5f*(vv[Y][i+1] - vv[Y][i]); interp[X][j+2] = interp[X][j+1]; interp[Y][j+2] = interp[Y][j+1]; interp[X][j+3] = vv[X][i+1]; interp[Y][j+3] = vv[Y][i+1]; } return interp; } /** BMF 2006-09-29 * Doubles the size of the color array by adding averaged colors * between existing colors. * @param colors Color array as returned by <code>getColorArray()</code>. * @return Interpreted color array. */ byte[][] interpolateColorArray(byte[][] colors) { if (colors == null) return null; byte[][] interp = new byte[colors.length][colors[0].length*2]; for(int i=0, j=0; i<colors[0].length; i+=2, j+=4) { for (int k=0; k<colors.length; k++) { byte avg = (byte) ((colors[k][i] + colors[k][i+1]) / 2); interp[k] [j] = colors[k][i]; interp[k][j+1] = avg; interp[k][j+2] = avg; interp[k][j+3] = colors[k][i+1]; } } // set all colors to white for debuging // for (int j=0; j<interp[0].length; j++){ // for (int i=0; i<interp.length; i++){ // if(i==3) interp[i][j] = (byte)255; // else interp[i][j] = (byte)255; // } // } return interp; } ContourStrip merge(ContourStrip c_strp) { if (this.lev_idx != c_strp.lev_idx) { System.out.println("Contour2D.ContourStrip.merge: !BIG ATTENTION!"); } int new_length; int[] new_idx_array = null; int[] thisLo = new int[2]; int[] thisHi = new int[2]; int[] thatLo = new int[2]; int[] thatHi = new int[2]; thisLo[0] = idx_array[low_idx]; thisLo[1] = idx_array[low_idx+1]; thisHi[0] = idx_array[hi_idx]; thisHi[1] = idx_array[hi_idx-1]; thatLo[0] = c_strp.idx_array[c_strp.low_idx]; thatLo[1] = c_strp.idx_array[c_strp.low_idx+1]; thatHi[0] = c_strp.idx_array[c_strp.hi_idx]; thatHi[1] = c_strp.idx_array[c_strp.hi_idx-1]; if (((thisLo[0] == thatLo[0])||(thisLo[0] == thatLo[1]))|| ((thisLo[1] == thatLo[0])||(thisLo[1] == thatLo[1]))) { new_length = (hi_idx-low_idx)+1 + (c_strp.hi_idx-c_strp.low_idx)+1; new_length -= 2; new_idx_array = new int[new_length]; int ii = 0; for (int kk = hi_idx; kk >= low_idx; kk--) { new_idx_array[ii] = idx_array[kk]; ii++; } for (int kk = c_strp.low_idx+2; kk <= c_strp.hi_idx; kk++) { new_idx_array[ii] = c_strp.idx_array[kk]; ii++; } } else if (((thisLo[0] == thatHi[0])||(thisLo[0] == thatHi[1]))|| ((thisLo[1] == thatHi[0])||(thisLo[1] == thatHi[1]))) { new_length = (hi_idx-low_idx)+1 + (c_strp.hi_idx-c_strp.low_idx)+1; new_length -= 2; new_idx_array = new int[new_length]; int ii = 0; for (int kk = hi_idx; kk >= low_idx; kk--) { new_idx_array[ii] = idx_array[kk]; ii++; } for (int kk = c_strp.hi_idx-2; kk >= c_strp.low_idx; kk--) { new_idx_array[ii] = c_strp.idx_array[kk]; ii++; } } else if (((thisHi[0] == thatHi[0])||(thisHi[0] == thatHi[1]))|| ((thisHi[1] == thatHi[0])||(thisHi[1] == thatHi[1]))) { new_length = (hi_idx-low_idx)+1 + (c_strp.hi_idx-c_strp.low_idx)+1; new_length -= 2; new_idx_array = new int[new_length]; int ii = 0; for (int kk = low_idx; kk <= hi_idx; kk++) { new_idx_array[ii] = idx_array[kk]; ii++; } for (int kk = c_strp.hi_idx-2; kk >= c_strp.low_idx; kk--) { new_idx_array[ii] = c_strp.idx_array[kk]; ii++; } } else if (((thisHi[0] == thatLo[0])||(thisHi[0] == thatLo[1]))|| ((thisHi[1] == thatLo[0])||(thisHi[1] == thatLo[1]))) { new_length = (hi_idx-low_idx)+1 + (c_strp.hi_idx-c_strp.low_idx)+1; new_length -= 2; new_idx_array = new int[new_length]; int ii = 0; for (int kk = low_idx; kk <= hi_idx; kk++) { new_idx_array[ii] = idx_array[kk]; ii++; } for (int kk = c_strp.low_idx+2; kk <= c_strp.hi_idx; kk++) { new_idx_array[ii] = c_strp.idx_array[kk]; ii++; } } else { return null; } return new ContourStrip(new_idx_array, lev_idx, plot, css); } public String toString() { return "("+idx_array[low_idx]+","+idx_array[low_idx+1]+"), ("+ idx_array[hi_idx]+","+idx_array[hi_idx-1]+")"; } }
false
true
public static void contour( float g[], int nr, int nc, float[] values, float lowlimit, float highlimit, float base, boolean dash, float vx1[][], float vy1[][], float[][] vz1, int maxv1, int[] numv1, float vx2[][], float vy2[][], float[][] vz2, int maxv2, int[] numv2, float vx3[][], float vy3[][], float[][] vz3, int maxv3, int[] numv3, float vx4[][], float vy4[][], float[][] vz4, int maxv4, int[] numv4, byte[][] auxValues, byte[][] auxLevels1, byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap, boolean fill, float[][] tri, byte[][] tri_color, float[][][] grd_normals, float[][] tri_normals, byte[][] interval_colors, float[][][][] lbl_vv, byte[][][][] lbl_cc, float[][][] lbl_loc, double scale_ratio, double label_size, byte[] labelColor, Gridded3DSet spatial_set) throws VisADException { /* System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit + " highlimit = " + highlimit + " base = " + base); boolean any = false; boolean anymissing = false; boolean anynotmissing = false; */ //System.out.println("contour: swap = " + swap[0] + " " + swap[1] + " " + swap[2]); dash = (fill == true) ? false : dash; PlotDigits plot = new PlotDigits(); int ir, ic; int nrm, ncm; int numc, il; int lr, lc, lc2, lrr, lr2, lcc; float xd, yd ,xx, yy; float xdd, ydd; // float clow, chi; float gg; int maxsize = maxv1+maxv2; float[] vx = new float[maxsize]; float[] vy = new float[maxsize]; // WLH 21 April 2000 // int[] ipnt = new int[2*maxsize]; int[] ipnt = new int[nr*nc+4]; int nump, ip; int numv; /* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */ float[] myvals = null; if (values != null) { myvals = (float[]) values.clone(); java.util.Arrays.sort(myvals); } // flags for each level indicating dashed rendering boolean[] dashFlags = new boolean[myvals.length]; int low; int hi; int t; byte[][] auxLevels = null; int naux = (auxValues != null) ? auxValues.length : 0; byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { if (auxLevels1 == null || auxLevels1.length != naux || auxLevels2 == null || auxLevels2.length != naux || auxLevels3 == null || auxLevels3.length != naux) { throw new SetException("Contour2D.contour: " +"auxLevels length doesn't match"); } for (int i=0; i<naux; i++) { if (auxValues[i].length != g.length) { throw new SetException("Contour2D.contour: " +"auxValues lengths don't match"); } } auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; auxLevels = new byte[naux][maxsize]; } else { if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) { throw new SetException("Contour2D.contour: " +"auxValues null but auxLevels not null"); } } // initialize vertex counts numv1[0] = 0; numv2[0] = 0; numv3[0] = 0; numv4[0] = 0; if (values == null) return; // WLH 24 Aug 99 /* DRM: 1999-05-19 - Not needed since dash is a boolean // check for bad contour interval if (interval==0.0) { throw new DisplayException("Contour2D.contour: interval cannot be 0"); } if (!dash) { // draw negative contour lines as dashed lines interval = -interval; idash = 1; } else { idash = 0; } */ nrm = nr-1; ncm = nc-1; xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0 ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0 /**-TDR xd = xdd - 0.0001f; yd = ydd - 0.0001f; gap too big **/ xd = xdd - 0.00002f; yd = ydd - 0.00002f; /* * set up mark array * mark= 0 if avail for label center, * 2 if in label, and * 1 if not available and not in label * * lr and lc give label size in grid boxes * lrr and lcc give unavailable radius */ if (swap[0]) { lr = 1+(nr-2)/10; lc = 1+(nc-2)/50; } else { lr = 1+(nr-2)/50; lc = 1+(nc-2)/10; } lc2 = lc/2; lr2 = lr/2; lrr = 1+(nr-2)/8; lcc = 1+(nc-2)/8; // allocate mark array char[] mark = new char[nr * nc]; // initialize mark array to zeros for (int i=0; i<nr * nc; i++) mark[i] = 0; // set top and bottom rows to 1 float max_g = -Float.MAX_VALUE; float min_g = Float.MAX_VALUE; for (ic=0;ic<nc;ic++) { for (ir=0;ir<lr;ir++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (ic) * nr + (nr-ir-2) ] = 1; float val = g[(ic) * nr + (ir)]; if (val > max_g) max_g = val; if (val < min_g) min_g = val; } } // set left and right columns to 1 for (ir=0;ir<nr;ir++) { for (ic=0;ic<lc;ic++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (nc-ic-2) * nr + (ir) ] = 1; } } numv = nump = 0; //- color fill arrays byte[][] color_bin = null; byte[][][] o_flags = null; short[][] n_lines = null; short[][] ctrLow = null; if (fill) { color_bin = interval_colors; o_flags = new byte[nrm][ncm][]; n_lines = new short[nrm][ncm]; ctrLow = new short[nrm][ncm]; } //- estimate contour difficutly int ctr_lo = 0; int ctr_hi = myvals.length-1; for (int k=0; k<myvals.length; k++) { if (min_g >= myvals[k]) ctr_lo = k; if (max_g >= myvals[k]) ctr_hi = k; } float ctr_int = myvals[1] - myvals[0]; int switch_cnt = 0; float[] last_diff = new float[(ctr_hi-ctr_lo)+1]; for (ir=2; ir<nrm-2; ir+=1) { for (int k=0; k<last_diff.length;k++) { last_diff[k] = g[ir] - myvals[ctr_lo+k]; for (ic=2; ic<ncm-2; ic+=1) { float diff = g[ic*nr + ir] - myvals[ctr_lo+k]; if ((diff*last_diff[k] < 0) && ((diff > 0.005*ctr_int) || (diff < -0.005*ctr_int)) ) { switch_cnt++; } last_diff[k] = diff; } } } int contourDifficulty = Contour2D.EASY; if (switch_cnt > Contour2D.DIFFICULTY_THRESHOLD) contourDifficulty = Contour2D.HARD; ContourStripSet ctrSet = new ContourStripSet(nrm, myvals, swap, scale_ratio, label_size, nr, nc, spatial_set, contourDifficulty); // compute contours for (ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; // = ir for (ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; float gv, gn, gx; float tmp1, tmp2; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } // save index of first vertex in this grid box ipnt[nump++] = numv; yy = ydd*ic+0.0f; // = ic /* ga = ( g[ (ic) * nr + (ir) ] ); gb = ( g[ (ic) * nr + (ir+1) ] ); gc = ( g[ (ic+1) * nr + (ir) ] ); gd = ( g[ (ic+1) * nr + (ir+1) ] ); boolean miss = false; if (ga != ga || gb != gb || gc != gc || gd != gd) { miss = true; System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " + ga + " " + gb + " " + gc + " " + gd); } */ /* if (ga != ga || gb != gb || gc != gc || gd != gd) { if (!anymissing) { anymissing = true; System.out.println("missing"); } } else { if (!anynotmissing) { anynotmissing = true; System.out.println("notmissing"); } } */ // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; /* DRM move outside the loop byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; */ if (naux > 0) { for (int i=0; i<naux; i++) { auxa[i] = auxValues[i][(ic) * nr + (ir)]; auxb[i] = auxValues[i][(ic) * nr + (ir+1)]; auxc[i] = auxValues[i][(ic+1) * nr + (ir)]; auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)]; } } // find average, min, and max of 4 corner values gv = (ga+gb+gc+gd)/4.0f; // gn = MIN4(ga,gb,gc,gd); tmp1 = ( (ga) < (gb) ? (ga) : (gb) ); tmp2 = ( (gc) < (gd) ? (gc) : (gd) ); gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) ); // gx = MAX4(ga,gb,gc,gd); tmp1 = ( (ga) > (gb) ? (ga) : (gb) ); tmp2 = ( (gc) > (gd) ? (gc) : (gd) ); gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) ); /* remove for new signature, replace with code below // compute clow and chi, low and high contour values in the box tmp1 = (gn-base) / interval; clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )-1); while (clow<gn) { clow += interval; } tmp1 = (gx-base) / interval; chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )+1); while (chi>gx) { chi -= interval; } // how many contour lines in the box: tmp1 = (chi-clow) / interval; numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) ); // gg is current contour line value gg = clow; */ low = 0; hi = myvals.length - 1; if (myvals[low] > gx || myvals[hi] < gn) // no contours { numc = 1; } else // some inside the box { for (int i = 0; i < myvals.length; i++) { if (i == 0 && myvals[i] >= gn) { low = i; } else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; } if (i == 0 && myvals[i] >= gx) { hi = i; } else if (myvals[i] >= gx && myvals[i-1] < gx) { hi = i; } } numc = hi - low + 1; } gg = myvals[low]; /* if (!any && numc > 0) { System.out.println("gn = " + gn + " gx = " + gx + " gv = " + gv); System.out.println("numc = " + numc + " clow = " + myvals[low] + " chi = " + myvals[hi]); any = true; } */ if (fill) { o_flags[ir][ic] = new byte[2*numc]; //- case flags n_lines[ir][ic] = 0; //- number of contour line segments ctrLow[ir][ic] = (short)hi; } for (il=0; il<numc; il++) { gg = myvals[low+il]; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } float gba, gca, gdb, gdc; int ii; // make sure gg is within contouring limits if (gg < gn) continue; if (gg > gx) break; if (gg < lowlimit) continue; if (gg > highlimit) break; // compute orientation of lines inside box ii = 0; if (gg > ga) ii = 1; if (gg > gb) ii += 2; if (gg > gc) ii += 4; if (gg > gd) ii += 8; if (ii > 7) ii = 15 - ii; if (ii <= 0) continue; if (fill) { if ((low+il) < ctrLow[ir][ic]) ctrLow[ir][ic] = (short)(low+il); } // DO LABEL HERE if (( mark[ (ic) * nr + (ir) ] )==0) { int kc, kr, mc, mr, jc, jr; float xk, yk, xm, ym, value; // Insert a label // BOX TO AVOID kc = ic-lc2-lcc; kr = ir-lr2-lrr; mc = kc+2*lcc+lc-1; mr = kr+2*lrr+lr-1; // OK here for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { if (( mark[ (jc) * nr + (jr) ] ) != 2) { mark[ (jc) * nr + (jr) ] = 1; } } } } } // BOX TO HOLD LABEL kc = ic-lc2; kr = ir-lr2; mc = kc+lc-1; mr = kr+lr-1; for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { mark[ (jc) * nr + (jr) ] = 2; } } } } xk = xdd*kr+0.0f; yk = ydd*kc+0.0f; xm = xdd*(mr+1.0f)+0.0f; ym = ydd*(mc+1.0f)+0.0f; value = gg; if (numv4[0]+1000 >= maxv4) { // allocate more space maxv4 = 2 * (numv4[0]+1000); float[][] tx = new float[][] {vx4[0]}; float[][] ty = new float[][] {vy4[0]}; vx4[0] = new float[maxv4]; vy4[0] = new float[maxv4]; System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]); System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]); tx = null; ty = null; } if (numv3[0]+1000 >= maxv3) { // allocate more space maxv3 = 2 * (numv3[0]+1000); float[][] tx = new float[][] {vx3[0]}; float[][] ty = new float[][] {vy3[0]}; vx3[0] = new float[maxv3]; vy3[0] = new float[maxv3]; System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]); System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels3; for (int i=0; i<naux; i++) { //byte[] taa = auxLevels3[i]; auxLevels3[i] = new byte[maxv3]; System.arraycopy(ta[i], 0, auxLevels3[i], 0, numv3[0]); } ta = null; } } plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap); System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts); System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts); if (naux > 0) { for (int i=0; i<naux; i++) { for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) { auxLevels3[i][j] = auxa[i]; } } } numv3[0] += plot.NumVerts; System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts); System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts); numv4[0] += plot.NumVerts; } switch (ii) { case 1: gba = gb-ga; gca = gc-ga; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratioca = (gg-ga)/gca; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) { vx[numv] = xx; } else { vx[numv] = xx+xd*(gg-ga)/gba; } vy[numv] = yy; numv++; if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) { vy[numv] = yy; } else { vy[numv] = yy+yd*(gg-ga)/gca; } vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] += 0.00001f; vy[numv-1] += 0.00001f; } break; case 2: gba = gb-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] -= 0.00001f; vy[numv-1] += 0.00001f; } break; case 3: gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 4: gca = gc-ga; gdc = gd-gc; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] += 0.00001f; vy[numv-2] -= 0.00001f; } break; case 5: gba = gb-ga; gdc = gd-gc; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 6: gba = gb-ga; gdc = gd-gc; gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; */ if ( (gg>gv) ^ (ga<gb) ) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } else { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+3] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; // here's a brain teaser if ( (gg>gv) ^ (ga<gb) ) { // (XOR) if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)1 + (byte)32; n_lines[ir][ic]++; } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)7 + (byte)32; n_lines[ir][ic]++; } numv++; } else { if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)2 + (byte)32; n_lines[ir][ic]++; } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)4 + (byte)32; n_lines[ir][ic]++; } } if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; break; case 7: gdb = gd-gb; gdc = gd-gc; if (naux > 0) { float ratiodb = (gg-gb)/gdb; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] -= 0.00001f; vy[numv-2] -= 0.00001f; } break; } // switch // If contour level is negative, make dashed line if (gg < base && dash) { /* DRM: 1999-05-19 */ // 2006-09-29 BMF -- Moved to ContourStrip.getDashedLineArray(...) // float vxa, vya, vxb, vyb; // vxa = vx[numv-2]; // vya = vy[numv-2]; // vxb = vx[numv-1]; // vyb = vy[numv-1]; // vx[numv-2] = (3.0f*vxa+vxb) * 0.25f; // vy[numv-2] = (3.0f*vya+vyb) * 0.25f; // vx[numv-1] = (vxa+3.0f*vxb) * 0.25f; // vy[numv-1] = (vya+3.0f*vyb) * 0.25f; dashFlags[low+il] = true; } /* if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) || (20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) { System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] + " ic, ir = " + ic + " " + ir); } */ if (ii == 6) { //- add last two pairs ctrSet.add(vx, vy, numv-4, numv-3, low+il, ic, ir); ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } else { ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } } // for il -- NOTE: gg incremented in for statement } // for ic } // for ir /**------------------- Color Fill -------------------------*/ if (fill) { fillGridBox(g, n_lines, vx, vy, xd, xdd, yd, ydd, nr, nrm, nc, ncm, ctrLow, tri, tri_color, o_flags, myvals, color_bin, grd_normals, tri_normals); // BMF 2006-10-04 do not return, ie. draw labels on filled contours // for now, just return because we don't need to do labels //return; } //---TDR, build Contour Strips float[][][] vvv = new float[2][][]; byte [][][] new_colors = new byte[2][][]; ctrSet.getLineColorArrays(vx, vy, auxLevels, labelColor, vvv, new_colors, lbl_vv, lbl_cc, lbl_loc, dashFlags, contourDifficulty); vx2[0] = vvv[1][0]; vy2[0] = vvv[1][1]; vz2[0] = vvv[1][2]; numv1[0] = vvv[0][0].length; numv2[0] = vvv[1][0].length; int n_lbls = lbl_vv[0].length; if (n_lbls > 0) { vx3[0] = lbl_vv[0][0][0]; vy3[0] = lbl_vv[0][0][1]; vz3[0] = lbl_vv[0][0][2]; vx4[0] = lbl_vv[1][0][0]; vy4[0] = lbl_vv[1][0][1]; vz4[0] = lbl_vv[1][0][2]; numv3[0] = lbl_vv[0][0][0].length; numv4[0] = lbl_vv[1][0][0].length; } if (auxLevels != null) { int clr_dim = auxValues.length; auxLevels1[0] = new_colors[0][0]; auxLevels1[1] = new_colors[0][1]; auxLevels1[2] = new_colors[0][2]; if (clr_dim == 4) auxLevels1[3] = new_colors[0][3]; auxLevels2[0] = new_colors[1][0]; auxLevels2[1] = new_colors[1][1]; auxLevels2[2] = new_colors[1][2]; if (clr_dim == 4) auxLevels2[3] = new_colors[1][3]; if (n_lbls > 0) { auxLevels3[0] = lbl_cc[0][0][0]; auxLevels3[1] = lbl_cc[0][0][1]; auxLevels3[2] = lbl_cc[0][0][2]; if (clr_dim == 4) auxLevels3[3] = lbl_cc[0][0][3]; } } if (contourDifficulty == Contour2D.EASY) { vx1[0] = vvv[0][0]; vy1[0] = vvv[0][1]; vz1[0] = vvv[0][2]; } else { int start = numv1[0]; float[][] vx_tmp = new float[1][]; float[][] vy_tmp = new float[1][]; float[][] vz_tmp = new float[1][]; byte[][] aux_tmp = new byte[4][]; float[] vx1_tmp = new float[numv]; float[] vy1_tmp = new float[numv]; float[] vz1_tmp = new float[numv]; byte[][] aux1_tmp = new byte[4][]; aux1_tmp[0] = new byte[numv]; aux1_tmp[1] = new byte[numv]; aux1_tmp[2] = new byte[numv]; int cnt = 0; for (int kk=0; kk<ctrSet.qSet.length;kk++) { ctrSet.qSet[kk].getArrays(vx, vy, auxLevels, vx_tmp, vy_tmp, vz_tmp, aux_tmp, spatial_set); int len = vx_tmp[0].length; System.arraycopy(vx_tmp[0], 0, vx1_tmp, cnt, len); System.arraycopy(vy_tmp[0], 0, vy1_tmp, cnt, len); System.arraycopy(vz_tmp[0], 0, vz1_tmp, cnt, len); System.arraycopy(aux_tmp[0], 0, aux1_tmp[0], cnt, len); System.arraycopy(aux_tmp[1], 0, aux1_tmp[1], cnt, len); System.arraycopy(aux_tmp[2], 0, aux1_tmp[2], cnt, len); cnt += len; } vx1[0] = new float[numv1[0]+cnt]; vy1[0] = new float[numv1[0]+cnt]; vz1[0] = new float[numv1[0]+cnt]; auxLevels1[0] = new byte[numv1[0]+cnt]; auxLevels1[1] = new byte[numv1[0]+cnt]; auxLevels1[2] = new byte[numv1[0]+cnt]; auxLevels1[3] = new byte[numv1[0]+cnt]; System.arraycopy(vvv[0][0], 0, vx1[0], 0, numv1[0]); System.arraycopy(vvv[0][1], 0, vy1[0], 0, numv1[0]); System.arraycopy(vvv[0][2], 0, vz1[0], 0, numv1[0]); System.arraycopy(new_colors[0][0], 0, auxLevels1[0], 0, numv1[0]); System.arraycopy(new_colors[0][1], 0, auxLevels1[1], 0, numv1[0]); System.arraycopy(new_colors[0][2], 0, auxLevels1[2], 0, numv1[0]); System.arraycopy(vx1_tmp, 0, vx1[0], start, cnt); System.arraycopy(vy1_tmp, 0, vy1[0], start, cnt); System.arraycopy(vz1_tmp, 0, vz1[0], start, cnt); System.arraycopy(aux1_tmp[0], 0, auxLevels1[0], start, cnt); System.arraycopy(aux1_tmp[1], 0, auxLevels1[1], start, cnt); System.arraycopy(aux1_tmp[2], 0, auxLevels1[2], start, cnt); numv1[0] += cnt; vx1_tmp = null; vy1_tmp = null; vz1_tmp = null; } } private static void fillGridBox(float[] g, short[][] n_lines, float[] vx, float[] vy, float xd, float xdd, float yd, float ydd, int nr, int nrm, int nc, int ncm, short[][] ctrLow, float[][] tri, byte[][] tri_color, byte[][][] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, float[][] tri_normals) { float xx, yy; int[] numv = new int[1]; numv[0] = 0; int n_tri = 0; for (int ir=0; ir<nrm; ir++) { for (int ic=0; ic<ncm; ic++) { if (n_lines[ir][ic] == 0) { n_tri +=2; } else { n_tri += (4 + (n_lines[ir][ic]-1)*2); } boolean any = false; if (o_flags[ir][ic] != null) { for (int k=0; k<o_flags[ir][ic].length; k++) { if (o_flags[ir][ic][k] > 32) any = true; } if (any) n_tri += 4; } } } tri[0] = new float[n_tri*3]; tri[1] = new float[n_tri*3]; for (int kk=0; kk<color_bin.length; kk++) { tri_color[kk] = new byte[n_tri*3]; } tri_normals[0] = new float[3*n_tri*3]; int[] t_idx = new int[1]; t_idx[0] = 0; int[] n_idx = new int[1]; n_idx[0] = 0; for (int ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; for (int ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; yy = ydd*ic+0.0f; // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; numv[0] += n_lines[ir][ic]*2; fillGridBox(new float[] {ga, gb, gc, gd}, n_lines[ir][ic], vx, vy, xx, yy, xd, yd, ic, ir, ctrLow[ir][ic], tri, t_idx, tri_color, numv[0], o_flags[ir][ic], values, color_bin, grd_normals, n_idx, tri_normals); } } } private static void fillGridBox(float[] corners, int numc, float[] vx, float[] vy, float xx, float yy, float xd, float yd, int nc, int nr, short ctrLow, float[][] tri, int[] t_idx, byte[][] tri_color, int numv, byte[] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, int[] n_idx, float[][] tri_normals_a) { float[] tri_normals = tri_normals_a[0]; int n_tri = 4 + (numc-1)*2; int[] cnt_tri = new int[1]; cnt_tri[0] = 0; int il = 0; int color_length = color_bin.length; float[] vec = new float[2]; float[] vec_last = new float[2]; float[] vv1 = new float[2]; float[] vv2 = new float[2]; float[] vv1_last = new float[2]; float[] vv2_last = new float[2]; float[][] vv = new float[2][2]; float[][] vv_last = new float[2][2]; float[] vv3 = new float[2]; int dir = 1; int start = numv-2; int o_start = numc-1; int x_min_idx = 0; int o_idx = 0; byte o_flag = o_flags[o_idx]; int ydir = 1; boolean special = false; int[] closed = {0}; boolean up; boolean right; float dist_sqrd = 0; int v_idx = start + dir*il*2; //-- color level at corners //------------------------------ byte[][] crnr_color = new byte[4][color_length]; boolean[] crnr_out = new boolean[] {true, true, true, true}; boolean all_out = true; for (int tt = 0; tt < corners.length; tt++) { int cc = 0; int kk = 0; for (kk = 0; kk < (values.length - 1); kk++) { if ((corners[tt] >= values[kk]) && (corners[tt] < values[kk+1])) { cc = kk; all_out = false; crnr_out[tt] = false; } } for (int ii=0; ii<color_length; ii++) { crnr_color[tt][ii] = color_bin[ii][cc]; } } int tt = t_idx[0]; //- initialize triangle vertex counter dir = 1; start = numv - numc*2; o_start = 0; v_idx = start + dir*il*2; up = false; right = false; float[] x_avg = new float[2]; float[] y_avg = new float[2]; if (numc > 1) { //-- first/next ctr line midpoints int idx = v_idx; x_avg[0] = (vx[idx] + vx[idx+1])/2; y_avg[0] = (vy[idx] + vy[idx+1])/2; idx = v_idx + 2; x_avg[1] = (vx[idx] + vx[idx+1])/2; y_avg[1] = (vy[idx] + vy[idx+1])/2; if ((x_avg[1] - x_avg[0]) > 0) up = true; if ((y_avg[1] - y_avg[0]) > 0) right = true; } else if ( numc == 1 ) { //- default values for logic below x_avg[0] = 0f; y_avg[0] = 0f; x_avg[1] = 1f; y_avg[1] = 1f; } else if ( numc == 0 ) //- empty grid box (no contour lines) { if (all_out) return; n_tri = 2; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; return; }//-- end no contour lines //--If any case 6 (saddle point), handle with special logic for (int iii=0; iii<o_flags.length; iii++) { if (o_flags[iii] > 32) { fillCaseSix(xx, yy, xd, yd, v_idx, dir, o_flags, ctrLow, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, color_bin, tri_color, color_length, grd_normals, n_idx, tri_normals, closed, cnt_tri); return; } } //-- start making triangles for color fill //--------------------------------------------- if (o_flag == 1 || o_flag == 4 || o_flag == 2 || o_flag == 7) { boolean opp = false; float dy = 0; float dx = 0; float dist_0 = 0; float dist_1 = 0; /** compare midpoints distances for first/next contour lines -------------------------------------------------*/ if (o_flag == 1) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 2) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (o_flag == 4) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 7) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (dist_1 < dist_0) opp = true; if (opp) { fillToOppCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (o_flags[o_idx] == 3) { int flag = 1; if (right) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (o_flags[o_idx] == 5) { int flag = 1; if (!up) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } byte last_o = o_flags[o_idx]; int cc_start = (dir > 0) ? (ctrLow-1) : (ctrLow+(numc-1)); //- move to next contour line //-------------------------------- il++; for ( il = 1; il < numc; il++ ) { v_idx = start + dir*il*2; o_idx = o_start + dir*il; int v_idx_last = v_idx - 2*dir; int cc = cc_start + dir*il; if (o_flags[o_idx] != last_o) //- contour line case change { byte[] side_s = new byte[2]; byte[] last_side_s = new byte[2]; byte[] b_arg = new byte[2]; boolean flip; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx, dir, o_flags[o_idx], b_arg); side_s[0] = b_arg[0]; side_s[1] = b_arg[1]; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx_last, dir, last_o, b_arg); last_side_s[0] = b_arg[0]; last_side_s[1] = b_arg[1]; if (side_s[0] == last_side_s[0]) { flip = false; } else if (side_s[0] == last_side_s[1]) { flip = true; } else if (side_s[1] == last_side_s[0]) { flip = true; } else if (side_s[1] == last_side_s[1]) { flip = false; } else { if(((side_s[0]+last_side_s[0]) & 1) == 1) { flip = false; } else { flip = true; } } if (!flip) { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv[0][0] = vx[v_idx]; vv[1][0] = vy[v_idx]; vv[0][1] = vx[v_idx+dir]; vv[1][1] = vy[v_idx+dir]; } else { vv1[0] = vx[v_idx+dir]; vv1[1] = vy[v_idx+dir]; vv2[0] = vx[v_idx]; vv2[1] = vy[v_idx]; vv[0][0] = vx[v_idx+dir]; vv[1][0] = vy[v_idx+dir]; vv[0][1] = vx[v_idx]; vv[1][1] = vy[v_idx]; } vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; vv_last[0][0] = vx[v_idx_last]; vv_last[1][0] = vy[v_idx_last]; vv_last[0][1] = vx[v_idx_last+dir]; vv_last[1][1] = vy[v_idx_last+dir]; //--- fill between contour lines fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); byte[] b_arg2 = new byte[2]; getBoxSide(vv[0], vv[1], xx, xd, yy, yd, 0, dir, o_flags[o_idx], b_arg); getBoxSide(vv_last[0], vv_last[1], xx, xd, yy, yd, 0, dir, last_o, b_arg2); for (int kk = 0; kk < 2; kk++) { //- close off corners float[] vvx = new float[2]; float[] vvy = new float[2]; byte side = 0; byte last_s = 0; side = b_arg[kk]; last_s = b_arg2[kk]; if ( side != last_s ) { if ((side == 0 && last_s == 3) || (side == 3 && last_s == 0)) { //- case 1 fillToNearCorner(xx, yy, xd, yd, 0, (byte)1, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 0 && last_s == 1) || (side == 1 && last_s == 0)) { //- case 2 fillToNearCorner(xx, yy, xd, yd, 0, (byte)2, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 3) || (side == 3 && last_s == 2)) { //- case 4 fillToNearCorner(xx, yy, xd, yd, 0, (byte)4, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 1) || (side == 1 && last_s == 2)) { //- case 7 fillToNearCorner(xx, yy, xd, yd, 0, (byte)7, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 0) || (side == 0 && last_s == 2)) { //- case 5 if (side == 0) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 1)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)5, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 1 && last_s == 3) || (side == 3 && last_s == 1)) { //- case 3 if (side == 3) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 8)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)3, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } } } else { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); } last_o = o_flags[o_idx]; }//---- contour loop /*- last or first/last contour line ------------------------------------*/ int flag_set = 0; if ((last_o == 1)||(last_o == 2)||(last_o == 4)||(last_o == 7)) { if(last_o == 1) flag_set = (closed[0] & 1); if(last_o == 2) flag_set = (closed[0] & 2); if(last_o == 4) flag_set = (closed[0] & 4); if(last_o == 7) flag_set = (closed[0] & 8); if (flag_set > 0) { fillToOppCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (last_o == 3) { int flag = -1; if (closed[0]==3) flag = 1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (last_o == 5) { int flag = 1; if (closed[0]==5) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } }//--- end fillGridBox private static void getBoxSide(float[] vx, float[] vy, float xx, float xd, float yy, float yd, int v_idx, int dir, byte o_flag, byte[] side) { /* if (vy[v_idx] == yy) side[0] = 0; // a-b if (vy[v_idx] == (yy + yd)) side[0] = 2; // c-d if (vx[v_idx] == xx) side[0] = 3; // a-c if (vx[v_idx] == (xx + xd)) side[0] = 1; // b-d */ for (int kk = 0; kk < 2; kk++) { int ii = v_idx + kk*dir; switch (o_flag) { case 1: side[kk] = 3; if (vy[ii] == yy) side[kk] = 0; break; case 2: side[kk] = 1; if (vy[ii] == yy) side[kk] = 0; break; case 4: side[kk] = 3; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 7: side[kk] = 1; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 3: side[kk] = 1; if (vx[ii] == xx) side[kk] = 3; break; case 5: side[kk] = 0; if (vy[ii] == (yy + yd)) side[kk] = 2; break; } } } private static void interpNormals(float vx, float vy, float xx, float yy, int nc, int nr, float xd, float yd, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int side = -1; float[] nn = new float[3]; if (vy == yy) side = 0; // a-b if (vy == (yy + yd)) side = 2; // c-d if (vx == xx) side = 3; // a-c if (vx == (xx + xd)) side = 1; // b-d float dx = vx - xx; float dy = vy - yy; switch (side) { case 0: nn[0] = ((grd_normals[nc][nr+1][0] - grd_normals[nc][nr][0])/xd)*dx + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc][nr+1][1] - grd_normals[nc][nr][1])/xd)*dx + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc][nr+1][2] - grd_normals[nc][nr][2])/xd)*dx + grd_normals[nc][nr][2]; break; case 3: nn[0] = ((grd_normals[nc+1][nr][0] - grd_normals[nc][nr][0])/yd)*dy + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc+1][nr][1] - grd_normals[nc][nr][1])/yd)*dy + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc+1][nr][2] - grd_normals[nc][nr][2])/yd)*dy + grd_normals[nc][nr][2]; break; case 1: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc][nr+1][0])/yd)*dy + grd_normals[nc][nr+1][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc][nr+1][1])/yd)*dy + grd_normals[nc][nr+1][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc][nr+1][2])/yd)*dy + grd_normals[nc][nr+1][2]; break; case 2: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc+1][nr][0])/xd)*dx + grd_normals[nc+1][nr][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc+1][nr][1])/xd)*dx + grd_normals[nc+1][nr][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc+1][nr][2])/xd)*dx + grd_normals[nc+1][nr][2]; break; default: System.out.println("interpNormals, bad side: "+side); } //- re-normalize float mag = (float) Math.sqrt(nn[0]*nn[0] + nn[1]*nn[1] + nn[2]*nn[2]); nn[0] /= mag; nn[1] /= mag; nn[2] /= mag; tri_normals[n_idx[0]++] = nn[0]; tri_normals[n_idx[0]++] = nn[1]; tri_normals[n_idx[0]++] = nn[2]; } private static void fillToLast(float xx, float yy, float xd, float yd, int nc, int nr, float[] vv1, float[] vv2, float[] vv1_last, float[] vv2_last, float[][] tri, int[] cnt_tri, int[] t_idx, byte[][] tri_color, byte[][] color_bin, int cc, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1[0]; tri[1][tt] = vv1[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri[0]++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2_last[0]; tri[1][tt] = vv2_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; t_idx[0] = tt; cnt_tri[0]++; } private static void fillCaseSix(float xx, float yy, float xd, float yd, int v_idx, int dir, byte[] o_flags, short ctrLow, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] color_bin, byte[][] tri_color, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed, int[] cnt_tri) { int n1 = 0; int n2 = 0; int n4 = 0; int n7 = 0; for (int kk = 0; kk < o_flags.length; kk++) { if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) n1++; if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) n2++; if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) n4++; if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) n7++; } float[][] vv1 = new float[2][n1*2]; float[][] vv2 = new float[2][n2*2]; float[][] vv4 = new float[2][n4*2]; float[][] vv7 = new float[2][n7*2]; int[] clr_idx1 = new int[n1]; int[] clr_idx2 = new int[n2]; int[] clr_idx4 = new int[n4]; int[] clr_idx7 = new int[n7]; float[] vvv1 = new float[2]; float[] vvv2 = new float[2]; float[] vvv1_last = new float[2]; float[] vvv2_last = new float[2]; n1 = 0; n2 = 0; n4 = 0; n7 = 0; int ii = v_idx; int cc = ctrLow - 1; int cnt = 0; int[] cases = {1, 2, 7, 4}; //- corner cases, clockwise around box for (int kk = 0; kk < o_flags.length; kk++) { if (o_flags[kk] > 32) cnt++; if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) { clr_idx1[n1] = cc; vv1[0][2*n1] = vx[ii]; vv1[1][2*n1] = vy[ii]; vv1[0][2*n1+1] = vx[ii+1]; vv1[1][2*n1+1] = vy[ii+1]; n1++; } else if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) { clr_idx2[n2] = cc; vv2[0][2*n2] = vx[ii]; vv2[1][2*n2] = vy[ii]; vv2[0][2*n2+1] = vx[ii+1]; vv2[1][2*n2+1] = vy[ii+1]; n2++; } else if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) { clr_idx4[n4] = cc; vv4[0][2*n4] = vx[ii]; vv4[1][2*n4] = vy[ii]; vv4[0][2*n4+1] = vx[ii+1]; vv4[1][2*n4+1] = vy[ii+1]; n4++; } else if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) { clr_idx7[n7] = cc; vv7[0][2*n7] = vx[ii]; vv7[1][2*n7] = vy[ii]; vv7[0][2*n7+1] = vx[ii+1]; vv7[1][2*n7+1] = vy[ii+1]; n7++; } if (o_flags[kk] < 32) { cc += 1; } else if (cnt == 2) { cnt = 0; cc++; } ii += 2; } int[] clr_idx = null; float[] vvx = null; float[] vvy = null; float[] x_avg = new float[2]; float[] y_avg = new float[2]; float dist_0 = 0; float dist_1 = 0; float xxx = 0; float yyy = 0; float dx = 0; float dy = 0; int nn = 0; int pt = 0; int n_pt = 0; int s_idx = 0; int ns_idx = 0; byte[] tmp = null; byte[] cntr_color = null; int cntr_clr = Integer.MIN_VALUE; float[][] edge_points = new float[2][8]; boolean[] edge_point_a_corner = {false, false, false, false, false, false, false, false}; boolean[] edge_point_out = {false, false, false, false, false, false, false, false}; boolean this_crnr_out = false; int n_crnr_out = 0; //- fill corners for (int kk = 0; kk < cases.length; kk++) { switch(cases[kk]) { case 1: nn = n1; clr_idx = clr_idx1; vvx = vv1[0]; vvy = vv1[1]; xxx = xx; yyy = yy; pt = 0; n_pt = 7; s_idx = 0; ns_idx = 1; tmp = crnr_color[0]; this_crnr_out = crnr_out[0]; break; case 2: nn = n2; clr_idx = clr_idx2; vvx = vv2[0]; vvy = vv2[1]; xxx = xx + xd; yyy = yy; pt = 1; n_pt = 2; s_idx = 0; ns_idx = 1; tmp = crnr_color[1]; this_crnr_out = crnr_out[1]; break; case 4: nn = n4; clr_idx = clr_idx4; vvx = vv4[0]; vvy = vv4[1]; xxx = xx; yyy = yy + yd; pt = 5; n_pt = 6; s_idx = 1; ns_idx = 0; tmp = crnr_color[2]; this_crnr_out = crnr_out[2]; break; case 7: nn = n7; clr_idx = clr_idx7; vvx = vv7[0]; vvy = vv7[1]; xxx = xx + xd; yyy = yy + yd; pt = 3; n_pt = 4; s_idx = 0; ns_idx = 1; tmp = crnr_color[3]; this_crnr_out = crnr_out[3]; break; } if ( nn == 0 ) { edge_points[0][pt] = xxx; edge_points[1][pt] = yyy; edge_points[0][n_pt] = xxx; edge_points[1][n_pt] = yyy; cntr_color = tmp; edge_point_a_corner[pt] = true; edge_point_a_corner[n_pt] = true; edge_point_out[pt] = this_crnr_out; edge_point_out[n_pt] = this_crnr_out; if (this_crnr_out) n_crnr_out++; } else if ( nn == 1) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } else { int il = 0; int idx = 0; x_avg[0] = (vvx[idx] + vvx[idx+1])/2; y_avg[0] = (vvy[idx] + vvy[idx+1])/2; idx = idx + 2; x_avg[1] = (vvx[idx] + vvx[idx+1])/2; y_avg[1] = (vvy[idx] + vvy[idx+1])/2; dy = (y_avg[1] - (yyy)); dx = (x_avg[1] - (xxx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yyy)); dx = (x_avg[0] - (xxx)); dist_0 = dy*dy + dx*dx; boolean cornerFirst = false; if ( dist_1 > dist_0) cornerFirst = true; if (cornerFirst) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } for (il = 1; il < nn; il++) { idx = dir*il*2; int idx_last = idx - 2*dir; vvv1[0] = vvx[idx]; vvv1[1] = vvy[idx]; vvv2[0] = vvx[idx+dir]; vvv2[1] = vvy[idx+dir]; vvv1_last[0] = vvx[idx_last]; vvv1_last[1] = vvy[idx_last]; vvv2_last[0] = vvx[idx_last+dir]; vvv2_last[1] = vvy[idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vvv1, vvv2, vvv1_last, vvv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, clr_idx[il], color_length, grd_normals, n_idx, tri_normals); if (!cornerFirst && il == (nn-1)) { fillToNearCorner(xx, yy, xd, yd, idx, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if (cornerFirst && il == (nn-1)) { edge_points[0][pt] = vvx[idx+s_idx]; edge_points[1][pt] = vvy[idx+s_idx]; edge_points[0][n_pt] = vvx[idx+ns_idx]; edge_points[1][n_pt] = vvy[idx+ns_idx]; if(clr_idx[il] > cntr_clr) cntr_clr = clr_idx[il]; } } } } //- fill remainder with tris all sharing center point //---------------------------------------------------- if (n_crnr_out == 2) { //- don't fill center region return; } if (cntr_color == null) { //- All corners were closed off cntr_color = new byte[color_length]; for (int c=0; c<color_length; c++) { cntr_color[c] = color_bin[c][cntr_clr]; } } int tt = t_idx[0]; for (int kk = 0; kk < edge_points[0].length; kk++) { pt = kk; n_pt = kk+1; if (kk == (edge_points[0].length - 1)) { pt = 0; n_pt = 7; } if (edge_point_a_corner[pt] || edge_point_a_corner[n_pt]) { if(edge_point_out[pt] || edge_point_out[n_pt]) continue; } for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][pt]; tri[1][tt] = edge_points[1][pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][n_pt]; tri[1][tt] = edge_points[1][n_pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; //- center point for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = xx + xd*0.5f; tri[1][tt] = yy + yd*0.5f; //- center normal, interpolate from corners float[] nrm = {0f, 0f, 0f}; for (int ic=0; ic<2; ic++) { for (int ir=0; ir<2; ir++) { nrm[0] += 0.25*grd_normals[nc+ic][nr+ir][0]; nrm[1] += 0.25*grd_normals[nc+ic][nr+ir][1]; nrm[2] += 0.25*grd_normals[nc+ic][nr+ir][2]; } } //- renormalize normal float mag = (float) Math.sqrt(nrm[0]*nrm[0] + nrm[1]*nrm[1] + nrm[2]*nrm[2]); nrm[0] /= mag; nrm[1] /= mag; nrm[2] /= mag; tri_normals[n_idx[0]++] = nrm[0]; tri_normals[n_idx[0]++] = nrm[1]; tri_normals[n_idx[0]++] = nrm[2]; tt++; cnt_tri[0]++; } t_idx[0] = tt; } private static void fillToNearCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx = 0; float cy = 0; int cc = 0; int color_length = crnr_color[0].length; int cnt_tri = cnt[0]; int tt = t_idx[0]; switch(o_flag) { case 1: cc = 0; closed[0] = closed[0] | 1; if (crnr_out[cc]) return; cx = xx; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; break; case 4: cc = 2; closed[0] = closed[0] | 4; if (crnr_out[cc]) return; cx = xx; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; break; case 2: cc = 1; closed[0] = closed[0] | 2; if (crnr_out[cc]) return; cx = xx + xd; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; break; case 7: cc = 3; closed[0] = closed[0] | 8; if (crnr_out[cc]) return; cx = xx + xd; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx; tri[1][tt] = cy; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToOppCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx1 = 0; float cx2 = 0; float cx3 = 0; float cy1 = 0; float cy2 = 0; float cy3 = 0; int cc = 0; int[][] grd = new int[3][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 1: closed[0] = closed[0] | 14; if (crnr_out[1] || crnr_out[2] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; cx3 = xx; cy3 = yy + yd; cc = 3; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; grd[2][0] = 0; grd[2][1] = 1; break; case 2: closed[0] = closed[0] | 13; if (crnr_out[0] || crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cx3 = xx + xd; cy3 = yy + yd; cc = 2; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; grd[2][0] = 1; grd[2][1] = 1; break; case 4: closed[0] = closed[0] | 11; if (crnr_out[0] || crnr_out[1] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cx3 = xx + xd; cy3 = yy + yd; cc = 1; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; grd[2][0] = 1; grd[2][1] = 1; break; case 7: closed[0] = closed[0] | 7; if (crnr_out[0] || crnr_out[1] || crnr_out[2]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx; cy2 = yy; cx3 = xx; cy3 = yy + yd; cc = 0; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 0; grd[2][0] = 0; grd[2][1] = 1; break; } int cnt_tri = cnt[0]; int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } else { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx3; tri[1][tt] = cy3; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToSide(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { int cnt_tri = cnt[0]; int tt = t_idx[0]; float cx1 = 0; float cy1 = 0; float cx2 = 0; float cy2 = 0; int cc = 0; int[][] grd = new int[2][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 3: switch (flag) { case 1: closed[0] = closed[0] | 12; if(crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy + yd; cx2 = xx + xd; cy2 = yy + yd; cc = 3; grd[0][0] = 0; grd[0][1] = 1; grd[1][0] = 1; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 3; if(crnr_out[0] || crnr_out[1]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; break; } break; case 5: switch (flag) { case 1: closed[0] = closed[0] | 5; if(crnr_out[0] || crnr_out[2]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 10; if(crnr_out[1] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; cc = 3; break; } break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; int i = grd[0][0]; int j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; i = grd[0][0]; j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if ( dir > 0 ) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; i = grd[1][0]; j = grd[1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } } // end class
public static void contour( float g[], int nr, int nc, float[] values, float lowlimit, float highlimit, float base, boolean dash, float vx1[][], float vy1[][], float[][] vz1, int maxv1, int[] numv1, float vx2[][], float vy2[][], float[][] vz2, int maxv2, int[] numv2, float vx3[][], float vy3[][], float[][] vz3, int maxv3, int[] numv3, float vx4[][], float vy4[][], float[][] vz4, int maxv4, int[] numv4, byte[][] auxValues, byte[][] auxLevels1, byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap, boolean fill, float[][] tri, byte[][] tri_color, float[][][] grd_normals, float[][] tri_normals, byte[][] interval_colors, float[][][][] lbl_vv, byte[][][][] lbl_cc, float[][][] lbl_loc, double scale_ratio, double label_size, byte[] labelColor, Gridded3DSet spatial_set) throws VisADException { /* System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit + " highlimit = " + highlimit + " base = " + base); boolean any = false; boolean anymissing = false; boolean anynotmissing = false; */ //System.out.println("contour: swap = " + swap[0] + " " + swap[1] + " " + swap[2]); dash = (fill == true) ? false : dash; PlotDigits plot = new PlotDigits(); int ir, ic; int nrm, ncm; int numc, il; int lr, lc, lc2, lrr, lr2, lcc; float xd, yd ,xx, yy; float xdd, ydd; // float clow, chi; float gg; int maxsize = maxv1+maxv2; float[] vx = new float[maxsize]; float[] vy = new float[maxsize]; // WLH 21 April 2000 // int[] ipnt = new int[2*maxsize]; int[] ipnt = new int[nr*nc+4]; int nump, ip; int numv; /* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */ float[] myvals = null; if (values != null) { myvals = (float[]) values.clone(); java.util.Arrays.sort(myvals); } // flags for each level indicating dashed rendering boolean[] dashFlags = new boolean[myvals.length]; int low; int hi; int t; byte[][] auxLevels = null; int naux = (auxValues != null) ? auxValues.length : 0; byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { if (auxLevels1 == null || auxLevels1.length != naux || auxLevels2 == null || auxLevels2.length != naux || auxLevels3 == null || auxLevels3.length != naux) { throw new SetException("Contour2D.contour: " +"auxLevels length doesn't match"); } for (int i=0; i<naux; i++) { if (auxValues[i].length != g.length) { throw new SetException("Contour2D.contour: " +"auxValues lengths don't match"); } } auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; auxLevels = new byte[naux][maxsize]; } else { if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) { throw new SetException("Contour2D.contour: " +"auxValues null but auxLevels not null"); } } // initialize vertex counts numv1[0] = 0; numv2[0] = 0; numv3[0] = 0; numv4[0] = 0; if (values == null) return; // WLH 24 Aug 99 /* DRM: 1999-05-19 - Not needed since dash is a boolean // check for bad contour interval if (interval==0.0) { throw new DisplayException("Contour2D.contour: interval cannot be 0"); } if (!dash) { // draw negative contour lines as dashed lines interval = -interval; idash = 1; } else { idash = 0; } */ nrm = nr-1; ncm = nc-1; xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0 ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0 /**-TDR xd = xdd - 0.0001f; yd = ydd - 0.0001f; gap too big **/ xd = xdd - 0.00002f; yd = ydd - 0.00002f; /* * set up mark array * mark= 0 if avail for label center, * 2 if in label, and * 1 if not available and not in label * * lr and lc give label size in grid boxes * lrr and lcc give unavailable radius */ if (swap[0]) { lr = 1+(nr-2)/10; lc = 1+(nc-2)/50; } else { lr = 1+(nr-2)/50; lc = 1+(nc-2)/10; } lc2 = lc/2; lr2 = lr/2; lrr = 1+(nr-2)/8; lcc = 1+(nc-2)/8; // allocate mark array char[] mark = new char[nr * nc]; // initialize mark array to zeros for (int i=0; i<nr * nc; i++) mark[i] = 0; // set top and bottom rows to 1 float max_g = -Float.MAX_VALUE; float min_g = Float.MAX_VALUE; for (ic=0;ic<nc;ic++) { for (ir=0;ir<lr;ir++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (ic) * nr + (nr-ir-2) ] = 1; float val = g[(ic) * nr + (ir)]; if (val > max_g) max_g = val; if (val < min_g) min_g = val; } } // set left and right columns to 1 for (ir=0;ir<nr;ir++) { for (ic=0;ic<lc;ic++) { mark[ (ic) * nr + (ir) ] = 1; mark[ (nc-ic-2) * nr + (ir) ] = 1; } } numv = nump = 0; //- color fill arrays byte[][] color_bin = null; byte[][][] o_flags = null; short[][] n_lines = null; short[][] ctrLow = null; if (fill) { color_bin = interval_colors; o_flags = new byte[nrm][ncm][]; n_lines = new short[nrm][ncm]; ctrLow = new short[nrm][ncm]; } //- estimate contour difficutly int ctr_lo = 0; int ctr_hi = myvals.length-1; for (int k=0; k<myvals.length; k++) { if (min_g >= myvals[k]) ctr_lo = k; if (max_g >= myvals[k]) ctr_hi = k; } int switch_cnt = 0; if (myvals.length > 1) { float ctr_int = myvals[1] - myvals[0]; float[] last_diff = new float[(ctr_hi-ctr_lo)+1]; for (ir=2; ir<nrm-2; ir+=1) { for (int k=0; k<last_diff.length;k++) { last_diff[k] = g[ir] - myvals[ctr_lo+k]; for (ic=2; ic<ncm-2; ic+=1) { float diff = g[ic*nr + ir] - myvals[ctr_lo+k]; if ((diff*last_diff[k] < 0) && ((diff > 0.005*ctr_int) || (diff < -0.005*ctr_int)) ) { switch_cnt++; } last_diff[k] = diff; } } } } int contourDifficulty = Contour2D.EASY; if (switch_cnt > Contour2D.DIFFICULTY_THRESHOLD) contourDifficulty = Contour2D.HARD; ContourStripSet ctrSet = new ContourStripSet(nrm, myvals, swap, scale_ratio, label_size, nr, nc, spatial_set, contourDifficulty); // compute contours for (ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; // = ir for (ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; float gv, gn, gx; float tmp1, tmp2; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } // save index of first vertex in this grid box ipnt[nump++] = numv; yy = ydd*ic+0.0f; // = ic /* ga = ( g[ (ic) * nr + (ir) ] ); gb = ( g[ (ic) * nr + (ir+1) ] ); gc = ( g[ (ic+1) * nr + (ir) ] ); gd = ( g[ (ic+1) * nr + (ir+1) ] ); boolean miss = false; if (ga != ga || gb != gb || gc != gc || gd != gd) { miss = true; System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " + ga + " " + gb + " " + gc + " " + gd); } */ /* if (ga != ga || gb != gb || gc != gc || gd != gd) { if (!anymissing) { anymissing = true; System.out.println("missing"); } } else { if (!anynotmissing) { anynotmissing = true; System.out.println("notmissing"); } } */ // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; /* DRM move outside the loop byte[] auxa = null; byte[] auxb = null; byte[] auxc = null; byte[] auxd = null; if (naux > 0) { auxa = new byte[naux]; auxb = new byte[naux]; auxc = new byte[naux]; auxd = new byte[naux]; */ if (naux > 0) { for (int i=0; i<naux; i++) { auxa[i] = auxValues[i][(ic) * nr + (ir)]; auxb[i] = auxValues[i][(ic) * nr + (ir+1)]; auxc[i] = auxValues[i][(ic+1) * nr + (ir)]; auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)]; } } // find average, min, and max of 4 corner values gv = (ga+gb+gc+gd)/4.0f; // gn = MIN4(ga,gb,gc,gd); tmp1 = ( (ga) < (gb) ? (ga) : (gb) ); tmp2 = ( (gc) < (gd) ? (gc) : (gd) ); gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) ); // gx = MAX4(ga,gb,gc,gd); tmp1 = ( (ga) > (gb) ? (ga) : (gb) ); tmp2 = ( (gc) > (gd) ? (gc) : (gd) ); gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) ); /* remove for new signature, replace with code below // compute clow and chi, low and high contour values in the box tmp1 = (gn-base) / interval; clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )-1); while (clow<gn) { clow += interval; } tmp1 = (gx-base) / interval; chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) )+1); while (chi>gx) { chi -= interval; } // how many contour lines in the box: tmp1 = (chi-clow) / interval; numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) ); // gg is current contour line value gg = clow; */ low = 0; hi = myvals.length - 1; if (myvals[low] > gx || myvals[hi] < gn) // no contours { numc = 1; } else // some inside the box { for (int i = 0; i < myvals.length; i++) { if (i == 0 && myvals[i] >= gn) { low = i; } else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; } if (i == 0 && myvals[i] >= gx) { hi = i; } else if (myvals[i] >= gx && myvals[i-1] < gx) { hi = i; } } numc = hi - low + 1; } gg = myvals[low]; /* if (!any && numc > 0) { System.out.println("gn = " + gn + " gx = " + gx + " gv = " + gv); System.out.println("numc = " + numc + " clow = " + myvals[low] + " chi = " + myvals[hi]); any = true; } */ if (fill) { o_flags[ir][ic] = new byte[2*numc]; //- case flags n_lines[ir][ic] = 0; //- number of contour line segments ctrLow[ir][ic] = (short)hi; } for (il=0; il<numc; il++) { gg = myvals[low+il]; // WLH 21 April 2000 // if (numv+8 >= maxsize || nump+4 >= 2*maxsize) { if (numv+8 >= maxsize) { // allocate more space maxsize = 2 * maxsize; /* WLH 21 April 2000 int[] tt = ipnt; ipnt = new int[2 * maxsize]; System.arraycopy(tt, 0, ipnt, 0, nump); */ float[] tx = vx; float[] ty = vy; vx = new float[maxsize]; vy = new float[maxsize]; System.arraycopy(tx, 0, vx, 0, numv); System.arraycopy(ty, 0, vy, 0, numv); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels; auxLevels = new byte[naux][maxsize]; for (int i=0; i<naux; i++) { System.arraycopy(ta[i], 0, auxLevels[i], 0, numv); } ta = null; } } float gba, gca, gdb, gdc; int ii; // make sure gg is within contouring limits if (gg < gn) continue; if (gg > gx) break; if (gg < lowlimit) continue; if (gg > highlimit) break; // compute orientation of lines inside box ii = 0; if (gg > ga) ii = 1; if (gg > gb) ii += 2; if (gg > gc) ii += 4; if (gg > gd) ii += 8; if (ii > 7) ii = 15 - ii; if (ii <= 0) continue; if (fill) { if ((low+il) < ctrLow[ir][ic]) ctrLow[ir][ic] = (short)(low+il); } // DO LABEL HERE if (( mark[ (ic) * nr + (ir) ] )==0) { int kc, kr, mc, mr, jc, jr; float xk, yk, xm, ym, value; // Insert a label // BOX TO AVOID kc = ic-lc2-lcc; kr = ir-lr2-lrr; mc = kc+2*lcc+lc-1; mr = kr+2*lrr+lr-1; // OK here for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { if (( mark[ (jc) * nr + (jr) ] ) != 2) { mark[ (jc) * nr + (jr) ] = 1; } } } } } // BOX TO HOLD LABEL kc = ic-lc2; kr = ir-lr2; mc = kc+lc-1; mr = kr+lr-1; for (jc=kc;jc<=mc;jc++) { if (jc >= 0 && jc < nc) { for (jr=kr;jr<=mr;jr++) { if (jr >= 0 && jr < nr) { mark[ (jc) * nr + (jr) ] = 2; } } } } xk = xdd*kr+0.0f; yk = ydd*kc+0.0f; xm = xdd*(mr+1.0f)+0.0f; ym = ydd*(mc+1.0f)+0.0f; value = gg; if (numv4[0]+1000 >= maxv4) { // allocate more space maxv4 = 2 * (numv4[0]+1000); float[][] tx = new float[][] {vx4[0]}; float[][] ty = new float[][] {vy4[0]}; vx4[0] = new float[maxv4]; vy4[0] = new float[maxv4]; System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]); System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]); tx = null; ty = null; } if (numv3[0]+1000 >= maxv3) { // allocate more space maxv3 = 2 * (numv3[0]+1000); float[][] tx = new float[][] {vx3[0]}; float[][] ty = new float[][] {vy3[0]}; vx3[0] = new float[maxv3]; vy3[0] = new float[maxv3]; System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]); System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]); tx = null; ty = null; if (naux > 0) { byte[][] ta = auxLevels3; for (int i=0; i<naux; i++) { //byte[] taa = auxLevels3[i]; auxLevels3[i] = new byte[maxv3]; System.arraycopy(ta[i], 0, auxLevels3[i], 0, numv3[0]); } ta = null; } } plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap); System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts); System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts); if (naux > 0) { for (int i=0; i<naux; i++) { for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) { auxLevels3[i][j] = auxa[i]; } } } numv3[0] += plot.NumVerts; System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts); System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts); numv4[0] += plot.NumVerts; } switch (ii) { case 1: gba = gb-ga; gca = gc-ga; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratioca = (gg-ga)/gca; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) { vx[numv] = xx; } else { vx[numv] = xx+xd*(gg-ga)/gba; } vy[numv] = yy; numv++; if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) { vy[numv] = yy; } else { vy[numv] = yy+yd*(gg-ga)/gca; } vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] += 0.00001f; vy[numv-1] += 0.00001f; } break; case 2: gba = gb-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-2] -= 0.00001f; vy[numv-1] += 0.00001f; } break; case 3: gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 4: gca = gc-ga; gdc = gd-gc; if (naux > 0) { float ratioca = (gg-ga)/gca; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] += 0.00001f; vy[numv-2] -= 0.00001f; } break; case 5: gba = gb-ga; gdc = gd-gc; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } break; case 6: gba = gb-ga; gdc = gd-gc; gca = gc-ga; gdb = gd-gb; if (naux > 0) { float ratioba = (gg-ga)/gba; float ratiodc = (gg-gc)/gdc; float ratioca = (gg-ga)/gca; float ratiodb = (gg-gb)/gdb; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioba * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba; */ if ( (gg>gv) ^ (ga<gb) ) { t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; */ } else { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ? ((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) + ratioca * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) ); auxLevels[i][numv+2] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256))); /* MEM_WLH auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb; auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca; */ } t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+3] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-ga)/gba; vy[numv] = yy; numv++; // here's a brain teaser if ( (gg>gv) ^ (ga<gb) ) { // (XOR) if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)1 + (byte)32; n_lines[ir][ic]++; } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)7 + (byte)32; n_lines[ir][ic]++; } numv++; } else { if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)2 + (byte)32; n_lines[ir][ic]++; } if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-ga)/gca; vx[numv] = xx; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)4 + (byte)32; n_lines[ir][ic]++; } } if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; break; case 7: gdb = gd-gb; gdc = gd-gc; if (naux > 0) { float ratiodb = (gg-gb)/gdb; float ratiodc = (gg-gc)/gdc; for (int i=0; i<naux; i++) { t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ? ((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) + ratiodb * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ? ((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) + ratiodc * ((auxd[i] < 0) ? ((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) ); auxLevels[i][numv+1] = (byte) ( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) ); /* MEM_WLH auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb; auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc; */ } } if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001) vy[numv] = yy; else vy[numv] = yy+yd*(gg-gb)/gdb; vx[numv] = xx+xd; numv++; if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001) vx[numv] = xx; else vx[numv] = xx+xd*(gg-gc)/gdc; vy[numv] = yy+yd; numv++; if (fill) { o_flags[ir][ic][n_lines[ir][ic]] = (byte)ii; n_lines[ir][ic]++; } if (vx[numv-2]==vx[numv-1] || vy[numv-2]==vy[numv-1]) { vx[numv-1] -= 0.00001f; vy[numv-2] -= 0.00001f; } break; } // switch // If contour level is negative, make dashed line if (gg < base && dash) { /* DRM: 1999-05-19 */ // 2006-09-29 BMF -- Moved to ContourStrip.getDashedLineArray(...) // float vxa, vya, vxb, vyb; // vxa = vx[numv-2]; // vya = vy[numv-2]; // vxb = vx[numv-1]; // vyb = vy[numv-1]; // vx[numv-2] = (3.0f*vxa+vxb) * 0.25f; // vy[numv-2] = (3.0f*vya+vyb) * 0.25f; // vx[numv-1] = (vxa+3.0f*vxb) * 0.25f; // vy[numv-1] = (vya+3.0f*vyb) * 0.25f; dashFlags[low+il] = true; } /* if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) || (20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) { System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] + " ic, ir = " + ic + " " + ir); } */ if (ii == 6) { //- add last two pairs ctrSet.add(vx, vy, numv-4, numv-3, low+il, ic, ir); ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } else { ctrSet.add(vx, vy, numv-2, numv-1, low+il, ic, ir); } } // for il -- NOTE: gg incremented in for statement } // for ic } // for ir /**------------------- Color Fill -------------------------*/ if (fill) { fillGridBox(g, n_lines, vx, vy, xd, xdd, yd, ydd, nr, nrm, nc, ncm, ctrLow, tri, tri_color, o_flags, myvals, color_bin, grd_normals, tri_normals); // BMF 2006-10-04 do not return, ie. draw labels on filled contours // for now, just return because we don't need to do labels //return; } //---TDR, build Contour Strips float[][][] vvv = new float[2][][]; byte [][][] new_colors = new byte[2][][]; ctrSet.getLineColorArrays(vx, vy, auxLevels, labelColor, vvv, new_colors, lbl_vv, lbl_cc, lbl_loc, dashFlags, contourDifficulty); vx2[0] = vvv[1][0]; vy2[0] = vvv[1][1]; vz2[0] = vvv[1][2]; numv1[0] = vvv[0][0].length; numv2[0] = vvv[1][0].length; int n_lbls = lbl_vv[0].length; if (n_lbls > 0) { vx3[0] = lbl_vv[0][0][0]; vy3[0] = lbl_vv[0][0][1]; vz3[0] = lbl_vv[0][0][2]; vx4[0] = lbl_vv[1][0][0]; vy4[0] = lbl_vv[1][0][1]; vz4[0] = lbl_vv[1][0][2]; numv3[0] = lbl_vv[0][0][0].length; numv4[0] = lbl_vv[1][0][0].length; } if (auxLevels != null) { int clr_dim = auxValues.length; auxLevels1[0] = new_colors[0][0]; auxLevels1[1] = new_colors[0][1]; auxLevels1[2] = new_colors[0][2]; if (clr_dim == 4) auxLevels1[3] = new_colors[0][3]; auxLevels2[0] = new_colors[1][0]; auxLevels2[1] = new_colors[1][1]; auxLevels2[2] = new_colors[1][2]; if (clr_dim == 4) auxLevels2[3] = new_colors[1][3]; if (n_lbls > 0) { auxLevels3[0] = lbl_cc[0][0][0]; auxLevels3[1] = lbl_cc[0][0][1]; auxLevels3[2] = lbl_cc[0][0][2]; if (clr_dim == 4) auxLevels3[3] = lbl_cc[0][0][3]; } } if (contourDifficulty == Contour2D.EASY) { vx1[0] = vvv[0][0]; vy1[0] = vvv[0][1]; vz1[0] = vvv[0][2]; } else { int start = numv1[0]; float[][] vx_tmp = new float[1][]; float[][] vy_tmp = new float[1][]; float[][] vz_tmp = new float[1][]; byte[][] aux_tmp = new byte[4][]; float[] vx1_tmp = new float[numv]; float[] vy1_tmp = new float[numv]; float[] vz1_tmp = new float[numv]; byte[][] aux1_tmp = new byte[4][]; aux1_tmp[0] = new byte[numv]; aux1_tmp[1] = new byte[numv]; aux1_tmp[2] = new byte[numv]; int cnt = 0; for (int kk=0; kk<ctrSet.qSet.length;kk++) { ctrSet.qSet[kk].getArrays(vx, vy, auxLevels, vx_tmp, vy_tmp, vz_tmp, aux_tmp, spatial_set); int len = vx_tmp[0].length; System.arraycopy(vx_tmp[0], 0, vx1_tmp, cnt, len); System.arraycopy(vy_tmp[0], 0, vy1_tmp, cnt, len); System.arraycopy(vz_tmp[0], 0, vz1_tmp, cnt, len); System.arraycopy(aux_tmp[0], 0, aux1_tmp[0], cnt, len); System.arraycopy(aux_tmp[1], 0, aux1_tmp[1], cnt, len); System.arraycopy(aux_tmp[2], 0, aux1_tmp[2], cnt, len); cnt += len; } vx1[0] = new float[numv1[0]+cnt]; vy1[0] = new float[numv1[0]+cnt]; vz1[0] = new float[numv1[0]+cnt]; auxLevels1[0] = new byte[numv1[0]+cnt]; auxLevels1[1] = new byte[numv1[0]+cnt]; auxLevels1[2] = new byte[numv1[0]+cnt]; auxLevels1[3] = new byte[numv1[0]+cnt]; System.arraycopy(vvv[0][0], 0, vx1[0], 0, numv1[0]); System.arraycopy(vvv[0][1], 0, vy1[0], 0, numv1[0]); System.arraycopy(vvv[0][2], 0, vz1[0], 0, numv1[0]); System.arraycopy(new_colors[0][0], 0, auxLevels1[0], 0, numv1[0]); System.arraycopy(new_colors[0][1], 0, auxLevels1[1], 0, numv1[0]); System.arraycopy(new_colors[0][2], 0, auxLevels1[2], 0, numv1[0]); System.arraycopy(vx1_tmp, 0, vx1[0], start, cnt); System.arraycopy(vy1_tmp, 0, vy1[0], start, cnt); System.arraycopy(vz1_tmp, 0, vz1[0], start, cnt); System.arraycopy(aux1_tmp[0], 0, auxLevels1[0], start, cnt); System.arraycopy(aux1_tmp[1], 0, auxLevels1[1], start, cnt); System.arraycopy(aux1_tmp[2], 0, auxLevels1[2], start, cnt); numv1[0] += cnt; vx1_tmp = null; vy1_tmp = null; vz1_tmp = null; } } private static void fillGridBox(float[] g, short[][] n_lines, float[] vx, float[] vy, float xd, float xdd, float yd, float ydd, int nr, int nrm, int nc, int ncm, short[][] ctrLow, float[][] tri, byte[][] tri_color, byte[][][] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, float[][] tri_normals) { float xx, yy; int[] numv = new int[1]; numv[0] = 0; int n_tri = 0; for (int ir=0; ir<nrm; ir++) { for (int ic=0; ic<ncm; ic++) { if (n_lines[ir][ic] == 0) { n_tri +=2; } else { n_tri += (4 + (n_lines[ir][ic]-1)*2); } boolean any = false; if (o_flags[ir][ic] != null) { for (int k=0; k<o_flags[ir][ic].length; k++) { if (o_flags[ir][ic][k] > 32) any = true; } if (any) n_tri += 4; } } } tri[0] = new float[n_tri*3]; tri[1] = new float[n_tri*3]; for (int kk=0; kk<color_bin.length; kk++) { tri_color[kk] = new byte[n_tri*3]; } tri_normals[0] = new float[3*n_tri*3]; int[] t_idx = new int[1]; t_idx[0] = 0; int[] n_idx = new int[1]; n_idx[0] = 0; for (int ir=0; ir<nrm; ir++) { xx = xdd*ir+0.0f; for (int ic=0; ic<ncm; ic++) { float ga, gb, gc, gd; yy = ydd*ic+0.0f; // get 4 corner values, skip box if any are missing ga = ( g[ (ic) * nr + (ir) ] ); // test for missing if (ga != ga) continue; gb = ( g[ (ic) * nr + (ir+1) ] ); // test for missing if (gb != gb) continue; gc = ( g[ (ic+1) * nr + (ir) ] ); // test for missing if (gc != gc) continue; gd = ( g[ (ic+1) * nr + (ir+1) ] ); // test for missing if (gd != gd) continue; numv[0] += n_lines[ir][ic]*2; fillGridBox(new float[] {ga, gb, gc, gd}, n_lines[ir][ic], vx, vy, xx, yy, xd, yd, ic, ir, ctrLow[ir][ic], tri, t_idx, tri_color, numv[0], o_flags[ir][ic], values, color_bin, grd_normals, n_idx, tri_normals); } } } private static void fillGridBox(float[] corners, int numc, float[] vx, float[] vy, float xx, float yy, float xd, float yd, int nc, int nr, short ctrLow, float[][] tri, int[] t_idx, byte[][] tri_color, int numv, byte[] o_flags, float[] values, byte[][] color_bin, float[][][] grd_normals, int[] n_idx, float[][] tri_normals_a) { float[] tri_normals = tri_normals_a[0]; int n_tri = 4 + (numc-1)*2; int[] cnt_tri = new int[1]; cnt_tri[0] = 0; int il = 0; int color_length = color_bin.length; float[] vec = new float[2]; float[] vec_last = new float[2]; float[] vv1 = new float[2]; float[] vv2 = new float[2]; float[] vv1_last = new float[2]; float[] vv2_last = new float[2]; float[][] vv = new float[2][2]; float[][] vv_last = new float[2][2]; float[] vv3 = new float[2]; int dir = 1; int start = numv-2; int o_start = numc-1; int x_min_idx = 0; int o_idx = 0; byte o_flag = o_flags[o_idx]; int ydir = 1; boolean special = false; int[] closed = {0}; boolean up; boolean right; float dist_sqrd = 0; int v_idx = start + dir*il*2; //-- color level at corners //------------------------------ byte[][] crnr_color = new byte[4][color_length]; boolean[] crnr_out = new boolean[] {true, true, true, true}; boolean all_out = true; for (int tt = 0; tt < corners.length; tt++) { int cc = 0; int kk = 0; for (kk = 0; kk < (values.length - 1); kk++) { if ((corners[tt] >= values[kk]) && (corners[tt] < values[kk+1])) { cc = kk; all_out = false; crnr_out[tt] = false; } } for (int ii=0; ii<color_length; ii++) { crnr_color[tt][ii] = color_bin[ii][cc]; } } int tt = t_idx[0]; //- initialize triangle vertex counter dir = 1; start = numv - numc*2; o_start = 0; v_idx = start + dir*il*2; up = false; right = false; float[] x_avg = new float[2]; float[] y_avg = new float[2]; if (numc > 1) { //-- first/next ctr line midpoints int idx = v_idx; x_avg[0] = (vx[idx] + vx[idx+1])/2; y_avg[0] = (vy[idx] + vy[idx+1])/2; idx = v_idx + 2; x_avg[1] = (vx[idx] + vx[idx+1])/2; y_avg[1] = (vy[idx] + vy[idx+1])/2; if ((x_avg[1] - x_avg[0]) > 0) up = true; if ((y_avg[1] - y_avg[0]) > 0) right = true; } else if ( numc == 1 ) { //- default values for logic below x_avg[0] = 0f; y_avg[0] = 0f; x_avg[1] = 1f; y_avg[1] = 1f; } else if ( numc == 0 ) //- empty grid box (no contour lines) { if (all_out) return; n_tri = 2; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx + xd; tri[1][tt++] = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[0][ii]; } tri[0][tt] = xx; tri[1][tt++] = yy + yd; t_idx[0] = tt; cnt_tri[0]++; return; }//-- end no contour lines //--If any case 6 (saddle point), handle with special logic for (int iii=0; iii<o_flags.length; iii++) { if (o_flags[iii] > 32) { fillCaseSix(xx, yy, xd, yd, v_idx, dir, o_flags, ctrLow, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, color_bin, tri_color, color_length, grd_normals, n_idx, tri_normals, closed, cnt_tri); return; } } //-- start making triangles for color fill //--------------------------------------------- if (o_flag == 1 || o_flag == 4 || o_flag == 2 || o_flag == 7) { boolean opp = false; float dy = 0; float dx = 0; float dist_0 = 0; float dist_1 = 0; /** compare midpoints distances for first/next contour lines -------------------------------------------------*/ if (o_flag == 1) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 2) { dy = (y_avg[1] - (yy)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (o_flag == 4) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx)); dist_0 = dy*dy + dx*dx; } if (o_flag == 7) { dy = (y_avg[1] - (yy + yd)); dx = (x_avg[1] - (xx + xd)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yy + yd)); dx = (x_avg[0] - (xx + xd)); dist_0 = dy*dy + dx*dx; } if (dist_1 < dist_0) opp = true; if (opp) { fillToOppCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, o_flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (o_flags[o_idx] == 3) { int flag = 1; if (right) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (o_flags[o_idx] == 5) { int flag = 1; if (!up) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, o_flag, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } byte last_o = o_flags[o_idx]; int cc_start = (dir > 0) ? (ctrLow-1) : (ctrLow+(numc-1)); //- move to next contour line //-------------------------------- il++; for ( il = 1; il < numc; il++ ) { v_idx = start + dir*il*2; o_idx = o_start + dir*il; int v_idx_last = v_idx - 2*dir; int cc = cc_start + dir*il; if (o_flags[o_idx] != last_o) //- contour line case change { byte[] side_s = new byte[2]; byte[] last_side_s = new byte[2]; byte[] b_arg = new byte[2]; boolean flip; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx, dir, o_flags[o_idx], b_arg); side_s[0] = b_arg[0]; side_s[1] = b_arg[1]; getBoxSide(vx, vy, xx, xd, yy, yd, v_idx_last, dir, last_o, b_arg); last_side_s[0] = b_arg[0]; last_side_s[1] = b_arg[1]; if (side_s[0] == last_side_s[0]) { flip = false; } else if (side_s[0] == last_side_s[1]) { flip = true; } else if (side_s[1] == last_side_s[0]) { flip = true; } else if (side_s[1] == last_side_s[1]) { flip = false; } else { if(((side_s[0]+last_side_s[0]) & 1) == 1) { flip = false; } else { flip = true; } } if (!flip) { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv[0][0] = vx[v_idx]; vv[1][0] = vy[v_idx]; vv[0][1] = vx[v_idx+dir]; vv[1][1] = vy[v_idx+dir]; } else { vv1[0] = vx[v_idx+dir]; vv1[1] = vy[v_idx+dir]; vv2[0] = vx[v_idx]; vv2[1] = vy[v_idx]; vv[0][0] = vx[v_idx+dir]; vv[1][0] = vy[v_idx+dir]; vv[0][1] = vx[v_idx]; vv[1][1] = vy[v_idx]; } vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; vv_last[0][0] = vx[v_idx_last]; vv_last[1][0] = vy[v_idx_last]; vv_last[0][1] = vx[v_idx_last+dir]; vv_last[1][1] = vy[v_idx_last+dir]; //--- fill between contour lines fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); byte[] b_arg2 = new byte[2]; getBoxSide(vv[0], vv[1], xx, xd, yy, yd, 0, dir, o_flags[o_idx], b_arg); getBoxSide(vv_last[0], vv_last[1], xx, xd, yy, yd, 0, dir, last_o, b_arg2); for (int kk = 0; kk < 2; kk++) { //- close off corners float[] vvx = new float[2]; float[] vvy = new float[2]; byte side = 0; byte last_s = 0; side = b_arg[kk]; last_s = b_arg2[kk]; if ( side != last_s ) { if ((side == 0 && last_s == 3) || (side == 3 && last_s == 0)) { //- case 1 fillToNearCorner(xx, yy, xd, yd, 0, (byte)1, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 0 && last_s == 1) || (side == 1 && last_s == 0)) { //- case 2 fillToNearCorner(xx, yy, xd, yd, 0, (byte)2, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 3) || (side == 3 && last_s == 2)) { //- case 4 fillToNearCorner(xx, yy, xd, yd, 0, (byte)4, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 1) || (side == 1 && last_s == 2)) { //- case 7 fillToNearCorner(xx, yy, xd, yd, 0, (byte)7, cnt_tri, 1, new float[] {vv[0][kk], vv_last[0][kk]}, new float[] {vv[1][kk], vv_last[1][kk]}, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 2 && last_s == 0) || (side == 0 && last_s == 2)) { //- case 5 if (side == 0) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 1)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)5, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if ((side == 1 && last_s == 3) || (side == 3 && last_s == 1)) { //- case 3 if (side == 3) { vvx[0] = vv[0][kk]; vvy[0] = vv[1][kk]; vvx[1] = vv_last[0][kk]; vvy[1] = vv_last[1][kk]; } else { vvx[0] = vv_last[0][kk]; vvy[0] = vv_last[1][kk]; vvx[1] = vv[0][kk]; vvy[1] = vv[1][kk]; } int flag = -1; if (((closed[0] & 4)==0)&&((closed[0] & 8)==0)) flag = 1; fillToSide(xx, yy, xd, yd, 0, (byte)3, flag, cnt_tri, 1, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } } } else { vv1[0] = vx[v_idx]; vv1[1] = vy[v_idx]; vv2[0] = vx[v_idx+dir]; vv2[1] = vy[v_idx+dir]; vv1_last[0] = vx[v_idx_last]; vv1_last[1] = vy[v_idx_last]; vv2_last[0] = vx[v_idx_last+dir]; vv2_last[1] = vy[v_idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vv1, vv2, vv1_last, vv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, cc, color_length, grd_normals, n_idx, tri_normals); } last_o = o_flags[o_idx]; }//---- contour loop /*- last or first/last contour line ------------------------------------*/ int flag_set = 0; if ((last_o == 1)||(last_o == 2)||(last_o == 4)||(last_o == 7)) { if(last_o == 1) flag_set = (closed[0] & 1); if(last_o == 2) flag_set = (closed[0] & 2); if(last_o == 4) flag_set = (closed[0] & 4); if(last_o == 7) flag_set = (closed[0] & 8); if (flag_set > 0) { fillToOppCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { fillToNearCorner(xx, yy, xd, yd, v_idx, last_o, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } } else if (last_o == 3) { int flag = -1; if (closed[0]==3) flag = 1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else if (last_o == 5) { int flag = 1; if (closed[0]==5) flag = -1; fillToSide(xx, yy, xd, yd, v_idx, last_o, flag, cnt_tri, dir, vx, vy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } }//--- end fillGridBox private static void getBoxSide(float[] vx, float[] vy, float xx, float xd, float yy, float yd, int v_idx, int dir, byte o_flag, byte[] side) { /* if (vy[v_idx] == yy) side[0] = 0; // a-b if (vy[v_idx] == (yy + yd)) side[0] = 2; // c-d if (vx[v_idx] == xx) side[0] = 3; // a-c if (vx[v_idx] == (xx + xd)) side[0] = 1; // b-d */ for (int kk = 0; kk < 2; kk++) { int ii = v_idx + kk*dir; switch (o_flag) { case 1: side[kk] = 3; if (vy[ii] == yy) side[kk] = 0; break; case 2: side[kk] = 1; if (vy[ii] == yy) side[kk] = 0; break; case 4: side[kk] = 3; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 7: side[kk] = 1; if (vy[ii] == (yy + yd)) side[kk] = 2; break; case 3: side[kk] = 1; if (vx[ii] == xx) side[kk] = 3; break; case 5: side[kk] = 0; if (vy[ii] == (yy + yd)) side[kk] = 2; break; } } } private static void interpNormals(float vx, float vy, float xx, float yy, int nc, int nr, float xd, float yd, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int side = -1; float[] nn = new float[3]; if (vy == yy) side = 0; // a-b if (vy == (yy + yd)) side = 2; // c-d if (vx == xx) side = 3; // a-c if (vx == (xx + xd)) side = 1; // b-d float dx = vx - xx; float dy = vy - yy; switch (side) { case 0: nn[0] = ((grd_normals[nc][nr+1][0] - grd_normals[nc][nr][0])/xd)*dx + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc][nr+1][1] - grd_normals[nc][nr][1])/xd)*dx + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc][nr+1][2] - grd_normals[nc][nr][2])/xd)*dx + grd_normals[nc][nr][2]; break; case 3: nn[0] = ((grd_normals[nc+1][nr][0] - grd_normals[nc][nr][0])/yd)*dy + grd_normals[nc][nr][0]; nn[1] = ((grd_normals[nc+1][nr][1] - grd_normals[nc][nr][1])/yd)*dy + grd_normals[nc][nr][1]; nn[2] = ((grd_normals[nc+1][nr][2] - grd_normals[nc][nr][2])/yd)*dy + grd_normals[nc][nr][2]; break; case 1: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc][nr+1][0])/yd)*dy + grd_normals[nc][nr+1][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc][nr+1][1])/yd)*dy + grd_normals[nc][nr+1][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc][nr+1][2])/yd)*dy + grd_normals[nc][nr+1][2]; break; case 2: nn[0] = ((grd_normals[nc+1][nr+1][0] - grd_normals[nc+1][nr][0])/xd)*dx + grd_normals[nc+1][nr][0]; nn[1] = ((grd_normals[nc+1][nr+1][1] - grd_normals[nc+1][nr][1])/xd)*dx + grd_normals[nc+1][nr][1]; nn[2] = ((grd_normals[nc+1][nr+1][2] - grd_normals[nc+1][nr][2])/xd)*dx + grd_normals[nc+1][nr][2]; break; default: System.out.println("interpNormals, bad side: "+side); } //- re-normalize float mag = (float) Math.sqrt(nn[0]*nn[0] + nn[1]*nn[1] + nn[2]*nn[2]); nn[0] /= mag; nn[1] /= mag; nn[2] /= mag; tri_normals[n_idx[0]++] = nn[0]; tri_normals[n_idx[0]++] = nn[1]; tri_normals[n_idx[0]++] = nn[2]; } private static void fillToLast(float xx, float yy, float xd, float yd, int nc, int nr, float[] vv1, float[] vv2, float[] vv1_last, float[] vv2_last, float[][] tri, int[] cnt_tri, int[] t_idx, byte[][] tri_color, byte[][] color_bin, int cc, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals) { int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1[0]; tri[1][tt] = vv1[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri[0]++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv1_last[0]; tri[1][tt] = vv1_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2_last[0]; tri[1][tt] = vv2_last[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = color_bin[ii][cc]; } tri[0][tt] = vv2[0]; tri[1][tt] = vv2[1]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; t_idx[0] = tt; cnt_tri[0]++; } private static void fillCaseSix(float xx, float yy, float xd, float yd, int v_idx, int dir, byte[] o_flags, short ctrLow, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] color_bin, byte[][] tri_color, int color_length, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed, int[] cnt_tri) { int n1 = 0; int n2 = 0; int n4 = 0; int n7 = 0; for (int kk = 0; kk < o_flags.length; kk++) { if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) n1++; if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) n2++; if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) n4++; if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) n7++; } float[][] vv1 = new float[2][n1*2]; float[][] vv2 = new float[2][n2*2]; float[][] vv4 = new float[2][n4*2]; float[][] vv7 = new float[2][n7*2]; int[] clr_idx1 = new int[n1]; int[] clr_idx2 = new int[n2]; int[] clr_idx4 = new int[n4]; int[] clr_idx7 = new int[n7]; float[] vvv1 = new float[2]; float[] vvv2 = new float[2]; float[] vvv1_last = new float[2]; float[] vvv2_last = new float[2]; n1 = 0; n2 = 0; n4 = 0; n7 = 0; int ii = v_idx; int cc = ctrLow - 1; int cnt = 0; int[] cases = {1, 2, 7, 4}; //- corner cases, clockwise around box for (int kk = 0; kk < o_flags.length; kk++) { if (o_flags[kk] > 32) cnt++; if ((o_flags[kk] - 32)==1 || o_flags[kk]==1) { clr_idx1[n1] = cc; vv1[0][2*n1] = vx[ii]; vv1[1][2*n1] = vy[ii]; vv1[0][2*n1+1] = vx[ii+1]; vv1[1][2*n1+1] = vy[ii+1]; n1++; } else if ((o_flags[kk] - 32)==2 || o_flags[kk]==2) { clr_idx2[n2] = cc; vv2[0][2*n2] = vx[ii]; vv2[1][2*n2] = vy[ii]; vv2[0][2*n2+1] = vx[ii+1]; vv2[1][2*n2+1] = vy[ii+1]; n2++; } else if ((o_flags[kk] - 32)==4 || o_flags[kk]==4) { clr_idx4[n4] = cc; vv4[0][2*n4] = vx[ii]; vv4[1][2*n4] = vy[ii]; vv4[0][2*n4+1] = vx[ii+1]; vv4[1][2*n4+1] = vy[ii+1]; n4++; } else if ((o_flags[kk] - 32)==7 || o_flags[kk]==7) { clr_idx7[n7] = cc; vv7[0][2*n7] = vx[ii]; vv7[1][2*n7] = vy[ii]; vv7[0][2*n7+1] = vx[ii+1]; vv7[1][2*n7+1] = vy[ii+1]; n7++; } if (o_flags[kk] < 32) { cc += 1; } else if (cnt == 2) { cnt = 0; cc++; } ii += 2; } int[] clr_idx = null; float[] vvx = null; float[] vvy = null; float[] x_avg = new float[2]; float[] y_avg = new float[2]; float dist_0 = 0; float dist_1 = 0; float xxx = 0; float yyy = 0; float dx = 0; float dy = 0; int nn = 0; int pt = 0; int n_pt = 0; int s_idx = 0; int ns_idx = 0; byte[] tmp = null; byte[] cntr_color = null; int cntr_clr = Integer.MIN_VALUE; float[][] edge_points = new float[2][8]; boolean[] edge_point_a_corner = {false, false, false, false, false, false, false, false}; boolean[] edge_point_out = {false, false, false, false, false, false, false, false}; boolean this_crnr_out = false; int n_crnr_out = 0; //- fill corners for (int kk = 0; kk < cases.length; kk++) { switch(cases[kk]) { case 1: nn = n1; clr_idx = clr_idx1; vvx = vv1[0]; vvy = vv1[1]; xxx = xx; yyy = yy; pt = 0; n_pt = 7; s_idx = 0; ns_idx = 1; tmp = crnr_color[0]; this_crnr_out = crnr_out[0]; break; case 2: nn = n2; clr_idx = clr_idx2; vvx = vv2[0]; vvy = vv2[1]; xxx = xx + xd; yyy = yy; pt = 1; n_pt = 2; s_idx = 0; ns_idx = 1; tmp = crnr_color[1]; this_crnr_out = crnr_out[1]; break; case 4: nn = n4; clr_idx = clr_idx4; vvx = vv4[0]; vvy = vv4[1]; xxx = xx; yyy = yy + yd; pt = 5; n_pt = 6; s_idx = 1; ns_idx = 0; tmp = crnr_color[2]; this_crnr_out = crnr_out[2]; break; case 7: nn = n7; clr_idx = clr_idx7; vvx = vv7[0]; vvy = vv7[1]; xxx = xx + xd; yyy = yy + yd; pt = 3; n_pt = 4; s_idx = 0; ns_idx = 1; tmp = crnr_color[3]; this_crnr_out = crnr_out[3]; break; } if ( nn == 0 ) { edge_points[0][pt] = xxx; edge_points[1][pt] = yyy; edge_points[0][n_pt] = xxx; edge_points[1][n_pt] = yyy; cntr_color = tmp; edge_point_a_corner[pt] = true; edge_point_a_corner[n_pt] = true; edge_point_out[pt] = this_crnr_out; edge_point_out[n_pt] = this_crnr_out; if (this_crnr_out) n_crnr_out++; } else if ( nn == 1) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } else { int il = 0; int idx = 0; x_avg[0] = (vvx[idx] + vvx[idx+1])/2; y_avg[0] = (vvy[idx] + vvy[idx+1])/2; idx = idx + 2; x_avg[1] = (vvx[idx] + vvx[idx+1])/2; y_avg[1] = (vvy[idx] + vvy[idx+1])/2; dy = (y_avg[1] - (yyy)); dx = (x_avg[1] - (xxx)); dist_1 = dy*dy + dx*dx; dy = (y_avg[0] - (yyy)); dx = (x_avg[0] - (xxx)); dist_0 = dy*dy + dx*dx; boolean cornerFirst = false; if ( dist_1 > dist_0) cornerFirst = true; if (cornerFirst) { fillToNearCorner(xx, yy, xd, yd, 0, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } else { edge_points[0][pt] = vvx[s_idx]; edge_points[1][pt] = vvy[s_idx]; edge_points[0][n_pt] = vvx[ns_idx]; edge_points[1][n_pt] = vvy[ns_idx]; if(clr_idx[0] > cntr_clr) cntr_clr = clr_idx[0]; } for (il = 1; il < nn; il++) { idx = dir*il*2; int idx_last = idx - 2*dir; vvv1[0] = vvx[idx]; vvv1[1] = vvy[idx]; vvv2[0] = vvx[idx+dir]; vvv2[1] = vvy[idx+dir]; vvv1_last[0] = vvx[idx_last]; vvv1_last[1] = vvy[idx_last]; vvv2_last[0] = vvx[idx_last+dir]; vvv2_last[1] = vvy[idx_last+dir]; fillToLast(xx, yy, xd, yd, nc, nr, vvv1, vvv2, vvv1_last, vvv2_last, tri, cnt_tri, t_idx, tri_color, color_bin, clr_idx[il], color_length, grd_normals, n_idx, tri_normals); if (!cornerFirst && il == (nn-1)) { fillToNearCorner(xx, yy, xd, yd, idx, (byte)cases[kk], cnt_tri, dir, vvx, vvy, nc, nr, crnr_color, crnr_out, tri, t_idx, tri_color, grd_normals, n_idx, tri_normals, closed); } if (cornerFirst && il == (nn-1)) { edge_points[0][pt] = vvx[idx+s_idx]; edge_points[1][pt] = vvy[idx+s_idx]; edge_points[0][n_pt] = vvx[idx+ns_idx]; edge_points[1][n_pt] = vvy[idx+ns_idx]; if(clr_idx[il] > cntr_clr) cntr_clr = clr_idx[il]; } } } } //- fill remainder with tris all sharing center point //---------------------------------------------------- if (n_crnr_out == 2) { //- don't fill center region return; } if (cntr_color == null) { //- All corners were closed off cntr_color = new byte[color_length]; for (int c=0; c<color_length; c++) { cntr_color[c] = color_bin[c][cntr_clr]; } } int tt = t_idx[0]; for (int kk = 0; kk < edge_points[0].length; kk++) { pt = kk; n_pt = kk+1; if (kk == (edge_points[0].length - 1)) { pt = 0; n_pt = 7; } if (edge_point_a_corner[pt] || edge_point_a_corner[n_pt]) { if(edge_point_out[pt] || edge_point_out[n_pt]) continue; } for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][pt]; tri[1][tt] = edge_points[1][pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = edge_points[0][n_pt]; tri[1][tt] = edge_points[1][n_pt]; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; //- center point for (int c=0; c<color_length; c++) { tri_color[c][tt] = cntr_color[c]; } tri[0][tt] = xx + xd*0.5f; tri[1][tt] = yy + yd*0.5f; //- center normal, interpolate from corners float[] nrm = {0f, 0f, 0f}; for (int ic=0; ic<2; ic++) { for (int ir=0; ir<2; ir++) { nrm[0] += 0.25*grd_normals[nc+ic][nr+ir][0]; nrm[1] += 0.25*grd_normals[nc+ic][nr+ir][1]; nrm[2] += 0.25*grd_normals[nc+ic][nr+ir][2]; } } //- renormalize normal float mag = (float) Math.sqrt(nrm[0]*nrm[0] + nrm[1]*nrm[1] + nrm[2]*nrm[2]); nrm[0] /= mag; nrm[1] /= mag; nrm[2] /= mag; tri_normals[n_idx[0]++] = nrm[0]; tri_normals[n_idx[0]++] = nrm[1]; tri_normals[n_idx[0]++] = nrm[2]; tt++; cnt_tri[0]++; } t_idx[0] = tt; } private static void fillToNearCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx = 0; float cy = 0; int cc = 0; int color_length = crnr_color[0].length; int cnt_tri = cnt[0]; int tt = t_idx[0]; switch(o_flag) { case 1: cc = 0; closed[0] = closed[0] | 1; if (crnr_out[cc]) return; cx = xx; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr][2]; break; case 4: cc = 2; closed[0] = closed[0] | 4; if (crnr_out[cc]) return; cx = xx; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr][2]; break; case 2: cc = 1; closed[0] = closed[0] | 2; if (crnr_out[cc]) return; cx = xx + xd; cy = yy; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc][nr+1][2]; break; case 7: cc = 3; closed[0] = closed[0] | 8; if (crnr_out[cc]) return; cx = xx + xd; cy = yy + yd; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][0]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+1][nr+1][2]; break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx; tri[1][tt] = cy; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToOppCorner(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { float cx1 = 0; float cx2 = 0; float cx3 = 0; float cy1 = 0; float cy2 = 0; float cy3 = 0; int cc = 0; int[][] grd = new int[3][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 1: closed[0] = closed[0] | 14; if (crnr_out[1] || crnr_out[2] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; cx3 = xx; cy3 = yy + yd; cc = 3; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; grd[2][0] = 0; grd[2][1] = 1; break; case 2: closed[0] = closed[0] | 13; if (crnr_out[0] || crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cx3 = xx + xd; cy3 = yy + yd; cc = 2; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; grd[2][0] = 1; grd[2][1] = 1; break; case 4: closed[0] = closed[0] | 11; if (crnr_out[0] || crnr_out[1] || crnr_out[3]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cx3 = xx + xd; cy3 = yy + yd; cc = 1; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; grd[2][0] = 1; grd[2][1] = 1; break; case 7: closed[0] = closed[0] | 7; if (crnr_out[0] || crnr_out[1] || crnr_out[2]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx; cy2 = yy; cx3 = xx; cy3 = yy + yd; cc = 0; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 0; grd[2][0] = 0; grd[2][1] = 1; break; } int cnt_tri = cnt[0]; int tt = t_idx[0]; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[0][1]][nr+grd[0][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } else { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx3; tri[1][tt] = cy3; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[2][1]][nr+grd[2][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if (dir > 0) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][0]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][1]; tri_normals[n_idx[0]++] = grd_normals[nc+grd[1][1]][nr+grd[1][0]][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } private static void fillToSide(float xx, float yy, float xd, float yd, int v_idx, byte o_flag, int flag, int[] cnt, int dir, float[] vx, float[] vy, int nc, int nr, byte[][] crnr_color, boolean[] crnr_out, float[][] tri, int[] t_idx, byte[][] tri_color, float[][][] grd_normals, int[] n_idx, float[] tri_normals, int[] closed) { int cnt_tri = cnt[0]; int tt = t_idx[0]; float cx1 = 0; float cy1 = 0; float cx2 = 0; float cy2 = 0; int cc = 0; int[][] grd = new int[2][2]; int color_length = crnr_color[0].length; switch (o_flag) { case 3: switch (flag) { case 1: closed[0] = closed[0] | 12; if(crnr_out[2] || crnr_out[3]) return; cx1 = xx; cy1 = yy + yd; cx2 = xx + xd; cy2 = yy + yd; cc = 3; grd[0][0] = 0; grd[0][1] = 1; grd[1][0] = 1; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 3; if(crnr_out[0] || crnr_out[1]) return; cx1 = xx; cy1 = yy; cx2 = xx + xd; cy2 = yy; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 0; break; } break; case 5: switch (flag) { case 1: closed[0] = closed[0] | 5; if(crnr_out[0] || crnr_out[2]) return; cx1 = xx; cy1 = yy; cx2 = xx; cy2 = yy + yd; cc = 0; grd[0][0] = 0; grd[0][1] = 0; grd[1][0] = 0; grd[1][1] = 1; break; case -1: closed[0] = closed[0] | 10; if(crnr_out[1] || crnr_out[3]) return; cx1 = xx + xd; cy1 = yy; cx2 = xx + xd; cy2 = yy + yd; grd[0][0] = 1; grd[0][1] = 0; grd[1][0] = 1; grd[1][1] = 1; cc = 3; break; } break; } for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; int i = grd[0][0]; int j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; cnt_tri++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx1; tri[1][tt] = cy1; i = grd[0][0]; j = grd[0][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } if ( dir > 0 ) { tri[0][tt] = vx[v_idx+dir]; tri[1][tt] = vy[v_idx+dir]; } else { tri[0][tt] = vx[v_idx]; tri[1][tt] = vy[v_idx]; } t_idx[0] = tt; interpNormals(tri[0][tt], tri[1][tt], xx, yy, nc, nr, xd, yd, grd_normals, n_idx, tri_normals); tt++; for (int ii=0; ii<color_length; ii++) { tri_color[ii][tt] = crnr_color[cc][ii]; } tri[0][tt] = cx2; tri[1][tt] = cy2; i = grd[1][0]; j = grd[1][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][0]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][1]; tri_normals[n_idx[0]++] = grd_normals[nc+j][nr+i][2]; tt++; cnt_tri++; cnt[0] = cnt_tri; t_idx[0] = tt; } } // end class
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugPreferencePage.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugPreferencePage.java index 00d273eb6..bc9398553 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugPreferencePage.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugPreferencePage.java @@ -1,263 +1,263 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui; import org.eclipse.core.runtime.Preferences; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferenceLinkArea; import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; import com.ibm.icu.text.MessageFormat; /** * Preference page for debug preferences that apply specifically to * Java Debugging. */ public class JavaDebugPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IPropertyChangeListener { /** * This class exists to provide visibility to the * <code>refreshValidState</code> method and to perform more intelligent * clearing of the error message. */ protected class JavaDebugIntegerFieldEditor extends IntegerFieldEditor { public JavaDebugIntegerFieldEditor(String name, String labelText, Composite parent) { super(name, labelText, parent); } protected void refreshValidState() { super.refreshValidState(); } protected void clearErrorMessage() { if (canClearErrorMessage()) { super.clearErrorMessage(); } } } // Suspend preference widgets private Button fSuspendButton; private Button fSuspendOnCompilationErrors; private Button fSuspendDuringEvaluations; private Button fOpenInspector; private Button fPromptUnableToInstallBreakpoint; private Combo fSuspendVMorThread; // Hot code replace preference widgets private Button fAlertHCRButton; private Button fAlertHCRNotSupportedButton; private Button fAlertObsoleteButton; private Button fPerformHCRWithCompilationErrors; // Timeout preference widgets private JavaDebugIntegerFieldEditor fTimeoutText; private JavaDebugIntegerFieldEditor fConnectionTimeoutText; public JavaDebugPreferencePage() { super(); setPreferenceStore(JDIDebugUIPlugin.getDefault().getPreferenceStore()); setDescription(DebugUIMessages.JavaDebugPreferencePage_description); } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite) */ protected Control createContents(Composite parent) { //The main composite Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 1, 1, 0, 0, GridData.FILL); new PreferenceLinkArea(composite, SWT.NONE, "org.eclipse.debug.ui.DebugPreferencePage", DebugUIMessages.JavaDebugPreferencePage_0, //$NON-NLS-1$ (IWorkbenchPreferenceContainer) getContainer(),null); Group group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Suspend_Execution_1, 2, 1, GridData.FILL_HORIZONTAL); fSuspendButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend__execution_on_uncaught_exceptions_1, null, false, 2); fSuspendOnCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend_execution_on_co_mpilation_errors_1, null, false, 2); fSuspendDuringEvaluations = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_14, null, false, 2); fOpenInspector = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_20, null, false, 2); SWTFactory.createLabel(group, DebugUIMessages.JavaDebugPreferencePage_21, 1); fSuspendVMorThread = new Combo(group, SWT.BORDER|SWT.READ_ONLY); fSuspendVMorThread.setItems(new String[]{DebugUIMessages.JavaDebugPreferencePage_22, DebugUIMessages.JavaDebugPreferencePage_23}); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Hot_Code_Replace_2, 1, 1, GridData.FILL_HORIZONTAL); fAlertHCRButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_fails_1, null, false, 1); fAlertHCRNotSupportedButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_is_not_supported_1, null, false, 1); fAlertObsoleteButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_obsolete_methods_remain_1, null, false, 1); fPerformHCRWithCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Replace_classfiles_containing_compilation_errors_1, null, false, 1); - fPromptUnableToInstallBreakpoint = SWTFactory.createCheckButton(composite, DebugUIMessages.JavaDebugPreferencePage_14, null, false, 1); + fPromptUnableToInstallBreakpoint = SWTFactory.createCheckButton(composite, DebugUIMessages.JavaDebugPreferencePage_19, null, false, 1); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Communication_1, 1, 1, GridData.FILL_HORIZONTAL); Composite space = SWTFactory.createComposite(group, group.getFont(), 1, 1, GridData.FILL_HORIZONTAL); int minValue; Preferences coreStore= JDIDebugModel.getPreferences(); Preferences runtimeStore= JavaRuntime.getPreferences(); fTimeoutText = new JavaDebugIntegerFieldEditor(JDIDebugModel.PREF_REQUEST_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage_Debugger__timeout__2, space); fTimeoutText.setPage(this); fTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= coreStore.getDefaultInt(JDIDebugModel.PREF_REQUEST_TIMEOUT); fTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fTimeoutText.load(); fConnectionTimeoutText = new JavaDebugIntegerFieldEditor(JavaRuntime.PREF_CONNECT_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage__Launch_timeout__ms___1, space); fConnectionTimeoutText.setPage(this); fConnectionTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= runtimeStore.getDefaultInt(JavaRuntime.PREF_CONNECT_TIMEOUT); fConnectionTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fConnectionTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fConnectionTimeoutText.load(); setValues(); fTimeoutText.setPropertyChangeListener(this); fConnectionTimeoutText.setPropertyChangeListener(this); applyDialogFont(composite); PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaDebugHelpContextIds.JAVA_DEBUG_PREFERENCE_PAGE); return composite; } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) {} /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store = getPreferenceStore(); Preferences coreStore = JDIDebugModel.getPreferences(); Preferences runtimeStore = JavaRuntime.getPreferences(); store.setValue(IJDIPreferencesConstants.PREF_SUSPEND_ON_UNCAUGHT_EXCEPTIONS, fSuspendButton.getSelection()); store.setValue(IJDIPreferencesConstants.PREF_SUSPEND_ON_COMPILATION_ERRORS, fSuspendOnCompilationErrors.getSelection()); coreStore.setValue(JDIDebugModel.PREF_SUSPEND_FOR_BREAKPOINTS_DURING_EVALUATION, fSuspendDuringEvaluations.getSelection()); int selectionIndex = fSuspendVMorThread.getSelectionIndex(); int policy = IJavaBreakpoint.SUSPEND_THREAD; if (selectionIndex > 0) { policy = IJavaBreakpoint.SUSPEND_VM; } coreStore.setValue(JDIDebugPlugin.PREF_DEFAULT_BREAKPOINT_SUSPEND_POLICY, policy); store.setValue(IJDIPreferencesConstants.PREF_ALERT_HCR_FAILED, fAlertHCRButton.getSelection()); store.setValue(IJDIPreferencesConstants.PREF_ALERT_HCR_NOT_SUPPORTED, fAlertHCRNotSupportedButton.getSelection()); store.setValue(IJDIPreferencesConstants.PREF_ALERT_OBSOLETE_METHODS, fAlertObsoleteButton.getSelection()); coreStore.setValue(JDIDebugModel.PREF_HCR_WITH_COMPILATION_ERRORS, fPerformHCRWithCompilationErrors.getSelection()); coreStore.setValue(JDIDebugModel.PREF_REQUEST_TIMEOUT, fTimeoutText.getIntValue()); runtimeStore.setValue(JavaRuntime.PREF_CONNECT_TIMEOUT, fConnectionTimeoutText.getIntValue()); store.setValue(IJDIPreferencesConstants.PREF_ALERT_UNABLE_TO_INSTALL_BREAKPOINT, fPromptUnableToInstallBreakpoint.getSelection()); store.setValue(IJDIPreferencesConstants.PREF_OPEN_INSPECT_POPUP_ON_EXCEPTION, fOpenInspector.getSelection()); JDIDebugModel.savePreferences(); JavaRuntime.savePreferences(); return true; } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store = getPreferenceStore(); Preferences coreStore= JDIDebugModel.getPreferences(); Preferences runtimeStore= JavaRuntime.getPreferences(); fSuspendButton.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_SUSPEND_ON_UNCAUGHT_EXCEPTIONS)); fSuspendOnCompilationErrors.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_SUSPEND_ON_COMPILATION_ERRORS)); fSuspendDuringEvaluations.setSelection(coreStore.getDefaultBoolean(JDIDebugModel.PREF_SUSPEND_FOR_BREAKPOINTS_DURING_EVALUATION)); int value = coreStore.getDefaultInt(JDIDebugPlugin.PREF_DEFAULT_BREAKPOINT_SUSPEND_POLICY); fSuspendVMorThread.select((value == IJavaBreakpoint.SUSPEND_THREAD) ? 0 : 1); fAlertHCRButton.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_ALERT_HCR_FAILED)); fAlertHCRNotSupportedButton.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_ALERT_HCR_NOT_SUPPORTED)); fAlertObsoleteButton.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_ALERT_OBSOLETE_METHODS)); fPerformHCRWithCompilationErrors.setSelection(coreStore.getDefaultBoolean(JDIDebugModel.PREF_HCR_WITH_COMPILATION_ERRORS)); fTimeoutText.setStringValue(new Integer(coreStore.getDefaultInt(JDIDebugModel.PREF_REQUEST_TIMEOUT)).toString()); fConnectionTimeoutText.setStringValue(new Integer(runtimeStore.getDefaultInt(JavaRuntime.PREF_CONNECT_TIMEOUT)).toString()); fPromptUnableToInstallBreakpoint.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_ALERT_UNABLE_TO_INSTALL_BREAKPOINT)); fOpenInspector.setSelection(store.getDefaultBoolean(IJDIPreferencesConstants.PREF_OPEN_INSPECT_POPUP_ON_EXCEPTION)); super.performDefaults(); } /** * Set the values of the component widgets based on the * values in the preference store */ private void setValues() { IPreferenceStore store = getPreferenceStore(); Preferences coreStore = JDIDebugModel.getPreferences(); Preferences runtimeStore = JavaRuntime.getPreferences(); fSuspendButton.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_SUSPEND_ON_UNCAUGHT_EXCEPTIONS)); fSuspendOnCompilationErrors.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_SUSPEND_ON_COMPILATION_ERRORS)); fSuspendDuringEvaluations.setSelection(coreStore.getBoolean(JDIDebugModel.PREF_SUSPEND_FOR_BREAKPOINTS_DURING_EVALUATION)); int value = coreStore.getInt(JDIDebugPlugin.PREF_DEFAULT_BREAKPOINT_SUSPEND_POLICY); fSuspendVMorThread.select((value == IJavaBreakpoint.SUSPEND_THREAD ? 0 : 1)); fAlertHCRButton.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_ALERT_HCR_FAILED)); fAlertHCRNotSupportedButton.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_ALERT_HCR_NOT_SUPPORTED)); fAlertObsoleteButton.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_ALERT_OBSOLETE_METHODS)); fPerformHCRWithCompilationErrors.setSelection(coreStore.getBoolean(JDIDebugModel.PREF_HCR_WITH_COMPILATION_ERRORS)); fTimeoutText.setStringValue(new Integer(coreStore.getInt(JDIDebugModel.PREF_REQUEST_TIMEOUT)).toString()); fConnectionTimeoutText.setStringValue(new Integer(runtimeStore.getInt(JavaRuntime.PREF_CONNECT_TIMEOUT)).toString()); fPromptUnableToInstallBreakpoint.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_ALERT_UNABLE_TO_INSTALL_BREAKPOINT)); fOpenInspector.setSelection(store.getBoolean(IJDIPreferencesConstants.PREF_OPEN_INSPECT_POPUP_ON_EXCEPTION)); } /* (non-Javadoc) * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(FieldEditor.IS_VALID)) { boolean newValue = ((Boolean) event.getNewValue()).booleanValue(); // If the new value is true then we must check all field editors. // If it is false, then the page is invalid in any case. if (newValue) { if (fTimeoutText != null && event.getSource() != fTimeoutText) { fTimeoutText.refreshValidState(); } if (fConnectionTimeoutText != null && event.getSource() != fConnectionTimeoutText) { fConnectionTimeoutText.refreshValidState(); } } setValid(fTimeoutText.isValid() && fConnectionTimeoutText.isValid()); getContainer().updateButtons(); updateApplyButton(); } } /** * if the error message can be cleared or not * @return true if the error message can be cleared, false otherwise */ protected boolean canClearErrorMessage() { if (fTimeoutText.isValid() && fConnectionTimeoutText.isValid()) { return true; } return false; } }
true
true
protected Control createContents(Composite parent) { //The main composite Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 1, 1, 0, 0, GridData.FILL); new PreferenceLinkArea(composite, SWT.NONE, "org.eclipse.debug.ui.DebugPreferencePage", DebugUIMessages.JavaDebugPreferencePage_0, //$NON-NLS-1$ (IWorkbenchPreferenceContainer) getContainer(),null); Group group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Suspend_Execution_1, 2, 1, GridData.FILL_HORIZONTAL); fSuspendButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend__execution_on_uncaught_exceptions_1, null, false, 2); fSuspendOnCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend_execution_on_co_mpilation_errors_1, null, false, 2); fSuspendDuringEvaluations = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_14, null, false, 2); fOpenInspector = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_20, null, false, 2); SWTFactory.createLabel(group, DebugUIMessages.JavaDebugPreferencePage_21, 1); fSuspendVMorThread = new Combo(group, SWT.BORDER|SWT.READ_ONLY); fSuspendVMorThread.setItems(new String[]{DebugUIMessages.JavaDebugPreferencePage_22, DebugUIMessages.JavaDebugPreferencePage_23}); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Hot_Code_Replace_2, 1, 1, GridData.FILL_HORIZONTAL); fAlertHCRButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_fails_1, null, false, 1); fAlertHCRNotSupportedButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_is_not_supported_1, null, false, 1); fAlertObsoleteButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_obsolete_methods_remain_1, null, false, 1); fPerformHCRWithCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Replace_classfiles_containing_compilation_errors_1, null, false, 1); fPromptUnableToInstallBreakpoint = SWTFactory.createCheckButton(composite, DebugUIMessages.JavaDebugPreferencePage_14, null, false, 1); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Communication_1, 1, 1, GridData.FILL_HORIZONTAL); Composite space = SWTFactory.createComposite(group, group.getFont(), 1, 1, GridData.FILL_HORIZONTAL); int minValue; Preferences coreStore= JDIDebugModel.getPreferences(); Preferences runtimeStore= JavaRuntime.getPreferences(); fTimeoutText = new JavaDebugIntegerFieldEditor(JDIDebugModel.PREF_REQUEST_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage_Debugger__timeout__2, space); fTimeoutText.setPage(this); fTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= coreStore.getDefaultInt(JDIDebugModel.PREF_REQUEST_TIMEOUT); fTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fTimeoutText.load(); fConnectionTimeoutText = new JavaDebugIntegerFieldEditor(JavaRuntime.PREF_CONNECT_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage__Launch_timeout__ms___1, space); fConnectionTimeoutText.setPage(this); fConnectionTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= runtimeStore.getDefaultInt(JavaRuntime.PREF_CONNECT_TIMEOUT); fConnectionTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fConnectionTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fConnectionTimeoutText.load(); setValues(); fTimeoutText.setPropertyChangeListener(this); fConnectionTimeoutText.setPropertyChangeListener(this); applyDialogFont(composite); PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaDebugHelpContextIds.JAVA_DEBUG_PREFERENCE_PAGE); return composite; }
protected Control createContents(Composite parent) { //The main composite Composite composite = SWTFactory.createComposite(parent, parent.getFont(), 1, 1, 0, 0, GridData.FILL); new PreferenceLinkArea(composite, SWT.NONE, "org.eclipse.debug.ui.DebugPreferencePage", DebugUIMessages.JavaDebugPreferencePage_0, //$NON-NLS-1$ (IWorkbenchPreferenceContainer) getContainer(),null); Group group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Suspend_Execution_1, 2, 1, GridData.FILL_HORIZONTAL); fSuspendButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend__execution_on_uncaught_exceptions_1, null, false, 2); fSuspendOnCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Suspend_execution_on_co_mpilation_errors_1, null, false, 2); fSuspendDuringEvaluations = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_14, null, false, 2); fOpenInspector = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_20, null, false, 2); SWTFactory.createLabel(group, DebugUIMessages.JavaDebugPreferencePage_21, 1); fSuspendVMorThread = new Combo(group, SWT.BORDER|SWT.READ_ONLY); fSuspendVMorThread.setItems(new String[]{DebugUIMessages.JavaDebugPreferencePage_22, DebugUIMessages.JavaDebugPreferencePage_23}); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Hot_Code_Replace_2, 1, 1, GridData.FILL_HORIZONTAL); fAlertHCRButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_fails_1, null, false, 1); fAlertHCRNotSupportedButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_hot_code_replace_is_not_supported_1, null, false, 1); fAlertObsoleteButton = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Alert_me_when_obsolete_methods_remain_1, null, false, 1); fPerformHCRWithCompilationErrors = SWTFactory.createCheckButton(group, DebugUIMessages.JavaDebugPreferencePage_Replace_classfiles_containing_compilation_errors_1, null, false, 1); fPromptUnableToInstallBreakpoint = SWTFactory.createCheckButton(composite, DebugUIMessages.JavaDebugPreferencePage_19, null, false, 1); group = SWTFactory.createGroup(composite, DebugUIMessages.JavaDebugPreferencePage_Communication_1, 1, 1, GridData.FILL_HORIZONTAL); Composite space = SWTFactory.createComposite(group, group.getFont(), 1, 1, GridData.FILL_HORIZONTAL); int minValue; Preferences coreStore= JDIDebugModel.getPreferences(); Preferences runtimeStore= JavaRuntime.getPreferences(); fTimeoutText = new JavaDebugIntegerFieldEditor(JDIDebugModel.PREF_REQUEST_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage_Debugger__timeout__2, space); fTimeoutText.setPage(this); fTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= coreStore.getDefaultInt(JDIDebugModel.PREF_REQUEST_TIMEOUT); fTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fTimeoutText.load(); fConnectionTimeoutText = new JavaDebugIntegerFieldEditor(JavaRuntime.PREF_CONNECT_TIMEOUT, DebugUIMessages.JavaDebugPreferencePage__Launch_timeout__ms___1, space); fConnectionTimeoutText.setPage(this); fConnectionTimeoutText.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); minValue= runtimeStore.getDefaultInt(JavaRuntime.PREF_CONNECT_TIMEOUT); fConnectionTimeoutText.setValidRange(minValue, Integer.MAX_VALUE); fConnectionTimeoutText.setErrorMessage(MessageFormat.format(DebugUIMessages.JavaDebugPreferencePage_Value_must_be_a_valid_integer_greater_than__0__ms_1, new Object[] {new Integer(minValue)})); fConnectionTimeoutText.load(); setValues(); fTimeoutText.setPropertyChangeListener(this); fConnectionTimeoutText.setPropertyChangeListener(this); applyDialogFont(composite); PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IJavaDebugHelpContextIds.JAVA_DEBUG_PREFERENCE_PAGE); return composite; }
diff --git a/src/org/linphone/jlinphone/gui/LinphoneScreen.java b/src/org/linphone/jlinphone/gui/LinphoneScreen.java index f51adea..9eb000a 100755 --- a/src/org/linphone/jlinphone/gui/LinphoneScreen.java +++ b/src/org/linphone/jlinphone/gui/LinphoneScreen.java @@ -1,395 +1,395 @@ /* LinphoneScreen.java Copyright (C) 2010 Belledonne Communications, Grenoble, France This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.linphone.jlinphone.gui; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.Timer; import java.util.TimerTask; import javax.microedition.media.Manager; import javax.microedition.media.Player; import javax.microedition.media.control.RecordControl; import org.linphone.bb.NetworkManager; import org.linphone.bb.LogHandler; import org.linphone.core.CallDirection; import org.linphone.core.LinphoneAddress; import org.linphone.core.LinphoneCall; import org.linphone.core.LinphoneCallLog; import org.linphone.core.LinphoneCore; import org.linphone.core.LinphoneCoreException; import org.linphone.core.LinphoneCoreFactory; import org.linphone.core.LinphoneCoreListener; import org.linphone.core.LinphoneProxyConfig; import org.linphone.core.LinphoneCall.State; import org.linphone.core.LinphoneCore.GlobalState; import org.linphone.core.LinphoneCore.RegistrationState; import org.linphone.jortp.JOrtpFactory; import org.linphone.jortp.Logger; import net.rim.device.api.applicationcontrol.ApplicationPermissions; import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.system.Audio; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.ControlledAccessException; import net.rim.device.api.system.EventLogger; import net.rim.device.api.system.KeyListener; import net.rim.device.api.system.RadioInfo; import net.rim.device.api.system.WLANInfo; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Font; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.SeparatorField; import net.rim.device.api.ui.component.Status; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.ui.container.VerticalFieldManager; import net.rim.device.api.ui.decor.BackgroundFactory; public class LinphoneScreen extends MainScreen implements LinphoneCoreListener , LinphoneResource { private LabelField mStatus; private static Logger sLogger=JOrtpFactory.instance().createLogger("Linphone"); private LinphoneCore mCore; private Timer mTimer; private SettingsScreen mSettingsScreen ; private ListField mCallLogs; private DialerField mDialer; private TabField mTabField; private final int HISTORY_TAB_INDEX=0; private final int DIALER_TAB_INDEX=1; private final int SETTINGS_TAB_INDEX=2; static int[] sPermissions = { ApplicationPermissions.PERMISSION_INTERNET ,ApplicationPermissions.PERMISSION_MEDIA ,ApplicationPermissions.PERMISSION_ORGANIZER_DATA ,ApplicationPermissions.PERMISSION_RECORDING ,ApplicationPermissions.PERMISSION_WIFI ,ApplicationPermissions.PERMISSION_FILE_API ,ApplicationPermissions.PERMISSION_SECURITY_DATA}; private static ResourceBundle mRes = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME); LinphoneScreen() { LinphoneCoreFactory.setFactoryClassName("org.linphone.jlinphone.core.LinphoneFactoryImpl"); LinphoneCoreFactory.instance().setLogHandler(new LogHandler()); LinphoneCoreFactory.instance().setDebugMode(true);//debug mode until configuration is loaded sLogger.warn(" Starting version "+ApplicationDescriptor.currentApplicationDescriptor().getVersion()); ApplicationPermissions lCurentPermission = ApplicationPermissionsManager.getInstance().getApplicationPermissions(); boolean lPermissionRequestNeeded = false; for (int i=0;i<sPermissions.length;i++) { if (!lCurentPermission.containsPermissionKey(sPermissions[i]) || lCurentPermission.getPermission(sPermissions[i]) != ApplicationPermissions.VALUE_ALLOW) { lPermissionRequestNeeded=true; } } if (lPermissionRequestNeeded) { ApplicationPermissions lLinphonePermission = new ApplicationPermissions(); for (int i=0;i<sPermissions.length;i++) { lLinphonePermission.addPermission(sPermissions[i]); } if (!ApplicationPermissionsManager.getInstance().invokePermissionsRequest(lLinphonePermission)) { sLogger.error("permission refused"); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(mRes.getString(ERROR_AUDIO_PERMISSION_DENY)); close(); } }); return; } } // volume control keys addKeyListener(new KeyListener() { final static int GREEN_BUTTON_KEY=1114112; final static int RED_BUTTON_KEY=1179648; final static int VOLUME_DOWN=268500992; final static int VOLUME_UP=268435456; private int mLastVolumeEvent; public boolean keyChar(char key, int status, int time) {return false;} public boolean keyDown(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY || keycode == RED_BUTTON_KEY) { return true; } else if (time != mLastVolumeEvent && (keycode == VOLUME_DOWN || keycode == VOLUME_UP)) { mLastVolumeEvent=time; // change volume int lLeveltoDisplay=100; if (mCore.isIncall() ) { if (keycode == VOLUME_DOWN && mCore.getPlayLevel() >= 0) { lLeveltoDisplay=Math.max(0,(mCore.getPlayLevel() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,mCore.getPlayLevel() + 10); } mCore.setPlayLevel(lLeveltoDisplay); }else { if (keycode == VOLUME_DOWN ) { lLeveltoDisplay=Math.max(0,(Audio.getVolume() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,Audio.getVolume() + 10); } Audio.setVolume(lLeveltoDisplay); } Status.show("Volume ["+lLeveltoDisplay+"]",500); return true; } else { return false; } } public boolean keyRepeat(int keycode, int time) {return false;} public boolean keyStatus(int keycode, int time) {return false;} public boolean keyUp(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY) { return callButtonPressed(); } else if (keycode == RED_BUTTON_KEY) { hangupButtonPressed(); return true; } else { return false; } } }); mStatus=new LabelField("",Field.FIELD_BOTTOM); mStatus.setFont(Font.getDefault().derive(Font.ANTIALIAS_STANDARD,20)); // Set the displayed title of the screen setTitle(mStatus); // init liblinphone try { mCore=LinphoneCoreFactory.instance().createLinphoneCore(this, null, null, this); } catch (final LinphoneCoreException e) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); close(); } }); return; } ((VerticalFieldManager)getMainManager()).setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTGREY)); mTabField = new TabField(); add(mTabField); //call logs mCallLogs = new CallLogsField(mCore, new CallLogsField.Listener() { public void onSelected(Object selected) { LinphoneAddress lAddress; - if (selected == CallDirection.Incoming) { + if (((LinphoneCallLog)selected).getDirection() == CallDirection.Incoming) { lAddress = ((LinphoneCallLog)selected).getFrom(); } else { lAddress = ((LinphoneCallLog)selected).getTo(); } mDialer.setAddress(lAddress.getUserName()); mDialer.setDisplayName(lAddress.getDisplayName()); mTabField.display(DIALER_TAB_INDEX); } }); mTabField.addTab(Bitmap.getBitmapResource("history_orange.png"), mCallLogs); //dialer mDialer = new DialerField(mCore); mTabField.addTab(Bitmap.getBitmapResource("dialer_orange.png"), mDialer); //settings mSettingsScreen = new SettingsScreen(mCore); mTabField.addTab(Bitmap.getBitmapResource("settings_orange.png"), new SettingField(mSettingsScreen.createSettingsFields())); mTabField.setDefault(DIALER_TAB_INDEX); //menu addMenuItem(new MenuItem(mRes.getString(SETTINGS), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(mSettingsScreen); } }); addMenuItem(new MenuItem(mRes.getString(CONSOLE), 110, 10) { public void run() { EventLogger.startEventLogViewer(); } }); addMenuItem(new MenuItem(mRes.getString(ABOUT), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(new AboutScreen()); } }); mTimer=new Timer(); TimerTask task=new TimerTask(){ public void run() { mCore.iterate(); } }; mTimer.scheduleAtFixedRate(task, 0, 200); NetworkManager lNetworkManager = new NetworkManager(mCore); //to kick off network state lNetworkManager.handleCnxStateChange(); Application.getApplication().addRadioListener(RadioInfo.WAF_3GPP|RadioInfo.WAF_CDMA,lNetworkManager ); WLANInfo.addListener(lNetworkManager); } /** * Displays a dialog box to the user with the text "Goodbye!" when the * application is closed. * * @see net.rim.device.api.ui.Screen#close() */ public void close() { try {// Display a farewell message before closing the application Dialog.alert(mRes.getString(GOODBYE)); if (mCore != null) mCore.destroy(); } finally { super.close(); } } private boolean callButtonPressed() { sLogger.info("Call button pressed."); try { if (mCore.isInComingInvitePending()){ mCore.acceptCall(mCore.getCurrentCall()); return true; } } catch (final LinphoneCoreException e) { sLogger.error("call error",e); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); } }); } return false; } public void hangupButtonPressed() { sLogger.info("Hangup button pressed"); mCore.terminateCall(mCore.getCurrentCall()); } public void authInfoRequested(LinphoneCore lc, String realm, String username) { // TODO Auto-generated method stub } public void byeReceived(LinphoneCore lc, String from) { // TODO Auto-generated method stub } public void displayMessage(LinphoneCore lc, String message) { // TODO Auto-generated method stub } public void displayStatus(LinphoneCore lc, final String message) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { mStatus.setText("Linphone "+message); } }); } public void displayWarning(LinphoneCore lc, String message) { // TODO Auto-generated method stub } public void inviteReceived(LinphoneCore lc, String from) { } public void show(LinphoneCore lc) { // TODO Auto-generated method stub } public void callState(LinphoneCore lc, LinphoneCall call, final State state, String message) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { if (state == LinphoneCall.State.IncomingReceived && !UiApplication.getUiApplication().isForeground()) { UiApplication.getUiApplication().requestForeground(); } if (state == LinphoneCall.State.OutgoingInit || state == LinphoneCall.State.IncomingReceived ) { mDialer.enableIncallFields(); } else if (state==LinphoneCall.State.CallEnd | state==LinphoneCall.State.Error) { mDialer.enableOutOfCallFields(); } } }); } public void globalState(LinphoneCore lc, GlobalState state, String message) { // TODO Auto-generated method stub } public void registrationState(LinphoneCore lc, LinphoneProxyConfig cfg, RegistrationState cstate, String smessage) { // TODO Auto-generated method stub } }
true
true
LinphoneScreen() { LinphoneCoreFactory.setFactoryClassName("org.linphone.jlinphone.core.LinphoneFactoryImpl"); LinphoneCoreFactory.instance().setLogHandler(new LogHandler()); LinphoneCoreFactory.instance().setDebugMode(true);//debug mode until configuration is loaded sLogger.warn(" Starting version "+ApplicationDescriptor.currentApplicationDescriptor().getVersion()); ApplicationPermissions lCurentPermission = ApplicationPermissionsManager.getInstance().getApplicationPermissions(); boolean lPermissionRequestNeeded = false; for (int i=0;i<sPermissions.length;i++) { if (!lCurentPermission.containsPermissionKey(sPermissions[i]) || lCurentPermission.getPermission(sPermissions[i]) != ApplicationPermissions.VALUE_ALLOW) { lPermissionRequestNeeded=true; } } if (lPermissionRequestNeeded) { ApplicationPermissions lLinphonePermission = new ApplicationPermissions(); for (int i=0;i<sPermissions.length;i++) { lLinphonePermission.addPermission(sPermissions[i]); } if (!ApplicationPermissionsManager.getInstance().invokePermissionsRequest(lLinphonePermission)) { sLogger.error("permission refused"); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(mRes.getString(ERROR_AUDIO_PERMISSION_DENY)); close(); } }); return; } } // volume control keys addKeyListener(new KeyListener() { final static int GREEN_BUTTON_KEY=1114112; final static int RED_BUTTON_KEY=1179648; final static int VOLUME_DOWN=268500992; final static int VOLUME_UP=268435456; private int mLastVolumeEvent; public boolean keyChar(char key, int status, int time) {return false;} public boolean keyDown(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY || keycode == RED_BUTTON_KEY) { return true; } else if (time != mLastVolumeEvent && (keycode == VOLUME_DOWN || keycode == VOLUME_UP)) { mLastVolumeEvent=time; // change volume int lLeveltoDisplay=100; if (mCore.isIncall() ) { if (keycode == VOLUME_DOWN && mCore.getPlayLevel() >= 0) { lLeveltoDisplay=Math.max(0,(mCore.getPlayLevel() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,mCore.getPlayLevel() + 10); } mCore.setPlayLevel(lLeveltoDisplay); }else { if (keycode == VOLUME_DOWN ) { lLeveltoDisplay=Math.max(0,(Audio.getVolume() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,Audio.getVolume() + 10); } Audio.setVolume(lLeveltoDisplay); } Status.show("Volume ["+lLeveltoDisplay+"]",500); return true; } else { return false; } } public boolean keyRepeat(int keycode, int time) {return false;} public boolean keyStatus(int keycode, int time) {return false;} public boolean keyUp(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY) { return callButtonPressed(); } else if (keycode == RED_BUTTON_KEY) { hangupButtonPressed(); return true; } else { return false; } } }); mStatus=new LabelField("",Field.FIELD_BOTTOM); mStatus.setFont(Font.getDefault().derive(Font.ANTIALIAS_STANDARD,20)); // Set the displayed title of the screen setTitle(mStatus); // init liblinphone try { mCore=LinphoneCoreFactory.instance().createLinphoneCore(this, null, null, this); } catch (final LinphoneCoreException e) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); close(); } }); return; } ((VerticalFieldManager)getMainManager()).setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTGREY)); mTabField = new TabField(); add(mTabField); //call logs mCallLogs = new CallLogsField(mCore, new CallLogsField.Listener() { public void onSelected(Object selected) { LinphoneAddress lAddress; if (selected == CallDirection.Incoming) { lAddress = ((LinphoneCallLog)selected).getFrom(); } else { lAddress = ((LinphoneCallLog)selected).getTo(); } mDialer.setAddress(lAddress.getUserName()); mDialer.setDisplayName(lAddress.getDisplayName()); mTabField.display(DIALER_TAB_INDEX); } }); mTabField.addTab(Bitmap.getBitmapResource("history_orange.png"), mCallLogs); //dialer mDialer = new DialerField(mCore); mTabField.addTab(Bitmap.getBitmapResource("dialer_orange.png"), mDialer); //settings mSettingsScreen = new SettingsScreen(mCore); mTabField.addTab(Bitmap.getBitmapResource("settings_orange.png"), new SettingField(mSettingsScreen.createSettingsFields())); mTabField.setDefault(DIALER_TAB_INDEX); //menu addMenuItem(new MenuItem(mRes.getString(SETTINGS), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(mSettingsScreen); } }); addMenuItem(new MenuItem(mRes.getString(CONSOLE), 110, 10) { public void run() { EventLogger.startEventLogViewer(); } }); addMenuItem(new MenuItem(mRes.getString(ABOUT), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(new AboutScreen()); } }); mTimer=new Timer(); TimerTask task=new TimerTask(){ public void run() { mCore.iterate(); } }; mTimer.scheduleAtFixedRate(task, 0, 200); NetworkManager lNetworkManager = new NetworkManager(mCore); //to kick off network state lNetworkManager.handleCnxStateChange(); Application.getApplication().addRadioListener(RadioInfo.WAF_3GPP|RadioInfo.WAF_CDMA,lNetworkManager ); WLANInfo.addListener(lNetworkManager); }
LinphoneScreen() { LinphoneCoreFactory.setFactoryClassName("org.linphone.jlinphone.core.LinphoneFactoryImpl"); LinphoneCoreFactory.instance().setLogHandler(new LogHandler()); LinphoneCoreFactory.instance().setDebugMode(true);//debug mode until configuration is loaded sLogger.warn(" Starting version "+ApplicationDescriptor.currentApplicationDescriptor().getVersion()); ApplicationPermissions lCurentPermission = ApplicationPermissionsManager.getInstance().getApplicationPermissions(); boolean lPermissionRequestNeeded = false; for (int i=0;i<sPermissions.length;i++) { if (!lCurentPermission.containsPermissionKey(sPermissions[i]) || lCurentPermission.getPermission(sPermissions[i]) != ApplicationPermissions.VALUE_ALLOW) { lPermissionRequestNeeded=true; } } if (lPermissionRequestNeeded) { ApplicationPermissions lLinphonePermission = new ApplicationPermissions(); for (int i=0;i<sPermissions.length;i++) { lLinphonePermission.addPermission(sPermissions[i]); } if (!ApplicationPermissionsManager.getInstance().invokePermissionsRequest(lLinphonePermission)) { sLogger.error("permission refused"); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(mRes.getString(ERROR_AUDIO_PERMISSION_DENY)); close(); } }); return; } } // volume control keys addKeyListener(new KeyListener() { final static int GREEN_BUTTON_KEY=1114112; final static int RED_BUTTON_KEY=1179648; final static int VOLUME_DOWN=268500992; final static int VOLUME_UP=268435456; private int mLastVolumeEvent; public boolean keyChar(char key, int status, int time) {return false;} public boolean keyDown(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY || keycode == RED_BUTTON_KEY) { return true; } else if (time != mLastVolumeEvent && (keycode == VOLUME_DOWN || keycode == VOLUME_UP)) { mLastVolumeEvent=time; // change volume int lLeveltoDisplay=100; if (mCore.isIncall() ) { if (keycode == VOLUME_DOWN && mCore.getPlayLevel() >= 0) { lLeveltoDisplay=Math.max(0,(mCore.getPlayLevel() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,mCore.getPlayLevel() + 10); } mCore.setPlayLevel(lLeveltoDisplay); }else { if (keycode == VOLUME_DOWN ) { lLeveltoDisplay=Math.max(0,(Audio.getVolume() - 10)); } else if (keycode == VOLUME_UP) { lLeveltoDisplay=Math.min(100,Audio.getVolume() + 10); } Audio.setVolume(lLeveltoDisplay); } Status.show("Volume ["+lLeveltoDisplay+"]",500); return true; } else { return false; } } public boolean keyRepeat(int keycode, int time) {return false;} public boolean keyStatus(int keycode, int time) {return false;} public boolean keyUp(int keycode, int time) { if (keycode == GREEN_BUTTON_KEY) { return callButtonPressed(); } else if (keycode == RED_BUTTON_KEY) { hangupButtonPressed(); return true; } else { return false; } } }); mStatus=new LabelField("",Field.FIELD_BOTTOM); mStatus.setFont(Font.getDefault().derive(Font.ANTIALIAS_STANDARD,20)); // Set the displayed title of the screen setTitle(mStatus); // init liblinphone try { mCore=LinphoneCoreFactory.instance().createLinphoneCore(this, null, null, this); } catch (final LinphoneCoreException e) { UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.alert(e.getMessage()); close(); } }); return; } ((VerticalFieldManager)getMainManager()).setBackground(BackgroundFactory.createSolidBackground(Color.LIGHTGREY)); mTabField = new TabField(); add(mTabField); //call logs mCallLogs = new CallLogsField(mCore, new CallLogsField.Listener() { public void onSelected(Object selected) { LinphoneAddress lAddress; if (((LinphoneCallLog)selected).getDirection() == CallDirection.Incoming) { lAddress = ((LinphoneCallLog)selected).getFrom(); } else { lAddress = ((LinphoneCallLog)selected).getTo(); } mDialer.setAddress(lAddress.getUserName()); mDialer.setDisplayName(lAddress.getDisplayName()); mTabField.display(DIALER_TAB_INDEX); } }); mTabField.addTab(Bitmap.getBitmapResource("history_orange.png"), mCallLogs); //dialer mDialer = new DialerField(mCore); mTabField.addTab(Bitmap.getBitmapResource("dialer_orange.png"), mDialer); //settings mSettingsScreen = new SettingsScreen(mCore); mTabField.addTab(Bitmap.getBitmapResource("settings_orange.png"), new SettingField(mSettingsScreen.createSettingsFields())); mTabField.setDefault(DIALER_TAB_INDEX); //menu addMenuItem(new MenuItem(mRes.getString(SETTINGS), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(mSettingsScreen); } }); addMenuItem(new MenuItem(mRes.getString(CONSOLE), 110, 10) { public void run() { EventLogger.startEventLogViewer(); } }); addMenuItem(new MenuItem(mRes.getString(ABOUT), 110, 10) { public void run() { UiApplication.getUiApplication().pushScreen(new AboutScreen()); } }); mTimer=new Timer(); TimerTask task=new TimerTask(){ public void run() { mCore.iterate(); } }; mTimer.scheduleAtFixedRate(task, 0, 200); NetworkManager lNetworkManager = new NetworkManager(mCore); //to kick off network state lNetworkManager.handleCnxStateChange(); Application.getApplication().addRadioListener(RadioInfo.WAF_3GPP|RadioInfo.WAF_CDMA,lNetworkManager ); WLANInfo.addListener(lNetworkManager); }
diff --git a/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java b/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java index 91479773..7d69c685 100644 --- a/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java +++ b/src/org/liberty/android/fantastischmemo/ui/QACardActivity.java @@ -1,710 +1,716 @@ /* Copyright (C) 2012 Haowen Ning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.ui; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.amr.arabic.ArabicUtilities; import org.apache.mycommons.lang3.StringUtils; import org.liberty.android.fantastischmemo.AMActivity; import org.liberty.android.fantastischmemo.AMEnv; import org.liberty.android.fantastischmemo.AnyMemoDBOpenHelper; import org.liberty.android.fantastischmemo.AnyMemoDBOpenHelperManager; import org.liberty.android.fantastischmemo.AnyMemoService; import org.liberty.android.fantastischmemo.R; import org.liberty.android.fantastischmemo.dao.CardDao; import org.liberty.android.fantastischmemo.dao.CategoryDao; import org.liberty.android.fantastischmemo.dao.LearningDataDao; import org.liberty.android.fantastischmemo.dao.SettingDao; import org.liberty.android.fantastischmemo.domain.Card; import org.liberty.android.fantastischmemo.domain.Option; import org.liberty.android.fantastischmemo.domain.Setting; import org.liberty.android.fantastischmemo.tts.AnyMemoTTS; import org.liberty.android.fantastischmemo.tts.AnyMemoTTSImpl; import org.liberty.android.fantastischmemo.ui.StudyActivity; import org.liberty.android.fantastischmemo.utils.AMGUIUtility; import org.liberty.android.fantastischmemo.utils.AMUtil; import org.liberty.android.fantastischmemo.utils.AnyMemoExecutor; import org.xml.sax.XMLReader; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.text.Editable; import android.text.Html; import android.text.Html.ImageGetter; import android.text.Html.TagHandler; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.TextView; abstract public class QACardActivity extends AMActivity { public static String EXTRA_DBPATH = "dbpath"; private String dbPath; private String dbName; private AnyMemoDBOpenHelper dbOpenHelper; /* DAOs */ private SettingDao settingDao; private CardDao cardDao; private LearningDataDao learningDataDao; private CategoryDao categoryDao; private Card currentCard; private int screenWidth; private int screenHeight; private int animationInResId = 0; private int animationOutResId = 0; private Option option; private Setting setting; private InitTask initTask = null; private WaitDbTask waitDbTask = null; private boolean isAnswerShown = true; private TextView smallTitleBar; private AnyMemoTTS questionTTS = null; private AnyMemoTTS answerTTS = null; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Bundle extras = getIntent().getExtras(); if (extras != null) { dbPath = extras.getString(EXTRA_DBPATH); } dbOpenHelper = AnyMemoDBOpenHelperManager.getHelper(this, dbPath); dbPath = extras.getString(EXTRA_DBPATH); setContentView(R.layout.qa_card_layout); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); screenWidth = display.getWidth(); screenHeight = display.getHeight(); // Set teh default animation animationInResId = R.anim.slide_left_in; animationOutResId = R.anim.slide_left_out; initTask = new InitTask(); initTask.execute(); } protected void setCurrentCard(Card card) { currentCard = card; } protected Card getCurrentCard() { return currentCard; } protected String getDbPath() { return dbPath; } protected String getDbName() { return dbName; } protected void displayCard(boolean showAnswer) { // First prepare the text to display String questionTypeface = setting.getQuestionFont(); String answerTypeface = setting.getAnswerFont(); boolean enableThirdPartyArabic = option.getEnableArabicEngine(); Setting.Align questionAlign = setting.getQuestionTextAlign(); Setting.Align answerAlign = setting.getAnswerTextAlign(); EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum(); String itemQuestion = currentCard.getQuestion(); String itemAnswer = currentCard.getAnswer(); String itemCategory = currentCard.getCategory().getName(); String itemNote = currentCard.getNote(); if(enableThirdPartyArabic){ itemQuestion = ArabicUtilities.reshape(itemQuestion); itemAnswer = ArabicUtilities.reshape(itemAnswer); itemCategory = ArabicUtilities.reshape(itemCategory); itemNote = ArabicUtilities.reshape(itemNote); } // For question field (field1) SpannableStringBuilder sq = new SpannableStringBuilder(); // For answer field (field2) SpannableStringBuilder sa = new SpannableStringBuilder(); /* Show the field that is enabled in settings */ EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum(); EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum(); /* Iterate all fields */ for (Setting.CardField cf : Setting.CardField.values()) { String str = ""; if (cf == Setting.CardField.QUESTION) { str = itemQuestion; } else if (cf == Setting.CardField.ANSWER) { str = itemAnswer; } else if (cf == Setting.CardField.NOTE) { str = itemNote; } else { throw new AssertionError("This is a bug! New CardField enum has been added but the display field haven't been nupdated"); } SpannableStringBuilder buffer = new SpannableStringBuilder(); /* Automatic check HTML */ if(AMUtil.isHTML(str) && (htmlDisplay.contains(cf))) { if(setting.getHtmlLineBreakConversion() == true) { String s = str.replace("\n", "<br />"); buffer.append(Html.fromHtml(s, imageGetter, tagHandler)); } else { buffer.append(Html.fromHtml(str, imageGetter, tagHandler)); } } else { if(buffer.length() != 0){ buffer.append("\n\n"); } buffer.append(str); } if (field1.contains(cf)) { if(sq.length() != 0) { sq.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sq.append(buffer); } if (field2.contains(cf)) { if(sa.length() != 0) { sa.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sa.append(buffer); } } int questionAlignValue; int answerAlignValue; /* Here is tricky to set up the alignment of the text */ if (questionAlign == Setting.Align.CENTER) { questionAlignValue = Gravity.CENTER; } else if (questionAlign == Setting.Align.RIGHT){ questionAlignValue = Gravity.RIGHT; } else { questionAlignValue = Gravity.LEFT; } if (answerAlign == Setting.Align.CENTER) { answerAlignValue = Gravity.CENTER; } else if (answerAlign == Setting.Align.RIGHT){ answerAlignValue = Gravity.RIGHT; } else { answerAlignValue = Gravity.LEFT; } String questionTypefaceValue = null; String answerTypefaceValue = null; /* Set the typeface of question and answer */ if (StringUtils.isNotEmpty(questionTypeface)) { questionTypefaceValue = questionTypeface; } if (StringUtils.isNotEmpty(answerTypeface)) { answerTypefaceValue = answerTypeface; } CardFragment questionFragment = new CardFragment.Builder(sq) .setTextAlignment(questionAlignValue) .setTypefaceFromFile(questionTypefaceValue) .setTextOnClickListener(onQuestionTextClickListener) .setCardOnClickListener(onQuestionViewClickListener) + .setTextFontSize(setting.getQuestionFontSize()) + .setTypefaceFromFile(setting.getQuestionFont()) .build(); CardFragment answerFragment = null; if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED || showAnswer) { answerFragment = new CardFragment.Builder(sa) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) + .setTextFontSize(setting.getAnswerFontSize()) + .setTypefaceFromFile(setting.getAnswerFont()) .build(); } else { answerFragment = new CardFragment.Builder(getString(R.string.memo_show_answer)) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) + .setTextFontSize(setting.getAnswerFontSize()) + .setTypefaceFromFile(setting.getAnswerFont()) .build(); } // Double sided card has no animation and no horizontal line if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) { if (showAnswer) { findViewById(R.id.question).setVisibility(View.GONE); findViewById(R.id.answer).setVisibility(View.VISIBLE); } else { findViewById(R.id.question).setVisibility(View.VISIBLE); findViewById(R.id.answer).setVisibility(View.GONE); } findViewById(R.id.horizontal_line).setVisibility(View.GONE); } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { // No animation here. } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.question, questionFragment); ft.commit(); ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { ft.setCustomAnimations(0, R.anim.slide_down); } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.answer, answerFragment); ft.commit(); isAnswerShown = showAnswer; // Set up the small title bar // It is defualt "GONE" so it won't take any space // if there is no text smallTitleBar = (TextView) findViewById(R.id.small_title_bar); onPostDisplayCard(); } protected boolean isAnswerShown() { return isAnswerShown; } protected AnyMemoDBOpenHelper getDbOpenHelper() { return dbOpenHelper; } protected Setting getSetting() { return setting; } protected Option getOption() { return option; } // Call when initializing thing abstract protected void onInit() throws Exception; // Called when the initalizing finished. protected void onPostInit() { // Do nothing } // Set the card animation, 0 = no animation protected void setAnimation(int animationInResId, int animationOutResId) { this.animationInResId = animationInResId; this.animationOutResId = animationOutResId; } private class InitTask extends AsyncTask<Void, Void, Exception> { private ProgressDialog progressDialog; @Override public void onPreExecute() { progressDialog = new ProgressDialog(QACardActivity.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setTitle(getString(R.string.loading_please_wait)); progressDialog.setMessage(getString(R.string.loading_database)); progressDialog.setCancelable(false); progressDialog.show(); option = new Option(QACardActivity.this); dbName = AMUtil.getFilenameFromPath(dbPath); } @Override public Exception doInBackground(Void... params) { try { cardDao = dbOpenHelper.getCardDao(); learningDataDao = dbOpenHelper.getLearningDataDao(); settingDao = dbOpenHelper.getSettingDao(); categoryDao = dbOpenHelper.getCategoryDao(); setting = settingDao.queryForId(1); // Call customized init funciton defined in // the subclass onInit(); // No Exception. return null; } catch (Exception e) { Log.e(TAG, "Excepting doing in bacground", e); return e; } } @Override public void onCancelled(){ return; } @Override public void onPostExecute(Exception e){ progressDialog.dismiss(); if (e != null) { AMGUIUtility.displayError(QACardActivity.this, getString(R.string.exception_text), getString(R.string.exception_message), e); return; } // Call customized method when init completed onPostInit(); } } @Override public void onResume() { super.onResume(); // Only if the initTask has been finished and no waitDbTask is waiting. if ((initTask != null && AsyncTask.Status.FINISHED.equals(initTask.getStatus())) && (waitDbTask == null || !AsyncTask.Status.RUNNING.equals(waitDbTask.getStatus()))) { waitDbTask = new WaitDbTask(); waitDbTask.execute((Void)null); } else { Log.i(TAG, "There is another task running. Do not run tasks"); } } @Override public void onDestroy(){ super.onDestroy(); AnyMemoDBOpenHelperManager.releaseHelper(dbOpenHelper); shutdownQAndATTS(); /* Update the widget because StudyActivity can be accessed though widget*/ Intent myIntent = new Intent(this, AnyMemoService.class); myIntent.putExtra("request_code", AnyMemoService.CANCEL_NOTIFICATION | AnyMemoService.UPDATE_WIDGET); startService(myIntent); } // Se public void setSmallTitle(CharSequence text) { if (StringUtils.isNotEmpty(text)) { smallTitleBar.setText(text); smallTitleBar.setVisibility(View.VISIBLE); } else { smallTitleBar.setVisibility(View.GONE); } } /* * Use AsyncTask to make sure there is no running task for a db */ private class WaitDbTask extends AsyncTask<Void, Void, Void>{ private ProgressDialog progressDialog; @Override public void onPreExecute(){ super.onPreExecute(); progressDialog = new ProgressDialog(QACardActivity.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setTitle(getString(R.string.loading_please_wait)); progressDialog.setMessage(getString(R.string.loading_save)); progressDialog.setCancelable(true); progressDialog.show(); } @Override public Void doInBackground(Void... nothing){ AnyMemoExecutor.waitAllTasks(); return null; } @Override public void onCancelled(){ return; } @Override public void onPostExecute(Void result){ super.onPostExecute(result); progressDialog.dismiss(); } } /* Called when the card is displayed. */ protected void onPostDisplayCard() { // Nothing } private ImageGetter imageGetter = new ImageGetter() { @Override public Drawable getDrawable(String source){ Log.v(TAG, "Source: " + source); String dbName = AMUtil.getFilenameFromPath(dbPath); try{ String[] paths = { /* Relative path */ "" + dbName + "/" + source, /* Try the image in /sdcard/anymemo/images/dbname/myimg.png */ AMEnv.DEFAULT_IMAGE_PATH + dbName + "/" + source, /* Try the image in /sdcard/anymemo/images/myimg.png */ AMEnv.DEFAULT_IMAGE_PATH + source}; Bitmap orngBitmap = null; for(String path : paths) { Log.v(TAG, "Try path: " + path); if(new File(path).exists()) { orngBitmap = BitmapFactory.decodeFile(path); break; } } /* Try the image from internet */ if(orngBitmap == null) { InputStream is = (InputStream)new URL(source).getContent(); orngBitmap = BitmapFactory.decodeStream(is); } int width = orngBitmap.getWidth(); int height = orngBitmap.getHeight(); int scaledWidth = width; int scaledHeight = height; float scaleFactor = ((float)screenWidth) / width; Matrix matrix = new Matrix(); if(scaleFactor < 1.0f){ matrix.postScale(scaleFactor, scaleFactor); scaledWidth = (int)(width * scaleFactor); scaledHeight = (int)(height * scaleFactor); } Bitmap resizedBitmap = Bitmap.createBitmap(orngBitmap, 0, 0, width, height, matrix, true); BitmapDrawable d = new BitmapDrawable(resizedBitmap); //d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); d.setBounds(0, 0, scaledWidth, scaledHeight); return d; } catch(Exception e){ Log.e(TAG, "getDrawable() Image handling error", e); } /* Fallback, display default image */ Drawable d = getResources().getDrawable(R.drawable.picture); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } }; protected void initTTS(){ String defaultLocation = AMEnv.DEFAULT_AUDIO_PATH; String dbName = getDbName(); if (setting.isQuestionAudioEnabled()) { String qa = setting.getQuestionAudio(); List<String> questionAudioSearchPath = new ArrayList<String>(); questionAudioSearchPath.add(setting.getQuestionAudioLocation()); questionAudioSearchPath.add(setting.getQuestionAudioLocation() + "/" + dbName); questionAudioSearchPath.add(defaultLocation + "/" + dbName); questionAudioSearchPath.add(setting.getQuestionAudioLocation()); questionTTS = new AnyMemoTTSImpl(this, qa, questionAudioSearchPath); } if (setting.isAnswerAudioEnabled()) { String aa = setting.getAnswerAudio(); List<String> answerAudioSearchPath = new ArrayList<String>(); answerAudioSearchPath.add(setting.getAnswerAudioLocation()); answerAudioSearchPath.add(setting.getAnswerAudioLocation() + "/" + dbName); answerAudioSearchPath.add(defaultLocation + "/" + dbName); answerAudioSearchPath.add(defaultLocation); answerTTS = new AnyMemoTTSImpl(this, aa, answerAudioSearchPath); } } protected boolean speakQuestion(String text){ if(questionTTS != null && text != null){ questionTTS.sayText(text); return true; } return false; } protected boolean speakAnswer(String text){ if(answerTTS != null && text != null){ answerTTS.sayText(text); return true; } return false; } protected void stopQAndATTS(){ stopAnswerTTS(); stopQuestionTTS(); } protected void stopQuestionTTS(){ if(questionTTS != null){ questionTTS.stop(); } } protected void stopAnswerTTS(){ if(answerTTS != null){ answerTTS.stop(); } } private void shutdownQAndATTS(){ if(questionTTS != null){ questionTTS.shutdown(); } if(answerTTS != null){ answerTTS.shutdown(); } } private TagHandler tagHandler = new TagHandler() { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader){ return; } }; protected void onClickQuestionText() { // Nothing } protected void onClickAnswerText() { // Nothing } protected void onClickQuestionView() { // Nothing } protected void onClickAnswerView() { // Nothing } private View.OnClickListener onQuestionTextClickListener = new View.OnClickListener() { @Override public void onClick(View v) { onClickQuestionText(); } }; private View.OnClickListener onAnswerTextClickListener = new View.OnClickListener() { @Override public void onClick(View v) { onClickAnswerText(); } }; private View.OnClickListener onQuestionViewClickListener = new View.OnClickListener() { @Override public void onClick(View v) { onClickQuestionView(); } }; private View.OnClickListener onAnswerViewClickListener = new View.OnClickListener() { @Override public void onClick(View v) { onClickAnswerView(); } }; }
false
true
protected void displayCard(boolean showAnswer) { // First prepare the text to display String questionTypeface = setting.getQuestionFont(); String answerTypeface = setting.getAnswerFont(); boolean enableThirdPartyArabic = option.getEnableArabicEngine(); Setting.Align questionAlign = setting.getQuestionTextAlign(); Setting.Align answerAlign = setting.getAnswerTextAlign(); EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum(); String itemQuestion = currentCard.getQuestion(); String itemAnswer = currentCard.getAnswer(); String itemCategory = currentCard.getCategory().getName(); String itemNote = currentCard.getNote(); if(enableThirdPartyArabic){ itemQuestion = ArabicUtilities.reshape(itemQuestion); itemAnswer = ArabicUtilities.reshape(itemAnswer); itemCategory = ArabicUtilities.reshape(itemCategory); itemNote = ArabicUtilities.reshape(itemNote); } // For question field (field1) SpannableStringBuilder sq = new SpannableStringBuilder(); // For answer field (field2) SpannableStringBuilder sa = new SpannableStringBuilder(); /* Show the field that is enabled in settings */ EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum(); EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum(); /* Iterate all fields */ for (Setting.CardField cf : Setting.CardField.values()) { String str = ""; if (cf == Setting.CardField.QUESTION) { str = itemQuestion; } else if (cf == Setting.CardField.ANSWER) { str = itemAnswer; } else if (cf == Setting.CardField.NOTE) { str = itemNote; } else { throw new AssertionError("This is a bug! New CardField enum has been added but the display field haven't been nupdated"); } SpannableStringBuilder buffer = new SpannableStringBuilder(); /* Automatic check HTML */ if(AMUtil.isHTML(str) && (htmlDisplay.contains(cf))) { if(setting.getHtmlLineBreakConversion() == true) { String s = str.replace("\n", "<br />"); buffer.append(Html.fromHtml(s, imageGetter, tagHandler)); } else { buffer.append(Html.fromHtml(str, imageGetter, tagHandler)); } } else { if(buffer.length() != 0){ buffer.append("\n\n"); } buffer.append(str); } if (field1.contains(cf)) { if(sq.length() != 0) { sq.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sq.append(buffer); } if (field2.contains(cf)) { if(sa.length() != 0) { sa.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sa.append(buffer); } } int questionAlignValue; int answerAlignValue; /* Here is tricky to set up the alignment of the text */ if (questionAlign == Setting.Align.CENTER) { questionAlignValue = Gravity.CENTER; } else if (questionAlign == Setting.Align.RIGHT){ questionAlignValue = Gravity.RIGHT; } else { questionAlignValue = Gravity.LEFT; } if (answerAlign == Setting.Align.CENTER) { answerAlignValue = Gravity.CENTER; } else if (answerAlign == Setting.Align.RIGHT){ answerAlignValue = Gravity.RIGHT; } else { answerAlignValue = Gravity.LEFT; } String questionTypefaceValue = null; String answerTypefaceValue = null; /* Set the typeface of question and answer */ if (StringUtils.isNotEmpty(questionTypeface)) { questionTypefaceValue = questionTypeface; } if (StringUtils.isNotEmpty(answerTypeface)) { answerTypefaceValue = answerTypeface; } CardFragment questionFragment = new CardFragment.Builder(sq) .setTextAlignment(questionAlignValue) .setTypefaceFromFile(questionTypefaceValue) .setTextOnClickListener(onQuestionTextClickListener) .setCardOnClickListener(onQuestionViewClickListener) .build(); CardFragment answerFragment = null; if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED || showAnswer) { answerFragment = new CardFragment.Builder(sa) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) .build(); } else { answerFragment = new CardFragment.Builder(getString(R.string.memo_show_answer)) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) .build(); } // Double sided card has no animation and no horizontal line if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) { if (showAnswer) { findViewById(R.id.question).setVisibility(View.GONE); findViewById(R.id.answer).setVisibility(View.VISIBLE); } else { findViewById(R.id.question).setVisibility(View.VISIBLE); findViewById(R.id.answer).setVisibility(View.GONE); } findViewById(R.id.horizontal_line).setVisibility(View.GONE); } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { // No animation here. } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.question, questionFragment); ft.commit(); ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { ft.setCustomAnimations(0, R.anim.slide_down); } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.answer, answerFragment); ft.commit(); isAnswerShown = showAnswer; // Set up the small title bar // It is defualt "GONE" so it won't take any space // if there is no text smallTitleBar = (TextView) findViewById(R.id.small_title_bar); onPostDisplayCard(); }
protected void displayCard(boolean showAnswer) { // First prepare the text to display String questionTypeface = setting.getQuestionFont(); String answerTypeface = setting.getAnswerFont(); boolean enableThirdPartyArabic = option.getEnableArabicEngine(); Setting.Align questionAlign = setting.getQuestionTextAlign(); Setting.Align answerAlign = setting.getAnswerTextAlign(); EnumSet<Setting.CardField> htmlDisplay = setting.getDisplayInHTMLEnum(); String itemQuestion = currentCard.getQuestion(); String itemAnswer = currentCard.getAnswer(); String itemCategory = currentCard.getCategory().getName(); String itemNote = currentCard.getNote(); if(enableThirdPartyArabic){ itemQuestion = ArabicUtilities.reshape(itemQuestion); itemAnswer = ArabicUtilities.reshape(itemAnswer); itemCategory = ArabicUtilities.reshape(itemCategory); itemNote = ArabicUtilities.reshape(itemNote); } // For question field (field1) SpannableStringBuilder sq = new SpannableStringBuilder(); // For answer field (field2) SpannableStringBuilder sa = new SpannableStringBuilder(); /* Show the field that is enabled in settings */ EnumSet<Setting.CardField> field1 = setting.getQuestionFieldEnum(); EnumSet<Setting.CardField> field2 = setting.getAnswerFieldEnum(); /* Iterate all fields */ for (Setting.CardField cf : Setting.CardField.values()) { String str = ""; if (cf == Setting.CardField.QUESTION) { str = itemQuestion; } else if (cf == Setting.CardField.ANSWER) { str = itemAnswer; } else if (cf == Setting.CardField.NOTE) { str = itemNote; } else { throw new AssertionError("This is a bug! New CardField enum has been added but the display field haven't been nupdated"); } SpannableStringBuilder buffer = new SpannableStringBuilder(); /* Automatic check HTML */ if(AMUtil.isHTML(str) && (htmlDisplay.contains(cf))) { if(setting.getHtmlLineBreakConversion() == true) { String s = str.replace("\n", "<br />"); buffer.append(Html.fromHtml(s, imageGetter, tagHandler)); } else { buffer.append(Html.fromHtml(str, imageGetter, tagHandler)); } } else { if(buffer.length() != 0){ buffer.append("\n\n"); } buffer.append(str); } if (field1.contains(cf)) { if(sq.length() != 0) { sq.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sq.append(buffer); } if (field2.contains(cf)) { if(sa.length() != 0) { sa.append(Html.fromHtml("<br /><br />", imageGetter, tagHandler)); } sa.append(buffer); } } int questionAlignValue; int answerAlignValue; /* Here is tricky to set up the alignment of the text */ if (questionAlign == Setting.Align.CENTER) { questionAlignValue = Gravity.CENTER; } else if (questionAlign == Setting.Align.RIGHT){ questionAlignValue = Gravity.RIGHT; } else { questionAlignValue = Gravity.LEFT; } if (answerAlign == Setting.Align.CENTER) { answerAlignValue = Gravity.CENTER; } else if (answerAlign == Setting.Align.RIGHT){ answerAlignValue = Gravity.RIGHT; } else { answerAlignValue = Gravity.LEFT; } String questionTypefaceValue = null; String answerTypefaceValue = null; /* Set the typeface of question and answer */ if (StringUtils.isNotEmpty(questionTypeface)) { questionTypefaceValue = questionTypeface; } if (StringUtils.isNotEmpty(answerTypeface)) { answerTypefaceValue = answerTypeface; } CardFragment questionFragment = new CardFragment.Builder(sq) .setTextAlignment(questionAlignValue) .setTypefaceFromFile(questionTypefaceValue) .setTextOnClickListener(onQuestionTextClickListener) .setCardOnClickListener(onQuestionViewClickListener) .setTextFontSize(setting.getQuestionFontSize()) .setTypefaceFromFile(setting.getQuestionFont()) .build(); CardFragment answerFragment = null; if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED || showAnswer) { answerFragment = new CardFragment.Builder(sa) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) .setTextFontSize(setting.getAnswerFontSize()) .setTypefaceFromFile(setting.getAnswerFont()) .build(); } else { answerFragment = new CardFragment.Builder(getString(R.string.memo_show_answer)) .setTextAlignment(answerAlignValue) .setTypefaceFromFile(answerTypefaceValue) .setTextOnClickListener(onAnswerTextClickListener) .setCardOnClickListener(onAnswerViewClickListener) .setTextFontSize(setting.getAnswerFontSize()) .setTypefaceFromFile(setting.getAnswerFont()) .build(); } // Double sided card has no animation and no horizontal line if (setting.getCardStyle() == Setting.CardStyle.DOUBLE_SIDED) { if (showAnswer) { findViewById(R.id.question).setVisibility(View.GONE); findViewById(R.id.answer).setVisibility(View.VISIBLE); } else { findViewById(R.id.question).setVisibility(View.VISIBLE); findViewById(R.id.answer).setVisibility(View.GONE); } findViewById(R.id.horizontal_line).setVisibility(View.GONE); } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { // No animation here. } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.question, questionFragment); ft.commit(); ft = getSupportFragmentManager().beginTransaction(); if (setting.getCardStyle() != Setting.CardStyle.DOUBLE_SIDED && option.getEnableAnimation()) { if (isAnswerShown == false && showAnswer == true) { ft.setCustomAnimations(0, R.anim.slide_down); } else { ft.setCustomAnimations(animationInResId, animationOutResId); } } ft.replace(R.id.answer, answerFragment); ft.commit(); isAnswerShown = showAnswer; // Set up the small title bar // It is defualt "GONE" so it won't take any space // if there is no text smallTitleBar = (TextView) findViewById(R.id.small_title_bar); onPostDisplayCard(); }
diff --git a/org.eclipse.scout.rt.ui.rap.mobile/src/org/eclipse/scout/rt/ui/rap/mobile/form/fields/groupbox/MobileGroupBoxFieldFactory.java b/org.eclipse.scout.rt.ui.rap.mobile/src/org/eclipse/scout/rt/ui/rap/mobile/form/fields/groupbox/MobileGroupBoxFieldFactory.java index 005d56d7aa..87a4909a28 100644 --- a/org.eclipse.scout.rt.ui.rap.mobile/src/org/eclipse/scout/rt/ui/rap/mobile/form/fields/groupbox/MobileGroupBoxFieldFactory.java +++ b/org.eclipse.scout.rt.ui.rap.mobile/src/org/eclipse/scout/rt/ui/rap/mobile/form/fields/groupbox/MobileGroupBoxFieldFactory.java @@ -1,45 +1,45 @@ /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * 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: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipse.scout.rt.ui.rap.mobile.form.fields.groupbox; import org.eclipse.scout.rt.client.ui.form.fields.IFormField; import org.eclipse.scout.rt.client.ui.form.fields.groupbox.IGroupBox; import org.eclipse.scout.rt.ui.rap.IRwtEnvironment; import org.eclipse.scout.rt.ui.rap.extension.IFormFieldFactory; import org.eclipse.scout.rt.ui.rap.form.fields.IRwtScoutFormField; import org.eclipse.scout.rt.ui.rap.form.fields.groupbox.IRwtScoutGroupBox; import org.eclipse.scout.rt.ui.rap.form.fields.groupbox.RwtScoutGroupBox; import org.eclipse.scout.rt.ui.rap.util.DeviceUtility; import org.eclipse.swt.widgets.Composite; /** * @since 3.8.0 */ public class MobileGroupBoxFieldFactory implements IFormFieldFactory { @Override public IRwtScoutFormField<?> createUiFormField(Composite parent, IFormField model, IRwtEnvironment uiEnvironment) { IRwtScoutGroupBox field; - if (DeviceUtility.isMobileDevice()) { + if (DeviceUtility.isMobileOrTabletDevice()) { field = new RwtScoutMobileGroupBox(); } else { field = new RwtScoutGroupBox(); } IGroupBox groupBox = (IGroupBox) model; field.createUiField(parent, groupBox, uiEnvironment); return field; } }
true
true
public IRwtScoutFormField<?> createUiFormField(Composite parent, IFormField model, IRwtEnvironment uiEnvironment) { IRwtScoutGroupBox field; if (DeviceUtility.isMobileDevice()) { field = new RwtScoutMobileGroupBox(); } else { field = new RwtScoutGroupBox(); } IGroupBox groupBox = (IGroupBox) model; field.createUiField(parent, groupBox, uiEnvironment); return field; }
public IRwtScoutFormField<?> createUiFormField(Composite parent, IFormField model, IRwtEnvironment uiEnvironment) { IRwtScoutGroupBox field; if (DeviceUtility.isMobileOrTabletDevice()) { field = new RwtScoutMobileGroupBox(); } else { field = new RwtScoutGroupBox(); } IGroupBox groupBox = (IGroupBox) model; field.createUiField(parent, groupBox, uiEnvironment); return field; }
diff --git a/src/com/android/launcher2/DragLayer.java b/src/com/android/launcher2/DragLayer.java index 2e72f622..eb539450 100644 --- a/src/com/android/launcher2/DragLayer.java +++ b/src/com/android/launcher2/DragLayer.java @@ -1,104 +1,106 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import com.android.launcher.R; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; /** * A ViewGroup that coordinates dragging across its descendants */ public class DragLayer extends FrameLayout { private DragController mDragController; private int[] mTmpXY = new int[2]; /** * Used to create a new DragLayer from XML. * * @param context The application's context. * @param attrs The attributes set containing the Workspace's customization values. */ public DragLayer(Context context, AttributeSet attrs) { super(context, attrs); // Disable multitouch across the workspace/all apps/customize tray setMotionEventSplittingEnabled(false); } public void setDragController(DragController controller) { mDragController = controller; } @Override public boolean dispatchKeyEvent(KeyEvent event) { return mDragController.dispatchKeyEvent(event) || super.dispatchKeyEvent(event); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); - final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); - final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); + if (w != null) { + final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); + final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); - if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { - post(new Runnable() { - public void run() { - if (!childrenLayout.isWidgetBeingResized()) { - childrenLayout.clearAllResizeFrames(); + if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { + post(new Runnable() { + public void run() { + if (!childrenLayout.isWidgetBeingResized()) { + childrenLayout.clearAllResizeFrames(); + } } - } - }); + }); + } } return mDragController.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { return mDragController.onTouchEvent(ev); } @Override public boolean dispatchUnhandledMove(View focused, int direction) { return mDragController.dispatchUnhandledMove(focused, direction); } public View createDragView(Bitmap b, int xPos, int yPos) { ImageView imageView = new ImageView(mContext); imageView.setImageBitmap(b); imageView.setX(xPos); imageView.setY(yPos); addView(imageView, b.getWidth(), b.getHeight()); return imageView; } public View createDragView(View v) { v.getLocationOnScreen(mTmpXY); return createDragView(mDragController.getViewBitmap(v), mTmpXY[0], mTmpXY[1]); } }
false
true
public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { post(new Runnable() { public void run() { if (!childrenLayout.isWidgetBeingResized()) { childrenLayout.clearAllResizeFrames(); } } }); } return mDragController.onInterceptTouchEvent(ev); }
public boolean onInterceptTouchEvent(MotionEvent ev) { // If the current CellLayoutChildren has a resize frame, we need to detect if any touch // event has occurred which doesn't result in resizing a widget. In this case, we // dismiss any visible resize frames. final Workspace w = (Workspace) findViewById(R.id.workspace); if (w != null) { final CellLayout currentPage = (CellLayout) w.getChildAt(w.getCurrentPage()); final CellLayoutChildren childrenLayout = currentPage.getChildrenLayout(); if (childrenLayout.hasResizeFrames() && !childrenLayout.isWidgetBeingResized()) { post(new Runnable() { public void run() { if (!childrenLayout.isWidgetBeingResized()) { childrenLayout.clearAllResizeFrames(); } } }); } } return mDragController.onInterceptTouchEvent(ev); }
diff --git a/src/techniques/StackingET.java b/src/techniques/StackingET.java index d6e0c1c..585672a 100644 --- a/src/techniques/StackingET.java +++ b/src/techniques/StackingET.java @@ -1,61 +1,62 @@ package techniques; import java.util.List; import org.encog.ensemble.Ensemble.TrainingAborted; import org.encog.ensemble.EnsembleAggregator; import org.encog.ensemble.EnsembleMLMethodFactory; import org.encog.ensemble.EnsembleTrainFactory; import org.encog.ensemble.bagging.Bagging; import org.encog.ensemble.stacking.Stacking; import org.encog.ml.data.MLData; import helpers.DataLoader; import helpers.ChainParams; public class StackingET extends EvaluationTechnique { private int dataSetSize; public StackingET(List<Integer> sizes, int dataSetSize, int maxIterations, ChainParams fullLabel, EnsembleMLMethodFactory mlMethod, EnsembleTrainFactory trainFactory, EnsembleAggregator aggregator) { this.sizes = sizes; this.dataSetSize = dataSetSize; this.label = fullLabel; this.mlMethod = mlMethod; this.trainFactory = trainFactory; this.aggregator = aggregator; this.maxIterations = maxIterations; } @Override public void init(DataLoader dataLoader, int fold) { ensemble = new Stacking(sizes.get(currentSizeIndex),dataSetSize,mlMethod,trainFactory,aggregator); setTrainingSet(dataLoader.getTrainingSet(fold)); setSelectionSet(dataLoader.getTestSet(fold)); ensemble.setTrainingData(trainingSet); } @Override public void trainStep() { ((Stacking) ensemble).trainStep(); } @Override public MLData compute(MLData input) { return ensemble.compute(input); } @Override public void step(boolean verbose) throws TrainingAborted { if (currentSizeIndex < sizes.size() -1) { for (int i = sizes.get(currentSizeIndex++); i < sizes.get(currentSizeIndex); i++) { ensemble.addNewMember(); ensemble.trainMember(i, trainToError, selectionError, selectionSet, verbose); } + aggregator.setTrainingErrorDivisor(sizes.get(currentSizeIndex)); ensemble.retrainAggregator(); } else { this.hasStepsLeft = false; } } }
true
true
public void step(boolean verbose) throws TrainingAborted { if (currentSizeIndex < sizes.size() -1) { for (int i = sizes.get(currentSizeIndex++); i < sizes.get(currentSizeIndex); i++) { ensemble.addNewMember(); ensemble.trainMember(i, trainToError, selectionError, selectionSet, verbose); } ensemble.retrainAggregator(); } else { this.hasStepsLeft = false; } }
public void step(boolean verbose) throws TrainingAborted { if (currentSizeIndex < sizes.size() -1) { for (int i = sizes.get(currentSizeIndex++); i < sizes.get(currentSizeIndex); i++) { ensemble.addNewMember(); ensemble.trainMember(i, trainToError, selectionError, selectionSet, verbose); } aggregator.setTrainingErrorDivisor(sizes.get(currentSizeIndex)); ensemble.retrainAggregator(); } else { this.hasStepsLeft = false; } }
diff --git a/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java b/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java index 08525d84..4cd9ddf2 100644 --- a/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java +++ b/lucene/contrib/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java @@ -1,295 +1,295 @@ /* * Created on 28-Oct-2004 */ package org.apache.lucene.search.highlight; /** * 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 java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.TermFreqVector; import org.apache.lucene.index.TermPositionVector; import org.apache.lucene.index.TermVectorOffsetInfo; import org.apache.lucene.util.ArrayUtil; /** * Hides implementation issues associated with obtaining a TokenStream for use * with the higlighter - can obtain from TermFreqVectors with offsets and * (optionally) positions or from Analyzer class reparsing the stored content. */ public class TokenSources { /** * A convenience method that tries to first get a TermPositionVector for the * specified docId, then, falls back to using the passed in * {@link org.apache.lucene.document.Document} to retrieve the TokenStream. * This is useful when you already have the document, but would prefer to use * the vector first. * * @param reader The {@link org.apache.lucene.index.IndexReader} to use to try * and get the vector from * @param docId The docId to retrieve. * @param field The field to retrieve on the document * @param doc The document to fall back on * @param analyzer The analyzer to use for creating the TokenStream if the * vector doesn't exist * @return The {@link org.apache.lucene.analysis.TokenStream} for the * {@link org.apache.lucene.document.Fieldable} on the * {@link org.apache.lucene.document.Document} * @throws IOException if there was an error loading */ public static TokenStream getAnyTokenStream(IndexReader reader, int docId, String field, Document doc, Analyzer analyzer) throws IOException { TokenStream ts = null; TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv != null) { if (tfv instanceof TermPositionVector) { ts = getTokenStream((TermPositionVector) tfv); } } // No token info stored so fall back to analyzing raw content if (ts == null) { ts = getTokenStream(doc, field, analyzer); } return ts; } /** * A convenience method that tries a number of approaches to getting a token * stream. The cost of finding there are no termVectors in the index is * minimal (1000 invocations still registers 0 ms). So this "lazy" (flexible?) * approach to coding is probably acceptable * * @param reader * @param docId * @param field * @param analyzer * @return null if field not stored correctly * @throws IOException */ public static TokenStream getAnyTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer) throws IOException { TokenStream ts = null; TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv != null) { if (tfv instanceof TermPositionVector) { ts = getTokenStream((TermPositionVector) tfv); } } // No token info stored so fall back to analyzing raw content if (ts == null) { ts = getTokenStream(reader, docId, field, analyzer); } return ts; } public static TokenStream getTokenStream(TermPositionVector tpv) { // assumes the worst and makes no assumptions about token position // sequences. return getTokenStream(tpv, false); } /** * Low level api. Returns a token stream or null if no offset info available * in index. This can be used to feed the highlighter with a pre-parsed token * stream * * In my tests the speeds to recreate 1000 token streams using this method * are: - with TermVector offset only data stored - 420 milliseconds - with * TermVector offset AND position data stored - 271 milliseconds (nb timings * for TermVector with position data are based on a tokenizer with contiguous * positions - no overlaps or gaps) The cost of not using TermPositionVector * to store pre-parsed content and using an analyzer to re-parse the original * content: - reanalyzing the original content - 980 milliseconds * * The re-analyze timings will typically vary depending on - 1) The complexity * of the analyzer code (timings above were using a * stemmer/lowercaser/stopword combo) 2) The number of other fields (Lucene * reads ALL fields off the disk when accessing just one document field - can * cost dear!) 3) Use of compression on field storage - could be faster due to * compression (less disk IO) or slower (more CPU burn) depending on the * content. * * @param tpv * @param tokenPositionsGuaranteedContiguous true if the token position * numbers have no overlaps or gaps. If looking to eek out the last * drops of performance, set to true. If in doubt, set to false. */ public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); - posincAtt = (PositionIncrementAttribute) addAttribute(PositionIncrementAttribute.class); + posincAtt = addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens String[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp] .getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); } public static TokenStream getTokenStream(IndexReader reader, int docId, String field) throws IOException { TermFreqVector tfv = reader.getTermFreqVector(docId, field); if (tfv == null) { throw new IllegalArgumentException(field + " in doc #" + docId + "does not have any term position data stored"); } if (tfv instanceof TermPositionVector) { TermPositionVector tpv = (TermPositionVector) reader.getTermFreqVector( docId, field); return getTokenStream(tpv); } throw new IllegalArgumentException(field + " in doc #" + docId + "does not have any term position data stored"); } // convenience method public static TokenStream getTokenStream(IndexReader reader, int docId, String field, Analyzer analyzer) throws IOException { Document doc = reader.document(docId); return getTokenStream(doc, field, analyzer); } public static TokenStream getTokenStream(Document doc, String field, Analyzer analyzer) { String contents = doc.get(field); if (contents == null) { throw new IllegalArgumentException("Field " + field + " in document is not stored and cannot be analyzed"); } return getTokenStream(field, contents, analyzer); } // convenience method public static TokenStream getTokenStream(String field, String contents, Analyzer analyzer) { try { return analyzer.reusableTokenStream(field, new StringReader(contents)); } catch (IOException ex) { throw new RuntimeException(ex); } } }
true
true
public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); posincAtt = (PositionIncrementAttribute) addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens String[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp] .getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); }
public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous) { if (!tokenPositionsGuaranteedContiguous && tpv.getTermPositions(0) != null) { return new TokenStreamFromTermPositionVector(tpv); } // an object used to iterate across an array of tokens final class StoredTokenStream extends TokenStream { Token tokens[]; int currentToken = 0; CharTermAttribute termAtt; OffsetAttribute offsetAtt; PositionIncrementAttribute posincAtt; StoredTokenStream(Token tokens[]) { this.tokens = tokens; termAtt = addAttribute(CharTermAttribute.class); offsetAtt = addAttribute(OffsetAttribute.class); posincAtt = addAttribute(PositionIncrementAttribute.class); } @Override public boolean incrementToken() throws IOException { if (currentToken >= tokens.length) { return false; } Token token = tokens[currentToken++]; clearAttributes(); termAtt.setEmpty().append(token); offsetAtt.setOffset(token.startOffset(), token.endOffset()); posincAtt .setPositionIncrement(currentToken <= 1 || tokens[currentToken - 1].startOffset() > tokens[currentToken - 2] .startOffset() ? 1 : 0); return true; } } // code to reconstruct the original sequence of Tokens String[] terms = tpv.getTerms(); int[] freq = tpv.getTermFrequencies(); int totalTokens = 0; for (int t = 0; t < freq.length; t++) { totalTokens += freq[t]; } Token tokensInOriginalOrder[] = new Token[totalTokens]; ArrayList<Token> unsortedTokens = null; for (int t = 0; t < freq.length; t++) { TermVectorOffsetInfo[] offsets = tpv.getOffsets(t); if (offsets == null) { throw new IllegalArgumentException( "Required TermVector Offset information was not found"); } int[] pos = null; if (tokenPositionsGuaranteedContiguous) { // try get the token position info to speed up assembly of tokens into // sorted sequence pos = tpv.getTermPositions(t); } if (pos == null) { // tokens NOT stored with positions or not guaranteed contiguous - must // add to list and sort later if (unsortedTokens == null) { unsortedTokens = new ArrayList<Token>(); } for (int tp = 0; tp < offsets.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp] .getEndOffset()); unsortedTokens.add(token); } } else { // We have positions stored and a guarantee that the token position // information is contiguous // This may be fast BUT wont work if Tokenizers used which create >1 // token in same position or // creates jumps in position numbers - this code would fail under those // circumstances // tokens stored with positions - can use this to index straight into // sorted array for (int tp = 0; tp < pos.length; tp++) { Token token = new Token(terms[t], offsets[tp].getStartOffset(), offsets[tp].getEndOffset()); tokensInOriginalOrder[pos[tp]] = token; } } } // If the field has been stored without position data we must perform a sort if (unsortedTokens != null) { tokensInOriginalOrder = unsortedTokens.toArray(new Token[unsortedTokens .size()]); ArrayUtil.mergeSort(tokensInOriginalOrder, new Comparator<Token>() { public int compare(Token t1, Token t2) { if (t1.startOffset() == t2.startOffset()) return t1.endOffset() - t2.endOffset(); else return t1.startOffset() - t2.startOffset(); } }); } return new StoredTokenStream(tokensInOriginalOrder); }
diff --git a/nuxeo-birt-reporting/src/main/java/org/nuxeo/ecm/platform/reporting/engine/BirtFSDeployer.java b/nuxeo-birt-reporting/src/main/java/org/nuxeo/ecm/platform/reporting/engine/BirtFSDeployer.java index cdc241e..4fbe90f 100644 --- a/nuxeo-birt-reporting/src/main/java/org/nuxeo/ecm/platform/reporting/engine/BirtFSDeployer.java +++ b/nuxeo-birt-reporting/src/main/java/org/nuxeo/ecm/platform/reporting/engine/BirtFSDeployer.java @@ -1,121 +1,123 @@ /* * (C) Copyright 2006-20011 Nuxeo SAS (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: * Nuxeo - initial API and implementation * */ package org.nuxeo.ecm.platform.reporting.engine; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.birt.core.framework.IPlatformContext; import org.nuxeo.common.Environment; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.common.utils.Path; import org.nuxeo.common.utils.ZipUtils; import org.nuxeo.ecm.platform.reporting.datasource.SupportedDBHelper; import org.nuxeo.runtime.api.Framework; /** * Because BIRT relies on Equinox deployment, this class is used to create an * OSGi/Equinox sandbox on the filesystem and start Birt deployment * * @author Tiry ([email protected]) * */ public class BirtFSDeployer implements IPlatformContext { protected String platformPath; public static final String BIRT_ZIP_NAME = "birt-runtime-all-2.6.1.zip"; protected static final String JDBC_JAR_DIR = "/plugins/org.eclipse.birt.report.data.oda.jdbc_2.6.1.v20100909/drivers/"; protected static Log log = LogFactory.getLog(BirtFSDeployer.class); public BirtFSDeployer() { } @Override public String getPlatform() { if (platformPath == null) { synchronized (this) { if (platformPath == null) { deployBirtPlatform(); } } } return platformPath; } /** * deploy the platform resources to file based platform. * */ protected void deployBirtPlatform() { if (platformPath == null) { File dataDir = Environment.getDefault().getData(); if (Framework.isTestModeSet()) { // runtime path will be removed too soon. - String dirPath = new Path(System.getProperty("java.io.tmpdir")).append( + String jarDestination = System.getProperty("java.io.tmpdir").contains("+") ? + "/tmp" : System.getProperty("java.io.tmpdir"); + String dirPath = new Path(jarDestination).append( "birt-fs" + System.currentTimeMillis()).toString(); dataDir = new File(dirPath); dataDir.mkdir(); } File birtPlatformFolder = new File(dataDir, "birt-platform"); birtPlatformFolder.mkdir(); try { copyResources(BIRT_ZIP_NAME, birtPlatformFolder); if (!Framework.isTestModeSet()) { // also need to copy the JDBC drivers List<String> driverJars = SupportedDBHelper.getDriverJars(); String targetPath = birtPlatformFolder.getAbsolutePath() + JDBC_JAR_DIR; for (String driverJar : driverJars) { FileUtils.copyFile(new File(driverJar), new File( targetPath)); } } } catch (Exception e) { log.error( "Error while copying birt resources into working dir", e); } platformPath = birtPlatformFolder.getAbsolutePath(); } } protected void copyResources(String resourcePath, File dir) throws Exception { URL url = Thread.currentThread().getContextClassLoader().getResource( resourcePath); if ("jar".equals(url.getProtocol())) { String jarPath = url.getFile().split("!")[0].replace("file:", ""); InputStream zipStream = ZipUtils.getEntryContentAsStream(new File( jarPath), BIRT_ZIP_NAME); ZipUtils.unzip(zipStream, dir); } else { // unziped jar (unit tests) File source = new File(url.toURI()); ZipUtils.unzip(source, dir); } } }
true
true
protected void deployBirtPlatform() { if (platformPath == null) { File dataDir = Environment.getDefault().getData(); if (Framework.isTestModeSet()) { // runtime path will be removed too soon. String dirPath = new Path(System.getProperty("java.io.tmpdir")).append( "birt-fs" + System.currentTimeMillis()).toString(); dataDir = new File(dirPath); dataDir.mkdir(); } File birtPlatformFolder = new File(dataDir, "birt-platform"); birtPlatformFolder.mkdir(); try { copyResources(BIRT_ZIP_NAME, birtPlatformFolder); if (!Framework.isTestModeSet()) { // also need to copy the JDBC drivers List<String> driverJars = SupportedDBHelper.getDriverJars(); String targetPath = birtPlatformFolder.getAbsolutePath() + JDBC_JAR_DIR; for (String driverJar : driverJars) { FileUtils.copyFile(new File(driverJar), new File( targetPath)); } } } catch (Exception e) { log.error( "Error while copying birt resources into working dir", e); } platformPath = birtPlatformFolder.getAbsolutePath(); } }
protected void deployBirtPlatform() { if (platformPath == null) { File dataDir = Environment.getDefault().getData(); if (Framework.isTestModeSet()) { // runtime path will be removed too soon. String jarDestination = System.getProperty("java.io.tmpdir").contains("+") ? "/tmp" : System.getProperty("java.io.tmpdir"); String dirPath = new Path(jarDestination).append( "birt-fs" + System.currentTimeMillis()).toString(); dataDir = new File(dirPath); dataDir.mkdir(); } File birtPlatformFolder = new File(dataDir, "birt-platform"); birtPlatformFolder.mkdir(); try { copyResources(BIRT_ZIP_NAME, birtPlatformFolder); if (!Framework.isTestModeSet()) { // also need to copy the JDBC drivers List<String> driverJars = SupportedDBHelper.getDriverJars(); String targetPath = birtPlatformFolder.getAbsolutePath() + JDBC_JAR_DIR; for (String driverJar : driverJars) { FileUtils.copyFile(new File(driverJar), new File( targetPath)); } } } catch (Exception e) { log.error( "Error while copying birt resources into working dir", e); } platformPath = birtPlatformFolder.getAbsolutePath(); } }
diff --git a/stax-mate/src/test/java/com/cedarsoft/serialization/stax/SerializingStrategySupportTest.java b/stax-mate/src/test/java/com/cedarsoft/serialization/stax/SerializingStrategySupportTest.java index f34767e3..3272e68a 100644 --- a/stax-mate/src/test/java/com/cedarsoft/serialization/stax/SerializingStrategySupportTest.java +++ b/stax-mate/src/test/java/com/cedarsoft/serialization/stax/SerializingStrategySupportTest.java @@ -1,78 +1,81 @@ package com.cedarsoft.serialization.stax; import com.cedarsoft.Version; import com.cedarsoft.serialization.SerializingStrategySupport; import org.codehaus.staxmate.out.SMOutputElement; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.testng.annotations.*; import javax.xml.stream.XMLStreamReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * */ public class SerializingStrategySupportTest { @Test public void testGenerics() { SerializingStrategySupport<String, MyStrategy> support = new SerializingStrategySupport<String, MyStrategy>( Arrays.asList( new MyStrategy() ) ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support2 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( Arrays.asList( new MyStrategy() ) ); List<StaxMateSerializingStrategy<? extends String>> strategies1 = Arrays.<StaxMateSerializingStrategy<? extends String>>asList( new MyStrategy() ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support5 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies1 ); Collection<? extends StaxMateSerializingStrategy<? extends String>> strategies = new ArrayList<StaxMateSerializingStrategy<? extends String>>(); - SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support3 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies ); + try { + SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support3 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies ); + } catch ( Exception ignore ) { + } } private static class MyStrategy implements StaxMateSerializingStrategy<String> { @Override @NotNull public String getId() { throw new UnsupportedOperationException(); } @Override public void serialize( @NotNull String object, @NotNull OutputStream out ) throws IOException { throw new UnsupportedOperationException(); } @NotNull @Override public String deserialize( @NotNull InputStream in ) throws IOException { throw new UnsupportedOperationException(); } @NotNull @Override public Version getFormatVersion() { throw new UnsupportedOperationException(); } @Override public boolean supports( @NotNull Object object ) { throw new UnsupportedOperationException(); } @Override @NotNull public SMOutputElement serialize( @NotNull SMOutputElement serializeTo, @NotNull String object ) throws IOException { throw new UnsupportedOperationException(); } @Override @NotNull public String deserialize( @NotNull @NonNls XMLStreamReader deserializeFrom ) throws IOException { throw new UnsupportedOperationException(); } } }
true
true
public void testGenerics() { SerializingStrategySupport<String, MyStrategy> support = new SerializingStrategySupport<String, MyStrategy>( Arrays.asList( new MyStrategy() ) ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support2 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( Arrays.asList( new MyStrategy() ) ); List<StaxMateSerializingStrategy<? extends String>> strategies1 = Arrays.<StaxMateSerializingStrategy<? extends String>>asList( new MyStrategy() ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support5 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies1 ); Collection<? extends StaxMateSerializingStrategy<? extends String>> strategies = new ArrayList<StaxMateSerializingStrategy<? extends String>>(); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support3 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies ); }
public void testGenerics() { SerializingStrategySupport<String, MyStrategy> support = new SerializingStrategySupport<String, MyStrategy>( Arrays.asList( new MyStrategy() ) ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support2 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( Arrays.asList( new MyStrategy() ) ); List<StaxMateSerializingStrategy<? extends String>> strategies1 = Arrays.<StaxMateSerializingStrategy<? extends String>>asList( new MyStrategy() ); SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support5 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies1 ); Collection<? extends StaxMateSerializingStrategy<? extends String>> strategies = new ArrayList<StaxMateSerializingStrategy<? extends String>>(); try { SerializingStrategySupport<String, StaxMateSerializingStrategy<String>> support3 = new SerializingStrategySupport<String, StaxMateSerializingStrategy<String>>( strategies ); } catch ( Exception ignore ) { } }
diff --git a/src/com/cyanogenmod/cmparts/activities/InputActivity.java b/src/com/cyanogenmod/cmparts/activities/InputActivity.java index b66dc35..066f4e6 100644 --- a/src/com/cyanogenmod/cmparts/activities/InputActivity.java +++ b/src/com/cyanogenmod/cmparts/activities/InputActivity.java @@ -1,222 +1,216 @@ package com.cyanogenmod.cmparts.activities; import com.cyanogenmod.cmparts.R; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.provider.Settings; import java.io.File; import java.util.ArrayList; public class InputActivity extends PreferenceActivity implements OnPreferenceChangeListener { private static final String TRACKBALL_WAKE_PREF = "pref_trackball_wake"; private static final String VOLBTN_MUSIC_CTRL_PREF = "pref_volbtn_music_controls"; private static final String CAMBTN_MUSIC_CTRL_PREF = "pref_cambtn_music_controls"; private static final String BUTTON_CATEGORY = "pref_category_button_settings"; private static final String USER_DEFINED_KEY1 = "pref_user_defined_key1"; private static final String USER_DEFINED_KEY2 = "pref_user_defined_key2"; private static final String USER_DEFINED_KEY3 = "pref_user_defined_key3"; private CheckBoxPreference mTrackballWakePref; private CheckBoxPreference mVolBtnMusicCtrlPref; private CheckBoxPreference mCamBtnMusicCtrlPref; private Preference mUserDefinedKey1Pref; private Preference mUserDefinedKey2Pref; private Preference mUserDefinedKey3Pref; private int mKeyNumber = 1; private static final int REQUEST_PICK_SHORTCUT = 1; private static final int REQUEST_PICK_APPLICATION = 2; private static final int REQUEST_CREATE_SHORTCUT = 3; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.input_settings_title_subhead); addPreferencesFromResource(R.xml.input_settings); PreferenceScreen prefSet = getPreferenceScreen(); /* Trackball Wake */ mTrackballWakePref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_WAKE_PREF); mTrackballWakePref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_WAKE_SCREEN, 0) == 1); /* Volume button music controls */ mVolBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(VOLBTN_MUSIC_CTRL_PREF); mVolBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.VOLBTN_MUSIC_CONTROLS, 1) == 1); mCamBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(CAMBTN_MUSIC_CTRL_PREF); mCamBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.CAMBTN_MUSIC_CONTROLS, 0) == 1); PreferenceCategory buttonCategory = (PreferenceCategory)prefSet.findPreference(BUTTON_CATEGORY); mUserDefinedKey1Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY1); mUserDefinedKey2Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY2); mUserDefinedKey3Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY3); - if (!"vision".equals(Build.DEVICE) && - !getResources().getBoolean(R.bool.has_trackball) && - !getResources().getBoolean(R.bool.has_camera_button)) { - prefSet.removePreference(buttonCategory); - } else { - if (!getResources().getBoolean(R.bool.has_trackball)) { - buttonCategory.removePreference(mTrackballWakePref); - } - if (!getResources().getBoolean(R.bool.has_camera_button)) { - buttonCategory.removePreference(mCamBtnMusicCtrlPref); - } - if (!"vision".equals(Build.DEVICE)) { - buttonCategory.removePreference(mUserDefinedKey1Pref); - buttonCategory.removePreference(mUserDefinedKey2Pref); - buttonCategory.removePreference(mUserDefinedKey3Pref); - } + if (!getResources().getBoolean(R.bool.has_trackball)) { + buttonCategory.removePreference(mTrackballWakePref); + } + if (!getResources().getBoolean(R.bool.has_camera_button)) { + buttonCategory.removePreference(mCamBtnMusicCtrlPref); + } + if (!"vision".equals(Build.DEVICE)) { + buttonCategory.removePreference(mUserDefinedKey1Pref); + buttonCategory.removePreference(mUserDefinedKey2Pref); + buttonCategory.removePreference(mUserDefinedKey3Pref); } } @Override public void onResume() { super.onResume(); mUserDefinedKey1Pref.setSummary(Settings.System.getString(getContentResolver(), Settings.System.USER_DEFINED_KEY1_APP)); mUserDefinedKey2Pref.setSummary(Settings.System.getString(getContentResolver(), Settings.System.USER_DEFINED_KEY2_APP)); mUserDefinedKey3Pref.setSummary(Settings.System.getString(getContentResolver(), Settings.System.USER_DEFINED_KEY3_APP)); } public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { boolean value; if (preference == mTrackballWakePref) { value = mTrackballWakePref.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.TRACKBALL_WAKE_SCREEN, value ? 1 : 0); return true; } else if (preference == mVolBtnMusicCtrlPref) { value = mVolBtnMusicCtrlPref.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.VOLBTN_MUSIC_CONTROLS, value ? 1 : 0); return true; } else if (preference == mCamBtnMusicCtrlPref) { value = mCamBtnMusicCtrlPref.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.CAMBTN_MUSIC_CONTROLS, value ? 1 : 0); return true; } else if (preference == mUserDefinedKey1Pref) { pickShortcut(1); return true; } else if (preference == mUserDefinedKey2Pref) { pickShortcut(2); return true; } else if (preference == mUserDefinedKey3Pref) { pickShortcut(3); return true; } return false; } public boolean onPreferenceChange(Preference preference, Object newValue) { return false; } private void pickShortcut(int keyNumber) { mKeyNumber = keyNumber; Bundle bundle = new Bundle(); ArrayList<String> shortcutNames = new ArrayList<String>(); shortcutNames.add(getString(R.string.group_applications)); bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>(); shortcutIcons.add(ShortcutIconResource.fromContext(this, R.drawable.ic_launcher_application)); bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT)); pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.select_custom_app_title)); pickIntent.putExtras(bundle); startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_PICK_APPLICATION: completeSetCustomApp(data); break; case REQUEST_CREATE_SHORTCUT: completeSetCustomShortcut(data); break; case REQUEST_PICK_SHORTCUT: processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT); break; } } } void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) { // Handle case where user selected "Applications" String applicationName = getResources().getString(R.string.group_applications); String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); if (applicationName != null && applicationName.equals(shortcutName)) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); startActivityForResult(pickIntent, requestCodeApplication); } else { startActivityForResult(intent, requestCodeShortcut); } } void completeSetCustomShortcut(Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); int keyNumber = mKeyNumber; if (keyNumber == 1){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY1_APP, intent.toUri(0))) { mUserDefinedKey1Pref.setSummary(intent.toUri(0)); } } else if (keyNumber == 2){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY2_APP, intent.toUri(0))) { mUserDefinedKey2Pref.setSummary(intent.toUri(0)); } } else if (keyNumber == 3){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY3_APP, intent.toUri(0))) { mUserDefinedKey3Pref.setSummary(intent.toUri(0)); } } } void completeSetCustomApp(Intent data) { int keyNumber = mKeyNumber; if (keyNumber == 1){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY1_APP, data.toUri(0))) { mUserDefinedKey1Pref.setSummary(data.toUri(0)); } } else if (keyNumber == 2){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY2_APP, data.toUri(0))) { mUserDefinedKey2Pref.setSummary(data.toUri(0)); } } else if (keyNumber == 3){ if (Settings.System.putString(getContentResolver(), Settings.System.USER_DEFINED_KEY3_APP, data.toUri(0))) { mUserDefinedKey3Pref.setSummary(data.toUri(0)); } } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.input_settings_title_subhead); addPreferencesFromResource(R.xml.input_settings); PreferenceScreen prefSet = getPreferenceScreen(); /* Trackball Wake */ mTrackballWakePref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_WAKE_PREF); mTrackballWakePref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_WAKE_SCREEN, 0) == 1); /* Volume button music controls */ mVolBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(VOLBTN_MUSIC_CTRL_PREF); mVolBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.VOLBTN_MUSIC_CONTROLS, 1) == 1); mCamBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(CAMBTN_MUSIC_CTRL_PREF); mCamBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.CAMBTN_MUSIC_CONTROLS, 0) == 1); PreferenceCategory buttonCategory = (PreferenceCategory)prefSet.findPreference(BUTTON_CATEGORY); mUserDefinedKey1Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY1); mUserDefinedKey2Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY2); mUserDefinedKey3Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY3); if (!"vision".equals(Build.DEVICE) && !getResources().getBoolean(R.bool.has_trackball) && !getResources().getBoolean(R.bool.has_camera_button)) { prefSet.removePreference(buttonCategory); } else { if (!getResources().getBoolean(R.bool.has_trackball)) { buttonCategory.removePreference(mTrackballWakePref); } if (!getResources().getBoolean(R.bool.has_camera_button)) { buttonCategory.removePreference(mCamBtnMusicCtrlPref); } if (!"vision".equals(Build.DEVICE)) { buttonCategory.removePreference(mUserDefinedKey1Pref); buttonCategory.removePreference(mUserDefinedKey2Pref); buttonCategory.removePreference(mUserDefinedKey3Pref); } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.input_settings_title_subhead); addPreferencesFromResource(R.xml.input_settings); PreferenceScreen prefSet = getPreferenceScreen(); /* Trackball Wake */ mTrackballWakePref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_WAKE_PREF); mTrackballWakePref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_WAKE_SCREEN, 0) == 1); /* Volume button music controls */ mVolBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(VOLBTN_MUSIC_CTRL_PREF); mVolBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.VOLBTN_MUSIC_CONTROLS, 1) == 1); mCamBtnMusicCtrlPref = (CheckBoxPreference) prefSet.findPreference(CAMBTN_MUSIC_CTRL_PREF); mCamBtnMusicCtrlPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.CAMBTN_MUSIC_CONTROLS, 0) == 1); PreferenceCategory buttonCategory = (PreferenceCategory)prefSet.findPreference(BUTTON_CATEGORY); mUserDefinedKey1Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY1); mUserDefinedKey2Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY2); mUserDefinedKey3Pref = (Preference) prefSet.findPreference(USER_DEFINED_KEY3); if (!getResources().getBoolean(R.bool.has_trackball)) { buttonCategory.removePreference(mTrackballWakePref); } if (!getResources().getBoolean(R.bool.has_camera_button)) { buttonCategory.removePreference(mCamBtnMusicCtrlPref); } if (!"vision".equals(Build.DEVICE)) { buttonCategory.removePreference(mUserDefinedKey1Pref); buttonCategory.removePreference(mUserDefinedKey2Pref); buttonCategory.removePreference(mUserDefinedKey3Pref); } }
diff --git a/org.facttype.diagram/src/org/facttype/formatting/DiagramFormatter.java b/org.facttype.diagram/src/org/facttype/formatting/DiagramFormatter.java index bb4697e..14a7842 100644 --- a/org.facttype.diagram/src/org/facttype/formatting/DiagramFormatter.java +++ b/org.facttype.diagram/src/org/facttype/formatting/DiagramFormatter.java @@ -1,322 +1,320 @@ /* * generated by Xtext */ package org.facttype.formatting; import org.eclipse.xtext.Keyword; import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter; import org.eclipse.xtext.formatting.impl.FormattingConfig; import org.eclipse.xtext.util.Pair; import org.facttype.services.DiagramGrammarAccess; /** * This class contains custom formatting description. * * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting * on how and when to use it * * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an example */ public class DiagramFormatter extends AbstractDeclarativeFormatter { @Override protected void configureFormatting(FormattingConfig c) { DiagramGrammarAccess f = (DiagramGrammarAccess) getGrammarAccess(); // Allow a width of 120. c.setAutoLinewrap(120); // Find common keywords and specify formatting for them. for (Pair<Keyword, Keyword> pair : f.findKeywordPairs("(", ")")) { c.setNoSpace().after(pair.getFirst()); c.setNoSpace().before(pair.getSecond()); } for (Keyword comma : f.findKeywords(",")) { c.setNoSpace().before(comma); c.setNoSpace().after(comma); } /* * Formatting for grammar rule types: * types { * String (10) * Number (2, 1) * } */ c.setIndentationIncrement().before ( f.getTypeAccess().getNameAssignment_0()); c.setIndentationDecrement().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().before( f.getTypeAccess().getNameAssignment_0()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap(2).after( f.getDiagramAccess().getRightCurlyBracketKeyword_2()); /* * Formatting for factTypeDiagram. */ c.setLinewrap().after( f.getFactTypeDiagramAccess().getDescriptionAssignment_3()); c.setIndentationIncrement().after ( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); -// c.setIndentationDecrement().before( -// f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); + c.setIndentationDecrement().before( + f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); -// c.setLinewrap().before( -// f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_8()); -// c.setLinewrap().after( -// f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_8()); + c.setLinewrap().before( + f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); + c.setLinewrap().after( + f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for sentence. */ c.setIndentationIncrement().after ( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setIndentationDecrement().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setLinewrap().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); /* * Formatting for column. */ c.setIndentationIncrement().after ( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); -// c.setIndentationDecrement().before( -// f.getColumnAccess().getRightCurlyBracketKeyword_12()); + c.setIndentationDecrement().before( + f.getColumnAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); -// c.setLinewrap().before( -// f.getColumnAccess().getRightCurlyBracketKeyword_12()); -// c.setLinewrap().after( -// f.getColumnAccess().getRightCurlyBracketKeyword_12()); + c.setLinewrap().before( + f.getColumnAccess().getRightCurlyBracketKeyword_11()); + c.setLinewrap().after( + f.getColumnAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().before( f.getColumnAccess().getTypeKeyword_5()); -// c.setLinewrap().before( -// f.getColumnAccess().getPrimaryKeyPrimaryKeyKeyword_7_0()); c.setLinewrap().before( f.getColumnAccess().getNotEmptyNotEmptyKeyword_7_0()); c.setLinewrap().before( f.getColumnAccess().getValuesKeyword_8()); /* * Formatting for alternative key. */ c.setIndentationIncrement().after ( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); /* * Formatting for SubsetRule. */ c.setIndentationIncrement().after ( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getSubsetRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getSubsetRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getSubsetRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for EqualityRule. */ c.setIndentationIncrement().after ( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getEqualityRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for PartialEqualityRule. */ c.setIndentationIncrement().after ( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getExcludingAssignment_5()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getColumnsKeyword_9()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); /* * Formatting for OccurrenceFrequencyRule. */ c.setIndentationIncrement().after ( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMinimumAssignment_4()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMaximumAssignment_5()); c.setLinewrap().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for NoOverlappingRule. */ c.setIndentationIncrement().after ( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for ExclusionRule. */ c.setIndentationIncrement().after ( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getExclusionRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getExclusionRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for GeneralConstraint. */ c.setIndentationIncrement().after ( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getGeneralConstraintAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for EventRule. */ c.setIndentationIncrement().after ( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEventRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getEventRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for DerivationRule. */ c.setIndentationIncrement().after ( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getDerivationRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getDerivationRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for ValueRule. */ c.setIndentationIncrement().after ( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getValueRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getValueRuleAccess().getColumnsKeyword_6()); c.setLinewrap().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for Comments. * It's usually a good idea to activate the following three statements. * They will add and preserve newlines around comments. */ c.setLinewrap(0, 1, 2).before(f.getSL_COMMENTRule()); c.setLinewrap(0, 1, 2).before(f.getML_COMMENTRule()); c.setLinewrap(0, 1, 1).after(f.getML_COMMENTRule()); } }
false
true
protected void configureFormatting(FormattingConfig c) { DiagramGrammarAccess f = (DiagramGrammarAccess) getGrammarAccess(); // Allow a width of 120. c.setAutoLinewrap(120); // Find common keywords and specify formatting for them. for (Pair<Keyword, Keyword> pair : f.findKeywordPairs("(", ")")) { c.setNoSpace().after(pair.getFirst()); c.setNoSpace().before(pair.getSecond()); } for (Keyword comma : f.findKeywords(",")) { c.setNoSpace().before(comma); c.setNoSpace().after(comma); } /* * Formatting for grammar rule types: * types { * String (10) * Number (2, 1) * } */ c.setIndentationIncrement().before ( f.getTypeAccess().getNameAssignment_0()); c.setIndentationDecrement().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().before( f.getTypeAccess().getNameAssignment_0()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap(2).after( f.getDiagramAccess().getRightCurlyBracketKeyword_2()); /* * Formatting for factTypeDiagram. */ c.setLinewrap().after( f.getFactTypeDiagramAccess().getDescriptionAssignment_3()); c.setIndentationIncrement().after ( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); // c.setIndentationDecrement().before( // f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); // c.setLinewrap().before( // f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_8()); // c.setLinewrap().after( // f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_8()); /* * Formatting for sentence. */ c.setIndentationIncrement().after ( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setIndentationDecrement().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setLinewrap().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); /* * Formatting for column. */ c.setIndentationIncrement().after ( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); // c.setIndentationDecrement().before( // f.getColumnAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); // c.setLinewrap().before( // f.getColumnAccess().getRightCurlyBracketKeyword_12()); // c.setLinewrap().after( // f.getColumnAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().before( f.getColumnAccess().getTypeKeyword_5()); // c.setLinewrap().before( // f.getColumnAccess().getPrimaryKeyPrimaryKeyKeyword_7_0()); c.setLinewrap().before( f.getColumnAccess().getNotEmptyNotEmptyKeyword_7_0()); c.setLinewrap().before( f.getColumnAccess().getValuesKeyword_8()); /* * Formatting for alternative key. */ c.setIndentationIncrement().after ( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); /* * Formatting for SubsetRule. */ c.setIndentationIncrement().after ( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getSubsetRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getSubsetRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getSubsetRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for EqualityRule. */ c.setIndentationIncrement().after ( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getEqualityRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for PartialEqualityRule. */ c.setIndentationIncrement().after ( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getExcludingAssignment_5()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getColumnsKeyword_9()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); /* * Formatting for OccurrenceFrequencyRule. */ c.setIndentationIncrement().after ( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMinimumAssignment_4()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMaximumAssignment_5()); c.setLinewrap().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for NoOverlappingRule. */ c.setIndentationIncrement().after ( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for ExclusionRule. */ c.setIndentationIncrement().after ( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getExclusionRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getExclusionRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for GeneralConstraint. */ c.setIndentationIncrement().after ( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getGeneralConstraintAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for EventRule. */ c.setIndentationIncrement().after ( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEventRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getEventRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for DerivationRule. */ c.setIndentationIncrement().after ( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getDerivationRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getDerivationRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for ValueRule. */ c.setIndentationIncrement().after ( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getValueRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getValueRuleAccess().getColumnsKeyword_6()); c.setLinewrap().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for Comments. * It's usually a good idea to activate the following three statements. * They will add and preserve newlines around comments. */ c.setLinewrap(0, 1, 2).before(f.getSL_COMMENTRule()); c.setLinewrap(0, 1, 2).before(f.getML_COMMENTRule()); c.setLinewrap(0, 1, 1).after(f.getML_COMMENTRule()); }
protected void configureFormatting(FormattingConfig c) { DiagramGrammarAccess f = (DiagramGrammarAccess) getGrammarAccess(); // Allow a width of 120. c.setAutoLinewrap(120); // Find common keywords and specify formatting for them. for (Pair<Keyword, Keyword> pair : f.findKeywordPairs("(", ")")) { c.setNoSpace().after(pair.getFirst()); c.setNoSpace().before(pair.getSecond()); } for (Keyword comma : f.findKeywords(",")) { c.setNoSpace().before(comma); c.setNoSpace().after(comma); } /* * Formatting for grammar rule types: * types { * String (10) * Number (2, 1) * } */ c.setIndentationIncrement().before ( f.getTypeAccess().getNameAssignment_0()); c.setIndentationDecrement().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().before( f.getTypeAccess().getNameAssignment_0()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap().after( f.getTypeAccess().getRightParenthesisKeyword_4()); c.setLinewrap(2).after( f.getDiagramAccess().getRightCurlyBracketKeyword_2()); /* * Formatting for factTypeDiagram. */ c.setLinewrap().after( f.getFactTypeDiagramAccess().getDescriptionAssignment_3()); c.setIndentationIncrement().after ( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getFactTypeDiagramAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().before( f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getFactTypeDiagramAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for sentence. */ c.setIndentationIncrement().after ( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setIndentationDecrement().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getSentenceTemplateKeyword_0()); c.setLinewrap().before( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); c.setLinewrap().after( f.getSentenceTemplateAccess().getRightCurlyBracketKeyword_3()); /* * Formatting for column. */ c.setIndentationIncrement().after ( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getColumnAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getColumnAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().before( f.getColumnAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getColumnAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().before( f.getColumnAccess().getTypeKeyword_5()); c.setLinewrap().before( f.getColumnAccess().getNotEmptyNotEmptyKeyword_7_0()); c.setLinewrap().before( f.getColumnAccess().getValuesKeyword_8()); /* * Formatting for alternative key. */ c.setIndentationIncrement().after ( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().before( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); c.setLinewrap().after( f.getAlternativeKeyAccess().getRightCurlyBracketKeyword_4()); /* * Formatting for SubsetRule. */ c.setIndentationIncrement().after ( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getSubsetRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getSubsetRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getSubsetRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getSubsetRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for EqualityRule. */ c.setIndentationIncrement().after ( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().before( f.getEqualityRuleAccess().getColumnsKeyword_8()); c.setLinewrap().before( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); c.setLinewrap().after( f.getEqualityRuleAccess().getRightCurlyBracketKeyword_11()); /* * Formatting for PartialEqualityRule. */ c.setIndentationIncrement().after ( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getSuperAssignment_4()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getExcludingAssignment_5()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getColumnsKeyword_9()); c.setLinewrap().before( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); c.setLinewrap().after( f.getPartialEqualityRuleAccess().getRightCurlyBracketKeyword_12()); /* * Formatting for OccurrenceFrequencyRule. */ c.setIndentationIncrement().after ( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMinimumAssignment_4()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getMaximumAssignment_5()); c.setLinewrap().before( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getOccurrenceFrequencyRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for NoOverlappingRule. */ c.setIndentationIncrement().after ( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getNoOverlappingRuleAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for ExclusionRule. */ c.setIndentationIncrement().after ( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getExclusionRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getExclusionRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getExclusionRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for GeneralConstraint. */ c.setIndentationIncrement().after ( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getGeneralConstraintAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); c.setLinewrap().after( f.getGeneralConstraintAccess().getRightCurlyBracketKeyword_7()); /* * Formatting for EventRule. */ c.setIndentationIncrement().after ( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getEventRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getEventRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getEventRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for DerivationRule. */ c.setIndentationIncrement().after ( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getDerivationRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getDerivationRuleAccess().getColumnsKeyword_7()); c.setLinewrap().before( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); c.setLinewrap().after( f.getDerivationRuleAccess().getRightCurlyBracketKeyword_10()); /* * Formatting for ValueRule. */ c.setIndentationIncrement().after ( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setIndentationDecrement().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getLeftCurlyBracketKeyword_2()); c.setLinewrap().after( f.getValueRuleAccess().getDescriptionAssignment_3()); c.setLinewrap().before( f.getValueRuleAccess().getColumnsKeyword_6()); c.setLinewrap().before( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); c.setLinewrap().after( f.getValueRuleAccess().getRightCurlyBracketKeyword_9()); /* * Formatting for Comments. * It's usually a good idea to activate the following three statements. * They will add and preserve newlines around comments. */ c.setLinewrap(0, 1, 2).before(f.getSL_COMMENTRule()); c.setLinewrap(0, 1, 2).before(f.getML_COMMENTRule()); c.setLinewrap(0, 1, 1).after(f.getML_COMMENTRule()); }
diff --git a/src/org/broad/igv/sam/CachingQueryReader.java b/src/org/broad/igv/sam/CachingQueryReader.java index fc107993..fd3c2468 100755 --- a/src/org/broad/igv/sam/CachingQueryReader.java +++ b/src/org/broad/igv/sam/CachingQueryReader.java @@ -1,802 +1,803 @@ /* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.sam; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.util.CloseableIterator; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.exceptions.DataLoadException; import org.broad.igv.feature.SpliceJunctionFeature; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.LRUCache; import org.broad.igv.util.ObjectCache; import org.broad.igv.util.RuntimeUtils; import org.broad.tribble.Feature; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.*; /** * A wrapper for an AlignmentQueryReader that caches query results * * @author jrobinso */ public class CachingQueryReader { private static Logger log = Logger.getLogger(CachingQueryReader.class); //private static final int LOW_MEMORY_THRESHOLD = 150000000; private static final int KB = 1000; private static final int MITOCHONDRIA_TILE_SIZE = 1000; private static int MAX_TILE_COUNT = 10; private static Set<WeakReference<CachingQueryReader>> activeReaders = Collections.synchronizedSet(new HashSet()); /** * Flag to mark a corrupt index. Without this attempted reads will continue in an infinite loop */ private boolean corruptIndex = false; private float visibilityWindow = 16; // Visibility window, in KB private String cachedChr = ""; private int tileSize; private AlignmentReader reader; private boolean cancel = false; private LRUCache<Integer, AlignmentTile> cache; private boolean pairedEnd = false; // Map of read group -> paired end stats //private PairedEndStats peStats; private static void cancelReaders() { for (WeakReference<CachingQueryReader> readerRef : activeReaders) { CachingQueryReader reader = readerRef.get(); if (reader != null) { reader.cancel = true; } } log.debug("Readers canceled"); activeReaders.clear(); } public CachingQueryReader(AlignmentReader reader) { this.reader = reader; activeReaders.add(new WeakReference<CachingQueryReader>(this)); updateCache(); } public static void visibilityWindowChanged() { for (WeakReference<CachingQueryReader> readerRef : activeReaders) { CachingQueryReader reader = readerRef.get(); if (reader != null) { reader.updateCache(); } } } private void updateCache() { float fvw = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MAX_VISIBLE_RANGE); // If the visibility window has changed by more than a factor of 2 change cache tile size float ratio = fvw / visibilityWindow; if (cache == null || (ratio < 0.5 || ratio > 2)) { // Set tile size to the visibility window tileSize = (int) (fvw * KB); cache = new LRUCache(this, MAX_TILE_COUNT); visibilityWindow = fvw; } } public AlignmentReader getWrappedReader() { return reader; } public void close() throws IOException { reader.close(); } public List<String> getSequenceNames() { return reader.getSequenceNames(); } public CloseableIterator<Alignment> iterator() { return reader.iterator(); } public boolean hasIndex() { return reader.hasIndex(); } public CloseableIterator<Alignment> query(String sequence, int start, int end, List<AlignmentCounts> counts, List<SpliceJunctionFeature> spliceJunctionFeatures, List<DownsampledInterval> downsampledIntervals, AlignmentDataManager.DownsampleOptions downsampleOptions, Map<String, PEStats> peStats, AlignmentTrack.BisulfiteContext bisulfiteContext) { // Get the tiles covering this interval int startTile = (start + 1) / getTileSize(sequence); int endTile = end / getTileSize(sequence); // <= inclusive List<AlignmentTile> tiles = getTiles(sequence, startTile, endTile, downsampleOptions, peStats, bisulfiteContext); if (tiles.size() == 0) { return EmptyAlignmentIterator.getInstance(); } // Count total # of records int recordCount = tiles.get(0).getOverlappingRecords().size(); for (AlignmentTile t : tiles) { recordCount += t.getContainedRecords().size(); } List<Alignment> alignments = new ArrayList(recordCount); alignments.addAll(tiles.get(0).getOverlappingRecords()); if (spliceJunctionFeatures != null) { List<SpliceJunctionFeature> tmp = tiles.get(0).getOverlappingSpliceJunctionFeatures(); if (tmp != null) spliceJunctionFeatures.addAll(tmp); } for (AlignmentTile t : tiles) { alignments.addAll(t.getContainedRecords()); counts.add(t.getCounts()); downsampledIntervals.addAll(t.getDownsampledIntervals()); if (spliceJunctionFeatures != null) { List<SpliceJunctionFeature> tmp = t.getContainedSpliceJunctionFeatures(); if (tmp != null) spliceJunctionFeatures.addAll(tmp); } } // Since we added in 2 passes, and downsampled, we need to sort Collections.sort(alignments, new AlignmentSorter()); return new TiledIterator(start, end, alignments); } public List<AlignmentTile> getTiles(String seq, int startTile, int endTile, AlignmentDataManager.DownsampleOptions downsampleOptions, Map<String, PEStats> peStats, AlignmentTrack.BisulfiteContext bisulfiteContext) { if (!seq.equals(cachedChr)) { cache.clear(); cachedChr = seq; } List<AlignmentTile> tiles = new ArrayList(endTile - startTile + 1); List<AlignmentTile> tilesToLoad = new ArrayList(endTile - startTile + 1); int tileSize = getTileSize(seq); for (int t = startTile; t <= endTile; t++) { AlignmentTile tile = cache.get(t); if (tile == null) { int start = t * tileSize; int end = start + tileSize; tile = new AlignmentTile(t, start, end, downsampleOptions, bisulfiteContext); } tiles.add(tile); // The current tile is loaded, load any preceding tiles we have pending and clear "to load" list if (tile.isLoaded()) { if (tilesToLoad.size() > 0) { boolean success = loadTiles(seq, tilesToLoad, peStats); if (!success) { // Loading was canceled, return what we have return tiles; } } tilesToLoad.clear(); } else { tilesToLoad.add(tile); } } if (tilesToLoad.size() > 0) { loadTiles(seq, tilesToLoad, peStats); } return tiles; } /** * Load alignments for the list of tiles * * @param chr Only tiles on this chromosome will be loaded * @param tiles * @param peStats * @return true if successful, false if canceled. */ private boolean loadTiles(String chr, List<AlignmentTile> tiles, Map<String, PEStats> peStats) { //assert (tiles.size() > 0); if (corruptIndex) { return false; } boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); //maxReadCount = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_MAX_READS); if (log.isDebugEnabled()) { int first = tiles.get(0).getTileNumber(); int end = tiles.get(tiles.size() - 1).getTileNumber(); log.debug("Loading tiles: " + first + "-" + end); } int start = tiles.get(0).start; int end = tiles.get(tiles.size() - 1).end; CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<CachingQueryReader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeReaders.add(ref); iter = reader.query(chr, start, end, false); int tileSize = getTileSize(chr); while (iter != null && iter.hasNext()) { if (cancel) { return false; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } // Range of tile indices that this alignment contributes to. int aStart = record.getStart(); int aEnd = record.getEnd(); int idx0 = Math.max(0, (aStart - start) / tileSize); int idx1 = Math.min(tiles.size() - 1, (aEnd - start) / tileSize); // Loop over tiles this read overlaps for (int i = idx0; i <= idx1; i++) { AlignmentTile t = null; t = tiles.get(i); t.addRecord(record); } alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return false; MessageUtils.setStatusBarMessage("Reads loaded: " + alignmentCount); if (checkMemory() == false) { cancelReaders(); return false; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } mappedMates = null; unmappedMates = null; for (AlignmentTile t : tiles) { t.setLoaded(true); cache.put(t.getTileNumber(), t); } return true; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return false; - } catch (IOException e) { + } catch (Exception e) { log.error("Error loading alignment data", e); - throw new DataLoadException("", "Error: " + e.toString()); + MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString()); + return false; } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeReaders.remove(ref); if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } } private static synchronized boolean checkMemory() { if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { LRUCache.clearCaches(); System.gc(); if (RuntimeUtils.getAvailableMemoryFraction() < 0.2) { String msg = "Memory is low, reading terminating."; MessageUtils.showMessage(msg); return false; } } return true; } /** * @param chr Chromosome name * @return the tileSize */ public int getTileSize(String chr) { if (chr.equals("M") || chr.equals("chrM") || chr.equals("MT") || chr.equals("chrMT")) { return MITOCHONDRIA_TILE_SIZE; } else { return tileSize; } } public void clearCache() { if (cache != null) cache.clear(); } /** * Does this file contain paired end data? Assume not until proven otherwise. */ public boolean isPairedEnd() { return pairedEnd; } public class TiledIterator implements CloseableIterator<Alignment> { Iterator<Alignment> currentSamIterator; int end; Alignment nextRecord; int start; List<Alignment> alignments; TiledIterator(int start, int end, List<Alignment> alignments) { this.alignments = alignments; this.start = start; this.end = end; currentSamIterator = alignments.iterator(); advanceToFirstRecord(); } public void close() { // No-op } public boolean hasNext() { return nextRecord != null; } public Alignment next() { Alignment ret = nextRecord; advanceToNextRecord(); return ret; } public void remove() { // ignored } private void advanceToFirstRecord() { advanceToNextRecord(); } private void advanceToNextRecord() { advance(); //We use exclusive end while ((nextRecord != null) && (nextRecord.getEnd() <= start)) { advance(); } } private void advance() { if (currentSamIterator.hasNext()) { nextRecord = currentSamIterator.next(); if (nextRecord.getStart() >= end) { nextRecord = null; } } else { nextRecord = null; } } } /** * Caches alignments and counts for the coverage plot. * <p/> * Notes: * A "bucket" is a virtual container holding all the alignments with identical start position. The concept * is introduced to control the # of alignments we hold in memory for deep coverage regions. In practice, * little or no information is added by displaying more than ~50X coverage. For an average alignment length L * and coverage depth D we do not need to store more than D/L alignments at any given start position. */ // public static class AlignmentTile { private boolean loaded = false; private int end; private int start; private int tileNumber; private AlignmentCounts counts; private List<Alignment> containedRecords; private List<Alignment> overlappingRecords; private List<DownsampledInterval> downsampledIntervals; private List<SpliceJunctionFeature> containedSpliceJunctionFeatures; private List<SpliceJunctionFeature> overlappingSpliceJunctionFeatures; private SpliceJunctionHelper spliceJunctionHelper; private boolean downsample; private int samplingWindowSize; private int samplingDepth; private SamplingBucket currentSamplingBucket; private static final Random RAND = new Random(System.currentTimeMillis()); AlignmentTile(int tileNumber, int start, int end, AlignmentDataManager.DownsampleOptions downsampleOptions, AlignmentTrack.BisulfiteContext bisulfiteContext) { this.tileNumber = tileNumber; this.start = start; this.end = end; containedRecords = new ArrayList(16000); overlappingRecords = new ArrayList(); downsampledIntervals = new ArrayList(); // Use a sparse array for large regions (> 10 mb) if ((end - start) > 10000000) { this.counts = new SparseAlignmentCounts(start, end, bisulfiteContext); } else { this.counts = new DenseAlignmentCounts(start, end, bisulfiteContext); } // Set the max depth, and the max depth of the sampling bucket. if (downsampleOptions == null) { // Use default settings (from preferences) downsampleOptions = new AlignmentDataManager.DownsampleOptions(); } this.downsample = downsampleOptions.isDownsample(); this.samplingWindowSize = downsampleOptions.getSampleWindowSize(); this.samplingDepth = Math.max(1, downsampleOptions.getMaxReadCount()); // TODO -- only if splice junctions are on if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK)) { containedSpliceJunctionFeatures = new ArrayList<SpliceJunctionFeature>(100); overlappingSpliceJunctionFeatures = new ArrayList<SpliceJunctionFeature>(100); spliceJunctionHelper = new SpliceJunctionHelper(); } } public int getTileNumber() { return tileNumber; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } int ignoredCount = 0; // <= just for debugging /** * Add an alignment record to this tile. This record is not necessarily retained after down-sampling. * * @param alignment */ public void addRecord(Alignment alignment) { counts.incCounts(alignment); if (downsample) { final int alignmentStart = alignment.getAlignmentStart(); if (currentSamplingBucket == null || alignmentStart >= currentSamplingBucket.end) { if (currentSamplingBucket != null) { emptyBucket(); } int end = alignmentStart + samplingWindowSize; currentSamplingBucket = new SamplingBucket(alignmentStart, end); } if (spliceJunctionHelper != null) { spliceJunctionHelper.addAlignment(alignment); } currentSamplingBucket.add(alignment); } else { allocateAlignment(alignment); } } private void emptyBucket() { if (currentSamplingBucket == null) { return; } //List<Alignment> sampledRecords = sampleCurrentBucket(); for (Alignment alignment : currentSamplingBucket.getAlignments()) { allocateAlignment(alignment); } if (currentSamplingBucket.isSampled()) { DownsampledInterval interval = new DownsampledInterval(currentSamplingBucket.start, currentSamplingBucket.end, currentSamplingBucket.downsampledCount); downsampledIntervals.add(interval); } currentSamplingBucket = null; } private void allocateAlignment(Alignment alignment) { int aStart = alignment.getStart(); int aEnd = alignment.getEnd(); if ((aStart >= start) && (aStart < end)) { containedRecords.add(alignment); } else if ((aEnd > start) && (aStart < start)) { overlappingRecords.add(alignment); } } public List<Alignment> getContainedRecords() { return containedRecords; } public List<Alignment> getOverlappingRecords() { return overlappingRecords; } public List<DownsampledInterval> getDownsampledIntervals() { return downsampledIntervals; } public boolean isLoaded() { return loaded; } public void setLoaded(boolean loaded) { this.loaded = loaded; if (loaded) { // Empty any remaining alignments in the current bucket emptyBucket(); currentSamplingBucket = null; finalizeSpliceJunctions(); counts.finish(); } } public AlignmentCounts getCounts() { return counts; } private void finalizeSpliceJunctions() { if (spliceJunctionHelper != null) { spliceJunctionHelper.finish(); List<SpliceJunctionFeature> features = spliceJunctionHelper.getFeatures(); for (SpliceJunctionFeature f : features) { if (f.getStart() >= start) { containedSpliceJunctionFeatures.add(f); } else { overlappingSpliceJunctionFeatures.add(f); } } } spliceJunctionHelper = null; } public List<SpliceJunctionFeature> getContainedSpliceJunctionFeatures() { return containedSpliceJunctionFeatures; } public List<SpliceJunctionFeature> getOverlappingSpliceJunctionFeatures() { return overlappingSpliceJunctionFeatures; } private class SamplingBucket { int start; int end; int downsampledCount = 0; List<Alignment> alignments; private SamplingBucket(int start, int end) { this.start = start; this.end = end; alignments = new ArrayList(samplingDepth); } public void add(Alignment alignment) { // If the current bucket is < max depth we keep it. Otherwise, keep with probability == samplingProb // If we have the mate in the bucket already, always keep it. if (alignments.size() < samplingDepth) { alignments.add(alignment); } else { double samplingProb = ((double) samplingDepth) / (samplingDepth + downsampledCount + 1); if (RAND.nextDouble() < samplingProb) { int idx = (int) (RAND.nextDouble() * (alignments.size() - 1)); // Replace random record with this one alignments.set(idx, alignment); } downsampledCount++; } } public List<Alignment> getAlignments() { return alignments; } public boolean isSampled() { return downsampledCount > 0; } public int getDownsampledCount() { return downsampledCount; } } } private static class AlignmentSorter implements Comparator<Alignment> { public int compare(Alignment alignment, Alignment alignment1) { return alignment.getStart() - alignment1.getStart(); } } public static class DownsampledInterval implements Feature { private int start; private int end; private int count; public DownsampledInterval(int start, int end, int count) { this.start = start; this.end = end; this.count = count; } public String toString() { return start + "-" + end + " (" + count + ")"; } public int getCount() { return count; } public int getEnd() { return end; } public int getStart() { return start; } public String getChr() { return null; } public String getValueString() { return "Interval [" + start + "-" + end + "] <br>" + count + " reads removed."; } } }
false
true
private boolean loadTiles(String chr, List<AlignmentTile> tiles, Map<String, PEStats> peStats) { //assert (tiles.size() > 0); if (corruptIndex) { return false; } boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); //maxReadCount = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_MAX_READS); if (log.isDebugEnabled()) { int first = tiles.get(0).getTileNumber(); int end = tiles.get(tiles.size() - 1).getTileNumber(); log.debug("Loading tiles: " + first + "-" + end); } int start = tiles.get(0).start; int end = tiles.get(tiles.size() - 1).end; CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<CachingQueryReader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeReaders.add(ref); iter = reader.query(chr, start, end, false); int tileSize = getTileSize(chr); while (iter != null && iter.hasNext()) { if (cancel) { return false; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } // Range of tile indices that this alignment contributes to. int aStart = record.getStart(); int aEnd = record.getEnd(); int idx0 = Math.max(0, (aStart - start) / tileSize); int idx1 = Math.min(tiles.size() - 1, (aEnd - start) / tileSize); // Loop over tiles this read overlaps for (int i = idx0; i <= idx1; i++) { AlignmentTile t = null; t = tiles.get(i); t.addRecord(record); } alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return false; MessageUtils.setStatusBarMessage("Reads loaded: " + alignmentCount); if (checkMemory() == false) { cancelReaders(); return false; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } mappedMates = null; unmappedMates = null; for (AlignmentTile t : tiles) { t.setLoaded(true); cache.put(t.getTileNumber(), t); } return true; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return false; } catch (IOException e) { log.error("Error loading alignment data", e); throw new DataLoadException("", "Error: " + e.toString()); } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeReaders.remove(ref); if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } }
private boolean loadTiles(String chr, List<AlignmentTile> tiles, Map<String, PEStats> peStats) { //assert (tiles.size() > 0); if (corruptIndex) { return false; } boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); //maxReadCount = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_MAX_READS); if (log.isDebugEnabled()) { int first = tiles.get(0).getTileNumber(); int end = tiles.get(tiles.size() - 1).getTileNumber(); log.debug("Loading tiles: " + first + "-" + end); } int start = tiles.get(0).start; int end = tiles.get(tiles.size() - 1).end; CloseableIterator<Alignment> iter = null; //log.debug("Loading : " + start + " - " + end); int alignmentCount = 0; WeakReference<CachingQueryReader> ref = new WeakReference(this); try { ObjectCache<String, Alignment> mappedMates = new ObjectCache<String, Alignment>(1000); ObjectCache<String, Alignment> unmappedMates = new ObjectCache<String, Alignment>(1000); activeReaders.add(ref); iter = reader.query(chr, start, end, false); int tileSize = getTileSize(chr); while (iter != null && iter.hasNext()) { if (cancel) { return false; } Alignment record = iter.next(); // Set mate sequence of unmapped mates // Put a limit on the total size of this collection. String readName = record.getReadName(); if (record.isPaired()) { pairedEnd = true; if (record.isMapped()) { if (!record.getMate().isMapped()) { // record is mapped, mate is not Alignment mate = unmappedMates.get(readName); if (mate == null) { mappedMates.put(readName, record); } else { record.setMateSequence(mate.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } else if (record.getMate().isMapped()) { // record not mapped, mate is Alignment mappedMate = mappedMates.get(readName); if (mappedMate == null) { unmappedMates.put(readName, record); } else { mappedMate.setMateSequence(record.getReadSequence()); unmappedMates.remove(readName); mappedMates.remove(readName); } } } if (!record.isMapped() || (!showDuplicates && record.isDuplicate()) || (filterFailedReads && record.isVendorFailedRead()) || record.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(record))) { continue; } // Range of tile indices that this alignment contributes to. int aStart = record.getStart(); int aEnd = record.getEnd(); int idx0 = Math.max(0, (aStart - start) / tileSize); int idx1 = Math.min(tiles.size() - 1, (aEnd - start) / tileSize); // Loop over tiles this read overlaps for (int i = idx0; i <= idx1; i++) { AlignmentTile t = null; t = tiles.get(i); t.addRecord(record); } alignmentCount++; int interval = Globals.isTesting() ? 100000 : 1000; if (alignmentCount % interval == 0) { if (cancel) return false; MessageUtils.setStatusBarMessage("Reads loaded: " + alignmentCount); if (checkMemory() == false) { cancelReaders(); return false; // <= TODO need to cancel all readers } } // Update pe stats if (peStats != null && record.isPaired() && record.isProperPair()) { String lb = record.getLibrary(); if (lb == null) lb = "null"; PEStats stats = peStats.get(lb); if (stats == null) { stats = new PEStats(lb); peStats.put(lb, stats); } stats.update(record); } } // End iteration over alignments // Compute peStats if (peStats != null) { // TODO -- something smarter re the percentiles. For small samples these will revert to min and max double minPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MIN_INSERT_SIZE_PERCENTILE); double maxPercentile = PreferenceManager.getInstance().getAsFloat(PreferenceManager.SAM_MAX_INSERT_SIZE_PERCENTILE); for (PEStats stats : peStats.values()) { stats.compute(minPercentile, maxPercentile); } } // Clean up any remaining unmapped mate sequences for (String mappedMateName : mappedMates.getKeys()) { Alignment mappedMate = mappedMates.get(mappedMateName); Alignment mate = unmappedMates.get(mappedMate.getReadName()); if (mate != null) { mappedMate.setMateSequence(mate.getReadSequence()); } } mappedMates = null; unmappedMates = null; for (AlignmentTile t : tiles) { t.setLoaded(true); cache.put(t.getTileNumber(), t); } return true; } catch (java.nio.BufferUnderflowException e) { // This almost always indicates a corrupt BAM index, or less frequently a corrupt bam file corruptIndex = true; MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString() + "<br>This is often caused by a corrupt index file."); return false; } catch (Exception e) { log.error("Error loading alignment data", e); MessageUtils.showMessage("<html>Error encountered querying alignments: " + e.toString()); return false; } finally { // reset cancel flag. It doesn't matter how we got here, the read is complete and this flag is reset // for the next time cancel = false; activeReaders.remove(ref); if (iter != null) { iter.close(); } if (!Globals.isHeadless()) { IGV.getInstance().resetStatusMessage(); } } }
diff --git a/src/spullen/com/invaders/entity/mob/Enemy.java b/src/spullen/com/invaders/entity/mob/Enemy.java index 6e8072e..48595fb 100644 --- a/src/spullen/com/invaders/entity/mob/Enemy.java +++ b/src/spullen/com/invaders/entity/mob/Enemy.java @@ -1,48 +1,48 @@ package spullen.com.invaders.entity.mob; import spullen.com.invaders.Game; public abstract class Enemy extends Mob { protected boolean exploding = false; protected int explosionCooldown = 120; public Enemy(int x, int y) { super(x, y); } public void update() { super.update(); checkForCollision(); if(exploding) { explosionCooldown--; } if(explosionCooldown == 0) { removed = true; } } protected void checkForCollision() { int lowerLeftX = x; int lowerRightX = x + sprite.WIDTH; int lowerY = y + sprite.HEIGHT; for(PlayerMissile missile : Game.playerMissiles) { - if(missile.y < lowerY && missile.x > lowerLeftX && missile.x < lowerRightX) { + if(missile.y < lowerY && missile.x >= lowerLeftX && missile.x <= lowerRightX) { System.out.println("X: " + x + ", Y: " + y); int pixelX = missile.x - x; int pixelY = missile.y - y; int pixel = sprite.pixels[pixelX + pixelY * sprite.WIDTH]; if(pixel != 0xffff00ff) { System.out.println("Hit!"); Game.removedPlayerMissiles.add(missile); exploding = true; } } } } }
true
true
protected void checkForCollision() { int lowerLeftX = x; int lowerRightX = x + sprite.WIDTH; int lowerY = y + sprite.HEIGHT; for(PlayerMissile missile : Game.playerMissiles) { if(missile.y < lowerY && missile.x > lowerLeftX && missile.x < lowerRightX) { System.out.println("X: " + x + ", Y: " + y); int pixelX = missile.x - x; int pixelY = missile.y - y; int pixel = sprite.pixels[pixelX + pixelY * sprite.WIDTH]; if(pixel != 0xffff00ff) { System.out.println("Hit!"); Game.removedPlayerMissiles.add(missile); exploding = true; } } } }
protected void checkForCollision() { int lowerLeftX = x; int lowerRightX = x + sprite.WIDTH; int lowerY = y + sprite.HEIGHT; for(PlayerMissile missile : Game.playerMissiles) { if(missile.y < lowerY && missile.x >= lowerLeftX && missile.x <= lowerRightX) { System.out.println("X: " + x + ", Y: " + y); int pixelX = missile.x - x; int pixelY = missile.y - y; int pixel = sprite.pixels[pixelX + pixelY * sprite.WIDTH]; if(pixel != 0xffff00ff) { System.out.println("Hit!"); Game.removedPlayerMissiles.add(missile); exploding = true; } } } }
diff --git a/bundles/ParserCore/src/main/java/org/paxle/parser/impl/ParserWorker.java b/bundles/ParserCore/src/main/java/org/paxle/parser/impl/ParserWorker.java index fbeaff7f..0841f1de 100644 --- a/bundles/ParserCore/src/main/java/org/paxle/parser/impl/ParserWorker.java +++ b/bundles/ParserCore/src/main/java/org/paxle/parser/impl/ParserWorker.java @@ -1,236 +1,236 @@ package org.paxle.parser.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.paxle.core.charset.ICharsetDetector; import org.paxle.core.doc.ICrawlerDocument; import org.paxle.core.doc.IParserDocument; import org.paxle.core.doc.ParserDocument; import org.paxle.core.io.temp.ITempFileManager; import org.paxle.core.mimetype.IMimeTypeDetector; import org.paxle.core.norm.IReferenceNormalizer; import org.paxle.core.queue.ICommand; import org.paxle.core.threading.AWorker; import org.paxle.parser.ISubParser; import org.paxle.parser.ISubParserManager; import org.paxle.parser.ParserContext; import org.paxle.parser.ParserException; public class ParserWorker extends AWorker<ICommand> { /** * A class to manage {@link ISubParser sub-parsers} */ private ISubParserManager subParserManager = null; /** * A class to detect mimetypes */ IMimeTypeDetector mimeTypeDetector = null; /** * A class to detect charsets */ ICharsetDetector charsetDetector = null; ITempFileManager tempFileManager = null; IReferenceNormalizer referenceNormalizer = null; /** * A logger class */ private final Log logger = LogFactory.getLog(ParserWorker.class); public ParserWorker(ISubParserManager subParserManager) { this.subParserManager = subParserManager; } /** * Init the parser context */ protected void initParserContext() { // init the parser context object ParserContext parserContext = new ParserContext( this.subParserManager, this.mimeTypeDetector, this.charsetDetector, this.tempFileManager, this.referenceNormalizer); ParserContext.setCurrentContext(parserContext); } @Override protected void execute(ICommand command) { final long start = System.currentTimeMillis(); IParserDocument parserDoc = null; try { /* ================================================================ * Input Parameter Check * ================================================================ */ String errorMsg = null; if (command.getResult() != ICommand.Result.Passed) { errorMsg = String.format( "Won't parse resource '%s'. Command status is: '%s' (%s)", command.getLocation(), command.getResult(), command.getResultText() ); } else if (command.getCrawlerDocument() == null) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document is null", command.getLocation() ); } else if (command.getCrawlerDocument().getStatus() != ICrawlerDocument.Status.OK) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document status is: '%s' (%s)", command.getLocation(), command.getCrawlerDocument().getStatus(), command.getCrawlerDocument().getStatusText() ); } if (errorMsg != null) { this.logger.warn(errorMsg); return; } /* ================================================================ * Parse Resource * * a) determine content mime-type * b) fetch appropriate parser * c) parse resource * d) process parser response * ================================================================ */ // init the parser context this.initParserContext(); // determine resource mimetype String mimeType = command.getCrawlerDocument().getMimeType(); if (mimeType == null) { // document not parsable this.logger.error(String.format("Unable to parse resource '%s'. No mime-type was specified.",command.getLocation())); command.setResult(ICommand.Result.Failure, "No mime-type was specified"); return; } // get appropriate parser this.logger.debug(String.format("Getting parser for mime-type '%s' ...", mimeType)); ISubParser parser = this.subParserManager.getSubParser(mimeType); if (parser == null) { // document not parsable this.logger.error(String.format("No parser for resource '%s' and mime-type '%s' found.",command.getLocation(),mimeType)); command.setResult( ICommand.Result.Failure, String.format("No parser for mime-type '%s' found.", mimeType) ); return; } this.logger.debug(String.format("Parser '%s' found for mime-type '%s'.", parser.getClass().getName(), mimeType)); // parse resource try { this.logger.info(String.format("Parsing resource '%s' with mime-type '%s' ...", command.getLocation(), mimeType)); parserDoc = parser.parse( command.getLocation(), command.getCrawlerDocument().getCharset(), command.getCrawlerDocument().getContent() ); } catch (ParserException e) { parserDoc = new ParserDocument(); parserDoc.setStatus(IParserDocument.Status.FAILURE, e.getMessage()); } /* ================================================================ * Process parser response * ================================================================ */ if (parserDoc == null) { command.setResult( ICommand.Result.Failure, String.format("Parser '%s' returned no parser-document.",parserDoc.getClass().getName()) ); return; } else if (parserDoc.getStatus() == null || parserDoc.getStatus() != IParserDocument.Status.OK) { command.setResult( ICommand.Result.Failure, String.format("Parser-document status is '%s'.",parserDoc.getStatus()) ); return; } // setting of default properties if (parserDoc.getMimeType() == null) { parserDoc.setMimeType(mimeType); } // setting command status to passed command.setResult(ICommand.Result.Passed,null); } catch (Exception e) { // setting command status command.setResult( ICommand.Result.Failure, String.format("Unexpected '%s' while parsing resource. %s",e.getClass().getName(),e.getMessage()) ); // log error this.logger.warn(String.format("Unexpected '%s' while parsing resource '%s'.", e.getClass().getName(), command.getLocation() ),e); } finally { /* * Append parser-doc to command object. * * This must be done even in error situations to * - allow filters to correct the error (if possible) * - to report the error back properly (e.g. to store it into db * or send it back to a remote peer). */ if (parserDoc != null) { command.setParserDocument(parserDoc); } ICrawlerDocument crawlerDoc = command.getCrawlerDocument(); if (logger.isDebugEnabled()) { this.logger.info(String.format( "Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tCrawler-Status: '%s' %s\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), (command.getCrawlerDocument() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), (crawlerDoc == null) ? "unknown" : crawlerDoc.getStatus().toString(), (crawlerDoc == null) ? "" : (crawlerDoc.getStatusText()==null)?"":crawlerDoc.getStatusText(), (parserDoc == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText() )); } else if (logger.isInfoEnabled()) { logger.info(String.format("Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), - (command.getCrawlerDocument() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), + (command.getCrawlerDocument() == null || command.getCrawlerDocument().getMimeType() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), - (parserDoc == null) ? "unknown" : parserDoc.getStatus().toString(), + (parserDoc == null || parserDoc.getStatus() == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText())); } } } @Override protected void reset() { // do some cleanup ParserContext parserContext = ParserContext.getCurrentContext(); if (parserContext != null) parserContext.reset(); // reset all from parent super.reset(); } }
false
true
protected void execute(ICommand command) { final long start = System.currentTimeMillis(); IParserDocument parserDoc = null; try { /* ================================================================ * Input Parameter Check * ================================================================ */ String errorMsg = null; if (command.getResult() != ICommand.Result.Passed) { errorMsg = String.format( "Won't parse resource '%s'. Command status is: '%s' (%s)", command.getLocation(), command.getResult(), command.getResultText() ); } else if (command.getCrawlerDocument() == null) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document is null", command.getLocation() ); } else if (command.getCrawlerDocument().getStatus() != ICrawlerDocument.Status.OK) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document status is: '%s' (%s)", command.getLocation(), command.getCrawlerDocument().getStatus(), command.getCrawlerDocument().getStatusText() ); } if (errorMsg != null) { this.logger.warn(errorMsg); return; } /* ================================================================ * Parse Resource * * a) determine content mime-type * b) fetch appropriate parser * c) parse resource * d) process parser response * ================================================================ */ // init the parser context this.initParserContext(); // determine resource mimetype String mimeType = command.getCrawlerDocument().getMimeType(); if (mimeType == null) { // document not parsable this.logger.error(String.format("Unable to parse resource '%s'. No mime-type was specified.",command.getLocation())); command.setResult(ICommand.Result.Failure, "No mime-type was specified"); return; } // get appropriate parser this.logger.debug(String.format("Getting parser for mime-type '%s' ...", mimeType)); ISubParser parser = this.subParserManager.getSubParser(mimeType); if (parser == null) { // document not parsable this.logger.error(String.format("No parser for resource '%s' and mime-type '%s' found.",command.getLocation(),mimeType)); command.setResult( ICommand.Result.Failure, String.format("No parser for mime-type '%s' found.", mimeType) ); return; } this.logger.debug(String.format("Parser '%s' found for mime-type '%s'.", parser.getClass().getName(), mimeType)); // parse resource try { this.logger.info(String.format("Parsing resource '%s' with mime-type '%s' ...", command.getLocation(), mimeType)); parserDoc = parser.parse( command.getLocation(), command.getCrawlerDocument().getCharset(), command.getCrawlerDocument().getContent() ); } catch (ParserException e) { parserDoc = new ParserDocument(); parserDoc.setStatus(IParserDocument.Status.FAILURE, e.getMessage()); } /* ================================================================ * Process parser response * ================================================================ */ if (parserDoc == null) { command.setResult( ICommand.Result.Failure, String.format("Parser '%s' returned no parser-document.",parserDoc.getClass().getName()) ); return; } else if (parserDoc.getStatus() == null || parserDoc.getStatus() != IParserDocument.Status.OK) { command.setResult( ICommand.Result.Failure, String.format("Parser-document status is '%s'.",parserDoc.getStatus()) ); return; } // setting of default properties if (parserDoc.getMimeType() == null) { parserDoc.setMimeType(mimeType); } // setting command status to passed command.setResult(ICommand.Result.Passed,null); } catch (Exception e) { // setting command status command.setResult( ICommand.Result.Failure, String.format("Unexpected '%s' while parsing resource. %s",e.getClass().getName(),e.getMessage()) ); // log error this.logger.warn(String.format("Unexpected '%s' while parsing resource '%s'.", e.getClass().getName(), command.getLocation() ),e); } finally { /* * Append parser-doc to command object. * * This must be done even in error situations to * - allow filters to correct the error (if possible) * - to report the error back properly (e.g. to store it into db * or send it back to a remote peer). */ if (parserDoc != null) { command.setParserDocument(parserDoc); } ICrawlerDocument crawlerDoc = command.getCrawlerDocument(); if (logger.isDebugEnabled()) { this.logger.info(String.format( "Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tCrawler-Status: '%s' %s\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), (command.getCrawlerDocument() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), (crawlerDoc == null) ? "unknown" : crawlerDoc.getStatus().toString(), (crawlerDoc == null) ? "" : (crawlerDoc.getStatusText()==null)?"":crawlerDoc.getStatusText(), (parserDoc == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText() )); } else if (logger.isInfoEnabled()) { logger.info(String.format("Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), (command.getCrawlerDocument() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), (parserDoc == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText())); } } }
protected void execute(ICommand command) { final long start = System.currentTimeMillis(); IParserDocument parserDoc = null; try { /* ================================================================ * Input Parameter Check * ================================================================ */ String errorMsg = null; if (command.getResult() != ICommand.Result.Passed) { errorMsg = String.format( "Won't parse resource '%s'. Command status is: '%s' (%s)", command.getLocation(), command.getResult(), command.getResultText() ); } else if (command.getCrawlerDocument() == null) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document is null", command.getLocation() ); } else if (command.getCrawlerDocument().getStatus() != ICrawlerDocument.Status.OK) { errorMsg = String.format( "Won't parse resource '%s'. Crawler-document status is: '%s' (%s)", command.getLocation(), command.getCrawlerDocument().getStatus(), command.getCrawlerDocument().getStatusText() ); } if (errorMsg != null) { this.logger.warn(errorMsg); return; } /* ================================================================ * Parse Resource * * a) determine content mime-type * b) fetch appropriate parser * c) parse resource * d) process parser response * ================================================================ */ // init the parser context this.initParserContext(); // determine resource mimetype String mimeType = command.getCrawlerDocument().getMimeType(); if (mimeType == null) { // document not parsable this.logger.error(String.format("Unable to parse resource '%s'. No mime-type was specified.",command.getLocation())); command.setResult(ICommand.Result.Failure, "No mime-type was specified"); return; } // get appropriate parser this.logger.debug(String.format("Getting parser for mime-type '%s' ...", mimeType)); ISubParser parser = this.subParserManager.getSubParser(mimeType); if (parser == null) { // document not parsable this.logger.error(String.format("No parser for resource '%s' and mime-type '%s' found.",command.getLocation(),mimeType)); command.setResult( ICommand.Result.Failure, String.format("No parser for mime-type '%s' found.", mimeType) ); return; } this.logger.debug(String.format("Parser '%s' found for mime-type '%s'.", parser.getClass().getName(), mimeType)); // parse resource try { this.logger.info(String.format("Parsing resource '%s' with mime-type '%s' ...", command.getLocation(), mimeType)); parserDoc = parser.parse( command.getLocation(), command.getCrawlerDocument().getCharset(), command.getCrawlerDocument().getContent() ); } catch (ParserException e) { parserDoc = new ParserDocument(); parserDoc.setStatus(IParserDocument.Status.FAILURE, e.getMessage()); } /* ================================================================ * Process parser response * ================================================================ */ if (parserDoc == null) { command.setResult( ICommand.Result.Failure, String.format("Parser '%s' returned no parser-document.",parserDoc.getClass().getName()) ); return; } else if (parserDoc.getStatus() == null || parserDoc.getStatus() != IParserDocument.Status.OK) { command.setResult( ICommand.Result.Failure, String.format("Parser-document status is '%s'.",parserDoc.getStatus()) ); return; } // setting of default properties if (parserDoc.getMimeType() == null) { parserDoc.setMimeType(mimeType); } // setting command status to passed command.setResult(ICommand.Result.Passed,null); } catch (Exception e) { // setting command status command.setResult( ICommand.Result.Failure, String.format("Unexpected '%s' while parsing resource. %s",e.getClass().getName(),e.getMessage()) ); // log error this.logger.warn(String.format("Unexpected '%s' while parsing resource '%s'.", e.getClass().getName(), command.getLocation() ),e); } finally { /* * Append parser-doc to command object. * * This must be done even in error situations to * - allow filters to correct the error (if possible) * - to report the error back properly (e.g. to store it into db * or send it back to a remote peer). */ if (parserDoc != null) { command.setParserDocument(parserDoc); } ICrawlerDocument crawlerDoc = command.getCrawlerDocument(); if (logger.isDebugEnabled()) { this.logger.info(String.format( "Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tCrawler-Status: '%s' %s\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), (command.getCrawlerDocument() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), (crawlerDoc == null) ? "unknown" : crawlerDoc.getStatus().toString(), (crawlerDoc == null) ? "" : (crawlerDoc.getStatusText()==null)?"":crawlerDoc.getStatusText(), (parserDoc == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText() )); } else if (logger.isInfoEnabled()) { logger.info(String.format("Finished parsing of resource '%s' with mime-type '%s' in %d ms.\r\n" + "\tParser-Status: '%s' %s", command.getLocation(), (command.getCrawlerDocument() == null || command.getCrawlerDocument().getMimeType() == null) ? "unknown" : command.getCrawlerDocument().getMimeType(), Long.valueOf(System.currentTimeMillis() - start), (parserDoc == null || parserDoc.getStatus() == null) ? "unknown" : parserDoc.getStatus().toString(), (parserDoc == null) ? "" : (parserDoc.getStatusText()==null)?"":parserDoc.getStatusText())); } } }
diff --git a/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/TextViewDetector.java b/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/TextViewDetector.java index be57a2a..e14d13c 100644 --- a/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/TextViewDetector.java +++ b/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/TextViewDetector.java @@ -1,240 +1,240 @@ /* * 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.tools.lint.checks; import static com.android.SdkConstants.ANDROID_URI; import static com.android.SdkConstants.ATTR_AUTO_TEXT; import static com.android.SdkConstants.ATTR_BUFFER_TYPE; import static com.android.SdkConstants.ATTR_CAPITALIZE; import static com.android.SdkConstants.ATTR_CURSOR_VISIBLE; import static com.android.SdkConstants.ATTR_DIGITS; import static com.android.SdkConstants.ATTR_EDITABLE; import static com.android.SdkConstants.ATTR_EDITOR_EXTRAS; import static com.android.SdkConstants.ATTR_ID; import static com.android.SdkConstants.ATTR_IME_ACTION_ID; import static com.android.SdkConstants.ATTR_IME_ACTION_LABEL; import static com.android.SdkConstants.ATTR_IME_OPTIONS; import static com.android.SdkConstants.ATTR_INPUT_METHOD; import static com.android.SdkConstants.ATTR_INPUT_TYPE; import static com.android.SdkConstants.ATTR_NUMERIC; import static com.android.SdkConstants.ATTR_ON_CLICK; import static com.android.SdkConstants.ATTR_PASSWORD; import static com.android.SdkConstants.ATTR_PHONE_NUMBER; import static com.android.SdkConstants.ATTR_PRIVATE_IME_OPTIONS; import static com.android.SdkConstants.ATTR_TEXT; import static com.android.SdkConstants.ATTR_TEXT_IS_SELECTABLE; import static com.android.SdkConstants.ATTR_VISIBILITY; import static com.android.SdkConstants.BUTTON; import static com.android.SdkConstants.CHECKED_TEXT_VIEW; import static com.android.SdkConstants.CHECK_BOX; import static com.android.SdkConstants.RADIO_BUTTON; import static com.android.SdkConstants.SWITCH; import static com.android.SdkConstants.TEXT_VIEW; import static com.android.SdkConstants.TOGGLE_BUTTON; import static com.android.SdkConstants.VALUE_EDITABLE; import static com.android.SdkConstants.VALUE_NONE; import static com.android.SdkConstants.VALUE_TRUE; import com.android.annotations.NonNull; import com.android.tools.lint.detector.api.Category; import com.android.tools.lint.detector.api.Implementation; import com.android.tools.lint.detector.api.Issue; import com.android.tools.lint.detector.api.LayoutDetector; import com.android.tools.lint.detector.api.Location; import com.android.tools.lint.detector.api.Scope; import com.android.tools.lint.detector.api.Severity; import com.android.tools.lint.detector.api.Speed; import com.android.tools.lint.detector.api.XmlContext; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import java.util.Arrays; import java.util.Collection; /** * Checks for cases where a TextView should probably be an EditText instead */ public class TextViewDetector extends LayoutDetector { private static final Implementation IMPLEMENTATION = new Implementation( TextViewDetector.class, Scope.RESOURCE_FILE_SCOPE); /** The main issue discovered by this detector */ public static final Issue ISSUE = Issue.create( "TextViewEdits", //$NON-NLS-1$ "TextView should probably be an EditText instead", "Looks for TextViews being used for input", "Using a `<TextView>` to input text is generally an error, you should be " + "using `<EditText>` instead. `EditText` is a subclass of `TextView`, and some " + "of the editing support is provided by `TextView`, so it's possible to set " + "some input-related properties on a `TextView`. However, using a `TextView` " + "along with input attributes is usually a cut & paste error. To input " + "text you should be using `<EditText>`." + "\n" + "This check also checks subclasses of `TextView`, such as `Button` and `CheckBox`, " + "since these have the same issue: they should not be used with editable " + "attributes.", Category.CORRECTNESS, 7, Severity.WARNING, IMPLEMENTATION); /** Text could be selectable */ public static final Issue SELECTABLE = Issue.create( "SelectableText", //$NON-NLS-1$ "Dynamic text should probably be selectable", "Looks for TextViews which should probably allow their text to be selected", "If a `<TextView>` is used to display data, the user might want to copy that " + "data and paste it elsewhere. To allow this, the `<TextView>` should specify " + "`android:textIsSelectable=\"true\"`.\n" + "\n" + "This lint check looks for TextViews which are likely to be displaying data: " + "views whose text is set dynamically. This value will be ignored on platforms " + "older than API 11, so it is okay to set it regardless of your `minSdkVersion`.", Category.USABILITY, 7, Severity.WARNING, IMPLEMENTATION) // Apparently setting this can have some undesirable side effects .setEnabledByDefault(false); /** Constructs a new {@link TextViewDetector} */ public TextViewDetector() { } @NonNull @Override public Speed getSpeed() { return Speed.FAST; } @Override public Collection<String> getApplicableElements() { return Arrays.asList( TEXT_VIEW, BUTTON, TOGGLE_BUTTON, CHECK_BOX, RADIO_BUTTON, CHECKED_TEXT_VIEW, SWITCH ); } @Override public void visitElement(@NonNull XmlContext context, @NonNull Element element) { if (element.getTagName().equals(TEXT_VIEW)) { if (!element.hasAttributeNS(ANDROID_URI, ATTR_TEXT) && element.hasAttributeNS(ANDROID_URI, ATTR_ID) && !element.hasAttributeNS(ANDROID_URI, ATTR_TEXT_IS_SELECTABLE) && !element.hasAttributeNS(ANDROID_URI, ATTR_VISIBILITY) && !element.hasAttributeNS(ANDROID_URI, ATTR_ON_CLICK) && context.getMainProject().getTargetSdk() >= 11) { context.report(SELECTABLE, element, context.getLocation(element), "Consider making the text value selectable by specifying " + "android:textIsSelectable=\"true\"", null); } } NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attribute = (Attr) attributes.item(i); String name = attribute.getLocalName(); - if (name == null) { + if (name == null || name.isEmpty()) { // Attribute not in a namespace; we only care about the android: ones continue; } boolean isEditAttribute = false; switch (name.charAt(0)) { case 'a': { isEditAttribute = name.equals(ATTR_AUTO_TEXT); break; } case 'b': { isEditAttribute = name.equals(ATTR_BUFFER_TYPE) && attribute.getValue().equals(VALUE_EDITABLE); break; } case 'p': { isEditAttribute = name.equals(ATTR_PASSWORD) || name.equals(ATTR_PHONE_NUMBER) || name.equals(ATTR_PRIVATE_IME_OPTIONS); break; } case 'c': { isEditAttribute = name.equals(ATTR_CAPITALIZE) || name.equals(ATTR_CURSOR_VISIBLE); break; } case 'd': { isEditAttribute = name.equals(ATTR_DIGITS); break; } case 'e': { if (name.equals(ATTR_EDITABLE)) { isEditAttribute = attribute.getValue().equals(VALUE_TRUE); } else { isEditAttribute = name.equals(ATTR_EDITOR_EXTRAS); } break; } case 'i': { if (name.equals(ATTR_INPUT_TYPE)) { String value = attribute.getValue(); isEditAttribute = !value.isEmpty() && !value.equals(VALUE_NONE); } else { isEditAttribute = name.equals(ATTR_INPUT_TYPE) || name.equals(ATTR_IME_OPTIONS) || name.equals(ATTR_IME_ACTION_LABEL) || name.equals(ATTR_IME_ACTION_ID) || name.equals(ATTR_INPUT_METHOD); } break; } case 'n': { isEditAttribute = name.equals(ATTR_NUMERIC); break; } } if (isEditAttribute && ANDROID_URI.equals(attribute.getNamespaceURI())) { Location location = context.getLocation(attribute); String message; String view = element.getTagName(); if (view.equals(TEXT_VIEW)) { message = String.format( "Attribute %1$s should not be used with <TextView>: " + "Change element type to <EditText> ?", attribute.getName()); } else { message = String.format( "Attribute %1$s should not be used with <%2$s>: " + "intended for editable text widgets", attribute.getName(), view); } context.report(ISSUE, attribute, location, message, null); } } } }
true
true
public void visitElement(@NonNull XmlContext context, @NonNull Element element) { if (element.getTagName().equals(TEXT_VIEW)) { if (!element.hasAttributeNS(ANDROID_URI, ATTR_TEXT) && element.hasAttributeNS(ANDROID_URI, ATTR_ID) && !element.hasAttributeNS(ANDROID_URI, ATTR_TEXT_IS_SELECTABLE) && !element.hasAttributeNS(ANDROID_URI, ATTR_VISIBILITY) && !element.hasAttributeNS(ANDROID_URI, ATTR_ON_CLICK) && context.getMainProject().getTargetSdk() >= 11) { context.report(SELECTABLE, element, context.getLocation(element), "Consider making the text value selectable by specifying " + "android:textIsSelectable=\"true\"", null); } } NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attribute = (Attr) attributes.item(i); String name = attribute.getLocalName(); if (name == null) { // Attribute not in a namespace; we only care about the android: ones continue; } boolean isEditAttribute = false; switch (name.charAt(0)) { case 'a': { isEditAttribute = name.equals(ATTR_AUTO_TEXT); break; } case 'b': { isEditAttribute = name.equals(ATTR_BUFFER_TYPE) && attribute.getValue().equals(VALUE_EDITABLE); break; } case 'p': { isEditAttribute = name.equals(ATTR_PASSWORD) || name.equals(ATTR_PHONE_NUMBER) || name.equals(ATTR_PRIVATE_IME_OPTIONS); break; } case 'c': { isEditAttribute = name.equals(ATTR_CAPITALIZE) || name.equals(ATTR_CURSOR_VISIBLE); break; } case 'd': { isEditAttribute = name.equals(ATTR_DIGITS); break; } case 'e': { if (name.equals(ATTR_EDITABLE)) { isEditAttribute = attribute.getValue().equals(VALUE_TRUE); } else { isEditAttribute = name.equals(ATTR_EDITOR_EXTRAS); } break; } case 'i': { if (name.equals(ATTR_INPUT_TYPE)) { String value = attribute.getValue(); isEditAttribute = !value.isEmpty() && !value.equals(VALUE_NONE); } else { isEditAttribute = name.equals(ATTR_INPUT_TYPE) || name.equals(ATTR_IME_OPTIONS) || name.equals(ATTR_IME_ACTION_LABEL) || name.equals(ATTR_IME_ACTION_ID) || name.equals(ATTR_INPUT_METHOD); } break; } case 'n': { isEditAttribute = name.equals(ATTR_NUMERIC); break; } } if (isEditAttribute && ANDROID_URI.equals(attribute.getNamespaceURI())) { Location location = context.getLocation(attribute); String message; String view = element.getTagName(); if (view.equals(TEXT_VIEW)) { message = String.format( "Attribute %1$s should not be used with <TextView>: " + "Change element type to <EditText> ?", attribute.getName()); } else { message = String.format( "Attribute %1$s should not be used with <%2$s>: " + "intended for editable text widgets", attribute.getName(), view); } context.report(ISSUE, attribute, location, message, null); } } }
public void visitElement(@NonNull XmlContext context, @NonNull Element element) { if (element.getTagName().equals(TEXT_VIEW)) { if (!element.hasAttributeNS(ANDROID_URI, ATTR_TEXT) && element.hasAttributeNS(ANDROID_URI, ATTR_ID) && !element.hasAttributeNS(ANDROID_URI, ATTR_TEXT_IS_SELECTABLE) && !element.hasAttributeNS(ANDROID_URI, ATTR_VISIBILITY) && !element.hasAttributeNS(ANDROID_URI, ATTR_ON_CLICK) && context.getMainProject().getTargetSdk() >= 11) { context.report(SELECTABLE, element, context.getLocation(element), "Consider making the text value selectable by specifying " + "android:textIsSelectable=\"true\"", null); } } NamedNodeMap attributes = element.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attribute = (Attr) attributes.item(i); String name = attribute.getLocalName(); if (name == null || name.isEmpty()) { // Attribute not in a namespace; we only care about the android: ones continue; } boolean isEditAttribute = false; switch (name.charAt(0)) { case 'a': { isEditAttribute = name.equals(ATTR_AUTO_TEXT); break; } case 'b': { isEditAttribute = name.equals(ATTR_BUFFER_TYPE) && attribute.getValue().equals(VALUE_EDITABLE); break; } case 'p': { isEditAttribute = name.equals(ATTR_PASSWORD) || name.equals(ATTR_PHONE_NUMBER) || name.equals(ATTR_PRIVATE_IME_OPTIONS); break; } case 'c': { isEditAttribute = name.equals(ATTR_CAPITALIZE) || name.equals(ATTR_CURSOR_VISIBLE); break; } case 'd': { isEditAttribute = name.equals(ATTR_DIGITS); break; } case 'e': { if (name.equals(ATTR_EDITABLE)) { isEditAttribute = attribute.getValue().equals(VALUE_TRUE); } else { isEditAttribute = name.equals(ATTR_EDITOR_EXTRAS); } break; } case 'i': { if (name.equals(ATTR_INPUT_TYPE)) { String value = attribute.getValue(); isEditAttribute = !value.isEmpty() && !value.equals(VALUE_NONE); } else { isEditAttribute = name.equals(ATTR_INPUT_TYPE) || name.equals(ATTR_IME_OPTIONS) || name.equals(ATTR_IME_ACTION_LABEL) || name.equals(ATTR_IME_ACTION_ID) || name.equals(ATTR_INPUT_METHOD); } break; } case 'n': { isEditAttribute = name.equals(ATTR_NUMERIC); break; } } if (isEditAttribute && ANDROID_URI.equals(attribute.getNamespaceURI())) { Location location = context.getLocation(attribute); String message; String view = element.getTagName(); if (view.equals(TEXT_VIEW)) { message = String.format( "Attribute %1$s should not be used with <TextView>: " + "Change element type to <EditText> ?", attribute.getName()); } else { message = String.format( "Attribute %1$s should not be used with <%2$s>: " + "intended for editable text widgets", attribute.getName(), view); } context.report(ISSUE, attribute, location, message, null); } } }