001/** 002 * Copyright (C) 2006-2018 Talend Inc. - www.talend.com 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.talend.sdk.component.junit; 017 018import org.talend.sdk.component.runtime.base.Lifecycle; 019import org.talend.sdk.component.runtime.output.InputFactory; 020import org.talend.sdk.component.runtime.output.OutputFactory; 021import org.talend.sdk.component.runtime.output.Processor; 022 023import lombok.RequiredArgsConstructor; 024 025/** 026 * Processor wrapper allowing to "auto" manage the chunking/grouping. 027 */ 028@RequiredArgsConstructor 029public class AutoChunkProcessor implements Lifecycle { 030 031 private static final OutputFactory FAILING_OUTPUT_FACTORY = name -> { 032 throw new IllegalArgumentException("Output from @AfterGroup is not supported here"); 033 }; 034 035 /** 036 * The size of the chunks. 037 */ 038 private final int chunkSize; 039 040 /** 041 * The delegate processor. 042 */ 043 private final Processor processor; 044 045 /** 046 * Internal counter to handle the chunking. 047 */ 048 private int processedItemCount = 0; 049 050 public void onElement(final InputFactory ins, final OutputFactory outs) { 051 if (processedItemCount == 0) { 052 processor.beforeGroup(); 053 } 054 try { 055 processor.onNext(ins, outs); 056 processedItemCount++; 057 } finally { 058 if (processedItemCount == chunkSize) { 059 processor.afterGroup(outs); 060 } 061 } 062 } 063 064 @Override 065 public void stop() { 066 try { 067 if (processedItemCount > 0) { 068 processor.afterGroup(FAILING_OUTPUT_FACTORY); 069 } 070 } finally { 071 processor.stop(); 072 } 073 } 074 075 @Override 076 public String plugin() { 077 return processor.plugin(); 078 } 079 080 @Override 081 public String rootName() { 082 return processor.rootName(); 083 } 084 085 @Override 086 public String name() { 087 return processor.name(); 088 } 089 090 @Override 091 public void start() { 092 processor.start(); 093 } 094}