<commit_before>/*
 * Copyright 2010-2012 h<EMAIL>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.orientechnologies.orient.core.schedule;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.OCallable;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.OrientDBInternal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentAbstract;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.exception.OValidationException;
import com.orientechnologies.orient.core.metadata.function.OFunction;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Scheduler default implementation.
 *
 * @author <NAME> (l.garulli--(at)--orientdb.com)
 * @author henryzhao<EMAIL>
 * @since Mar 28, 2013
 */
public class OSchedulerImpl {
  private ConcurrentHashMap<String, OScheduledEvent> events =
      new ConcurrentHashMap<String, OScheduledEvent>();

  private final OrientDBInternal orientDB;

  public OSchedulerImpl(OrientDBInternal orientDB) {
    this.orientDB = orientDB;
  }

  public void scheduleEvent(final OScheduledEvent event) {
    if (event.getDocument().getIdentity().isNew())
      // FIST TIME: SAVE IT
      event.save();

    if (events.putIfAbsent(event.getName(), event) == null) {
      String database = event.getDocument().getDatabase().getName();
      event.schedule(database, "admin", orientDB);
    }
  }

  public OScheduledEvent removeEventInternal(final String eventName) {
    final OScheduledEvent event = events.remove(eventName);

    if (event != null) {
      event.interrupt();
    }
    return event;
  }

  public void removeEvent(final String eventName) {
    OLogManager.instance().debug(this, "Removing scheduled event '%s'...", eventName);

    final OScheduledEvent event = removeEventInternal(eventName);

    if (event != null) {

      try {
        event.getDocument().reload();
      } catch (ORecordNotFoundException ignore) {
        // ALREADY DELETED, JUST RETURN
        return;
      }

      // RECORD EXISTS: DELETE THE EVENT RECORD
      ODatabaseDocumentAbstract.executeWithRetries(
          new OCallable<Object, Integer>() {
            @Override
            public Object call(Integer iArgument) {
              OLogManager.instance()
                  .debug(
                      this,
                      "Deleting scheduled event '%s' rid=%s...",
                      event,
                      event.getDocument().getIdentity());
              event.getDocument().delete();
              return null;
            }
          },
          10,
          0,
          new ORecord[] {event.getDocument()});
    }
  }

  public void updateEvent(final OScheduledEvent event) {
    final OScheduledEvent oldEvent = events.remove(event.getName());
    if (oldEvent != null) oldEvent.interrupt();
    scheduleEvent(event);
    OLogManager.instance()
        .debug(
            this,
            "Updated scheduled event '%s' rid=%s...",
            event,
            event.getDocument().getIdentity());
  }

  public Map<String, OScheduledEvent> getEvents() {
    return events;
  }

  public OScheduledEvent getEvent(final String name) {
    return events.get(name);
  }

  public void load() {
    throw new UnsupportedOperationException();
  }

  public void load(ODatabaseDocumentInternal database) {

    if (database.getMetadata().getSchema().existsClass(OScheduledEvent.CLASS_NAME)) {
      final Iterable<ODocument> result = database.browseClass(OScheduledEvent.CLASS_NAME);
      for (ODocument d : result) {
        final OScheduledEvent event = new OScheduledEvent(d);

        if (events.putIfAbsent(event.getName(), event) == null) this.scheduleEvent(event);
      }
    }
  }

  public void close() {
    for (OScheduledEvent event : events.values()) {
      event.interrupt();
    }
    events.clear();
  }

