org.opengis.referencing.ReferenceIdentifier Java Examples

The following examples show how to use org.opengis.referencing.ReferenceIdentifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MapProjectionTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the primary name of the given parameter is the given name in the EPSG namespace.
 * Then asserts that the first alias (ignoring other EPSG alias) of the given parameter is the
 * given name in the OGC namespace.
 */
private static void assertParamEquals(final String epsgName, final String ogcName, final boolean isMandatory,
        final GeneralParameterDescriptor actual)
{
    if (epsgName != null) {
        assertEpsgIdentifierEquals(epsgName, actual.getName());
    } else {
        assertOgcIdentifierEquals(ogcName, actual.getName());
    }
    assertEquals("minimumOccurs", isMandatory ? 1 : 0, actual.getMinimumOccurs());
    if (epsgName != null) {
        for (final GenericName alias : actual.getAlias()) {
            if (alias instanceof ReferenceIdentifier && ((ReferenceIdentifier) alias).getAuthority() != Citations.EPSG) {
                assertOgcIdentifierEquals(ogcName, (ReferenceIdentifier) alias);
                return;
            }
        }
        fail("OGC alias not found.");
    }
}
 
Example #2
Source File: PropertyAccessorTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the constructor with a method which override an other method with covariant return type.
 * This test may need to be updated if a future GeoAPI release modifies the {@link GeographicCRS} interface.
 */
@Test
@DependsOnMethod("testConstructorWithInheritance")
public void testConstructorWithCovariantReturnType() {
    final Class<?> type = GeographicCRS.class;
    assertMappingEquals(new PropertyAccessor(type, type, type),
    //……Declaring type……………………………Method……………………………………………JavaBeans……………………………UML identifier………………Sentence…………………………………Type…………………………………………………………
        GeographicCRS.class,    "getCoordinateSystem", "coordinateSystem", "coordinateSystem", "Coordinate system",  EllipsoidalCS.class,       // Covariant return type
        GeodeticCRS.class,      "getDatum",            "datum",            "datum",            "Datum",              GeodeticDatum.class,       // Covariant return type
        IdentifiedObject.class, "getName",             "name",             "name",             "Name",               ReferenceIdentifier.class,
        IdentifiedObject.class, "getAlias",            "alias",            "alias",            "Alias",              GenericName[].class,
        ReferenceSystem.class,  "getDomainOfValidity", "domainOfValidity", "domainOfValidity", "Domain of validity", Extent.class,
        IdentifiedObject.class, "getIdentifiers",      "identifiers",      "identifier",       "Identifiers",        ReferenceIdentifier[].class,
        IdentifiedObject.class, "getRemarks",          "remarks",          "remarks",          "Remarks",            InternationalString.class,
        ReferenceSystem.class,  "getScope",            "scope",            "SC_CRS.scope",     "Scope",              InternationalString.class);
}
 
Example #3
Source File: CharSequenceSubstitutionTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests unmarshalling of {@code "RS_Identifier"} element. This element was defined in legacy ISO 19139:2007
 * but has been removed in ISO 19115-3. That element is extensively used for Coordinate Reference Systems in
 * GML 3.2.
 *
 * @throws JAXBException if the unmarshalling failed.
 */
@Test
@DependsOnMethod("testAnchorForString")
public void testLegacy() throws JAXBException {
    final String expected =
            "<gmd:MD_ReferenceSystem xmlns:gmd=\""   + LegacyNamespaces.GMD + '"' +
                                   " xmlns:gmx=\""   + LegacyNamespaces.GMX + '"' +
                                   " xmlns:gco=\""   + LegacyNamespaces.GCO + '"' +
                                   " xmlns:xlink=\"" + Namespaces.XLINK + "\">\n" +
            "  <gmd:referenceSystemIdentifier>" +
            "    <gmd:RS_Identifier>" +
            "      <gmd:code>\n" +
            "        <gmx:Anchor xlink:href=\"SDN:L101:2:4326\">EPSG:4326</gmx:Anchor>\n" +
            "      </gmd:code>\n" +
            "      <gmd:codeSpace>\n" +
            "        <gco:CharacterString>L101</gco:CharacterString>\n" +
            "      </gmd:codeSpace>\n" +
            "    </gmd:RS_Identifier>" +
            "  </gmd:referenceSystemIdentifier>" +
            "</gmd:MD_ReferenceSystem>";

    final ReferenceSystemMetadata md = unmarshal(ReferenceSystemMetadata.class, expected);
    final ReferenceIdentifier id = md.getName();
    assertEquals("codespace", "L101", id.getCodeSpace());
    assertEquals("code", "EPSG:4326", id.getCode());
}
 
