All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.cdap.cdap.pipeline.AbstractStage Maven / Gradle / Ivy

/*
 * Copyright © 2014-2017 Cask Data, Inc.
 *
 * 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 io.cdap.cdap.pipeline;

import com.google.common.reflect.TypeToken;

/**
 * Abstract implementation of {@link Stage} allowing ability to determine type to invoke the actual
 * processing of event.
 *
 * @param  Type of object processed by this stage.
 */
public abstract class AbstractStage implements Stage {

  private Context ctx;
  private TypeToken typeToken;

  /**
   * Constructor that allows determining the type {@link Stage} is looking to process.
   *
   * @param typeToken instance to determine type of data {@link Stage} is processing.
   */
  protected AbstractStage(TypeToken typeToken) {
    this.typeToken = typeToken;
  }

  /**
   * Processes an object passed to it from context.
   *
   * @param ctx of processing.
   */
  @Override
  @SuppressWarnings("unchecked")
  public final void process(Context ctx) throws Exception {
    this.ctx = ctx;
    Object upStream = ctx.getUpStream();

    // If the type match, call process. Otherwise, just pass the object to next stage.
    if (typeToken.getRawType().isAssignableFrom(upStream.getClass())) {
      process((T) typeToken.getRawType().cast(upStream));
    } else {
      emit(upStream);
    }
  }

  /**
   * Emits the object to send to next {@link Stage} in processing.
   *
   * @param o to be emitted to downstream
   */
  protected final void emit(Object o) {
    ctx.setDownStream(o);
  }

  /**
   * Returns the current {@link Context} object.
   */
  protected final Context getContext() {
    return ctx;
  }

  /**
   * Abstract process that does a safe cast to the type.
   *
   * @param o Object to be processed which is of type T
   */
  public abstract void process(T o) throws Exception;
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy