Example usage for org.joda.time.format DateTimeFormatter parseDateTime

List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter parseDateTime.

Prototype

public DateTime parseDateTime(String text) 

Source Link

Document

Parses a date-time from the given text, returning a new DateTime.

Usage

From source file:org.craftercms.search.service.impl.SolrDocumentBuilder.java

License:Open Source License

protected String convertToISODateTimeString(String dateTimeStr) {
    DateTimeFormatter incomingFormatter = DateTimeFormat.forPattern(dateTimeFieldPattern);
    DateTimeFormatter outgoingFormatter = ISODateTimeFormat.dateTime();

    return outgoingFormatter.print(incomingFormatter.parseDateTime(dateTimeStr));
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchValueTypeMapper.java

License:Apache License

public Date parseDate(ElasticSearchDataSetDef definition, String columnId, String date) throws ParseException {
    if (isEmpty(date))
        return null;

    String datePattern = definition.getPattern(columnId);
    boolean isDefaultDateFormat = isEmpty(datePattern) || datePattern.equalsIgnoreCase(DATE_DEFAULT_FORMAT_KEY);
    DateTimeFormatter formatter = isDefaultDateFormat ? DATE_DEFAULT_FORMAT_PARSER
            : DateTimeFormat.forPattern(datePattern);
    DateTime dateTime = formatter.parseDateTime(date);
    return dateTime.toDate();
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The formatted value for the given column type.
 *//*from  w ww  .  ja va 2s .c o  m*/
public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata,
        DataColumn column, JsonElement valueElement) {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();

    ColumnType columnType = column.getColumnType();

    if (ColumnType.NUMBER.equals(columnType)) {

        return valueElement.getAsDouble();

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {

            DateTimeFormatter formatter = null;
            String datePattern = metadata.getFieldPattern(column.getId());
            if (datePattern == null || datePattern.trim().length() == 0) {
                // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser
                formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER;
            } else {
                // Obtain the date value by parsing using the EL pattern specified for this field.
                formatter = DateTimeFormat.forPattern(datePattern);
            }

            DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString());
            return dateTime.toDate();
        }

        if (valuePrimitive.isNumber()) {

            return new Date(valuePrimitive.getAsLong());

        }

        throw new UnsupportedOperationException(
                "Value core type not supported. Expecting string or number when using date core field types.");

    }

    // LABEL, TEXT or grouped DATE column types.
    String valueAsString = valueElement.getAsString();
    ColumnGroup columnGroup = column.getColumnGroup();

    // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1")
    if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy())
            && valueAsString.startsWith("0"))
        return valueAsString.substring(1);

    return valueAsString;
}

From source file:org.datacleaner.beans.transform.DateMaskMatcherTransformer.java

License:Open Source License