Example #4
Source File: SimpleIdentifiedObject.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a pseudo-WKT representation for debugging purpose.
 */
@Override
public String toString() {
    final String code, codespace;
    final Citation authority;
    final ReferenceIdentifier name = this.name;
    if (name != null) {
        code      = name.getCode();
        codespace = name.getCodeSpace();
        authority = name.getAuthority();
    } else {
        code      = null;
        codespace = null;
        authority = null;
    }
    final StringBuilder buffer = new StringBuilder("IdentifiedObject[\"");
    if (codespace != null) {
        buffer.append(codespace).append(Constants.DEFAULT_SEPARATOR);
    }
    buffer.append(code).append('"');
    final String identifier = Identifiers.getIdentifier(authority, true);
    if (identifier != null) {
        buffer.append(", Id[\"").append(identifier).append("\"]");   // "Id" should be consistent with WKTKeywords.Id.
    }
    return buffer.append(']').toString();
}
 
Example #5
Source File: AbstractProvider.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Work around for RFE #4093999 in Sun's bug database
 * ("Relax constraint on placement of this()/super() call in constructors").
 */
@Workaround(library="JDK", version="1.7")
private static Map<String,Object> toMap(final IdentifiedObject parameters) {
    ArgumentChecks.ensureNonNull("parameters", parameters);
    final Map<String,Object> properties = new HashMap<>(4);
    properties.put(NAME_KEY, parameters.getName());
    final Collection<ReferenceIdentifier> identifiers = parameters.getIdentifiers();
    int size = identifiers.size();
    if (size != 0) {
        properties.put(IDENTIFIERS_KEY, identifiers.toArray(new ReferenceIdentifier[size]));
    }
    final Collection<GenericName> aliases = parameters.getAlias();
    size = aliases.size();
    if (size != 0) {
        properties.put(ALIAS_KEY, aliases.toArray(new GenericName[size]));
    }
    return properties;
}
 
Example #6
Source File: ServicesForMetadata.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an identifier for the given object, giving precedence to EPSG identifier if available.
 * The returned string should be of the form {@code "AUTHORITY:CODE"} if possible (no guarantees).
 *
 * @param  object  the object for which to get an identifier.
 * @return an identifier for the given object, with preference given to EPSG codes.
 * @throws FactoryException if an error occurred while searching for the EPSG code.
 *
 * @since 1.0
 */
@Override
public String getPreferredIdentifier(final IdentifiedObject object) throws FactoryException {
    final Integer code = IdentifiedObjects.lookupEPSG(object);
    if (code != null) {
        return Constants.EPSG + Constants.DEFAULT_SEPARATOR + code;
    }
    /*
     * If above code did not found an EPSG code, discard EPSG codes that
     * we may find in the loop below because they are probably invalid.
     */
    for (final ReferenceIdentifier id : object.getIdentifiers()) {
        if (!Constants.EPSG.equalsIgnoreCase(id.getCodeSpace())) {
            return IdentifiedObjects.toString(id);
        }
    }
    return IdentifiedObjects.getSimpleNameOrIdentifier(object);
}
 
