Search in sources :

Example 1 with Duration

use of org.apache.cassandra.cql3.Duration in project cassandra by apache.

the class TemporalType method substractDuration.

/**
     * Substract the duration from the specified value.
     *
     * @param temporal the value to substract from
     * @param duration the duration to substract
     * @return the substracion result
     */
public ByteBuffer substractDuration(ByteBuffer temporal, ByteBuffer duration) {
    long timeInMillis = toTimeInMillis(temporal);
    Duration d = DurationType.instance.compose(duration);
    validateDuration(d);
    return fromTimeInMillis(d.substractFrom(timeInMillis));
}
Also used : Duration(org.apache.cassandra.cql3.Duration)

Example 2 with Duration

use of org.apache.cassandra.cql3.Duration in project Etar-Calendar by Etar-Group.

the class GoogleCalendarUriIntentFilter method onCreate.

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Intent intent = getIntent();
    if (intent != null) {
        Uri uri = intent.getData();
        if (uri != null) {
            String[] eidParts = extractEidAndEmail(uri);
            if (eidParts == null) {
                Log.i(TAG, "Could not find event for uri: " + uri);
            } else {
                final String syncId = eidParts[0];
                final String ownerAccount = eidParts[1];
                if (debug)
                    Log.d(TAG, "eidParts=" + syncId + "/" + ownerAccount);
                final String selection = Events._SYNC_ID + " LIKE \"%" + syncId + "\" AND " + Calendars.OWNER_ACCOUNT + " LIKE \"" + ownerAccount + "\"";
                if (debug)
                    Log.d(TAG, "selection: " + selection);
                Cursor eventCursor = getContentResolver().query(Events.CONTENT_URI, EVENT_PROJECTION, selection, null, Calendars.CALENDAR_ACCESS_LEVEL + " desc");
                if (debug)
                    Log.d(TAG, "Found: " + eventCursor.getCount());
                if (eventCursor == null || eventCursor.getCount() == 0) {
                    Log.i(TAG, "NOTE: found no matches on event with id='" + syncId + "'");
                    return;
                }
                Log.i(TAG, "NOTE: found " + eventCursor.getCount() + " matches on event with id='" + syncId + "'");
                try {
                    // Get info from Cursor
                    while (eventCursor.moveToNext()) {
                        int eventId = eventCursor.getInt(EVENT_INDEX_ID);
                        long startMillis = eventCursor.getLong(EVENT_INDEX_START);
                        long endMillis = eventCursor.getLong(EVENT_INDEX_END);
                        if (debug)
                            Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID));
                        if (debug)
                            Log.d(TAG, "startMillis: " + startMillis);
                        if (debug)
                            Log.d(TAG, "endMillis:   " + endMillis);
                        if (endMillis == 0) {
                            String duration = eventCursor.getString(EVENT_INDEX_DURATION);
                            if (debug)
                                Log.d(TAG, "duration:    " + duration);
                            if (TextUtils.isEmpty(duration)) {
                                continue;
                            }
                            try {
                                Duration d = new Duration();
                                d.parse(duration);
                                endMillis = startMillis + d.getMillis();
                                if (debug)
                                    Log.d(TAG, "startMillis! " + startMillis);
                                if (debug)
                                    Log.d(TAG, "endMillis!   " + endMillis);
                                if (endMillis < startMillis) {
                                    continue;
                                }
                            } catch (DateException e) {
                                if (debug)
                                    Log.d(TAG, "duration:" + e.toString());
                                continue;
                            }
                        }
                        // Pick up attendee status action from uri clicked
                        int attendeeStatus = Attendees.ATTENDEE_STATUS_NONE;
                        if ("RESPOND".equals(uri.getQueryParameter("action"))) {
                            try {
                                switch(Integer.parseInt(uri.getQueryParameter("rst"))) {
                                    case // Yes
                                    1:
                                        attendeeStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
                                        break;
                                    case // No
                                    2:
                                        attendeeStatus = Attendees.ATTENDEE_STATUS_DECLINED;
                                        break;
                                    case // Maybe
                                    3:
                                        attendeeStatus = Attendees.ATTENDEE_STATUS_TENTATIVE;
                                        break;
                                }
                            } catch (NumberFormatException e) {
                            // ignore this error as if the response code
                            // wasn't in the uri.
                            }
                        }
                        final Uri calendarUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventId);
                        intent = new Intent(Intent.ACTION_VIEW, calendarUri);
                        intent.setClass(this, EventInfoActivity.class);
                        intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis);
                        intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis);
                        if (attendeeStatus == Attendees.ATTENDEE_STATUS_NONE) {
                            startActivity(intent);
                        } else {
                            updateSelfAttendeeStatus(eventId, ownerAccount, attendeeStatus, intent);
                        }
                        finish();
                        return;
                    }
                } finally {
                    eventCursor.close();
                }
            }
        }
        // Can't handle the intent. Pass it on to the next Activity.
        try {
            startNextMatchingActivity(intent);
        } catch (ActivityNotFoundException ex) {
        // no browser installed? Just drop it.
        }
    }
    finish();
}
Also used : ActivityNotFoundException(android.content.ActivityNotFoundException) DateException(com.android.calendarcommon2.DateException) Intent(android.content.Intent) Duration(com.android.calendarcommon2.Duration) Cursor(android.database.Cursor) Uri(android.net.Uri)