@Override
public Object[] transform(InputRow inputRow) {
    Object[] result = new Object[_dateMasks.length];

    if (_outputType == MatchOutputType.TRUE_FALSE) {
        Arrays.fill(result, false);
    }//from ww  w  .ja  v a 2s .c  o m

    String value = inputRow.getValue(_column);
    if (value != null) {
        for (int i = 0; i < _dateTimeFormatters.length; i++) {
            DateTimeFormatter dateTimeFormatter = _dateTimeFormatters[i];
            if (dateTimeFormatter != null) {
                boolean match = false;
                try {
                    // this will throw an exception if the value is not
                    // complying to the pattern
                    dateTimeFormatter.parseDateTime(value);
                    match = true;
                } catch (Exception e) {
                    // ignore, it doesn't match
                }

                if (_outputType == MatchOutputType.TRUE_FALSE) {
                    result[i] = match;
                } else if (_outputType == MatchOutputType.INPUT_OR_NULL) {
                    if (match) {
                        result[i] = value;
                    } else {
                        result[i] = null;
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.datacleaner.components.convert.ConvertToDateTransformer.java

License:Open Source License

protected Date convertFromString(final String value) {
    if ("now()".equalsIgnoreCase(value)) {
        return new NowDate();
    }/*from   w w w. jav  a2s .c  om*/
    if ("today()".equalsIgnoreCase(value)) {
        return new TodayDate();
    }
    if ("yesterday()".equalsIgnoreCase(value)) {
        return new YesterdayDate();
    }

    for (DateTimeFormatter formatter : _dateTimeFormatters) {
        try {
            return formatter.parseDateTime(value).toDate();
        } catch (Exception e) {
            // proceed to next formatter
        }
    }

    try {
        long longValue = Long.parseLong(value);
        return convertFromNumber(longValue, false);
    } catch (NumberFormatException e) {
        // do nothing, proceed to dateFormat parsing
    }

    // try also with SimpleDateFormat since it is more fault tolerant in
    // millisecond parsing
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
    format.setTimeZone(TimeZone.getTimeZone(timeZone));
    try {
        return format.parse(value);
    } catch (ParseException e) {
        // do nothing
    }

    return null;
}

From source file:org.datacleaner.components.convert.ConvertToDateTransformer.java

License:Open Source License

protected Date convertFromNumber(Number value, boolean tryDateTimeFormatters) {
    final Number numberValue = (Number) value;
    final long longValue = numberValue.longValue();

    final String stringValue = Long.toString(longValue);

    if (tryDateTimeFormatters) {
        for (int i = 0; i < _dateTimeFormatters.length; i++) {
            final String dateMask = dateMasks[i];
            final boolean isPotentialNumberDateMask = dateMask.indexOf("-") == -1 && dateMask.indexOf(".") == -1
                    && dateMask.indexOf("/") == -1;
            if (isPotentialNumberDateMask) {
                final DateTimeFormatter formatter = _dateTimeFormatters[i];
                try {
                    return formatter.parseDateTime(stringValue).toDate();
                } catch (Exception e) {
                    // proceed to next formatter
                }// w  ww  .j  a v  a2 s.co m
            }
        }
    }

    // test if the number is actually a format of the type yyyyMMdd
    if (stringValue.length() == 8 && (stringValue.startsWith("1") || stringValue.startsWith("2"))) {
        try {
            return _numberBasedDateTimeFormatterLong.parseDateTime(stringValue).toDate();
        } catch (Exception e) {
            // do nothing, proceed to next method of conversion
        }
    }

    // test if the number is actually a format of the type yyMMdd
    if (stringValue.length() == 6) {
        try {
            return _numberBasedDateTimeFormatterShort.parseDateTime(stringValue).toDate();
        } catch (Exception e) {
            // do nothing, proceed to next method of conversion
        }
    }

    if (longValue > 5000000) {
        // this number is most probably amount of milliseconds since
        // 1970
        return new Date(longValue);
    } else {
        // this number is most probably the amount of days since
        // 1970
        return new Date(longValue * 1000 * 60 * 60 * 24);
    }
}

From source file:org.dataconservancy.cos.osf.client.support.JodaSupport.java

License:Apache License

/**
 * Parses a string timestamp into a Joda {@code DateTime} object.
 * <p>/*from  w  w  w  . jav a2 s. c om*/
 * This method is able to parse multiple representations of a timestamp:
 * </p>
 * <ul>
 *   <li>yyyy-MM-dd'T'HH:mm:ss.SSSSSS</li>
 *   <li>yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'</li>
 *   <li>yyyy-MM-dd'T'HH:mm:ss.SSS'Z'</li>
 *   <li>yyyy-MM-dd'T'HH:mm:ss'Z'</li>
 * </ul>
 *
 * @param dateTime a string representing a timestamp
 * @return the Joda {@code DateTime} for the timestamp
 * @throws RuntimeException if the string representing the timestamp cannot be parsed
 */
public static DateTime parseDateTime(final String dateTime) {
    for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) {
        try {
            return formatter.parseDateTime(dateTime);
        } catch (Exception e) {
            // nothing we can do, try the next formatter in line, or error out below.
        }
    }
    throw new RuntimeException(
            "Unable to parse '" + dateTime + "' to a Joda DateTime object: Missing a DateTimeFormatter.");
}

From source file:org.ddialliance.ddiftp.util.Translator.java

License:Open Source License

/**
 * Format an ISO8601 time string defined by into a Calendar<BR>
 * Defined by '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)?
 * (zzzzzz)?// w w w .jav  a  2s .  c om
 * 
 * @see http://www.w3.org/TR/xmlschema-2/#dateTime
 * @param time
 *            string
 * @return calendar
 * @throws DDIFtpException
 */
public static Calendar formatIso8601DateTime(String time) throws DDIFtpException {
    // yyyy-MM-dd'T'HH:mm:ss.SSSZZ full format
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    try {
        DateTime dateTime = fmt.parseDateTime(time);
        return dateTime.toCalendar(getLocale());
    } catch (IllegalArgumentException e) {
        try {
            // yyyy-MM-dd'T'HH:mm:ssZZ with out millisecond
            fmt = ISODateTimeFormat.dateTimeNoMillis();
            fmt.withLocale(getLocale());
            fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
            DateTime dateTime = fmt.parseDateTime(time);
            return dateTime.toCalendar(getLocale());
        } catch (IllegalArgumentException e1) {
            try {
                // yyyy-MM-dd'T'HH:mm:ss.SS with out time zone
                fmt = ISODateTimeFormat.dateHourMinuteSecondFraction();
                fmt.withLocale(getLocale());
                fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                DateTime dateTime = fmt.parseDateTime(time);
                return dateTime.toCalendar(getLocale());
            } catch (Exception e2) {
                try {
                    // yyyy-MM-dd'T'HH:mm:ss with out millisecond and time
                    // zone
                    fmt = ISODateTimeFormat.dateHourMinuteSecond();
                    fmt.withLocale(getLocale());
                    fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                    DateTime dateTime = fmt.parseDateTime(time);
                    return dateTime.toCalendar(getLocale());
                } catch (IllegalArgumentException e3) {
                    try {
                        fmt = ISODateTimeFormat.dateParser();
                        fmt.withLocale(getLocale());
                        fmt.withZone(DateTimeZone.forTimeZone(getTimeZone()));
                        DateTime dateTime = fmt.parseDateTime(time);
                        return dateTime.toCalendar(getLocale());
                    } catch (Exception e4) {
                        throw new DDIFtpException("translate.timeformat.error",
                                new Object[] { time,
                                        "'-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)?" },
                                e);
                    }
                }
            }
        }
    }
}

From source file:org.dllearner.reasoning.ClosedWorldReasoner.java

License:Open Source License

@Override
public boolean hasTypeImpl(OWLClassExpression description, OWLIndividual individual)
        throws ReasoningMethodUnsupportedException {

    if (description.isOWLThing()) {
        return true;
    } else if (description.isOWLNothing()) {
        return false;
    } else if (!description.isAnonymous()) {
        return classInstancesPos.get(description.asOWLClass()).contains(individual);
    } else if (description instanceof OWLObjectComplementOf) {
        OWLClassExpression operand = ((OWLObjectComplementOf) description).getOperand();
        if (!operand.isAnonymous()) {
            if (isDefaultNegation()) {
                return !classInstancesPos.get(operand).contains(individual);
            } else {
                return classInstancesNeg.get(operand).contains(individual);
            }//from   w  w w  .ja va  2  s .  co m
        } else {
            if (isDefaultNegation()) {
                return !hasTypeImpl(operand, individual);
            } else {
                logger.debug(
                        "Converting class expression to negation normal form in fast instance check (should be avoided if possible).");
                return hasTypeImpl(description.getNNF(), individual);
            }
        }
    } else if (description instanceof OWLObjectUnionOf) {
        for (OWLClassExpression operand : ((OWLObjectUnionOf) description).getOperands()) {
            if (hasTypeImpl(operand, individual)) {
                return true;
            }
        }
        return false;
    } else if (description instanceof OWLObjectIntersectionOf) {
        for (OWLClassExpression operand : ((OWLObjectIntersectionOf) description).getOperands()) {
            if (!hasTypeImpl(operand, individual)) {
                return false;
            }
        }
        return true;
    } else if (description instanceof OWLObjectSomeValuesFrom) {
        OWLObjectPropertyExpression property = ((OWLObjectSomeValuesFrom) description).getProperty();
        OWLClassExpression fillerConcept = ((OWLObjectSomeValuesFrom) description).getFiller();

        if (property.isAnonymous()) {// \exists r^{-1}.C
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property.getNamedProperty());

            for (Entry<OWLIndividual, SortedSet<OWLIndividual>> entry : mapping.entrySet()) {
                OWLIndividual subject = entry.getKey();
                SortedSet<OWLIndividual> objects = entry.getValue();

                // check if the individual is contained in the objects and
                // subject is of type C
                if (objects.contains(individual)) {
                    if (hasTypeImpl(fillerConcept, subject)) {
                        return true;
                    }
                }
            }
        } else {// \exists r.C
            if (handlePunning && property == OWLPunningDetector.punningProperty && fillerConcept.isOWLThing()) {
                return true;
            }

            SortedSet<OWLIndividual> values = opPos.get(property).get(individual);

            if (values == null) {
                return false;
            }

            for (OWLIndividual value : values) {
                if (hasTypeImpl(fillerConcept, value)) {
                    return true;
                }
            }
        }

        return false;
    } else if (description instanceof OWLObjectAllValuesFrom) {
        OWLObjectPropertyExpression property = ((OWLObjectAllValuesFrom) description).getProperty();
        OWLClassExpression fillerConcept = ((OWLObjectAllValuesFrom) description).getFiller();

        // \forall r.\top \equiv \top -> TRUE
        if (fillerConcept.isOWLThing()) {
            return true;
        }

        if (property.isAnonymous()) {// \forall r^{-1}.C
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property.getNamedProperty());

            Set<OWLIndividual> values = new HashSet<>();

            for (Entry<OWLIndividual, SortedSet<OWLIndividual>> entry : mapping.entrySet()) {
                OWLIndividual subject = entry.getKey();
                SortedSet<OWLIndividual> objects = entry.getValue();

                if (objects.contains(individual)) {
                    values.add(subject);
                }
            }

            // if there is no value, by standard semantics we have to return TRUE
            if (values.isEmpty()) {
                return forAllSemantics == ForallSemantics.Standard;
            }

            boolean hasCorrectFiller = false;
            for (OWLIndividual value : values) {
                if (hasTypeImpl(fillerConcept, value)) {
                    hasCorrectFiller = true;
                } else {
                    return false;
                }
            }

            if (forAllSemantics == ForallSemantics.SomeOnly) {
                return hasCorrectFiller;
            } else {
                return true;
            }

        } else {// \forall r.C
            SortedSet<OWLIndividual> values = opPos.get(property).get(individual);

            // if there is no value, by standard semantics we have to return TRUE
            if (values == null) {
                return forAllSemantics == ForallSemantics.Standard;
            }

            boolean hasCorrectFiller = false;
            for (OWLIndividual value : values) {
                if (hasTypeImpl(fillerConcept, value)) {
                    hasCorrectFiller = true;
                } else {
                    return false;
                }
            }

            if (forAllSemantics == ForallSemantics.SomeOnly) {
                return hasCorrectFiller;
            } else {
                return true;
            }
        }

    } else if (description instanceof OWLObjectMinCardinality) {
        int cardinality = ((OWLObjectMinCardinality) description).getCardinality();

        // special case: there are always at least zero fillers
        if (cardinality == 0) {
            return true;
        }

        OWLObjectPropertyExpression property = ((OWLObjectMinCardinality) description).getProperty();
        OWLClassExpression fillerConcept = ((OWLObjectMinCardinality) description).getFiller();

        if (property.isAnonymous()) {
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property.getNamedProperty());

            int index = 0;
            int nrOfFillers = 0;
            int nrOfEntries = mapping.keySet().size();
            for (Entry<OWLIndividual, SortedSet<OWLIndividual>> entry : mapping.entrySet()) {
                OWLIndividual subject = entry.getKey();
                SortedSet<OWLIndividual> objects = entry.getValue();

                // count the number of subjects which are related to the individual such that
                // subject is of type C
                if (objects.contains(individual)) {
                    if (hasTypeImpl(fillerConcept, subject)) {
                        nrOfFillers++;

                        if (nrOfFillers == cardinality) {
                            return true;
                        }
                    } else {
                        if (nrOfEntries - index < cardinality) {
                            return false;
                        }
                    }
                }
            }
        } else {
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property);

            int nrOfFillers = 0;

            SortedSet<OWLIndividual> values = mapping.get(individual);

            // return false if there are none or not enough role fillers
            if (values == null
                    || (values.size() < cardinality && property != OWLPunningDetector.punningProperty)) {
                return false;
            }

            int index = 0;
            for (OWLIndividual roleFiller : values) {
                index++;
                if (hasTypeImpl(fillerConcept, roleFiller)) {
                    nrOfFillers++;
                    if (nrOfFillers == cardinality
                            || (handlePunning && property == OWLPunningDetector.punningProperty)) {
                        return true;
                    }
                    // early abort: e.g. >= 10 hasStructure.Methyl;
                    // if there are 11 fillers and 2 are not Methyl, the result
                    // is false
                } else {
                    if (values.size() - index < cardinality) {
                        return false;
                    }
                }
            }
        }

        return false;
    } else if (description instanceof OWLObjectMaxCardinality) {
        OWLObjectPropertyExpression property = ((OWLObjectMaxCardinality) description).getProperty();
        OWLClassExpression fillerConcept = ((OWLObjectMaxCardinality) description).getFiller();
        int cardinality = ((OWLObjectMaxCardinality) description).getCardinality();

        if (property.isAnonymous()) {
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property.getNamedProperty());

            int nrOfFillers = 0;
            int nrOfSubjects = mapping.keySet().size();

            // return TRUE if there are none or not enough subjects
            if (nrOfSubjects < cardinality) {
                return true;
            }

            int index = 0;
            for (Entry<OWLIndividual, SortedSet<OWLIndividual>> entry : mapping.entrySet()) {
                index++;
                OWLIndividual subject = entry.getKey();
                SortedSet<OWLIndividual> objects = entry.getValue();
                if (objects.contains(individual) && hasTypeImpl(fillerConcept, subject)) {
                    nrOfFillers++;
                    if (nrOfFillers > cardinality) {
                        return false;
                    }
                    // early abort: e.g. <= 5 hasStructure.Methyl;
                    // if there are 6 fillers and 2 are not Methyl, the result
                    // is true
                } else {
                    if (nrOfSubjects - index <= cardinality) {
                        return true;
                    }
                }
            }
        } else {
            Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property);

            int nrOfFillers = 0;

            SortedSet<OWLIndividual> roleFillers = mapping.get(individual);

            // return true if there are none or not enough role fillers
            if (roleFillers == null || roleFillers.size() < cardinality) {
                return true;
            }

            int index = 0;
            for (OWLIndividual roleFiller : roleFillers) {
                index++;
                if (hasTypeImpl(fillerConcept, roleFiller)) {
                    nrOfFillers++;
                    if (nrOfFillers > cardinality) {
                        return false;
                    }
                    // early abort: e.g. <= 5 hasStructure.Methyl;
                    // if there are 6 fillers and 2 are not Methyl, the result
                    // is true
                } else {
                    if (roleFillers.size() - index <= cardinality) {
                        return true;
                    }
                }
            }
        }

        return true;
    } else if (description instanceof OWLObjectHasValue) {
        OWLObjectPropertyExpression property = ((OWLObjectHasValue) description).getProperty();
        OWLIndividual value = ((OWLObjectHasValue) description).getFiller();

        Map<OWLIndividual, SortedSet<OWLIndividual>> mapping = opPos.get(property.getNamedProperty());

        if (property.isAnonymous()) {

            for (Entry<OWLIndividual, SortedSet<OWLIndividual>> entry : mapping.entrySet()) {
                OWLIndividual subject = entry.getKey();
                SortedSet<OWLIndividual> objects = entry.getValue();

                if (objects.contains(individual) && subject.equals(value)) {
                    return true;
                }
            }
            return false;
        } else {

            SortedSet<OWLIndividual> values = mapping.get(individual);

            return values != null && values.contains(value);
        }
    } //      else if (OWLClassExpression instanceof BooleanValueRestriction) {
      //         DatatypeProperty dp = ((BooleanValueRestriction) description)
      //               .getRestrictedPropertyExpression();
      //         boolean value = ((BooleanValueRestriction) description).getBooleanValue();
      //
      //         if (value) {
      //            // check whether the OWLIndividual is in the set of individuals
      //            // mapped
      //            // to true by this datatype property
      //            return bdPos.get(dp).contains(individual);
      //         } else {
      //            return bdNeg.get(dp).contains(individual);
      //         }
      //      }
    else if (description instanceof OWLDataSomeValuesFrom) {
        OWLDataPropertyExpression property = ((OWLDataSomeValuesFrom) description).getProperty();
        OWLDataRange filler = ((OWLDataSomeValuesFrom) description).getFiller();

        if (property.isAnonymous()) {
            throw new ReasoningMethodUnsupportedException("Retrieval for class expression " + description
                    + " unsupported. Inverse object properties not supported.");
        }

        if (filler.isDatatype()) { // filler is a datatype
            return dpPos.get(property).containsKey(individual);
        } else if (filler instanceof OWLDatatypeRestriction) {
            OWLDatatype datatype = ((OWLDatatypeRestriction) filler).getDatatype();
            Set<OWLFacetRestriction> facetRestrictions = ((OWLDatatypeRestriction) filler)
                    .getFacetRestrictions();

            if (OWLAPIUtils.floatDatatypes.contains(datatype)) {
                SortedSet<Double> values = dd.get(property).get(individual);

                // no value exists
                if (values == null) {
                    return false;
                }

                double min = -Double.MAX_VALUE;
                double max = Double.MAX_VALUE;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = Double.parseDouble(facet.getFacetValue().getLiteral());
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = Double.parseDouble(facet.getFacetValue().getLiteral());
                    }
                }

                //we can return false if largest number is below minimum or lowest number is above maximum
                if (values.last() < min || values.first() > max) {
                    return false;
                }

                //search a value which is in the interval
                for (Double value : values) {
                    if (value >= min && value <= max) {
                        return true;
                    }
                }
            } else if (OWLAPIUtils.intDatatypes.contains(datatype)) {
                SortedSet<Integer> values = id.get(property).get(individual);

                // no value exists
                if (values == null) {
                    return false;
                }

                int min = Integer.MIN_VALUE;
                int max = Integer.MAX_VALUE;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = facet.getFacetValue().parseInteger();
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = facet.getFacetValue().parseInteger();
                    }
                }

                //we can return false if largest number is below minimum or lowest number is above maximum
                if (values.last() < min || values.first() > max) {
                    return false;
                }

                //search a value which is in the interval
                for (Integer value : values) {
                    if (value >= min && value <= max) {
                        return true;
                    }
                }
            } else if (OWLAPIUtils.dtDatatypes.contains(datatype)) {
                SortedSet<OWLLiteral> values = dpPos.get(property).get(individual);

                // TODO we cannot ensure the sorting, because OWL API does only String comparison
                // on the lexical String value
                // no value exists
                if (values == null) {
                    return false;
                }

                OWLLiteral min = null;
                OWLLiteral max = null;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = facet.getFacetValue();
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = facet.getFacetValue();
                    }
                }

                // we can return false if largest number is below minimum or lowest number is above maximum
                DateTimeFormatter parser = OWLAPIUtils.dateTimeParsers.get(datatype);
                DateTime minDateTime = null;
                if (min != null) {
                    minDateTime = parser.parseDateTime(min.getLiteral());
                }
                DateTime maxDateTime = null;
                if (max != null) {
                    maxDateTime = parser.parseDateTime(max.getLiteral());
                }

                if ((minDateTime != null
                        && parser.parseDateTime(values.last().getLiteral()).isBefore(minDateTime))
                        || (maxDateTime != null
                                && parser.parseDateTime(values.first().getLiteral()).isAfter(maxDateTime))) {
                    return false;
                }

                //search a value which is in the interval
                for (OWLLiteral value : values) {
                    if (OWLAPIUtils.inRange(value, min, max)) {
                        return true;
                    }
                }
                return false;
            }
        } else if (filler.getDataRangeType() == DataRangeType.DATA_ONE_OF) {
            OWLDataOneOf dataOneOf = (OWLDataOneOf) filler;
            Set<OWLLiteral> values = dataOneOf.getValues();

            // given \exists r.{v_1,...,v_n} we can check for each value v_i
            // if (\exists r.{v_i})(ind) holds
            for (OWLLiteral value : values) {

                boolean hasValue = hasTypeImpl(df.getOWLDataHasValue(property, value), individual);

                if (hasValue) {
                    return true;
                }
            }
            return false;
        }
    } else if (description instanceof OWLDataHasValue) {
        OWLDataPropertyExpression property = ((OWLDataHasValue) description).getProperty();
        OWLLiteral value = ((OWLDataHasValue) description).getFiller();

        if (property.isAnonymous()) {
            throw new ReasoningMethodUnsupportedException("Retrieval for class expression " + description
                    + " unsupported. Inverse object properties not supported.");
        }

        Map<OWLIndividual, SortedSet<OWLLiteral>> mapping = dpPos.get(property);

        SortedSet<OWLLiteral> values = mapping.get(individual);

        return values != null && values.contains(value);
    } else if (description instanceof OWLObjectOneOf) {
        return ((OWLObjectOneOf) description).getIndividuals().contains(individual);
    }

    throw new ReasoningMethodUnsupportedException("Instance check for class expression " + description
            + " of type " + description.getClassExpressionType() + " unsupported.");
}