Example #7
Source File: ParametersTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of {@link #testValueDomain()} on a single descriptor instance.
 * This method test two paths:
 *
 * <ul>
 *   <li>The special case for {@link DefaultParameterDescriptor} instances.</li>
 *   <li>The fallback for generic cases. For that test, we wrap the descriptor in an anonymous class
 *       for hiding the fact that the descriptor is an instance of {@code DefaultParameterDescriptor}.</li>
 * </ul>
 */
private static <T extends Comparable<? super T>> void verifyValueDomain(
        final Range<T> valueDomain, final ParameterDescriptor<T> descriptor)
{
    assertEquals(valueDomain, Parameters.getValueDomain(descriptor));
    assertEquals(valueDomain, Parameters.getValueDomain(new ParameterDescriptor<T>() {
        @Override public ReferenceIdentifier      getName()          {return descriptor.getName();}
        @Override public Collection<GenericName>  getAlias()         {return descriptor.getAlias();}
        @Override public Set<ReferenceIdentifier> getIdentifiers()   {return descriptor.getIdentifiers();}
        @Override public InternationalString      getRemarks()       {return descriptor.getRemarks();}
        @Override public int                      getMinimumOccurs() {return descriptor.getMinimumOccurs();}
        @Override public int                      getMaximumOccurs() {return descriptor.getMaximumOccurs();}
        @Override public Class<T>                 getValueClass()    {return descriptor.getValueClass();}
        @Override public Set<T>                   getValidValues()   {return descriptor.getValidValues();}
        @Override public Comparable<T>            getMinimumValue()  {return descriptor.getMinimumValue();}
        @Override public Comparable<T>            getMaximumValue()  {return descriptor.getMaximumValue();}
        @Override public T                        getDefaultValue()  {return descriptor.getDefaultValue();}
        @Override public Unit<?>                  getUnit()          {return descriptor.getUnit();}
        @Override public ParameterValue<T>        createValue()      {return descriptor.createValue();}
        @Override public String                   toWKT()            {return descriptor.toWKT();}
    }));
}
 
Example #8
Source File: DefaultGeographicCRS.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a coordinate reference system of the same type than this CRS but with different axes.
 *
 * <h4>Special case</h4>
 * If the first axis is the longitude in the [-180 … +180]° range and the identifier is EPSG:4267,
 * EPSG:4269 or EPSG:4326, then this method magically add the CRS:27, CRS:83 or CRS:84 identifier.
 * Without this special case, the normal behavior would be no identifier. The expected behavior is
 * that {@code CommonCRS.WGS84.normalizedGeographic()} returns a CRS having the "CRS:84" identifier.
 */
@Override
final AbstractCRS createSameType(Map<String,?> properties, final CoordinateSystem cs) {
    final CoordinateSystemAxis axis = cs.getAxis(0);
    if (axis.getMinimumValue() == Longitude.MIN_VALUE &&
        axis.getMaximumValue() == Longitude.MAX_VALUE) // For excluding the AxesConvention.POSITIVE_RANGE case.
    {
        for (final ReferenceIdentifier identifier : super.getIdentifiers()) {
            if (EPSG.equals(identifier.getCodeSpace())) try {
                final int i = Arrays.binarySearch(EPSG_CODES, Short.parseShort(identifier.getCode()));
                if (i >= 0) {
                    final Map<String,Object> c = new HashMap<>(properties);
                    c.put(IDENTIFIERS_KEY, new ImmutableIdentifier(Citations.WMS, CRS, Short.toString(CRS_CODES[i])));
                    properties = c;
                }
            } catch (NumberFormatException e) {
                // Okay to igore, because it is not the purpose of this method to disallow non-numeric codes.
            }
        }
    }
    return new DefaultGeographicCRS(properties, super.getDatum(), (EllipsoidalCS) cs);
}
 
Example #9
Source File: ServiceParameter.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the parameter name as a {@code MemberName}. This method first checks if the primary name is an instance of
 * {@code MemberName}. If not, this method searches for the first alias which is an instance of {@code MemberName}.
 * If none is found, then this method tries to build a member name from the primary name and value class.
 *
 * @param  parameter  the parameter from which to get the name (may be {@code null}).
 * @return the member name, or {@code null} if none.
 */
public static MemberName getMemberName(final ParameterDescriptor<?> parameter) {
    if (parameter != null) {
        final ReferenceIdentifier id = parameter.getName();
        if (id instanceof MemberName) {
            return (MemberName) id;
        }
        for (final GenericName alias : nonNull(parameter.getAlias())) {
            if (alias instanceof MemberName) {
                return (MemberName) alias;
            }
        }
        if (id != null) {
            final Class<?> valueClass = parameter.getValueClass();
            if (valueClass != null) {
                final String code = id.getCode();
                if (code != null) {
                    return Names.createMemberName(id.getCodeSpace(), null, code, valueClass);
                }
            }
        }
    }
    return null;
}
 
Example #10
Source File: CoordinateOperationMethods.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the primary name and aliases.
 */
private void writeName(final ParameterDescriptor<?> param) throws IOException {
    final int td = openTag("td class=\"sep\"");
    openTag("details");
    final ReferenceIdentifier name = param.getName();
    final String codeSpace = name.getCodeSpace();
    if (Constants.EPSG.equalsIgnoreCase(codeSpace)) {
        println("summary", escape(name.getCode()));
    } else {
        println("summary", "<span class=\"non-epsg\">" + codeSpace + ":</span>" +
                           "<code>" + name.getCode() + "</code>");
    }
    openTag("table class=\"aliases\"");
    for (final GenericName alias : param.getAlias()) {
        reopenTag("tr");
        println("th", escape(alias.head().toString() + ':'));
        println("td", escape(alias.tip().toString()));
    }
    closeTags(td);
}
 
Example #11
Source File: IdentifiedObjectFormat.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Formats the given object.
 */
@Override
public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
    final ReferenceIdentifier identifier = ((IdentifiedObject) obj).getName();
    if (identifier == null) {
        return toAppendTo.append(Vocabulary.getResources(locale).getString(Vocabulary.Keys.Unnamed));
    }
    if (identifier instanceof GenericName) {
        // The toString() behavior is specified by the GenericName javadoc.
        return toAppendTo.append(((GenericName) identifier).toInternationalString().toString(locale));
    }
    final String code = identifier.getCode();
    String cs = identifier.getCodeSpace();
    if (cs == null || cs.isEmpty()) {
        cs = MetadataServices.getInstance().getUnicodeIdentifier(identifier.getAuthority());
    }
    if (cs != null) {
        toAppendTo.append(cs).append(Constants.DEFAULT_SEPARATOR);
    }
    return toAppendTo.append(code);
}
 
