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.examples.group.bgd.utils; 020 021import org.apache.reef.driver.task.TaskConfiguration; 022import org.apache.reef.driver.task.TaskConfigurationOptions; 023import org.apache.reef.examples.group.bgd.MasterTask; 024import org.apache.reef.tang.*; 025import org.apache.reef.tang.annotations.Name; 026import org.apache.reef.tang.exceptions.InjectionException; 027 028import java.util.logging.Level; 029import java.util.logging.Logger; 030 031/** 032 * Subconfiguration: limit given configuration to a given list of classes. 033 */ 034public final class SubConfiguration { 035 036 private static final Logger LOG = Logger.getLogger(SubConfiguration.class.getName()); 037 038 @SafeVarargs 039 public static Configuration from( 040 final Configuration baseConf, final Class<? extends Name<?>>... classes) { 041 042 final Injector injector = Tang.Factory.getTang().newInjector(baseConf); 043 final JavaConfigurationBuilder confBuilder = Tang.Factory.getTang().newConfigurationBuilder(); 044 045 for (final Class<? extends Name<?>> clazz : classes) { 046 try { 047 confBuilder.bindNamedParameter(clazz, 048 injector.getNamedInstance((Class<? extends Name<Object>>) clazz).toString()); 049 } catch (final InjectionException ex) { 050 final String msg = "Exception while creating subconfiguration"; 051 LOG.log(Level.WARNING, msg, ex); 052 throw new RuntimeException(msg, ex); 053 } 054 } 055 056 return confBuilder.build(); 057 } 058 059 public static void main(final String[] args) throws InjectionException { 060 061 final Configuration conf = TaskConfiguration.CONF 062 .set(TaskConfiguration.IDENTIFIER, "TASK") 063 .set(TaskConfiguration.TASK, MasterTask.class) 064 .build(); 065 066 final Configuration subConf = SubConfiguration.from(conf, TaskConfigurationOptions.Identifier.class); 067 LOG.log(Level.INFO, "OUT: Base conf:\n{0}", Configurations.toString(conf)); 068 LOG.log(Level.INFO, "OUT: Sub conf:\n{0}", Configurations.toString(subConf)); 069 } 070 071 /** 072 * Empty private constructor to prohibit instantiation of utility class. 073 */ 074 private SubConfiguration() { 075 } 076}