repository restructure git-svn-id: http://dev.eclipse.org/svnroot/technology/org.eclipse.stem/trunk/data@2195 92a21009-5b66-0410-b83a-dc787c41c6e9
diff --git a/geography/org.eclipse.stem.data.geography/.classpath b/geography/org.eclipse.stem.data.geography/.classpath new file mode 100644 index 0000000..304e861 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.classpath
@@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="output" path="bin"/> +</classpath>
diff --git a/geography/org.eclipse.stem.data.geography/.cvsignore b/geography/org.eclipse.stem.data.geography/.cvsignore new file mode 100644 index 0000000..8d6685b --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.cvsignore
@@ -0,0 +1,3 @@ +resources +plugin.properties +plugin.xml
diff --git a/geography/org.eclipse.stem.data.geography/.fbprefs b/geography/org.eclipse.stem.data.geography/.fbprefs new file mode 100644 index 0000000..e759194 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.fbprefs
@@ -0,0 +1,125 @@ +#FindBugs User Preferences +#Tue Aug 11 14:39:38 EDT 2009 +detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true +detectorBadAppletConstructor=BadAppletConstructor|false +detectorBadResultSetAccess=BadResultSetAccess|true +detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true +detectorBadUseOfReturnValue=BadUseOfReturnValue|true +detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true +detectorBooleanReturnNull=BooleanReturnNull|true +detectorCallToUnsupportedMethod=CallToUnsupportedMethod|true +detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true +detectorCheckTypeQualifiers=CheckTypeQualifiers|true +detectorCloneIdiom=CloneIdiom|true +detectorComparatorIdiom=ComparatorIdiom|true +detectorConfusedInheritance=ConfusedInheritance|true +detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true +detectorCrossSiteScripting=CrossSiteScripting|true +detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true +detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true +detectorDontUseEnum=DontUseEnum|true +detectorDroppedException=DroppedException|true +detectorDumbMethodInvocations=DumbMethodInvocations|true +detectorDumbMethods=DumbMethods|true +detectorDuplicateBranches=DuplicateBranches|true +detectorEmptyZipFileEntry=EmptyZipFileEntry|true +detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true +detectorFinalizerNullsFields=FinalizerNullsFields|true +detectorFindBadCast2=FindBadCast2|true +detectorFindBadForLoop=FindBadForLoop|true +detectorFindCircularDependencies=FindCircularDependencies|false +detectorFindDeadLocalStores=FindDeadLocalStores|true +detectorFindDoubleCheck=FindDoubleCheck|true +detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true +detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true +detectorFindFinalizeInvocations=FindFinalizeInvocations|true +detectorFindFloatEquality=FindFloatEquality|true +detectorFindHEmismatch=FindHEmismatch|true +detectorFindInconsistentSync2=FindInconsistentSync2|true +detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true +detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true +detectorFindMaskedFields=FindMaskedFields|true +detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true +detectorFindNakedNotify=FindNakedNotify|true +detectorFindNonSerializableStoreIntoSession=FindNonSerializableStoreIntoSession|true +detectorFindNonSerializableValuePassedToWriteObject=FindNonSerializableValuePassedToWriteObject|true +detectorFindNonShortCircuit=FindNonShortCircuit|true +detectorFindNullDeref=FindNullDeref|true +detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true +detectorFindOpenStream=FindOpenStream|true +detectorFindPuzzlers=FindPuzzlers|true +detectorFindRefComparison=FindRefComparison|true +detectorFindReturnRef=FindReturnRef|true +detectorFindRunInvocations=FindRunInvocations|true +detectorFindSelfComparison=FindSelfComparison|true +detectorFindSelfComparison2=FindSelfComparison2|true +detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true +detectorFindSpinLoop=FindSpinLoop|true +detectorFindSqlInjection=FindSqlInjection|true +detectorFindTwoLockWait=FindTwoLockWait|true +detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true +detectorFindUnconditionalWait=FindUnconditionalWait|true +detectorFindUninitializedGet=FindUninitializedGet|true +detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true +detectorFindUnreleasedLock=FindUnreleasedLock|true +detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true +detectorFindUnsyncGet=FindUnsyncGet|true +detectorFindUselessControlFlow=FindUselessControlFlow|true +detectorFormatStringChecker=FormatStringChecker|true +detectorHugeSharedStringConstants=HugeSharedStringConstants|true +detectorIDivResultCastToDouble=IDivResultCastToDouble|true +detectorIncompatMask=IncompatMask|true +detectorInconsistentAnnotations=InconsistentAnnotations|true +detectorInefficientMemberAccess=InefficientMemberAccess|false +detectorInefficientToArray=InefficientToArray|true +detectorInfiniteLoop=InfiniteLoop|true +detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true +detectorInfiniteRecursiveLoop2=InfiniteRecursiveLoop2|false +detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true +detectorInitializationChain=InitializationChain|true +detectorInstantiateStaticClass=InstantiateStaticClass|true +detectorInvalidJUnitTest=InvalidJUnitTest|true +detectorIteratorIdioms=IteratorIdioms|true +detectorLazyInit=LazyInit|true +detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true +detectorMethodReturnCheck=MethodReturnCheck|true +detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true +detectorMutableLock=MutableLock|true +detectorMutableStaticFields=MutableStaticFields|true +detectorNaming=Naming|true +detectorNumberConstructor=NumberConstructor|true +detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true +detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true +detectorPublicSemaphores=PublicSemaphores|false +detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true +detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true +detectorRedundantInterfaces=RedundantInterfaces|true +detectorRepeatedConditionals=RepeatedConditionals|true +detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true +detectorSerializableIdiom=SerializableIdiom|true +detectorStartInConstructor=StartInConstructor|true +detectorStaticCalendarDetector=StaticCalendarDetector|true +detectorStringConcatenation=StringConcatenation|true +detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true +detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true +detectorSwitchFallthrough=SwitchFallthrough|true +detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true +detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true +detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true +detectorURLProblems=URLProblems|true +detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true +detectorUnnecessaryMath=UnnecessaryMath|true +detectorUnreadFields=UnreadFields|true +detectorUseObjectEquals=UseObjectEquals|false +detectorUselessSubclassMethod=UselessSubclassMethod|false +detectorVarArgsProblems=VarArgsProblems|true +detectorVolatileUsage=VolatileUsage|true +detectorWaitInLoop=WaitInLoop|true +detectorWrongMapIterator=WrongMapIterator|true +detectorXMLFactoryBypass=XMLFactoryBypass|true +detector_threshold=2 +effort=max +excludefilter0=.settings/findbugs.exclude.xml +filter_settings=Medium|BAD_PRACTICE,CORRECTNESS,MT_CORRECTNESS,PERFORMANCE,STYLE|false +filter_settings_neg=MALICIOUS_CODE,NOISE,I18N,SECURITY,EXPERIMENTAL| +run_at_full_build=false
diff --git a/geography/org.eclipse.stem.data.geography/.project b/geography/org.eclipse.stem.data.geography/.project new file mode 100644 index 0000000..f373608 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.project
@@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.stem.data.geography</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription>
diff --git a/geography/org.eclipse.stem.data.geography/.settings/findbugs.exclude.xml b/geography/org.eclipse.stem.data.geography/.settings/findbugs.exclude.xml new file mode 100644 index 0000000..eed6b4d --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.settings/findbugs.exclude.xml
@@ -0,0 +1,6 @@ +<FindBugsFilter> + <Match> + <Package name="~org\.eclipse\.stem\.data\.geography\.*" /> + <Bug code="ST,LI" /> + </Match> +</FindBugsFilter> \ No newline at end of file
diff --git a/geography/org.eclipse.stem.data.geography/.settings/org.eclipse.jdt.core.prefs b/geography/org.eclipse.stem.data.geography/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..0307302 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,70 @@ +#Mon Feb 23 19:54:54 EST 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5
diff --git a/geography/org.eclipse.stem.data.geography/META-INF/MANIFEST.MF b/geography/org.eclipse.stem.data.geography/META-INF/MANIFEST.MF new file mode 100644 index 0000000..460cbe7 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/META-INF/MANIFEST.MF
@@ -0,0 +1,16 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: STEM Generated Geography Data +Bundle-SymbolicName: org.eclipse.stem.data.geography;singleton:=true +Bundle-Version: 1.2.0 +Bundle-Localization: plugin +Bundle-Activator: org.eclipse.stem.data.geography.Activator +Require-Bundle: org.eclipse.stem.core, + org.eclipse.core.runtime +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Bundle-ActivationPolicy: lazy +Export-Package: org.eclipse.stem.data.geography, + org.eclipse.stem.data.geography.centers +Bundle-Vendor: Eclipse.org + +
diff --git a/geography/org.eclipse.stem.data.geography/build.properties b/geography/org.eclipse.stem.data.geography/build.properties new file mode 100644 index 0000000..a0cbc1b --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/build.properties
@@ -0,0 +1,8 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + resources/,\ + plugin.xml,\ + plugin.properties +src.includes = resources/
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/.cvsignore b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/.cvsignore new file mode 100644 index 0000000..f84f1fd --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/.cvsignore
@@ -0,0 +1,2 @@ +*_names.properties +level0ISONames.properties
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/Activator.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/Activator.java new file mode 100644 index 0000000..189730b --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/Activator.java
@@ -0,0 +1,119 @@ +package org.eclipse.stem.data.geography; + +/******************************************************************************* + * Copyright (c) 2009 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 + *******************************************************************************/ + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Plugin; +import org.eclipse.core.runtime.Status; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends Plugin { + + /** + * The plug-in ID + */ + public static final String PLUGIN_ID = "org.eclipse.stem.data.geography"; //$NON-NLS-1$ + + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + plugin = this; + } + + /** + * @param context + * @throws Exception + */ + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + } + + /** + * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) + */ + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + + /** + * Log an error to the ILog for this plugin + * + * @param message + * the localized error message text + * @param exception + * the associated exception, or null + */ + public static void logError(String message, Throwable exception) { + plugin.getLog().log( + new Status(IStatus.ERROR, plugin.getBundle().getSymbolicName(), + 0, message, exception)); + } // logError + + /** + * Log information to the ILog for this plugin + * + * @param message + * the localized information message text + * @param exception + * the associated exception, or null + */ + public static void logInformation(String message, Throwable exception) { + plugin.getLog().log( + new Status(IStatus.INFO, plugin.getBundle().getSymbolicName(), + 0, message, exception)); + } // logInformation + + /** + * Log information to the ILog for this plugin + * The method is overloaded to allow for logInformation without an error + * method sets the error to null. This should be used instead of System.out.println + * throughout the code. + * @param message + * the localized information message text + * + */ + public static void logInformation(String message) { + // Do we have a plugin? + if (plugin != null) { + // Yes + plugin.getLog().log( + new Status(IStatus.INFO, plugin.getBundle().getSymbolicName(), + 0, message, null)); + } + else { + // No + System.out.println(message); + } + } // logInformation + + +} // Activator
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicMapper.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicMapper.java new file mode 100644 index 0000000..170e7bc --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicMapper.java
@@ -0,0 +1,278 @@ +// GeographicMapper.java +package org.eclipse.stem.data.geography; + +/******************************************************************************* + * Copyright (c) 2008 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 + *******************************************************************************/ + +import java.io.BufferedInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.ResourceBundle; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.resource.URIConverter; +import org.eclipse.emf.ecore.resource.impl.URIConverterImpl; +import org.eclipse.stem.core.Constants; + +/** + * This class maps geographic locations to specific data/information about the + * location. + */ +@SuppressWarnings("deprecation") +abstract public class GeographicMapper { + + /** + * The String that is used internally like an ISO-3166 alpha3 key to + * represent the Earth as if it was a country. + */ + public static final String EARTH_ALPHA3_ISO_KEY = "ZZZ"; //$NON-NLS-1$ + /** + * The name of the file that maps ISO-3166 alpha2 keys to ISO-3166 alpha3 + * keys. + */ + public static final String ALPHA2_TO_ALPHA3_NAME = "level0ISOKeys.properties"; //$NON-NLS-1$ + + private static final URI LEVEL_0_ISO_MAPPING_FILE_URI = URI + .createURI("platform:/plugin/" + Activator.PLUGIN_ID + "/resources/data/country/" + EARTH_ALPHA3_ISO_KEY + "/" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + ALPHA2_TO_ALPHA3_NAME); + + protected static final String RB_PREFIX = Constants.ID_ROOT + + ".data.geography"; //$NON-NLS-1$ + private static Properties alpha2ToAlpha3Map = null; + private static Properties alpha3ToAlpha2Map = null; + + /** + * @param propertyFile + * @return the properties read from the file + */ + protected static Properties readPropertyFiles(final URI propertyFileURI) { + final URIConverter converter = new URIConverterImpl(); + + final Properties retValue = new Properties(); + BufferedInputStream propertiesInputStream = null; + try { + propertiesInputStream = new BufferedInputStream(converter + .createInputStream(propertyFileURI)); + retValue.load(propertiesInputStream); + propertiesInputStream.close(); + } catch (final FileNotFoundException e) { + Activator.logError(EARTH_ALPHA3_ISO_KEY, e); + } catch (final IOException e) { + Activator.logError(EARTH_ALPHA3_ISO_KEY, e); + } + return retValue; + } // readPropertyFiles + + /** + * @param key + * @return the level of the key + */ + protected static int keyLevel(final String key) { + int level = 0; + int start = 0; + for (int temp = key.indexOf("-"); temp > 0;) { //$NON-NLS-1$ + level++; + start += temp + 1; + temp = key.substring(start).indexOf("-"); //$NON-NLS-1$ + } // for + return level; + } // keyLevel + + /** + * + */ + protected static Properties getAlpha2ToAlpha3Map() { + // Got the alpha2->alpha3 map? + if (alpha2ToAlpha3Map == null) { + // No + alpha2ToAlpha3Map = readPropertyFiles(LEVEL_0_ISO_MAPPING_FILE_URI); + } // if + // Got it now? + if (alpha2ToAlpha3Map == null) { + // No + Activator.logError( + "Can't read the alpha2 to alpha3 mapping file \"" //$NON-NLS-1$ + + ALPHA2_TO_ALPHA3_NAME + "\"", null); //$NON-NLS-1$ + } // if + return alpha2ToAlpha3Map; + } // getAlpha2ToAlpha3Map + + /** + * @param alpha2ISOKey + * @return the alpha 3 ISO key of the alpha2 key, or the alpha 2 key if + * there is an error + */ + public static String getAlpha3(final String alpha2ISOKey) { + String retValue = alpha2ISOKey; + final Properties alpha2ToAlpha3Map = getAlpha2ToAlpha3Map(); + // Do we have the map? + if (alpha2ToAlpha3Map != null) { + // Yes + retValue = alpha2ToAlpha3Map.getProperty(alpha2ISOKey); + } // if + return retValue; + } // getAlpha3 + + /** + * @param alpha3ISOKey + * @return the alpha 2 ISO key of the alpha2 key, or the alpha 2 key if + * there is an error + */ + public static String getAlpha2(final String alpha3ISOKey) { + String retValue = alpha3ISOKey; + + final Properties alpha3toAlpha2Map = getAlpha3toAlpha2Map(); + // Do we have the map? + if (alpha3toAlpha2Map != null) { + // Yes + retValue = alpha3toAlpha2Map.getProperty(alpha3ISOKey); + } // if + return retValue; + } + + private static Properties getAlpha3toAlpha2Map() { + // Already created the map? + if (alpha3ToAlpha2Map == null) { + // No + final Properties alpha2ToAlpha3Map = getAlpha2ToAlpha3Map(); + // Do we have the reverse map? + if (alpha2ToAlpha3Map != null) { + // Yes + alpha3ToAlpha2Map = new Properties(); + for (final Entry<Object,Object> entry : alpha2ToAlpha3Map.entrySet()) { + alpha3ToAlpha2Map.put(entry.getValue(), + entry.getKey()); + } // for each String + } // if + } // if + + return alpha3ToAlpha2Map; + } + + /** + * @param alpha3ISOKey + * the ISO-3166 alpha-3 key + * @param bundlePrefix + * TODO + * @param bundleType + * a {@link String} that identifies the type of bundle + * @return the name of the bundle that contains the names for the iso key's + * country. + */ + protected static String makeBundleName(final String alpha3ISOKey, + final String bundlePrefix, final String bundleType) { + final StringBuilder sb = new StringBuilder(bundlePrefix); + sb.append("."); //$NON-NLS-1$ + sb.append(alpha3ISOKey); + sb.append("_"); //$NON-NLS-1$ + sb.append(bundleType); + return sb.toString(); + } // makeBundleName + + /** + * @param alpha2ISOKey + * the ISO-3166 alpha-3 key + * @param bundlePrefix + * TODO + * @param bundleType + * a {@link String} that identifies the type of bundle + * @return the {@link ResourceBundle} for the country identified by the + * ISO-3166 alpha2 key + */ + protected static ResourceBundle readResourceBundle( + final String alpha2ISOKey, final String bundlePrefix, + final String bundleType) { + ResourceBundle retValue = null; + final Properties alpha2ToAlpha3Map = getAlpha2ToAlpha3Map(); + // Got it? + if (alpha2ToAlpha3Map != null) { + // Yes + final String alpha3ISOKey = alpha2ToAlpha3Map + .getProperty(alpha2ISOKey); + retValue = ResourceBundle.getBundle(makeBundleName(alpha3ISOKey, + bundlePrefix, bundleType)); + } // if + + return retValue; + } // readResourceBundle + + /** + * @param isoKey + * @param bundlePrefix + * TODO + * @param bundleType + * a {@link String} that identifies the type of bundle + * @param level0RBName + * the name of the {@link ResourceBundle} file that contains the + * level 0 resources + * @param level0RB + * the reference of the level 0 {@link ResourceBundle} + * @param rbMap + * a {@link Map} between alpha-2 iso key and + * {@link ResourceBundle}s + * @return the {@link ResourceBundle} that contains the mapping + */ + protected static ResourceBundle getResourceBundle(final String isoKey, + final int level, final String bundlePrefix, + final String bundleType, final String level0RBName, + ResourceBundle level0RB, Map<String, ResourceBundle> rbMap) { + ResourceBundle retValue = null; + // If the level is 0, we handle things specially. There is a single + // resource bundle that contains all of the level 0 mappings (i.e., the + // names of all countries) This allows us to avoid reading in all of the + // other (245!) resource bundles just to obtain the names of the + // countries. For the other levels we retrieve the bundle specific to + // the country because it has the names for all levels (i.e., all ISO + // keys). + + // Level 0? + if (level == -1 || level == 0) { + // Yes + // Have we retrieved the level 0 resource bundle yet? + if (level0RB == null) { + // No + level0RB = ResourceBundle.getBundle(level0RBName); + } // if + retValue = level0RB; + } // if level 0 + else { + // No + final String alpha2ISOKey = isoKey.substring(0, 2); + + // We use that value as the key to "cache" the resource bundle + retValue = rbMap.get(alpha2ISOKey); + + // Have we retrieved this ResourceBundle before? + if (retValue == null) { + // No + retValue = readResourceBundle(alpha2ISOKey, bundlePrefix, + bundleType); + // Were we successful? + if (retValue == null) { + // No + Activator.logError( + "Could not read Resource Bundle of type " //$NON-NLS-1$ + + bundleType + " for \"" + alpha2ISOKey //$NON-NLS-1$ + + "\"", null); //$NON-NLS-1$ + } // if + else { + // No + rbMap.put(alpha2ISOKey, retValue); + } // else + } // if + } // else + return retValue; + } // getResourceBundle + +} // GeographicMapper
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicNames.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicNames.java new file mode 100644 index 0000000..a721ed4 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/GeographicNames.java
@@ -0,0 +1,225 @@ +// GeographicNames.java +package org.eclipse.stem.data.geography; + +/******************************************************************************* + * Copyright (c) 2007 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.ResourceBundle; + +import org.eclipse.emf.common.util.URI; + +/** + * This class is responsible for providing NLS'd names for geographic locations. + */ +public class GeographicNames extends GeographicMapper { + + /** + * This is the string that identifies the type of bundle for geographic + * names. + */ + private static final String NAMES_BUNDLE_TYPE = "names"; //$NON-NLS-1$ + + /** + * The root name of the file that contains the level 0 names. + */ + public static final String LEVEL_0_ISO_NAMES_ROOT_NAME = "level0ISONames"; //$NON-NLS-1$ + + private static final String LEVEL_0_RB_NAME = RB_PREFIX + "." //$NON-NLS-1$ + + LEVEL_0_ISO_NAMES_ROOT_NAME; + + private static ResourceBundle level0RB = null; + + private static Map<String, ResourceBundle> rbMap = new HashMap<String, ResourceBundle>(); + + /** + * @param isoKey + * @return the name of the geographic location that matches isoKey + */ + public static String getName(final String isoKey) { + return getName(isoKey, keyLevel(isoKey)); + } // getName + + /** + * @param isoKey + * @param level + * @return the name of the geographic location that matches isoKey + */ + public static String getName(final String isoKey, final int level) { + try { + String isoKey2 = isoKey; + // alpha3 key? + if (isoKey.length() == 3) { + // Yes + isoKey2 = getAlpha2(isoKey); + } // if + + final ResourceBundle rb = getResourceBundle(isoKey2, level, + RB_PREFIX, NAMES_BUNDLE_TYPE, LEVEL_0_RB_NAME, level0RB, rbMap); + return rb.getString(isoKey2).trim(); + } catch (final MissingResourceException e) { + return isoKey; + } catch (final NullPointerException e) { + return '!' + isoKey + '!'; + } // catch NullPointerException + } // getName + + /** + * @param uri the {@link URI} of a geographic location + * @return the name of the geographic location that matches {@link URI} + */ + public static String getName(URI uri) { + return getName(uri.lastSegment().toString()); + } // getName + + /** + * @param isoKey + * the ISO-3166 alpha2 or alpha3 key of a geographic location + * @return the name of the location specified by the isoKey in reverse + * hierarchy, e.g., "Santa Clara Country, California, USA" for the + * ISO Key "US-CA-06085" + */ + public static String getReverseHierarchyName(final String isoKey) { + final StringBuilder sb = new StringBuilder(getName(isoKey)); + + String temp = isoKey; + int i = temp.lastIndexOf("-"); //$NON-NLS-1$ + while( i > 0) { + // Strip off the last segment of the key + temp = isoKey.substring(0,i); + sb.append(", "); //$NON-NLS-1$ + sb.append(getName(temp)); + i = temp.lastIndexOf("-"); //$NON-NLS-1$ + } + return sb.toString(); + } // getReverseHierarchyName + + /** + * @param isoKey + * the isoKey for which any "sub" keys at the level should be + * returned. + * @param level + * the administrative level of the key + * @return an array of the ISO keys that have the passed key as a prefix. + */ + public static Object[] getSubISOKeys(final String isoKey, final int level) { + Object[] retValue = new Object[] {}; + + // Earth (ZZZ)? + if (isoKey.equals(EARTH_ALPHA3_ISO_KEY)) { + // Yes + final Properties alpha2ToAlpha3Map = getAlpha2ToAlpha3Map(); + // Do we have the map? + if (alpha2ToAlpha3Map != null) { + // Yes + // retValue = alpha2ToAlpha3Map.keySet().toArray(); + retValue = alpha2ToAlpha3Map.values().toArray(); + } // if + } // if Earth + else { + // No + try { + final ResourceBundle rb = getResourceBundle(isoKey, level, + RB_PREFIX, NAMES_BUNDLE_TYPE, LEVEL_0_RB_NAME, level0RB, rbMap); + final List<String> temp = new ArrayList<String>(); + for (final Enumeration<String> keys = rb.getKeys(); keys + .hasMoreElements();) { + final String tempKey = keys.nextElement(); + // Is this key at the next level? + if (tempKey.startsWith(isoKey) + && keyLevel(tempKey) == level /* + 1 */) { + // Yes + temp.add(tempKey); + } // if + } // for each key + retValue = temp.toArray(new String[] {}); + } catch (final MissingResourceException mre) { + Activator.logError(mre.getMessage(), mre); + } + } // else + + return retValue; + } // getSubISOKeys + + /** + * @param isoKey + * @param bundlePrefix + * TODO + * @param bundleType + * a {@link String} that identifies the type of bundle + * @param level0RBName + * the name of the {@link ResourceBundle} file that contains the + * level 0 resources + * @param level0RB + * the reference of the level 0 {@link ResourceBundle} + * @param rbMap + * a {@link Map} between alpha-2 iso key and + * {@link ResourceBundle}s + * @return the {@link ResourceBundle} that contains the mapping + */ + protected static ResourceBundle getResourceBundle(final String isoKey, + final int level, final String bundlePrefix, + final String bundleType, final String level0RBName, + ResourceBundle level0RB, Map<String, ResourceBundle> rbMap) { + ResourceBundle retValue = null; + // If the level is 0, we handle things specially. There is a single + // resource bundle that contains all of the level 0 mappings (i.e., the + // names of all countries) This allows us to avoid reading in all of the + // other (245!) resource bundles just to obtain the names of the + // countries. For the other levels we retrieve the bundle specific to + // the country because it has the names for all levels (i.e., all ISO + // keys). + + // Level 0? + if (level == -1 || level == 0) { + // Yes + // Have we retrieved the level 0 resource bundle yet? + if (level0RB == null) { + // No + level0RB = ResourceBundle.getBundle(level0RBName); + } // if + retValue = level0RB; + } // if level 0 + else { + // No + final String alpha2ISOKey = isoKey.substring(0, 2); + + // We use that value as the key to "cache" the resource bundle + retValue = rbMap.get(alpha2ISOKey); + + // Have we retrieved this ResourceBundle before? + if (retValue == null) { + // No + retValue = readResourceBundle(alpha2ISOKey, bundlePrefix, + bundleType); + // Were we successful? + if (retValue == null) { + // No + Activator.logError( + "Could not read Resource Bundle of type " //$NON-NLS-1$ + + bundleType + " for \"" + alpha2ISOKey //$NON-NLS-1$ + + "\"", null); //$NON-NLS-1$ + } // if + else { + // No + rbMap.put(alpha2ISOKey, retValue); + } // else + } // if + } // else + return retValue; + } // getResourceBundle +} // GeographicNames
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/ISOKey.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/ISOKey.java new file mode 100644 index 0000000..86222ed --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/ISOKey.java
@@ -0,0 +1,93 @@ +// ISOKey.java +package org.eclipse.stem.data.geography; + +/******************************************************************************* + * Copyright (c) 2006, 2008 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 + *******************************************************************************/ + +/** + * This class represents an ISO-3166-1 alpha3 or alpha2 country key (or + * combination). + */ +public class ISOKey implements Comparable<ISOKey> { + /** + * This is the ISO key used to represent The Earth + */ + public static final ISOKey EARTH = new ISOKey("ZZZ"); //$NON-NLS-1$ + + private String key = null; + + /** + * @param key + * the key + */ + public ISOKey(final String key) { + this.key = key.trim(); + } + + /** + * @return the key + */ + public final String getKey() { + return key; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return key.hashCode(); + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ISOKey other = (ISOKey) obj; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; + } + return true; + } + + /** + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return key; + } + + /** + * @param isoKey + * the key to compare to + * @return the value of string compareTo + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + public int compareTo(final ISOKey isoKey) { + return this.key.compareTo(isoKey.key); + } + +} // ISOKey
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/NameReader.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/NameReader.java new file mode 100644 index 0000000..c87f770 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/NameReader.java
@@ -0,0 +1,182 @@ +package org.eclipse.stem.data.geography; + +/******************************************************************************* + * Copyright (c) 2011 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 + *******************************************************************************/ + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; + +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; +import org.osgi.framework.Bundle; + +/** + * This class is still under construction + * TODO: works but must remove hard coded strings + * + * process the raw region names files to obtain a map + * of names keyed by stemIDs + * + */ +public class NameReader { + + + static final String nameFilesPrefix = "src/org/eclipse/stem/data/geography/"; //$NON-NLS-1$ + //static final String nameFilesPrefix = "platform:/plugin/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/"; //$NON-NLS-1$ + + static final String nameFilesSuffix = "_names.properties"; //$NON-NLS-1$ + + + public Map<String, String> regionNamesMap= new HashMap<String, String>(); + + /** + * process the raw region names files to obtain a map + * of names keyed by stemIDs + * + */ + public NameReader() { + + } + + /** + * main method for testing + * @param args + */ +// @SuppressWarnings("nls") +// public static void main(String[] args) { +// +// NameReader nr = new NameReader(); +// String nameFilesPrefix = "/Users/jhkauf/Documents/workspace/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/"; //$NON-NLS-1$ +// String testfileName = nameFilesPrefix+"MEX_names.properties"; +//// nr.readNames(testfileName); +// }// main() + + + /** + * + * @param countryCode + * @return + */ + @SuppressWarnings("nls") + public Map<String, String> readNamesByCountryCode(String countryCode) { + Bundle bundle = Platform.getBundle("org.eclipse.stem.data.geography"); + Path path = new Path(nameFilesPrefix+countryCode+nameFilesSuffix); + URL fileURL = FileLocator.find(bundle, path, null); +// String fileName = rootWorkspace+nameFilesPrefix+countryCode+nameFilesSuffix; +// File nameFile = new File(fileName); + return readNames(fileURL); + } + + /** + * read in the level one Names and keys + * + */ + @SuppressWarnings("nls") + public Map<String, String> readNames(URL url) { + + //Activator.logInformation("reading Names for "+fileName); + String fname = url.getFile(); + BufferedReader fileReader = openReader(fname); + try { + // Add all the source URLs for this country. + + if (fileReader != null) { + String buffer = null; + while (EOF(buffer = fileReader.readLine()) != true) { + + //Activator.logInformation(" "+buffer); + // Tokenize + // + if((buffer.indexOf("SOURCE")==-1)&&(buffer.indexOf("VALID")==-1)&&(buffer.indexOf("#")==-1)&&(buffer.indexOf("-")>=0)) { + StringTokenizer tokenizer = new StringTokenizer(buffer, "="); //$NON-NLS-1$ + + // Level 2 + + String stemID2 = tokenizer.nextToken().trim(); + String name = tokenizer.nextToken(); + + + regionNamesMap.put(stemID2, name); + //Activator.logInformation(" mapped "+stemID2+" to "+name ); + } + + + } + } + }catch (Exception e) { + Activator.logInformation("Error reading file"+fname,e); + e.printStackTrace(); + System.exit(1); + } + return regionNamesMap; + + }// readName(String fileName) + + + /** + * Create a newBufferedReader + * + * @param fileName + * the name of the file we want to open for reading + * + * @return a reader to a given file + */ + static protected BufferedReader openReader(String file) { + + try { + + File f = new File(file); + + if (f.exists() == false) { + return null; + } + + return new BufferedReader(new FileReader(file)); + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + + + + /** + * Indicate End-Of-File + * + * @param buffer + * A buffer of diva data + * + * @return True if we have reached End-Of-File + */ + static protected boolean EOF(String buffer) { + if (buffer == null ) + return true; + return false; + } + + + + + + + + +}// class \ No newline at end of file
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/.cvsignore b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/.cvsignore new file mode 100644 index 0000000..778e556 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/.cvsignore
@@ -0,0 +1 @@ +*centers.properties
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/CenterReader.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/CenterReader.java new file mode 100644 index 0000000..a1fd19a --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/CenterReader.java
@@ -0,0 +1,299 @@ +package org.eclipse.stem.data.geography.centers; + +/******************************************************************************* + * Copyright (c) 2011 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 + *******************************************************************************/ + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import org.eclipse.stem.data.geography.Activator; +import org.eclipse.stem.data.geography.GeographicMapper; + +/** + * + * THIS CLASS is working but still under construction + * + */ +public class CenterReader extends GeographicMapper{ + + public static Map<String, String> regionCentersMap= new HashMap<String, String>(); + + // TODO: Fix this, this is not the right way + public static final String DATA_PATH = "/Users/jhkauf/Documents/workspace/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/"; //$NON-NLS-1$ + + //public static final String dataPath = "./src/org/eclipse/stem/data/geography/centers/"; //$NON-NLS-1$ + public static String root; + static List<String> allCentersFiles = new ArrayList<String>(); + List<String> allCountryIDs = new ArrayList<String>(); + /** + * This class reads all the centers in STEM + */ + @SuppressWarnings("nls") + public CenterReader() { + try { + //String top = parentDir.getCanonicalPath(); + root = DATA_PATH; + }catch(Exception e) { + e.printStackTrace(); + } + getAllCenterFileNames(); + for(int i = 0; i < allCentersFiles.size(); i ++) { + String fileName = allCentersFiles.get(i); + readCenters(fileName); + + int idx = fileName.indexOf("_centers.properties"); + if(idx >3) { + String id3 = fileName.substring(idx-3,idx); + if(id3.indexOf("ZZZ")==-1) allCountryIDs.add(id3); + } + + } + + } + + /** + * This class reads all the centers in STEM + */ + @SuppressWarnings("nls") + public CenterReader(List<String> centersFiles) { + allCentersFiles = centersFiles; + getAllCenterFileNames(); + for(int i = 0; i < allCentersFiles.size(); i ++) { + String fileName = allCentersFiles.get(i); + readCenters(fileName); + + int idx = fileName.indexOf("_centers.properties"); + if(idx >3) { + String id3 = fileName.substring(idx-3,idx); + if(id3.indexOf("ZZZ")==-1) allCountryIDs.add(id3); + } + } + } + + /** + * for testing + * @param args + */ + public static void main(String[] args) { + CenterReader cr = new CenterReader(); + } + + /** + * Get an array of country codes + * @return + */ + public String[] getCountryIDs() { + String[] id3s = allCountryIDs.toArray(new String[allCountryIDs.size()]); + Arrays.sort(id3s); + return id3s; + } + + /** + * read in the Centers and keys + * + */ + public Map<String, String> readCenters(String fileName) { + + BufferedReader fileReader = openReader(fileName); + + try { + // Add all the source URLs for this country. + + if (fileReader != null) { + String buffer = null; + while (EOF(buffer = fileReader.readLine()) != true) { + + //Activator.logInformation(" "+buffer); + // Tokenize + // + if((buffer.indexOf("SOURCE")==-1)&&(buffer.indexOf("VALID")==-1)&&(buffer.indexOf("#")==-1)&&(buffer.indexOf("=")>=0)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + StringTokenizer tokenizer = new StringTokenizer(buffer, "="); //$NON-NLS-1$ + String stemID2 = tokenizer.nextToken().trim(); + String center = tokenizer.nextToken(); + regionCentersMap.put(stemID2, center); + //Activator.logInformation(" mapped "+stemID2+" to "+Name.doubleValue() ); + } + } + } + }catch (Exception e) { + Activator.logInformation("Error reading file"+fileName); //$NON-NLS-1$ + e.printStackTrace(); + System.exit(1); + } + return regionCentersMap; + + }// readName(String fileName) + + + /** + * Create a newBufferedReader + * + * @param fileName + * the center of the file we want to open for reading + * + * @return a reader to a given file + */ + static protected BufferedReader openReader(String file) { + + try { + + File f = new File(file); + + if (f.exists() == false) { + return null; + } + + return new BufferedReader(new FileReader(file)); + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + + + + /** + * Indicate End-Of-File + * + * @param buffer + * A buffer of diva data + * + * @return True if we have reached End-Of-File + */ + static protected boolean EOF(String buffer) { + if (buffer == null ) + return true; + return false; + } + + /** + * + */ + static protected void getAllCenterFileNames() { + try { + File f = new File(root); + + if(f.isDirectory()) { + File[] dataFiles = filterAndSortFiles(f.listFiles()); + // remember the area files + for(int j = 0; j < dataFiles.length; j ++) { + + allCentersFiles.add(dataFiles[j].getAbsolutePath()); + } + } + }catch (Exception e) { + Activator.logInformation("Error reading file"+e.getMessage()); //$NON-NLS-1$ + e.printStackTrace(); + System.exit(1); + } + } + + /** + * filter the list of files and return a sorted array + * @param files + * @return + */ + static File[] filterAndSortFiles(File[] files) { + List<File> filtered = new ArrayList<File>(); + for (int i = 0; i < files.length; i ++) { + String name = files[i].getName(); + + if(name.indexOf("_centers.properties")>=1) { //$NON-NLS-1$ + filtered.add(files[i]); + } + } + File[] retVal = new File[filtered.size()]; + for (int i = 0; i < filtered.size(); i ++) { + retVal[i] = filtered.get(i); + } + Arrays.sort(retVal); + return retVal; + } + + /** + * filter the list of files and return a sorted array + * @param files + * @return + */ + @SuppressWarnings("nls") + static File[] filterAndSortCountryDirs(File[] files) { + List<File> filtered = new ArrayList<File>(); + for (int i = 0; i < files.length; i ++) { + String name = files[i].getName(); + + if((name.indexOf("svn")<=-1)&&(name.indexOf("ZZZ")<=-1)&&(name.indexOf("DS_Store")<=-1)) { + filtered.add(files[i]); + } + } + File[] retVal = new File[filtered.size()]; + for (int i = 0; i < filtered.size(); i ++) { + retVal[i] = filtered.get(i); + } + Arrays.sort(retVal); + return retVal; + } + + /** + * + * @param id + * @return + */ + public double getLatitude(String id) { + if(regionCentersMap.containsKey(id)) { + String center = this.regionCentersMap.get(id); + StringTokenizer tokenizer = new StringTokenizer(center, ","); //$NON-NLS-1$ + String lat = tokenizer.nextToken().trim(); + double latVal = (new Double(lat)).doubleValue(); + return latVal; + } else { + Activator.logInformation("1. CenterReader(): Error, region "+id+" not found"); //$NON-NLS-1$ //$NON-NLS-2$ + return -999; + } + + } + + /** + * returns double[2] (lat,lng) + * @param id + * @return + */ + public double[] getLatLong(String id) { + double[] retVal = new double[2]; + if(regionCentersMap.containsKey(id)) { + String center = this.regionCentersMap.get(id); + StringTokenizer tokenizer = new StringTokenizer(center, ","); //$NON-NLS-1$ + String lat = tokenizer.nextToken().trim(); + String lng = tokenizer.nextToken().trim(); + retVal[0] = (new Double(lat)).doubleValue(); + retVal[1] = (new Double(lng)).doubleValue(); + return retVal; + } else { + Activator.logInformation("2. CenterReader(): Warning, region "+id+" not found"); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + + } + + + + +}// class \ No newline at end of file
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/GeographicCenters.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/GeographicCenters.java new file mode 100644 index 0000000..6743153 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/GeographicCenters.java
@@ -0,0 +1,187 @@ +// GeographicCenters.java +package org.eclipse.stem.data.geography.centers; + +/******************************************************************************* + * Copyright (c) 2008 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 + *******************************************************************************/ + +import java.util.HashMap; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.NoSuchElementException; +import java.util.ResourceBundle; +import java.util.StringTokenizer; + +import org.eclipse.stem.data.geography.Activator; +import org.eclipse.stem.data.geography.GeographicMapper; + +/** + * This class is responsible for providing pre-computed geographic Latitude and + * Longitude for the center of geographic locations. + */ +@SuppressWarnings("nls") +public class GeographicCenters extends GeographicMapper { + /** + * This is the string that identifies the type of bundle for geographic + * centers. + */ + private static final String CENTERS_BUNDLE_TYPE = "centers"; //$NON-NLS-1$ + + /** + * The root name of the file that contains the level 0 names. + */ + public static final String LEVEL_0_ISO_NAMES_ROOT_NAME = "level0ISONames"; //$NON-NLS-1$ + + private static final String LEVEL_0_RB_NAME = RB_PREFIX + "." //$NON-NLS-1$ + + LEVEL_0_ISO_NAMES_ROOT_NAME; + + private static ResourceBundle level0RB = null; + + private static Map<String, ResourceBundle> rbMap = new HashMap<String, ResourceBundle>(); + + /** + * @param isoKey + * the ISO-3166 alpha2 or alpha3 key of a geographic location + * @return the center of the geographic location that matches isoKey, the + * first index (0) of the array is the latitude, the second (1) is + * the longitude, or <code>null</code> if the center could not be + * found for the key. + */ + public static double[] getCenter(final String isoKey) { + return getCenter(isoKey, keyLevel(isoKey)); + } // getCenter + + /** + * @param isoKey + * the ISO-3166 alpha2 or alpha3 key of a geographic location + * @param level + * the level of the key + * @return the latitude and longitude of the center of the geographic region + * that matches isoKey, or <code>null</code> if not found. + */ + + public static double[] getCenter(final String isoKey, final int level) { + double[] retValue = null; + String latLongString = ""; + + + try { + // World is special + if(isoKey.equalsIgnoreCase("ZZZ")) { + retValue = new double[2]; + retValue[0] = 0.0; + retValue[1] = 0.0; + return retValue; + } + + String isoKey2 = isoKey; + // alpha3 key? + if (isoKey.length() == 3) { + // Yes + isoKey2 = getAlpha2(isoKey); + } // if + + ResourceBundle rb = getResourceBundle(isoKey2, level, + RB_PREFIX + ".centers", CENTERS_BUNDLE_TYPE, + LEVEL_0_RB_NAME, level0RB, rbMap); + try { + latLongString = rb.getString(isoKey2).trim(); + } catch (final MissingResourceException e) { + // Try the 3 letter version + rb = getResourceBundle(isoKey, level, + RB_PREFIX + ".centers", CENTERS_BUNDLE_TYPE, + LEVEL_0_RB_NAME, level0RB, rbMap); + latLongString = rb.getString(isoKey).trim(); + } + // Did we get anything? + if (latLongString != null && !latLongString.equals("")) { + // Yes + final StringTokenizer st = new StringTokenizer(latLongString, + ","); + final String latitudeString = st.nextToken(); + final String longitudeString = st.nextToken(); + + retValue = new double[2]; + retValue[0] = Double.parseDouble(latitudeString); + retValue[1] = Double.parseDouble(longitudeString); + } // if + + } catch (final MissingResourceException e) { + retValue = null; + } catch (final NullPointerException e) { + retValue = null; + } // catch NullPointerException + catch (NumberFormatException nfe) { + Activator.logError("Error parsing \"" + latLongString + + "\" for the lat/long center of \"" + isoKey + + "\" Number format?", nfe); + } // catch NumberFormatException + catch (NoSuchElementException nsee) { + Activator.logError("Error parsing \"" + latLongString + + "\" for the lat/long center of \"" + isoKey + + "\" Missing value?", nsee); + } // catch NoSuchElementException + + return retValue; + } // getCenter + + /** + * @param isoKey + * @param bundlePrefix + * TODO + * @param bundleType + * a {@link String} that identifies the type of bundle + * @param level0RBName + * the name of the {@link ResourceBundle} file that contains the + * level 0 resources + * @param level0RB + * the reference of the level 0 {@link ResourceBundle} + * @param rbMap + * a {@link Map} between alpha-2 iso key and + * {@link ResourceBundle}s + * @return the {@link ResourceBundle} that contains the mapping + */ + protected static ResourceBundle getResourceBundle(final String isoKey, + final int level, + final String bundlePrefix, final String bundleType, + final String level0RBName, ResourceBundle level0RB, + Map<String, ResourceBundle> rbMap) { + ResourceBundle retValue = null; + + String alpha2ISOKey = isoKey; + if (isoKey.length() == 3) { + alpha2ISOKey = getAlpha2(isoKey); + } + else { + alpha2ISOKey = (isoKey.trim()).substring(0, 2); + } + + // We use that value as the key to "cache" the resource bundle + retValue = rbMap.get(alpha2ISOKey); + + // Have we retrieved this ResourceBundle before? + if (retValue == null) { + // No + retValue = readResourceBundle(alpha2ISOKey, bundlePrefix, + bundleType); + // Were we successful? + if (retValue == null) { + // No + Activator.logError("Could not read Resource Bundle of type " + + bundleType + " for \"" + alpha2ISOKey + "\"", null); + } // if + else { + // No + rbMap.put(alpha2ISOKey, retValue); + } // else + } // if + return retValue; + } // getResourceBundle +} // GeographicCenters
diff --git a/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/PluginCenterReader.java b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/PluginCenterReader.java new file mode 100644 index 0000000..a8abd51 --- /dev/null +++ b/geography/org.eclipse.stem.data.geography/src/org/eclipse/stem/data/geography/centers/PluginCenterReader.java
@@ -0,0 +1,297 @@ +package org.eclipse.stem.data.geography.centers; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Platform; +import org.eclipse.stem.data.geography.Activator; +import org.eclipse.stem.data.geography.GeographicMapper; +import org.osgi.framework.Bundle; + +/** + * + * Same as CenterReader but uses OSGI bundle API's to load resources. + * + */ +public class PluginCenterReader extends GeographicMapper{ + + public static Map<String, String> regionCentersMap= new HashMap<String, String>(); + + public static final String GEOGRAPHY_DATA_PLUGIN = "org.eclipse.stem.data.geography"; + public static final String DATA_PATH = "src/org/eclipse/stem/data/geography/centers/"; //$NON-NLS-1$ + + //public static final String dataPath = "./src/org/eclipse/stem/data/geography/centers/"; //$NON-NLS-1$ + public static Bundle geoBundle; + static List<URL> allCentersFiles = new ArrayList<URL>(); + List<String> allCountryIDs = new ArrayList<String>(); + /** + * This class reads all the centers in STEM + */ + @SuppressWarnings("nls") + public PluginCenterReader() { + try { + //String top = parentDir.getCanonicalPath(); + geoBundle=Platform.getBundle(GEOGRAPHY_DATA_PLUGIN); + + }catch(Exception e) { + e.printStackTrace(); + } + getAllCenterFileNames(); + for(int i = 0; i < allCentersFiles.size(); i ++) { + URL url = allCentersFiles.get(i); + readCenters(url); + + int idx = url.toString().indexOf("_centers.properties"); + if(idx >3) { + String id3 = url.toString().substring(idx-3,idx); + if(id3.indexOf("ZZZ")==-1) allCountryIDs.add(id3); + } + + } + + } + + /** + * This class reads all the centers in STEM + */ + @SuppressWarnings("nls") + public PluginCenterReader(List<URL> centersFiles) { + allCentersFiles = centersFiles; + getAllCenterFileNames(); + for(int i = 0; i < allCentersFiles.size(); i ++) { + URL url = allCentersFiles.get(i); + readCenters(url); + + int idx = url.toString().indexOf("_centers.properties"); + if(idx >3) { + String id3 = url.toString().substring(idx-3,idx); + if(id3.indexOf("ZZZ")==-1) allCountryIDs.add(id3); + } + } + } + + /** + * @param args + */ + public static void main(String[] args) { + PluginCenterReader cr = new PluginCenterReader(); + } + + /** + * Get an array of country codes + * @return + */ + public String[] getCountryIDs() { + String[] id3s = allCountryIDs.toArray(new String[allCountryIDs.size()]); + Arrays.sort(id3s); + return id3s; + } + + /** + * read in the Centers and keys + * + */ + public Map<String, String> readCenters(URL url) { + + BufferedReader fileReader = openReader(url); + + try { + // Add all the source URLs for this country. + + if (fileReader != null) { + String buffer = null; + while (EOF(buffer = fileReader.readLine()) != true) { + + //Activator.logInformation(" "+buffer); + // Tokenize + // + if((buffer.indexOf("SOURCE")==-1)&&(buffer.indexOf("VALID")==-1)&&(buffer.indexOf("#")==-1)&&(buffer.indexOf("=")>=0)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + StringTokenizer tokenizer = new StringTokenizer(buffer, "="); //$NON-NLS-1$ + String stemID2 = tokenizer.nextToken().trim(); + String center = tokenizer.nextToken(); + regionCentersMap.put(stemID2, center); + //Activator.logInformation(" mapped "+stemID2+" to "+Name.doubleValue() ); + } + } + } + }catch (Exception e) { + Activator.logInformation("Error reading file"+url); //$NON-NLS-1$ + e.printStackTrace(); + System.exit(1); + } + return regionCentersMap; + + }// readName(String fileName) + + + /** + * Create a newBufferedReader + * + * @param fileName + * the center of the file we want to open for reading + * + * @return a reader to a given file + */ + static protected BufferedReader openReader(URL url) { + + try { + +// File f = new File(file); + +// if (f.exists() == false) { +// return null; +// } + + return new BufferedReader((new InputStreamReader(url.openStream()))); + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + + + + /** + * Indicate End-Of-File + * + * @param buffer + * A buffer of diva data + * + * @return True if we have reached End-Of-File + */ + static protected boolean EOF(String buffer) { + if (buffer == null ) + return true; + return false; + } + + /** + * + */ + static protected void getAllCenterFileNames() { + try { + Path p = new Path(DATA_PATH); + Enumeration<URL> allFiles = geoBundle.findEntries(DATA_PATH, "*.properties", false); + + URL[] dataFiles = filterAndSortFiles(allFiles); + // remember the area files + for(int j = 0; j < dataFiles.length; j ++) { + + allCentersFiles.add(dataFiles[j]); + } + }catch (Exception e) { + Activator.logInformation("Error reading file"+e.getMessage()); //$NON-NLS-1$ + e.printStackTrace(); + System.exit(1); + } + } + + /** + * filter the list of files and return a sorted array + * @param files + * @return + */ + static URL[] filterAndSortFiles(Enumeration<URL>allFiles) { + List<URL> filtered = new ArrayList<URL>(); + while(allFiles.hasMoreElements()) { + URL url = allFiles.nextElement(); + + if(url.getPath().indexOf("_centers.properties")>=1) { //$NON-NLS-1$ + filtered.add(url); + } + } + URL[] retVal = new URL[filtered.size()]; + for (int i = 0; i < filtered.size(); i ++) { + retVal[i] = filtered.get(i); + } + Arrays.sort(retVal, new Comparator<URL>() { + public int compare(URL ua, URL ub) { + return ua.getPath().compareTo(ub.toString()); + } + }); + return retVal; + } + + /** + * filter the list of files and return a sorted array + * @param files + * @return + */ + @SuppressWarnings("nls") + static File[] filterAndSortCountryDirs(File[] files) { + List<File> filtered = new ArrayList<File>(); + for (int i = 0; i < files.length; i ++) { + String name = files[i].getName(); + + if((name.indexOf("svn")<=-1)&&(name.indexOf("ZZZ")<=-1)&&(name.indexOf("DS_Store")<=-1)) { + filtered.add(files[i]); + } + } + File[] retVal = new File[filtered.size()]; + for (int i = 0; i < filtered.size(); i ++) { + retVal[i] = filtered.get(i); + } + Arrays.sort(retVal); + return retVal; + } + + /** + * + * @param id + * @return + */ + public double getLatitude(String id) { + if(regionCentersMap.containsKey(id)) { + String center = this.regionCentersMap.get(id); + StringTokenizer tokenizer = new StringTokenizer(center, ","); //$NON-NLS-1$ + String lat = tokenizer.nextToken().trim(); + double latVal = (new Double(lat)).doubleValue(); + return latVal; + } else { + Activator.logInformation("1. CenterReader(): Error, region "+id+" not found"); //$NON-NLS-1$ //$NON-NLS-2$ + return -999; + } + + } + + /** + * returns double[2] (lat,lng) + * @param id + * @return + */ + public double[] getLatLong(String id) { + double[] retVal = new double[2]; + if(regionCentersMap.containsKey(id)) { + String center = this.regionCentersMap.get(id); + StringTokenizer tokenizer = new StringTokenizer(center, ","); //$NON-NLS-1$ + String lat = tokenizer.nextToken().trim(); + String lng = tokenizer.nextToken().trim(); + retVal[0] = (new Double(lat)).doubleValue(); + retVal[1] = (new Double(lng)).doubleValue(); + return retVal; + } else { + Activator.logInformation("2. CenterReader(): Warning, region "+id+" not found"); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + + } + + + + +}// class \ No newline at end of file