Example #12
Source File: NamedIdentifierTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the {@link NamedIdentifier#NamedIdentifier(GenericName)} constructor.
 */
@Test
public void testCreateFromName() {
    final NameFactory factory = DefaultFactories.forBuildin(NameFactory.class);
    final NameSpace scope = factory.createNameSpace(factory.createLocalName(null, "IOGP"), null);
    final NamedIdentifier identifier = new NamedIdentifier(factory.createGenericName(scope, "EPSG", "4326"));
    Validators.validate((ReferenceIdentifier) identifier);
    Validators.validate((GenericName) identifier);

    // ImmutableIdentifier properties
    assertEquals("code",      "4326", identifier.getCode());
    assertEquals("codeSpace", "EPSG", identifier.getCodeSpace());
    assertEquals("authority", "IOGP", Citations.toCodeSpace(identifier.getAuthority()));
    assertNull  ("version",           identifier.getVersion());
    assertNull  ("description",       identifier.getDescription());

    // NamedIdentifier properties
    assertEquals("depth",  2,          identifier.depth());
    assertEquals("tip",   "4326",      identifier.tip().toString());
    assertEquals("head",  "EPSG",      identifier.head().toString());
    assertEquals("name",  "EPSG:4326", identifier.toString());
    assertSame  ("scope", scope,       identifier.scope());
    assertFalse ("scope.isGlobal",     scope.isGlobal());
    assertEquals("scope", "IOGP",      scope.name().toString());
}
 
Example #13
Source File: ProductLayerAssistantPage.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private static boolean haveCommonReferenceIdentifiers(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2) {
    Set<ReferenceIdentifier> identifiers1 = crs1.getIdentifiers();
    Set<ReferenceIdentifier> identifiers2 = crs2.getIdentifiers();
    // If a CRS does not have identifiers or if they have different number of identifiers
    // they cannot be equal.
    if (identifiers1 == null || identifiers1.isEmpty()
            || identifiers2 == null || identifiers2.isEmpty()
            || identifiers1.size() != identifiers2.size()) {
        return false;
    }
    // The two CRSs can only be equal if they have the same number of identifiers
    // and all of them are common to both.
    int eqCount = 0;
    for (ReferenceIdentifier refId1 : identifiers1) {
        for (ReferenceIdentifier refId2 : identifiers2) {
            if (compareRefIds(refId1, refId2)) {
                eqCount++;
                break;
            }
        }
    }
    return eqCount == identifiers1.size();
}
 
Example #14
Source File: CoordManager.java    From sldeditor with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets the CRS code.
 *
 * @param coordinateReferenceSystem the coordinate reference system
 * @return the CRS code
 */
public String getCRSCode(CoordinateReferenceSystem coordinateReferenceSystem) {
    ReferenceIdentifier identifier = null;
    if (coordinateReferenceSystem != null) {
        Set<ReferenceIdentifier> indentifierList = coordinateReferenceSystem.getIdentifiers();

        if ((indentifierList != null) && indentifierList.iterator().hasNext()) {
            identifier = indentifierList.iterator().next();
        }
    }

    String code = NOT_SET_CRS;

    if (identifier != null) {
        ValueComboBoxData data = crsMap.get(identifier.toString());
        if (data != null) {
            code = data.getKey();
        }
    }
    return code;
}
 
Example #15
Source File: MD_Identifier.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by JAXB at marshalling time for getting the actual metadata to write
 * inside the {@code <mcc:MD_Identifier>} or {@code RS_Identifier} XML element.
 * This is the value or a copy of the value given in argument to the {@code wrap} method.
 *
 * @return the metadata to be marshalled.
 */
@XmlElementRef
public final DefaultIdentifier getElement() {
    if (FilterByVersion.LEGACY_METADATA.accept() && metadata instanceof ReferenceIdentifier) {
        /*
         * In legacy specification, "code space" and "version" were not defined in <gmd:MD_Identifier> but were
         * defined in <gmd:RS_Identifier> subclass. In newer specification there is no longer such special case.
         * Note that "description" did not existed anywhere in legacy specification.
         */
        final ReferenceIdentifier id = (ReferenceIdentifier) metadata;
        if (id.getCodeSpace() != null || id.getVersion() != null) {
            return RS_Identifier.wrap(id);
        }
    }
    return DefaultIdentifier.castOrCopy(metadata);
}
 
Example #16
Source File: Builder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an identifier for the given authority, code space and version.
 * The new identifier will be marked as deprecated if {@link #isDeprecated()} returns {@code true}.
 */
private ReferenceIdentifier createIdentifier(final Citation authority,
        final String codeSpace, final String identifier, final String version)
{
    if (isDeprecated()) {
        return new DeprecatedCode(authority, codeSpace, identifier, version, null, getRemarks());
    } else {
        return new ImmutableIdentifier(authority, codeSpace, identifier, version, getDescription());
    }
}
 
Example #17
Source File: Builder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new builder initialized to properties of the given object.
 * The properties recognized by this constructor are documented
 * {@linkplain IdentifiedObjects#getProperties(IdentifiedObject, String...) here}.
 *
 * @param object  the identified object from which to inherit properties, or {@code null}.
 *
 * @since 0.6
 */
protected Builder(final IdentifiedObject object) {
    this();
    if (object != null) {
        properties.putAll(IdentifiedObjects.getProperties(object));
        final GenericName[] valueAlias = (GenericName[]) properties.remove(IdentifiedObject.ALIAS_KEY);
        final ReferenceIdentifier[] valueIds = (ReferenceIdentifier[]) properties.remove(IdentifiedObject.IDENTIFIERS_KEY);
        if (valueAlias != null) aliases.addAll(Arrays.asList(valueAlias));
        if (valueIds != null) identifiers.addAll(Arrays.asList(valueIds));
    }
}
 
Example #18
Source File: AbstractIdentifiedObject.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by JAXB at unmarshalling time for each identifier. The first identifier will be taken
 * as the name and all other identifiers (if any) as aliases.
 *
 * <p>Some (but not all) JAXB implementations never invoke setter method for collections.
 * Instead they invoke {@link AbstractIdentifiedObject#getNames()} and add directly the identifiers
 * in the returned collection. Consequently this method must writes directly in the enclosing object.
 * See <a href="https://java.net/jira/browse/JAXB-488">JAXB-488</a> for more information.</p>
 */
@Override
public boolean add(final ReferenceIdentifier id) {
    if (NameIterator.isUnnamed(name)) {
        name = id;
    } else {
        /*
         * Our Code and RS_Identifier implementations should always create NamedIdentifier instance,
         * so the 'instanceof' check should not be necessary. But we do a paranoiac check anyway.
         */
        final GenericName n = id instanceof GenericName ? (GenericName) id : new NamedIdentifier(id);
        if (alias == null) {
            alias = Collections.singleton(n);
        } else {
            /*
             * This implementation is inefficient since each addition copies the array, but we rarely
             * have more than two aliases.  This implementation is okay for a small number of aliases
             * and ensures that the enclosing AbstractIdentifiedObject is unmodifiable except by this
             * add(…) method.
             *
             * Note about alternative approaches
             * ---------------------------------
             * An alternative approach could be to use an ArrayList and replace it by an unmodifiable
             * list only after unmarshalling (using an afterUnmarshal(Unmarshaller, Object) method),
             * but we want to avoid Unmarshaller dependency (for reducing classes loading for users
             * who are not interrested in XML) and it may actually be less efficient for the vast
             * majority of cases where there is less than 3 aliases.
             */
            final int size = alias.size();
            final GenericName[] names = alias.toArray(new GenericName[size + 1]);
            names[size] = n;
            alias = UnmodifiableArrayList.wrap(names);
        }
    }
    return true;
}
 
Example #19
Source File: ImmutableIdentifier.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new identifier from the specified one. This is a copy constructor which
 * get the code, codespace, authority and version from the given identifier.
 *
 * @param identifier  the identifier to copy.
 *
 * @see #castOrCopy(ReferenceIdentifier)
 */
public ImmutableIdentifier(final ReferenceIdentifier identifier) {
    ensureNonNull("identifier", identifier);
    code        = identifier.getCode();
    codeSpace   = identifier.getCodeSpace();
    authority   = identifier.getAuthority();
    version     = identifier.getVersion();
    if (identifier instanceof DefaultIdentifier) {
        description = ((DefaultIdentifier) identifier).getDescription();
    } else {
        description = null;
    }
    validate(null);
}
 
Example #20
Source File: CrsUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if a crs is valid, i.e. if it is not a wildcard default one.
 * 
 * @param crs the crs to check.
 */
public static boolean isCrsValid( CoordinateReferenceSystem crs ) {
    if (crs instanceof AbstractSingleCRS) {
        AbstractSingleCRS aCrs = (AbstractSingleCRS) crs;
        Datum datum = aCrs.getDatum();
        ReferenceIdentifier name = datum.getName();
        String code = name.getCode();
        if (code.equalsIgnoreCase("Unknown")) {
            return false;
        }
    }
    return true;
}
 
Example #21
Source File: CC_GeneralOperationParameter.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Given an {@link Identifier} or {@link GenericName} instance, returns that instance as a {@link NamedIdentifier}
 * implementation. The intent is to allow {@code Object.equals(Object)} and hash code to correctly recognize two
 * names or identifiers as equal even if they are of different implementations.
 *
 * <p>Note that {@link NamedIdentifier} is the type of unmarshalled names, aliases and identifiers.
 * So this method should not create any new object in a majority of cases.</p>
 */
private static NamedIdentifier toNamedIdentifier(final Object name) {
    if (name == null || name.getClass() == NamedIdentifier.class) {
        return (NamedIdentifier) name;
    } else if (name instanceof ReferenceIdentifier) {
        return new NamedIdentifier((ReferenceIdentifier) name);
    } else {
        return new NamedIdentifier((GenericName) name);
    }
}
 
Example #22
Source File: Code.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a wrapper initialized to the values of the given identifier.
 * Version number, if presents, will be appended after the codespace with a semicolon separator.
 * The {@link #getIdentifier()} method shall be able to perform the opposite operation (split the
 * above in separated codespace and version attributes).
 *
 * @param identifier  the identifier from which to get the values.
 */
Code(final ReferenceIdentifier identifier) {
    code      = identifier.getCode();
    codeSpace = identifier.getCodeSpace();
    String version = identifier.getVersion();
    if (version != null) {
        final StringBuilder buffer = new StringBuilder();
        if (codeSpace != null) {
            buffer.append(codeSpace);
        }
        codeSpace = buffer.append(DefinitionURI.SEPARATOR).append(version).toString();
    }
}
 
Example #23
Source File: CodeTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Code#forIdentifiedObject(Class, Iterable)}.
 */
@Test
@DependsOnMethod("testWithVersion")
public void testForIdentifiedObject() {
    final ReferenceIdentifier id = new ImmutableIdentifier(Citations.EPSG, "EPSG", "4326", "8.2", null);
    final Code value = Code.forIdentifiedObject(GeographicCRS.class, Collections.singleton(id));
    assertNotNull(value);
    assertEquals("codeSpace", Constants.IOGP, value.codeSpace);
    assertEquals("code", "urn:ogc:def:crs:EPSG:8.2:4326", value.code);
}
 
Example #24
Source File: CoordinateOperationMethods.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first EPSG code found in the given collection, or {@code null} if none.
 */
private static String getFirstEpsgCode(final Iterable<? extends ReferenceIdentifier> identifiers) {
    for (final ReferenceIdentifier id : identifiers) {
        if (Constants.EPSG.equalsIgnoreCase(id.getCodeSpace())) {
            return id.getCode();
        }
    }
    return null;
}
 
Example #25
Source File: BuilderTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Builder#setCodeSpace(Citation, String)}.
 */
@Test
public void testSetCodeSpace() {
    final BuilderMock builder = new BuilderMock();
    builder.setCodeSpace(Citations.EPSG, "EPSG");
    builder.addName("Mercator (variant A)");
    /*
     * Setting the same codespace should have no effect, while attempt to
     * set a new codespace after we added a name shall not be allowed.
     */
    final SimpleCitation IOGP = new SimpleCitation("IOGP");
    builder.setCodeSpace(Citations.EPSG, "EPSG");
    try {
        builder.setCodeSpace(IOGP, "EPSG");
        fail("Setting a different codespace shall not be allowed.");
    } catch (IllegalStateException e) {
        final String message = e.getMessage();
        assertTrue(message, message.contains(Identifier.AUTHORITY_KEY));
    }
    /*
     * The failed attempt to set a new codespace shall not have modified builder state.
     */
    assertEquals("EPSG",         builder.properties.get(ReferenceIdentifier.CODESPACE_KEY));
    assertSame  (Citations.EPSG, builder.properties.get(Identifier.AUTHORITY_KEY));
    /*
     * After a cleanup (normally after a createXXX(…) method call), user shall be allowed to
     * set a new codespace again. Note that the cleanup operation shall not clear the codespace.
     */
    builder.onCreate(true);
    assertEquals("EPSG",         builder.properties.get(ReferenceIdentifier.CODESPACE_KEY));
    assertSame  (Citations.EPSG, builder.properties.get(Identifier.AUTHORITY_KEY));
    builder.setCodeSpace(IOGP, "EPSG");
    assertEquals("EPSG", builder.properties.get(ReferenceIdentifier.CODESPACE_KEY));
    assertSame  ( IOGP,  builder.properties.get(Identifier.AUTHORITY_KEY));
}
 
Example #26
Source File: BuilderTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests {@link Builder#addNamesAndIdentifiers(IdentifiedObject)}.
 *
 * @since 0.6
 */
@Test
@DependsOnMethod({"testAddNameWithScope", "testAddIdentifiers"})
public void testAddNamesAndIdentifiers() {
    final BuilderMock builder = createMercator(true, true);
    final AbstractIdentifiedObject object = new AbstractIdentifiedObject(builder.properties);
    builder.onCreate(true);
    for (final Map.Entry<String,?> entry : builder.properties.entrySet()) {
        final Object value = entry.getValue();
        switch (entry.getKey()) {
            case Identifier.AUTHORITY_KEY: {
                assertSame("Authority and codespace shall be unchanged.", Citations.EPSG, value);
                break;
            }
            case ReferenceIdentifier.CODESPACE_KEY: {
                assertEquals("Authority and codespace shall be unchanged.", "EPSG", value);
                break;
            }
            default: {
                assertNull("Should not contain any non-null value except the authority.", value);
                break;
            }
        }
    }
    assertSame(builder, builder.addNamesAndIdentifiers(object));
    builder.onCreate(false);
    assertSame       ("name",        object.getName(),                  builder.getName());
    assertArrayEquals("aliases",     object.getAlias().toArray(),       builder.getAliases());
    assertArrayEquals("identifiers", object.getIdentifiers().toArray(), builder.getIdentifiers());
}
 
Example #27
Source File: AbstractIdentifiedObjectTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the {@link AbstractIdentifiedObject#AbstractIdentifiedObject(Map)} constructor without identifier.
 * This method compares the property values against the expected values.
 */
@Test
public void testWithoutIdentifier() {
    final Set<ReferenceIdentifier> identifiers = Collections.emptySet();
    final AbstractIdentifiedObject object      = new AbstractIdentifiedObject(properties(identifiers));
    final ReferenceIdentifier      gmlId       = validate(object, identifiers, "GRS1980");
    assertNull("gmlId", gmlId);
}
 
Example #28
Source File: AbstractIdentifiedObjectTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the {@link AbstractIdentifiedObject#AbstractIdentifiedObject(Map)} constructor
 * with only one identifier. The methods of interest for this test are:
 *
 * <ul>
 *   <li>{@link AbstractIdentifiedObject#getIdentifiers()}</li>
 *   <li>{@link AbstractIdentifiedObject#getIdentifier()}</li>
 *   <li>{@link AbstractIdentifiedObject#getID()}</li>
 * </ul>
 */
@Test
@DependsOnMethod("testWithoutIdentifier")
public void testWithSingleIdentifier() {
    final ReferenceIdentifier      identifier  = new ImmutableIdentifier(null, "EPSG", "7019");
    final Set<ReferenceIdentifier> identifiers = Collections.singleton(identifier);
    final AbstractIdentifiedObject object      = new AbstractIdentifiedObject(properties(identifiers));
    final ReferenceIdentifier      gmlId       = validate(object, identifiers, "epsg-7019");
    assertNotNull("gmlId",                   gmlId);
    assertEquals ("gmlId.codespace", "EPSG", gmlId.getCodeSpace());
    assertEquals ("gmlId.code",      "7019", gmlId.getCode());
}
 
Example #29
Source File: AbstractIdentifiedObjectTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the {@link AbstractIdentifiedObject#AbstractIdentifiedObject(Map)} constructor
 * with more than one identifier. This method also tries a different identifier implementation
 * than the one used by {@link #testWithSingleIdentifier()}.
 */
@Test
@DependsOnMethod("testWithSingleIdentifier")
public void testWithManyIdentifiers() {
    final Set<ReferenceIdentifier> identifiers = new LinkedHashSet<>(4);
    assertTrue(identifiers.add(new NamedIdentifier(EPSG, "7019")));
    assertTrue(identifiers.add(new NamedIdentifier(EPSG, "IgnoreMe")));
    final AbstractIdentifiedObject object = new AbstractIdentifiedObject(properties(identifiers));
    final ReferenceIdentifier      gmlId  = validate(object, identifiers, "epsg-7019");
    assertNotNull("gmlId",                   gmlId);
    assertEquals ("gmlId.codespace", "EPSG", gmlId.getCodeSpace());
    assertEquals ("gmlId.code",      "7019", gmlId.getCode());
}
 
Example #30
Source File: AbstractIdentifiedObjectTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests serialization.
 */
@Test
@DependsOnMethod("testWithoutIdentifier")
public void testSerialization() {
    final Set<ReferenceIdentifier> identifiers = Collections.emptySet();
    final AbstractIdentifiedObject object = new AbstractIdentifiedObject(properties(identifiers));
    final AbstractIdentifiedObject actual = assertSerializedEquals(object);
    assertNotSame(object, actual);
    assertNull("gmlId", validate(actual, identifiers, "GRS1980"));
}