Example 3 with Duration

use of org.apache.cassandra.cql3.Duration in project Etar-Calendar by Etar-Group.

the class EventInfoFragment method updateEvent.

private void updateEvent(View view) {
    if (mEventCursor == null || view == null) {
        return;
    }
    Context context = view.getContext();
    if (context == null) {
        return;
    }
    String eventName = mEventCursor.getString(EVENT_INDEX_TITLE);
    if (eventName == null || eventName.length() == 0) {
        eventName = getActivity().getString(R.string.no_title_label);
    }
    // Events.CONTENT_URI intent.  Update these with values read from the db.
    if (mStartMillis == 0 && mEndMillis == 0) {
        mStartMillis = mEventCursor.getLong(EVENT_INDEX_DTSTART);
        mEndMillis = mEventCursor.getLong(EVENT_INDEX_DTEND);
        if (mEndMillis == 0) {
            String duration = mEventCursor.getString(EVENT_INDEX_DURATION);
            if (!TextUtils.isEmpty(duration)) {
                try {
                    Duration d = new Duration();
                    d.parse(duration);
                    long endMillis = mStartMillis + d.getMillis();
                    if (endMillis >= mStartMillis) {
                        mEndMillis = endMillis;
                    } else {
                        Log.d(TAG, "Invalid duration string: " + duration);
                    }
                } catch (DateException e) {
                    Log.d(TAG, "Error parsing duration string " + duration, e);
                }
            }
            if (mEndMillis == 0) {
                mEndMillis = mStartMillis;
            }
        }
    }
    mAllDay = mEventCursor.getInt(EVENT_INDEX_ALL_DAY) != 0;
    String location = mEventCursor.getString(EVENT_INDEX_EVENT_LOCATION);
    String description = mEventCursor.getString(EVENT_INDEX_DESCRIPTION);
    String rRule = mEventCursor.getString(EVENT_INDEX_RRULE);
    String eventTimezone = mEventCursor.getString(EVENT_INDEX_EVENT_TIMEZONE);
    mHeadlines.setBackgroundColor(mCurrentColor);
    // What
    if (eventName != null) {
        setTextCommon(view, R.id.title, eventName);
    }
    // When
    // Set the date and repeats (if any)
    String localTimezone = Utils.getTimeZone(mActivity, mTZUpdater);
    Resources resources = context.getResources();
    String displayedDatetime = Utils.getDisplayedDatetime(mStartMillis, mEndMillis, System.currentTimeMillis(), localTimezone, mAllDay, context);
    String displayedTimezone = null;
    if (!mAllDay) {
        displayedTimezone = Utils.getDisplayedTimezone(mStartMillis, localTimezone, eventTimezone);
    }
    // Display the datetime.  Make the timezone (if any) transparent.
    if (displayedTimezone == null) {
        setTextCommon(view, R.id.when_datetime, displayedDatetime);
    } else {
        int timezoneIndex = displayedDatetime.length();
        displayedDatetime += "  " + displayedTimezone;
        SpannableStringBuilder sb = new SpannableStringBuilder(displayedDatetime);
        ForegroundColorSpan transparentColorSpan = new ForegroundColorSpan(resources.getColor(R.color.event_info_headline_transparent_color));
        sb.setSpan(transparentColorSpan, timezoneIndex, displayedDatetime.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        setTextCommon(view, R.id.when_datetime, sb);
    }
    // Display the repeat string (if any)
    String repeatString = null;
    if (!TextUtils.isEmpty(rRule)) {
        EventRecurrence eventRecurrence = new EventRecurrence();
        eventRecurrence.parse(rRule);
        Time date = new Time(localTimezone);
        date.set(mStartMillis);
        if (mAllDay) {
            date.timezone = Time.TIMEZONE_UTC;
        }
        eventRecurrence.setStartDate(date);
        repeatString = EventRecurrenceFormatter.getRepeatString(mContext, resources, eventRecurrence, true);
    }
    if (repeatString == null) {
        view.findViewById(R.id.when_repeat).setVisibility(View.GONE);
    } else {
        setTextCommon(view, R.id.when_repeat, repeatString);
    }
    // Where
    if (location == null || location.trim().length() == 0) {
        setVisibilityCommon(view, R.id.where, View.GONE);
    } else {
        final TextView textView = mWhere;
        if (textView != null) {
            textView.setAutoLinkMask(0);
            textView.setText(location.trim());
            try {
                textView.setText(Utils.extendedLinkify(textView.getText().toString(), true));
                // Linkify.addLinks() sets the TextView movement method if it finds any links.
                // We must do the same here, in case linkify by itself did not find any.
                // (This is cloned from Linkify.addLinkMovementMethod().)
                MovementMethod mm = textView.getMovementMethod();
                if ((mm == null) || !(mm instanceof LinkMovementMethod)) {
                    if (textView.getLinksClickable()) {
                        textView.setMovementMethod(LinkMovementMethod.getInstance());
                    }
                }
            } catch (Exception ex) {
                // unexpected
                Log.e(TAG, "Linkification failed", ex);
            }
            textView.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    try {
                        return v.onTouchEvent(event);
                    } catch (ActivityNotFoundException e) {
                        // ignore
                        return true;
                    }
                }
            });
        }
    }
    // Description
    if (description != null && description.length() != 0) {
        mDesc.setText(description);
    }
    // Launch Custom App
    if (Utils.isJellybeanOrLater()) {
        updateCustomAppButton();
    }
}
Also used : Context(android.content.Context) OnTouchListener(android.view.View.OnTouchListener) ForegroundColorSpan(android.text.style.ForegroundColorSpan) LinkMovementMethod(android.text.method.LinkMovementMethod) Duration(com.android.calendarcommon2.Duration) Time(android.text.format.Time) ScrollView(android.widget.ScrollView) View(android.view.View) AdapterView(android.widget.AdapterView) AttendeesView(com.android.calendar.event.AttendeesView) TextView(android.widget.TextView) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) DateException(com.android.calendarcommon2.DateException) MotionEvent(android.view.MotionEvent) EventRecurrence(com.android.calendarcommon2.EventRecurrence) ActivityNotFoundException(android.content.ActivityNotFoundException) LinkMovementMethod(android.text.method.LinkMovementMethod) MovementMethod(android.text.method.MovementMethod) DateException(com.android.calendarcommon2.DateException) TextView(android.widget.TextView) Resources(android.content.res.Resources) SpannableStringBuilder(android.text.SpannableStringBuilder)

