001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.reef.runtime.common.evaluator.context;
020
021import org.apache.reef.evaluator.context.parameters.ContextIdentifier;
022import org.apache.reef.tang.Configuration;
023import org.apache.reef.tang.Tang;
024import org.apache.reef.tang.exceptions.InjectionException;
025import org.apache.reef.util.Optional;
026
027/**
028 * Thrown when we encounter a problem with client code in a context.
029 */
030public final class ContextClientCodeException extends Exception {
031  private final String contextID;
032  private final Optional<String> parentID;
033
034  /**
035   * @param contextID the ID of the failed context.
036   * @param parentID  the ID of the failed context's parent, if any.
037   * @param message   the error message.
038   * @param cause     the exception that caused the error.
039   */
040  public ContextClientCodeException(final String contextID,
041                                    final Optional<String> parentID,
042                                    final String message,
043                                    final Throwable cause) {
044    super("Failure in context '" + contextID + "': " + message, cause);
045    this.contextID = contextID;
046    this.parentID = parentID;
047  }
048
049  /**
050   * Extracts a context id from the given configuration.
051   *
052   * @param c
053   * @return the context id in the given configuration.
054   * @throws RuntimeException if the configuration can't be parsed.
055   */
056  public static String getIdentifier(final Configuration c) {
057    try {
058      return Tang.Factory.getTang().newInjector(c).getNamedInstance(
059          ContextIdentifier.class);
060    } catch (final InjectionException e) {
061      throw new RuntimeException("Unable to determine context identifier. Giving up.", e);
062    }
063  }
064
065  /**
066   * @return the ID of the failed context
067   */
068  public String getContextID() {
069    return this.contextID;
070  }
071
072  /**
073   * @return the ID of the failed context's parent, if any
074   */
075  public Optional<String> getParentID() {
076    return this.parentID;
077  }
078}