001/*
002 * Copyright (c) 2016 Chris K Wensel <chris@wensel.net>. All Rights Reserved.
003 * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
004 *
005 * Project and contact information: http://www.cascading.org/
006 *
007 * This file is part of the Cascading project.
008 *
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *     http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 */
021
022package cascading.flow.planner.iso.transformer;
023
024import java.util.Set;
025
026import cascading.flow.FlowElement;
027import cascading.flow.planner.graph.ElementGraph;
028import cascading.flow.planner.graph.ElementGraphs;
029import cascading.flow.planner.iso.expression.ElementCapture;
030import cascading.flow.planner.iso.expression.ExpressionGraph;
031import cascading.flow.planner.iso.finder.Match;
032import cascading.util.Util;
033
034/**
035 *
036 */
037public class RemoveBranchGraphTransformer extends MutateGraphTransformer
038  {
039  public RemoveBranchGraphTransformer( ExpressionGraph filter )
040    {
041    super( filter );
042    }
043
044  public RemoveBranchGraphTransformer( GraphTransformer graphTransformer, ExpressionGraph filter )
045    {
046    super( graphTransformer, filter );
047    }
048
049  @Override
050  protected boolean transformGraphInPlaceUsing( Transformed<ElementGraph> transformed, ElementGraph graph, Match match )
051    {
052    Set<FlowElement> primary = match.getCapturedElements( ElementCapture.Primary );
053    Set<FlowElement> secondary = match.getCapturedElements( ElementCapture.Secondary );
054
055    if( primary.isEmpty() )
056      return false;
057
058    if( primary.size() != 1 )
059      throw new IllegalStateException( "too many captured primary elements" );
060
061    if( secondary.isEmpty() )
062      {
063      boolean found = ElementGraphs.removeBranchContaining( graph, Util.getFirst( primary ) );
064
065      if( !found )
066        throw new IllegalStateException( "no branch found at: " + Util.getFirst( primary ) );
067      }
068    else
069      {
070      if( secondary.size() != 1 )
071        throw new IllegalStateException( "too many captured secondary elements" );
072
073      boolean found = ElementGraphs.removeBranchBetween( graph, Util.getFirst( primary ), Util.getFirst( secondary ), false );
074
075      if( !found )
076        throw new IllegalStateException( "no branch found between: " + Util.getFirst( primary ) + " and " + Util.getFirst( secondary ) );
077      }
078
079    return true;
080    }
081  }