Example 4 with Duration

use of org.apache.cassandra.cql3.Duration in project cassandra by apache.

the class CreateViewStatement method announceMigration.

public Event.SchemaChange announceMigration(QueryState queryState, boolean isLocalOnly) throws RequestValidationException {
    // We need to make sure that:
    //  - primary key includes all columns in base table's primary key
    //  - make sure that the select statement does not have anything other than columns
    //    and their names match the base table's names
    //  - make sure that primary key does not include any collections
    //  - make sure there is no where clause in the select statement
    //  - make sure there is not currently a table or view
    //  - make sure baseTable gcGraceSeconds > 0
    properties.validate();
    if (properties.useCompactStorage)
        throw new InvalidRequestException("Cannot use 'COMPACT STORAGE' when defining a materialized view");
    // specific replica would break
    if (!baseName.getKeyspace().equals(keyspace()))
        throw new InvalidRequestException("Cannot create a materialized view on a table in a separate keyspace");
    TableMetadata metadata = Schema.instance.validateTable(baseName.getKeyspace(), baseName.getColumnFamily());
    if (metadata.isCounter())
        throw new InvalidRequestException("Materialized views are not supported on counter tables");
    if (metadata.isView())
        throw new InvalidRequestException("Materialized views cannot be created against other materialized views");
    if (metadata.params.gcGraceSeconds == 0) {
        throw new InvalidRequestException(String.format("Cannot create materialized view '%s' for base table " + "'%s' with gc_grace_seconds of 0, since this value is " + "used to TTL undelivered updates. Setting gc_grace_seconds" + " too low might cause undelivered updates to expire " + "before being replayed.", cfName.getColumnFamily(), baseName.getColumnFamily()));
    }
    Set<ColumnIdentifier> included = Sets.newHashSetWithExpectedSize(selectClause.size());
    for (RawSelector selector : selectClause) {
        Selectable.Raw selectable = selector.selectable;
        if (selectable instanceof Selectable.WithFieldSelection.Raw)
            throw new InvalidRequestException("Cannot select out a part of type when defining a materialized view");
        if (selectable instanceof Selectable.WithFunction.Raw)
            throw new InvalidRequestException("Cannot use function when defining a materialized view");
        if (selectable instanceof Selectable.WritetimeOrTTL.Raw)
            throw new InvalidRequestException("Cannot use function when defining a materialized view");
        if (selector.alias != null)
            throw new InvalidRequestException("Cannot use alias when defining a materialized view");
        Selectable s = selectable.prepare(metadata);
        if (s instanceof Term.Raw)
            throw new InvalidRequestException("Cannot use terms in selection when defining a materialized view");
        ColumnMetadata cdef = (ColumnMetadata) s;
        included.add(cdef.name);
    }
    Set<ColumnMetadata.Raw> targetPrimaryKeys = new HashSet<>();
    for (ColumnMetadata.Raw identifier : Iterables.concat(partitionKeys, clusteringKeys)) {
        if (!targetPrimaryKeys.add(identifier))
            throw new InvalidRequestException("Duplicate entry found in PRIMARY KEY: " + identifier);
        ColumnMetadata cdef = identifier.prepare(metadata);
        if (cdef.type.isMultiCell())
            throw new InvalidRequestException(String.format("Cannot use MultiCell column '%s' in PRIMARY KEY of materialized view", identifier));
        if (cdef.isStatic())
            throw new InvalidRequestException(String.format("Cannot use Static column '%s' in PRIMARY KEY of materialized view", identifier));
        if (cdef.type instanceof DurationType)
            throw new InvalidRequestException(String.format("Cannot use Duration column '%s' in PRIMARY KEY of materialized view", identifier));
    }
    // build the select statement
    Map<ColumnMetadata.Raw, Boolean> orderings = Collections.emptyMap();
    List<ColumnMetadata.Raw> groups = Collections.emptyList();
    SelectStatement.Parameters parameters = new SelectStatement.Parameters(orderings, groups, false, true, false);
    SelectStatement.RawStatement rawSelect = new SelectStatement.RawStatement(baseName, parameters, selectClause, whereClause, null, null);
    ClientState state = ClientState.forInternalCalls();
    state.setKeyspace(keyspace());
    rawSelect.prepareKeyspace(state);
    rawSelect.setBoundVariables(getBoundVariables());
    ParsedStatement.Prepared prepared = rawSelect.prepare(true);
    SelectStatement select = (SelectStatement) prepared.statement;
    StatementRestrictions restrictions = select.getRestrictions();
    if (!prepared.boundNames.isEmpty())
        throw new InvalidRequestException("Cannot use query parameters in CREATE MATERIALIZED VIEW statements");
    String whereClauseText = View.relationsToWhereClause(whereClause.relations);
    Set<ColumnIdentifier> basePrimaryKeyCols = new HashSet<>();
    for (ColumnMetadata definition : Iterables.concat(metadata.partitionKeyColumns(), metadata.clusteringColumns())) basePrimaryKeyCols.add(definition.name);
    List<ColumnIdentifier> targetClusteringColumns = new ArrayList<>();
    List<ColumnIdentifier> targetPartitionKeys = new ArrayList<>();
    // This is only used as an intermediate state; this is to catch whether multiple non-PK columns are used
    boolean hasNonPKColumn = false;
    for (ColumnMetadata.Raw raw : partitionKeys) hasNonPKColumn |= getColumnIdentifier(metadata, basePrimaryKeyCols, hasNonPKColumn, raw, targetPartitionKeys, restrictions);
    for (ColumnMetadata.Raw raw : clusteringKeys) hasNonPKColumn |= getColumnIdentifier(metadata, basePrimaryKeyCols, hasNonPKColumn, raw, targetClusteringColumns, restrictions);
    // We need to include all of the primary key columns from the base table in order to make sure that we do not
    // overwrite values in the view. We cannot support "collapsing" the base table into a smaller number of rows in
    // the view because if we need to generate a tombstone, we have no way of knowing which value is currently being
    // used in the view and whether or not to generate a tombstone. In order to not surprise our users, we require
    // that they include all of the columns. We provide them with a list of all of the columns left to include.
    boolean missingClusteringColumns = false;
    StringBuilder columnNames = new StringBuilder();
    List<ColumnIdentifier> includedColumns = new ArrayList<>();
    for (ColumnMetadata def : metadata.columns()) {
        ColumnIdentifier identifier = def.name;
        boolean includeDef = included.isEmpty() || included.contains(identifier);
        if (includeDef && def.isStatic()) {
            throw new InvalidRequestException(String.format("Unable to include static column '%s' which would be included by Materialized View SELECT * statement", identifier));
        }
        boolean defInTargetPrimaryKey = targetClusteringColumns.contains(identifier) || targetPartitionKeys.contains(identifier);
        if (includeDef && !defInTargetPrimaryKey) {
            includedColumns.add(identifier);
        }
        if (!def.isPrimaryKeyColumn())
            continue;
        if (!defInTargetPrimaryKey) {
            if (missingClusteringColumns)
                columnNames.append(',');
            else
                missingClusteringColumns = true;
            columnNames.append(identifier);
        }
    }
    if (missingClusteringColumns)
        throw new InvalidRequestException(String.format("Cannot create Materialized View %s without primary key columns from base %s (%s)", columnFamily(), baseName.getColumnFamily(), columnNames.toString()));
    if (targetPartitionKeys.isEmpty())
        throw new InvalidRequestException("Must select at least a column for a Materialized View");
    if (targetClusteringColumns.isEmpty())
        throw new InvalidRequestException("No columns are defined for Materialized View other than primary key");
    TableParams params = properties.properties.asNewTableParams();
    if (params.defaultTimeToLive > 0) {
        throw new InvalidRequestException("Cannot set default_time_to_live for a materialized view. " + "Data in a materialized view always expire at the same time than " + "the corresponding data in the parent table.");
    }
    TableMetadata.Builder builder = TableMetadata.builder(keyspace(), columnFamily(), properties.properties.getId()).isView(true).params(params);
    add(metadata, targetPartitionKeys, builder::addPartitionKeyColumn);
    add(metadata, targetClusteringColumns, builder::addClusteringColumn);
    add(metadata, includedColumns, builder::addRegularColumn);
    ViewMetadata definition = new ViewMetadata(keyspace(), columnFamily(), metadata.id, metadata.name, included.isEmpty(), rawSelect, whereClauseText, builder.build());
    try {
        MigrationManager.announceNewView(definition, isLocalOnly);
        return new Event.SchemaChange(Event.SchemaChange.Change.CREATED, Event.SchemaChange.Target.TABLE, keyspace(), columnFamily());
    } catch (AlreadyExistsException e) {
        if (ifNotExists)
            return null;
        throw e;
    }
}
Also used : ClientState(org.apache.cassandra.service.ClientState) RawSelector(org.apache.cassandra.cql3.selection.RawSelector) ColumnMetadata(org.apache.cassandra.schema.ColumnMetadata) Selectable(org.apache.cassandra.cql3.selection.Selectable) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) StatementRestrictions(org.apache.cassandra.cql3.restrictions.StatementRestrictions) ViewMetadata(org.apache.cassandra.schema.ViewMetadata) TableMetadata(org.apache.cassandra.schema.TableMetadata) DurationType(org.apache.cassandra.db.marshal.DurationType) TableParams(org.apache.cassandra.schema.TableParams) AlreadyExistsException(org.apache.cassandra.exceptions.AlreadyExistsException)