From source file:org.dllearner.reasoning.ClosedWorldReasoner.java

License:Open Source License

@SuppressWarnings("unchecked")
public SortedSet<OWLIndividual> getIndividualsImplFast(OWLClassExpression description)
        throws ReasoningMethodUnsupportedException {
    // policy: returned sets are clones, i.e. can be modified
    // (of course we only have to clone the leafs of a class OWLClassExpression tree)
    if (description.isOWLThing()) {
        return (TreeSet<OWLIndividual>) individuals.clone();
    } else if (description.isOWLNothing()) {
        return new TreeSet<>();
    } else if (!description.isAnonymous()) {
        if (classInstancesPos.containsKey(description.asOWLClass())) {
            return (TreeSet<OWLIndividual>) classInstancesPos.get(description).clone();
        } else {//from  ww  w  .jav a 2s  .c  o  m
            return new TreeSet<>();
        }
    } else if (description instanceof OWLObjectComplementOf) {
        OWLClassExpression operand = ((OWLObjectComplementOf) description).getOperand();
        if (!operand.isAnonymous()) {
            if (isDefaultNegation()) {
                if (precomputeNegations) {
                    return (TreeSet<OWLIndividual>) classInstancesNeg.get(operand).clone();
                }
                SetView<OWLIndividual> diff = Sets.difference(individuals, classInstancesPos.get(operand));
                return new TreeSet<>(diff);
            } else {
                return (TreeSet<OWLIndividual>) classInstancesNeg.get(operand).clone();
            }
        }
        // implement retrieval as default negation
        return new TreeSet<>(Sets.difference(individuals, getIndividualsImpl(operand)));
    } else if (description instanceof OWLObjectUnionOf) {
        SortedSet<OWLIndividual> ret = new TreeSet<>();
        for (OWLClassExpression operand : ((OWLObjectUnionOf) description).getOperands()) {
            ret.addAll(getIndividualsImpl(operand));
        }
        return ret;
    } else if (description instanceof OWLObjectIntersectionOf) {
        Iterator<OWLClassExpression> iterator = ((OWLObjectIntersectionOf) description).getOperands()
                .iterator();
        // copy instances of first element and then subtract all others
        SortedSet<OWLIndividual> ret = getIndividualsImpl(iterator.next());
        while (iterator.hasNext()) {
            ret.retainAll(getIndividualsImpl(iterator.next()));
        }
        return ret;
    } else if (description instanceof OWLObjectSomeValuesFrom) {
        SortedSet<OWLIndividual> returnSet = new TreeSet<>();

        OWLObjectPropertyExpression property = ((OWLObjectSomeValuesFrom) description).getProperty();
        OWLClassExpression filler = ((OWLObjectSomeValuesFrom) description).getFiller();

        //get instances of filler concept
        SortedSet<OWLIndividual> targetSet = getIndividualsImpl(filler);

        // the mapping of instances related by r
        Map<OWLIndividual, ? extends Collection<OWLIndividual>> mapping = opPos
                .get(property.getNamedProperty());

        if (property.isAnonymous()) { // \exists r^{-1}.C
            // invert the mapping
            // get all objects that are related by r to (at least) one subject which is of type C
            Multimap<OWLIndividual, OWLIndividual> mappingInv = Multimaps.invertFrom(
                    MapUtils.createSortedMultiMap(opPos.get(property.getNamedProperty())),
                    TreeMultimap.<OWLIndividual, OWLIndividual>create());

            mapping = mappingInv.asMap();
        }

        // each individual is connected to a set of individuals via the property;
        // we loop through the complete mapping
        for (Entry<OWLIndividual, ? extends Collection<OWLIndividual>> entry : mapping.entrySet()) {
            Collection<OWLIndividual> inds = entry.getValue();
            for (OWLIndividual ind : inds) {
                if (targetSet.contains(ind)) {
                    returnSet.add(entry.getKey());
                    // once we found an individual, we do not need to check the others
                    break;
                }
            }
        }

        return returnSet;
    } else if (description instanceof OWLObjectAllValuesFrom) {
        // \forall restrictions are difficult to handle; assume we want to check
        // \forall hasChild.male with domain(hasChild)=Person; then for all non-persons
        // this is satisfied trivially (all of their non-existing children are male)
        //         if(!configurator.getForallRetrievalSemantics().equals("standard")) {
        //            throw new Error("Only forallExists semantics currently implemented.");
        //         }

        // problem: we need to make sure that \neg \exists r.\top \equiv \forall r.\bot
        // can still be reached in an algorithm (\forall r.\bot \equiv \bot under forallExists
        // semantics)
        OWLObjectPropertyExpression property = ((OWLObjectAllValuesFrom) description).getProperty();
        OWLClassExpression filler = ((OWLObjectAllValuesFrom) description).getFiller();

        // get instances of filler concept
        SortedSet<OWLIndividual> targetSet = getIndividualsImpl(filler);

        // the mapping of instances related by r
        Map<OWLIndividual, ? extends Collection<OWLIndividual>> mapping = opPos
                .get(property.getNamedProperty());

        if (property.isAnonymous()) { // \forall r^{-1}.C
            // invert the mapping
            // get all objects that are related by r to (at least) one subject which is of type C
            Multimap<OWLIndividual, OWLIndividual> mappingInv = Multimaps.invertFrom(
                    MapUtils.createSortedMultiMap(opPos.get(property.getNamedProperty())),
                    TreeMultimap.<OWLIndividual, OWLIndividual>create());

            mapping = mappingInv.asMap();
        }

        //         SortedSet<OWLIndividual> returnSet = new TreeSet<OWLIndividual>(mapping.keySet());
        SortedSet<OWLIndividual> returnSet = (SortedSet<OWLIndividual>) individuals.clone();

        // each individual is connected to a set of individuals via the property;
        // we loop through the complete mapping
        for (Entry<OWLIndividual, ? extends Collection<OWLIndividual>> entry : mapping.entrySet()) {
            Collection<OWLIndividual> inds = entry.getValue();
            for (OWLIndividual ind : inds) {
                if (!targetSet.contains(ind)) {
                    returnSet.remove(entry.getKey());
                    break;
                }
            }
        }
        return returnSet;
    } else if (description instanceof OWLObjectMinCardinality) {
        OWLObjectPropertyExpression property = ((OWLObjectMinCardinality) description).getProperty();
        OWLClassExpression filler = ((OWLObjectMinCardinality) description).getFiller();

        //get instances of filler concept
        SortedSet<OWLIndividual> targetSet = getIndividualsImpl(filler);

        // the mapping of instances related by r
        Map<OWLIndividual, ? extends Collection<OWLIndividual>> mapping = opPos
                .get(property.getNamedProperty());

        if (property.isAnonymous()) { // \forall r^{-1}.C
            // invert the mapping
            // get all objects that are related by r to (at least) one subject which is of type C
            Multimap<OWLIndividual, OWLIndividual> mappingInv = Multimaps.invertFrom(
                    MapUtils.createSortedMultiMap(opPos.get(property.getNamedProperty())),
                    TreeMultimap.<OWLIndividual, OWLIndividual>create());

            mapping = mappingInv.asMap();
        }

        SortedSet<OWLIndividual> returnSet = new TreeSet<>();

        int number = ((OWLObjectMinCardinality) description).getCardinality();

        for (Entry<OWLIndividual, ? extends Collection<OWLIndividual>> entry : mapping.entrySet()) {
            int nrOfFillers = 0;
            int index = 0;
            Collection<OWLIndividual> inds = entry.getValue();

            // we do not need to run tests if there are not sufficiently many fillers
            if (inds.size() < number) {
                continue;
            }

            for (OWLIndividual ind : inds) {
                // stop inner loop when nr of fillers is reached
                if (nrOfFillers >= number) {
                    returnSet.add(entry.getKey());
                    break;
                }
                // early abort when too many instance checks failed
                if (inds.size() - index < number) {
                    break;
                }
                if (targetSet.contains(ind)) {
                    nrOfFillers++;
                }
                index++;
            }
        }

        return returnSet;
    } else if (description instanceof OWLObjectMaxCardinality) {
        OWLObjectPropertyExpression property = ((OWLObjectMaxCardinality) description).getProperty();
        OWLClassExpression filler = ((OWLObjectMaxCardinality) description).getFiller();
        int number = ((OWLObjectMaxCardinality) description).getCardinality();

        //get instances of filler concept
        SortedSet<OWLIndividual> targetSet = getIndividualsImpl(filler);

        // the mapping of instances related by r
        Map<OWLIndividual, ? extends Collection<OWLIndividual>> mapping = opPos
                .get(property.getNamedProperty());

        if (property.isAnonymous()) { // \forall r^{-1}.C
            // invert the mapping
            // get all objects that are related by r to (at least) one subject which is of type C
            Multimap<OWLIndividual, OWLIndividual> mappingInv = Multimaps.invertFrom(
                    MapUtils.createSortedMultiMap(opPos.get(property.getNamedProperty())),
                    TreeMultimap.<OWLIndividual, OWLIndividual>create());

            mapping = mappingInv.asMap();
        }

        // initially all individuals are in the return set and we then remove those
        // with too many fillers
        SortedSet<OWLIndividual> returnSet = (SortedSet<OWLIndividual>) individuals.clone();

        for (Entry<OWLIndividual, ? extends Collection<OWLIndividual>> entry : mapping.entrySet()) {
            int nrOfFillers = 0;
            int index = 0;
            Collection<OWLIndividual> inds = entry.getValue();

            // we do not need to run tests if there are not sufficiently many fillers
            if (number < inds.size()) {
                returnSet.add(entry.getKey());
                continue;
            }

            for (OWLIndividual ind : inds) {
                // stop inner loop when nr of fillers is reached
                if (nrOfFillers >= number) {
                    break;
                }
                // early abort when too many instance are true already
                if (inds.size() - index < number) {
                    returnSet.add(entry.getKey());
                    break;
                }
                if (targetSet.contains(ind)) {
                    nrOfFillers++;
                }
                index++;
            }
        }

        return returnSet;
    } else if (description instanceof OWLObjectHasValue) {
        OWLObjectPropertyExpression property = ((OWLObjectHasValue) description).getProperty();
        OWLIndividual value = ((OWLObjectHasValue) description).getFiller();

        // the mapping of instances related by r
        Map<OWLIndividual, ? extends Collection<OWLIndividual>> mapping = opPos
                .get(property.getNamedProperty());

        if (property.isAnonymous()) { // \exists r^{-1}.{a}
            // invert the mapping
            // get all objects that are related by r to (at least) one subject which is of type C
            Multimap<OWLIndividual, OWLIndividual> mappingInv = Multimaps.invertFrom(
                    MapUtils.createSortedMultiMap(opPos.get(property.getNamedProperty())),
                    TreeMultimap.<OWLIndividual, OWLIndividual>create());

            mapping = mappingInv.asMap();
        }

        SortedSet<OWLIndividual> returnSet = new TreeSet<>();

        for (Entry<OWLIndividual, ? extends Collection<OWLIndividual>> entry : mapping.entrySet()) {
            if (entry.getValue().contains(value)) {
                returnSet.add(entry.getKey());
            }
        }
        return returnSet;
    } else if (description instanceof OWLDataSomeValuesFrom) {
        OWLDataPropertyExpression property = ((OWLDataSomeValuesFrom) description).getProperty();
        OWLDataRange filler = ((OWLDataSomeValuesFrom) description).getFiller();

        if (filler.isDatatype()) {
            //we assume that the values are of the given datatype
            return new TreeSet<>(dpPos.get(property).keySet());
            //            OWLDatatype dt = filler.asOWLDatatype();
            //            if(dt.isDouble()){
            //               return new TreeSet<OWLIndividual>(dd.get(property).keySet());
            //            } else if(dt.isInteger()){
            //               return new TreeSet<OWLIndividual>(id.get(property).keySet());
            //            } else if(dt.isBoolean()){
            //               return bdPos.get(property);
            //            }
        } else if (filler instanceof OWLDatatypeRestriction) {
            OWLDatatype datatype = ((OWLDatatypeRestriction) filler).getDatatype();
            Set<OWLFacetRestriction> facetRestrictions = ((OWLDatatypeRestriction) filler)
                    .getFacetRestrictions();

            if (OWLAPIUtils.floatDatatypes.contains(datatype)) {
                double min = -Double.MAX_VALUE;
                double max = Double.MAX_VALUE;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = Double.parseDouble(facet.getFacetValue().getLiteral());
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = Double.parseDouble(facet.getFacetValue().getLiteral());
                    }
                }
                Map<OWLIndividual, SortedSet<Double>> mapping = dd.get(property);
                SortedSet<OWLIndividual> returnSet = new TreeSet<>();

                for (Entry<OWLIndividual, SortedSet<Double>> entry : mapping.entrySet()) {
                    //we can skip of largest number is below minimum or lowest number is above maximum
                    if (entry.getValue().last() < min || entry.getValue().first() > max) {
                        continue;
                    }

                    //search a value which is in the interval
                    for (Double value : entry.getValue()) {
                        if (value >= min && value <= max) {
                            returnSet.add(entry.getKey());
                            break;
                        }
                    }
                }
                return returnSet;
            } else if (OWLAPIUtils.intDatatypes.contains(datatype)) {
                int min = Integer.MIN_VALUE;
                int max = Integer.MAX_VALUE;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = facet.getFacetValue().parseInteger();
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = facet.getFacetValue().parseInteger();
                    }
                }
                Map<OWLIndividual, SortedSet<Integer>> mapping = id.get(property);
                SortedSet<OWLIndividual> returnSet = new TreeSet<>();
                for (Entry<OWLIndividual, SortedSet<Integer>> entry : mapping.entrySet()) {
                    //we can skip of largest number is below minimum or lowest number is above maximum
                    if (entry.getValue().last() < min || entry.getValue().first() > max) {
                        continue;
                    }

                    //search a value which is in the interval
                    for (Integer value : entry.getValue()) {
                        if (value >= min && value <= max) {
                            returnSet.add(entry.getKey());
                            break;
                        }
                    }
                }
                return returnSet;
            } else if (OWLAPIUtils.dtDatatypes.contains(datatype)) {
                // TODO we cannot ensure the sorting, because OWL API does only String comparison
                // on the lexical String value
                OWLLiteral min = null;
                OWLLiteral max = null;
                for (OWLFacetRestriction facet : facetRestrictions) {
                    if (facet.getFacet() == OWLFacet.MIN_INCLUSIVE) {
                        min = facet.getFacetValue();
                    } else if (facet.getFacet() == OWLFacet.MAX_INCLUSIVE) {
                        max = facet.getFacetValue();
                    }
                }
                Map<OWLIndividual, SortedSet<OWLLiteral>> mapping = dpPos.get(property);
                // we can return false if largest number is below minimum or lowest number is above maximum
                DateTimeFormatter parser = OWLAPIUtils.dateTimeParsers.get(datatype);
                DateTime minDateTime = null;
                if (min != null) {
                    minDateTime = parser.parseDateTime(min.getLiteral());
                }
                DateTime maxDateTime = null;
                if (max != null) {
                    maxDateTime = parser.parseDateTime(max.getLiteral());
                }
                SortedSet<OWLIndividual> returnSet = new TreeSet<>();
                for (Entry<OWLIndividual, SortedSet<OWLLiteral>> entry : mapping.entrySet()) {
                    //search a value which is in the interval
                    for (OWLLiteral value : entry.getValue()) {
                        if (OWLAPIUtils.inRange(value, min, max)) {
                            returnSet.add(entry.getKey());
                        }
                    }
                }
                return returnSet;
            }
        } else if (filler.getDataRangeType() == DataRangeType.DATA_ONE_OF) {
            OWLDataOneOf dataOneOf = (OWLDataOneOf) filler;
            Set<OWLLiteral> values = dataOneOf.getValues();

            Map<OWLIndividual, SortedSet<OWLLiteral>> mapping = dpPos.get(property);
            SortedSet<OWLIndividual> returnSet = new TreeSet<>();

            for (Entry<OWLIndividual, SortedSet<OWLLiteral>> entry : mapping.entrySet()) {
                OWLIndividual ind = entry.getKey();
                SortedSet<OWLLiteral> indValues = entry.getValue();

                if (!Sets.intersection(values, indValues).isEmpty()) {
                    returnSet.add(ind);
                }
            }
            return returnSet;
        }
    } else if (description instanceof OWLDataHasValue) {
        OWLDataPropertyExpression property = ((OWLDataHasValue) description).getProperty();
        OWLLiteral value = ((OWLDataHasValue) description).getFiller();

        SortedSet<OWLIndividual> returnSet = new TreeSet<>();

        Map<OWLIndividual, SortedSet<OWLLiteral>> mapping = dpPos.get(property);

        for (Entry<OWLIndividual, SortedSet<OWLLiteral>> entry : mapping.entrySet()) {
            if (entry.getValue().contains(value)) {
                returnSet.add(entry.getKey());
            }
        }

        return returnSet;
    } else if (description instanceof OWLObjectOneOf) {
        return new TreeSet(((OWLObjectOneOf) description).getIndividuals());
    }

    throw new ReasoningMethodUnsupportedException(
            "Retrieval for class expression " + description + " unsupported.");

}