  public void create(ODatabaseDocumentInternal database) {
    if (database.getMetadata().getSchema().existsClass(OScheduledEvent.CLASS_NAME)) return;
    final OClass f = database.getMetadata().getSchema().createClass(OScheduledEvent.CLASS_NAME);
    f.createProperty(OScheduledEvent.PROP_NAME, OType.STRING, (OType) null, true)
        .setMandatory(true)
        .setNotNull(true);
    f.createProperty(OScheduledEvent.PROP_RULE, OType.STRING, (OType) null, true)
        .setMandatory(true)
        .setNotNull(true);
    f.createProperty(OScheduledEvent.PROP_ARGUMENTS, OType.EMBEDDEDMAP, (OType) null, true);
    f.createProperty(OScheduledEvent.PROP_STATUS, OType.STRING, (OType) null, true);<commit_msg>Fix firing of all OSchedule on server start: fix #9500<commit_after>/*
 * Copyright 2010-2012 <EMAIL>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.orientechnologies.orient.core.schedule;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.OCallable;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.OrientDBInternal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentAbstract;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.exception.OValidationException;
import com.orientechnologies.orient.core.metadata.function.OFunction;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Scheduler default implementation.
 *
 * @author <NAME> (l.garulli--(at)--orientdb.com)
 * @author henryzhao81-at-gmail.com
 * @since Mar 28, 2013
 */
public class OSchedulerImpl {
  private ConcurrentHashMap<String, OScheduledEvent> events =
      new ConcurrentHashMap<String, OScheduledEvent>();

  private final OrientDBInternal orientDB;

  public OSchedulerImpl(OrientDBInternal orientDB) {
    this.orientDB = orientDB;
  }

  public void scheduleEvent(final OScheduledEvent event) {
    if (event.getDocument().getIdentity().isNew())
      // FIST TIME: SAVE IT
      event.save();

    if (events.putIfAbsent(event.getName(), event) == null) {
      String database = event.getDocument().getDatabase().getName();
      event.schedule(database, "admin", orientDB);
    }
  }

  public OScheduledEvent removeEventInternal(final String eventName) {
    final OScheduledEvent event = events.remove(eventName);

    if (event != null) {
      event.interrupt();
    }
    return event;
  }

  public void removeEvent(final String eventName) {
    OLogManager.instance().debug(this, "Removing scheduled event '%s'...", eventName);

    final OScheduledEvent event = removeEventInternal(eventName);

    if (event != null) {

      try {
        event.getDocument().reload();
      } catch (ORecordNotFoundException ignore) {
        // ALREADY DELETED, JUST RETURN
        return;
      }

      // RECORD EXISTS: DELETE THE EVENT RECORD
      ODatabaseDocumentAbstract.executeWithRetries(
          new OCallable<Object, Integer>() {
            @Override
            public Object call(Integer iArgument) {
              OLogManager.instance()
                  .debug(
                      this,
                      "Deleting scheduled event '%s' rid=%s...",
                      event,
                      event.getDocument().getIdentity());
              event.getDocument().delete();
              return null;
            }
          },
          10,
          0,
          new ORecord[] {event.getDocument()});
    }
  }

  public void updateEvent(final OScheduledEvent event) {
    final OScheduledEvent oldEvent = events.remove(event.getName());
    if (oldEvent != null) oldEvent.interrupt();
    scheduleEvent(event);
    OLogManager.instance()
        .debug(
            this,
            "Updated scheduled event '%s' rid=%s...",
            event,
            event.getDocument().getIdentity());
  }

  public Map<String, OScheduledEvent> getEvents() {
    return events;
  }

  public OScheduledEvent getEvent(final String name) {
    return events.get(name);
  }

  public void load() {
    throw new UnsupportedOperationException();
  }

  public void load(ODatabaseDocumentInternal database) {

    if (database.getMetadata().getSchema().existsClass(OScheduledEvent.CLASS_NAME)) {
      final Iterable<ODocument> result = database.browseClass(OScheduledEvent.CLASS_NAME);
      for (ODocument d : result) {
        scheduleEvent(new OScheduledEvent(d));
      }
    }
  }

  public void close() {
    for (OScheduledEvent event : events.values()) {
      event.interrupt();
    }
    events.clear();
  }

  public void create(ODatabaseDocumentInternal database) {
    if (database.getMetadata().getSchema().existsClass(OScheduledEvent.CLASS_NAME)) return;
    final OClass f = database.getMetadata().getSchema().createClass(OScheduledEvent.CLASS_NAME);
    f.createProperty(OScheduledEvent.PROP_NAME, OType.STRING, (OType) null, true)
        .setMandatory(true)
        .setNotNull(true);
    f.createProperty(OScheduledEvent.PROP_RULE, OType.STRING, (OType) null, true)
        .setMandatory(true)
        .setNotNull(true);
    f.createProperty(OScheduledEvent.PROP_ARGUMENTS, OType.EMBEDDEDMAP, (OType) null, true);
    f.createProperty(OScheduledEvent.PROP_STATUS, OType.STRING, (OType) null, true);
{'fraction_non_alphanumeric': 0.10781068265187438, 'fraction_numerical': 0.00429453341683815, 'mean_word_length': 3.3241779497098647, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4558792', 'n_tokens_mistral': 3210, 'n_tokens_neox': 3177, 'n_words': 720}