Example 5 with Duration

use of org.apache.cassandra.cql3.Duration in project cassandra by apache.

the class TemporalType method addDuration.

/**
     * Adds the duration to the specified value.
     *
     * @param temporal the value to add to
     * @param duration the duration to add
     * @return the addition result
     */
public ByteBuffer addDuration(ByteBuffer temporal, ByteBuffer duration) {
    long timeInMillis = toTimeInMillis(temporal);
    Duration d = DurationType.instance.compose(duration);
    validateDuration(d);
    return fromTimeInMillis(d.addTo(timeInMillis));
}
Also used : Duration(org.apache.cassandra.cql3.Duration)

Aggregations

ActivityNotFoundException (android.content.ActivityNotFoundException)2 DateException (com.android.calendarcommon2.DateException)2 Duration (com.android.calendarcommon2.Duration)2 Duration (org.apache.cassandra.cql3.Duration)2 Context (android.content.Context)1 Intent (android.content.Intent)1 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)1 Resources (android.content.res.Resources)1 Cursor (android.database.Cursor)1 Uri (android.net.Uri)1 SpannableStringBuilder (android.text.SpannableStringBuilder)1 Time (android.text.format.Time)1 LinkMovementMethod (android.text.method.LinkMovementMethod)1 MovementMethod (android.text.method.MovementMethod)1 ForegroundColorSpan (android.text.style.ForegroundColorSpan)1 MotionEvent (android.view.MotionEvent)1 View (android.view.View)1 OnTouchListener (android.view.View.OnTouchListener)1 AdapterView (android.widget.AdapterView)1 ScrollView (android.widget.ScrollView)1