index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/LDoFnContext.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.TaskInputOutputContext; /** * Context object for implementing distributed operations in terms of Lambda expressions. * @param <S> Input type of LDoFn * @param <T> Output type of LDoFn */ public interface LDoFnContext<S, T> { /** Get the input element */ S element(); /** Emit t to the output */ void emit(T t); /** Get the underlying {@link TaskInputOutputContext} (for special cases) */ TaskInputOutputContext getContext(); /** Get the current Hadoop {@link Configuration} */ Configuration getConfiguration(); /** Increment a counter by 1 */ void increment(String groupName, String counterName); /** Increment a counter by value */ void increment(String groupName, String counterName, long value); /** Increment a counter by 1 */ void increment(Enum<?> counterName); /** Increment a counter by value */ void increment(Enum<?> counterName, long value); }
2,400
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/LTable.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda; import org.apache.crunch.GroupingOptions; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.Target; import org.apache.crunch.lambda.fn.SFunction; import org.apache.crunch.lambda.fn.SPredicate; import org.apache.crunch.lib.join.DefaultJoinStrategy; import org.apache.crunch.lib.join.JoinStrategy; import org.apache.crunch.lib.join.JoinType; import org.apache.crunch.types.PTableType; import org.apache.crunch.types.PType; import java.util.Collection; /** * Java 8 friendly version of the {@link PTable} interface, allowing distributed operations to be expressed in * terms of lambda expressions and method references, instead of creating a new class implementation for each operation. * @param <K> key type for this table * @param <V> value type for this table */ public interface LTable<K, V> extends LCollection<Pair<K, V>> { /** * Get the underlying {@link PTable} for this LCollection */ PTable<K, V> underlying(); /** * Group this table by key to yield a {@link LGroupedTable} */ default LGroupedTable<K, V> groupByKey() { return factory().wrap(underlying().groupByKey()); } /** * Group this table by key to yield a {@link LGroupedTable} */ default LGroupedTable<K, V> groupByKey(int numReducers) { return factory().wrap(underlying().groupByKey(numReducers)); } /** * Group this table by key to yield a {@link LGroupedTable} */ default LGroupedTable<K, V> groupByKey(GroupingOptions opts) { return factory().wrap(underlying().groupByKey(opts)); } /** * Get an {@link LCollection} containing just the keys from this table */ default LCollection<K> keys() { return factory().wrap(underlying().keys()); } /** * Get an {@link LCollection} containing just the values from this table */ default LCollection<V> values() { return factory().wrap(underlying().values()); } /** * Transform the keys of this table using the given function */ default <T> LTable<T, V> mapKeys(SFunction<K, T> fn, PType<T> pType) { return parallelDo( ctx -> ctx.emit(Pair.of(fn.apply(ctx.element().first()), ctx.element().second())), ptf().tableOf(pType, valueType())); } /** * Transform the values of this table using the given function */ default <T> LTable<K, T> mapValues(SFunction<V, T> fn, PType<T> pType) { return parallelDo( ctx -> ctx.emit(Pair.of(ctx.element().first(), fn.apply(ctx.element().second()))), ptf().tableOf(keyType(), pType)); } /** * Filter the rows of the table using the supplied predicate. */ default LTable<K, V> filter(SPredicate<Pair<K, V>> predicate) { return parallelDo(ctx -> { if (predicate.test(ctx.element())) ctx.emit(ctx.element());}, pType()); } /** * Filter the rows of the table using the supplied predicate applied to the key part of each record. */ default LTable<K, V> filterByKey(SPredicate<K> predicate) { return parallelDo(ctx -> { if (predicate.test(ctx.element().first())) ctx.emit(ctx.element());}, pType()); } /** * Filter the rows of the table using the supplied predicate applied to the value part of each record. */ default LTable<K, V> filterByValue(SPredicate<V> predicate) { return parallelDo(ctx -> { if (predicate.test(ctx.element().second())) ctx.emit(ctx.element());}, pType()); } /** * Join this table to another {@link LTable} which has the same key type using the provided {@link JoinType} and * {@link JoinStrategy} */ default <U> LTable<K, Pair<V, U>> join(LTable<K, U> other, JoinType joinType, JoinStrategy<K, V, U> joinStrategy) { return factory().wrap(joinStrategy.join(underlying(), other.underlying(), joinType)); } /** * Join this table to another {@link LTable} which has the same key type using the provide {@link JoinType} and * the {@link DefaultJoinStrategy} (reduce-side join). */ default <U> LTable<K, Pair<V, U>> join(LTable<K, U> other, JoinType joinType) { return join(other, joinType, new DefaultJoinStrategy<>()); } /** * Inner join this table to another {@link LTable} which has the same key type using a reduce-side join */ default <U> LTable<K, Pair<V, U>> join(LTable<K, U> other) { return join(other, JoinType.INNER_JOIN); } /** * Cogroup this table with another {@link LTable} with the same key type, collecting the set of values from * each side. */ default <U> LTable<K, Pair<Collection<V>, Collection<U>>> cogroup(LTable<K, U> other) { return factory().wrap(underlying().cogroup(other.underlying())); } /** * Get the underlying {@link PTableType} used to serialize key/value pairs in this table */ default PTableType<K, V> pType() { return underlying().getPTableType(); } /** * Get a {@link PType} which can be used to serialize the key part of this table */ default PType<K> keyType() { return underlying().getKeyType(); } /** * Get a {@link PType} which can be used to serialize the value part of this table */ default PType<V> valueType() { return underlying().getValueType(); } /** * Write this table to the {@link Target} supplied. */ default LTable<K, V> write(Target target) { underlying().write(target); return this; } /** * Write this table to the {@link Target} supplied. */ default LTable<K, V> write(Target target, Target.WriteMode writeMode) { underlying().write(target, writeMode); return this; } /** {@inheritDoc} */ default LTable<K, V> increment(Enum<?> counter) { return parallelDo(ctx -> { ctx.increment(counter); ctx.emit(ctx.element()); }, pType()); } /** {@inheritDoc} */ default LTable<K, V> increment(String counterGroup, String counterName) { return parallelDo(ctx -> { ctx.increment(counterGroup, counterName); ctx.emit(ctx.element()); }, pType()); } /** {@inheritDoc} */ default LTable<K, V> incrementIf(Enum<?> counter, SPredicate<Pair<K, V>> condition) { return parallelDo(ctx -> { if (condition.test(ctx.element())) ctx.increment(counter); ctx.emit(ctx.element()); }, pType()); } /** {@inheritDoc} */ default LTable<K, V> incrementIf(String counterGroup, String counterName, SPredicate<Pair<K, V>> condition) { return parallelDo(ctx -> { if (condition.test(ctx.element())) ctx.increment(counterGroup, counterName); ctx.emit(ctx.element()); }, pType()); } /** {@inheritDoc */ default LTable<K, V> union(LTable<K, V> other) { return factory().wrap(underlying().union(other.underlying())); } /** {@inheritDoc */ default LTable<K, V> union(PTable<K, V> other) { return factory().wrap(underlying().union(other)); } }
2,401
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/LDoFn.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda; import org.apache.crunch.DoFn; import java.io.Serializable; /** * A Java lambdas friendly version of the {@link DoFn} class. */ public interface LDoFn<S, T> extends Serializable { void process(LDoFnContext<S, T> context); }
2,402
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/LCollectionFactoryImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda; import org.apache.crunch.PCollection; import org.apache.crunch.PGroupedTable; import org.apache.crunch.PTable; class LCollectionFactoryImpl implements LCollectionFactory { @Override public <S> LCollection<S> wrap(final PCollection<S> collection) { return new LCollection<S>() { @Override public PCollection<S> underlying() { return collection; } @Override public LCollectionFactory factory() { return LCollectionFactoryImpl.this; } }; } @Override public <K, V> LTable<K, V> wrap(final PTable<K, V> collection) { return new LTable<K, V>() { @Override public PTable<K, V> underlying() { return collection; } @Override public LCollectionFactory factory() { return LCollectionFactoryImpl.this; } }; } @Override public <K, V> LGroupedTable<K, V> wrap(final PGroupedTable<K, V> collection) { return new LGroupedTable<K, V>() { @Override public PGroupedTable<K, V> underlying() { return collection; } @Override public LCollectionFactory factory() { return LCollectionFactoryImpl.this; } }; } }
2,403
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * <p>Alternative Crunch API using Java 8 features to allow construction of pipelines using lambda functions and method * references. It works by wrapping standards Java {@link org.apache.crunch.PCollection}, * {@link org.apache.crunch.PTable} and {@link org.apache.crunch.PGroupedTable} instances into the corresponding * {@link org.apache.crunch.lambda.LCollection}, {@link org.apache.crunch.lambda.LTable} and * {@link org.apache.crunch.lambda.LGroupedTable classes}.</p> * * <p>The static class {@link org.apache.crunch.lambda.Lambda} has methods to create these. Please also see the Javadocs * for {@link org.apache.crunch.lambda.Lambda} for usage examples</p> */ package org.apache.crunch.lambda;
2,404
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SBiConsumer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.BiConsumer; /** * Serializable version of the Java BiConsumer functional interface. */ @FunctionalInterface public interface SBiConsumer<K, V> extends BiConsumer<K, V>, Serializable { }
2,405
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SConsumer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.Consumer; /** * Serializable version of the Java Consumer functional interface. */ @FunctionalInterface public interface SConsumer<T> extends Consumer<T>, Serializable { }
2,406
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SBiFunction.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.BiFunction; /** * Serializable version of the Java BiFunction functional interface. */ @FunctionalInterface public interface SBiFunction<K, V, T> extends BiFunction<K, V, T>, Serializable { }
2,407
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SFunction.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.Function; /** * Serializable version of the Java Function functional interface. */ @FunctionalInterface public interface SFunction<S, T> extends Function<S, T>, Serializable { }
2,408
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SBinaryOperator.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.BinaryOperator; /** * Serializable version of the Java BinaryOperator functional interface. */ @FunctionalInterface public interface SBinaryOperator<T> extends BinaryOperator<T>, Serializable { }
2,409
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SPredicate.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.Predicate; /** * Serializable version of the Java Predicate functional interface. */ @FunctionalInterface public interface SPredicate<T> extends Predicate<T>, Serializable { }
2,410
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/SSupplier.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lambda.fn; import java.io.Serializable; import java.util.function.Supplier; /** * Serializable version of the Java Supplier functional interface. */ @FunctionalInterface public interface SSupplier<T> extends Supplier<T>, Serializable { }
2,411
0
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda
Create_ds/crunch/crunch-lambda/src/main/java/org/apache/crunch/lambda/fn/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Serializable versions of the functional interfaces that ship with Java 8 */ package org.apache.crunch.lambda.fn;
2,412
0
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/test
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/test/java/TokenizerTest.java
## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.apache.crunch.Emitter; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TokenizerTest { @Mock private Emitter<String> emitter; @Test public void testProcess() { Tokenizer splitter = new Tokenizer(); splitter.process(" foo bar ", emitter); verify(emitter).emit("foo"); verify(emitter).emit("bar"); verifyNoMoreInteractions(emitter); } }
2,413
0
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/test
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/test/java/StopWordFilterTest.java
## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.is; import org.apache.crunch.FilterFn; import org.junit.Test; public class StopWordFilterTest { @Test public void testFilter() { FilterFn<String> filter = new StopWordFilter(); assertThat(filter.accept("foo"), is(true)); assertThat(filter.accept("the"), is(false)); assertThat(filter.accept("a"), is(false)); } }
2,414
0
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main/java/StopWordFilter.java
## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import java.util.Set; import org.apache.crunch.FilterFn; import com.google.common.collect.ImmutableSet; /** * A filter that removes known stop words. */ public class StopWordFilter extends FilterFn<String> { // English stop words, borrowed from Lucene. private static final Set<String> STOP_WORDS = ImmutableSet.copyOf(new String[] { "a", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "s", "such", "t", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with" }); @Override public boolean accept(String word) { return !STOP_WORDS.contains(word); } }
2,415
0
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main/java/Tokenizer.java
## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import com.google.common.base.Splitter; /** * Splits a line of text, filtering known stop words. */ public class Tokenizer extends DoFn<String, String> { private static final Splitter SPLITTER = Splitter.onPattern("${symbol_escape}${symbol_escape}s+").omitEmptyStrings(); @Override public void process(String line, Emitter<String> emitter) { for (String word : SPLITTER.split(line)) { emitter.emit(word); } } }
2,416
0
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main
Create_ds/crunch/crunch-archetype/src/main/resources/archetype-resources/src/main/java/WordCount.java
## ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you 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. ## #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineResult; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * A word count example for Apache Crunch, based on Crunch's example projects. */ public class WordCount extends Configured implements Tool { public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new WordCount(), args); } public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: hadoop jar ${artifactId}-${version}-job.jar" + " [generic options] input output"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } String inputPath = args[0]; String outputPath = args[1]; // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(WordCount.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(inputPath); // Define a function that splits each line in a PCollection of Strings into // a PCollection made up of the individual words in the file. // The second argument sets the serialization format. PCollection<String> words = lines.parallelDo(new Tokenizer(), Writables.strings()); // Take the collection of words and remove known stop words. PCollection<String> noStopWords = words.filter(new StopWordFilter()); // The count method applies a series of Crunch primitives and returns // a map of the unique words in the input PCollection to their counts. PTable<String, Long> counts = noStopWords.count(); // Instruct the pipeline to write the resulting counts to a text file. pipeline.writeTextFile(counts, outputPath); // Execute the pipeline as a MapReduce. PipelineResult result = pipeline.done(); return result.succeeded() ? 0 : 1; } }
2,417
0
Create_ds/crunch/crunch-test/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/test/java/org/apache/crunch/test/CrunchTestSupportTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.junit.Test; public class CrunchTestSupportTest { enum CT { ONE, }; @Test public void testContext() { Configuration sampleConfig = new Configuration(); String status = "test"; TaskInputOutputContext<?, ?, ?, ?> testContext = CrunchTestSupport.getTestContext(sampleConfig); assertEquals(sampleConfig, testContext.getConfiguration()); TaskAttemptID taskAttemptID = testContext.getTaskAttemptID(); assertEquals(taskAttemptID, testContext.getTaskAttemptID()); assertNotNull(taskAttemptID); assertNull(testContext.getStatus()); testContext.setStatus(status); assertEquals(status, testContext.getStatus()); assertEquals(0, testContext.getCounter(CT.ONE).getValue()); testContext.getCounter(CT.ONE).increment(1); assertEquals(1, testContext.getCounter(CT.ONE).getValue()); testContext.getCounter(CT.ONE).increment(4); assertEquals(5, testContext.getCounter(CT.ONE).getValue()); } }
2,418
0
Create_ds/crunch/crunch-test/src/it/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/it/java/org/apache/crunch/test/TemporaryPathIT.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.junit.Rule; import org.junit.Test; public class TemporaryPathIT { @Rule public TemporaryPath tmpDir = new TemporaryPath("foo.tmp", "bar.tmp"); @Test public void testRoot() throws IOException { assertThat(tmpDir.getRootFile().exists(), is(true)); assertThat(new File(tmpDir.getRootFileName()).exists(), is(true)); assertThat(getFs().exists(tmpDir.getRootPath()), is(true)); } @Test public void testFile() throws IOException { assertThat(tmpDir.getFile("foo").getParentFile(), is(tmpDir.getRootFile())); assertThat(tmpDir.getFile("foo").getName(), is("foo")); assertThat(tmpDir.getFile("foo").exists(), is(false)); } @Test public void testPath() throws IOException { assertThat(tmpDir.getPath("foo").getParent(), is(tmpDir.getRootPath())); assertThat(tmpDir.getPath("foo").getName(), is("foo")); assertThat(getFs().exists(tmpDir.getPath("foo")), is(false)); } @Test public void testFileName() { assertThat(new File(tmpDir.getRootFileName()), is(tmpDir.getRootFile())); assertThat(new File(tmpDir.getFileName("foo").toString()), is(tmpDir.getFile("foo"))); } @Test public void testCopyResource() throws IOException { File dest = tmpDir.getFile("data.txt"); assertThat(dest.exists(), is(false)); tmpDir.copyResourceFile("data.txt"); assertThat(dest.exists(), is(true)); } @Test public void testGetDefaultConfiguration() { Configuration conf = tmpDir.getDefaultConfiguration(); String fooDir = conf.get("foo.tmp"); String barDir = conf.get("bar.tmp"); assertThat(fooDir, startsWith(tmpDir.getRootFileName())); assertThat(barDir, startsWith(tmpDir.getRootFileName())); assertThat(fooDir, is(not(barDir))); } @Test public void testOverridePathProperties() { Configuration conf = new Configuration(); conf.set("foo.tmp", "whatever"); conf.set("other.dir", "/my/dir"); tmpDir.overridePathProperties(conf); assertThat(conf.get("foo.tmp"), startsWith(tmpDir.getRootFileName())); assertThat(conf.get("other.dir"), is("/my/dir")); } private LocalFileSystem getFs() throws IOException { return FileSystem.getLocal(new Configuration()); } }
2,419
0
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch/test/CrunchTestSupport.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.junit.Rule; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; /** * A temporary workaround for Scala tests to use when working with Rule * annotations until it gets fixed in JUnit 4.11. */ public class CrunchTestSupport { @Rule public TemporaryPath tempDir = new TemporaryPath("crunch.tmp.dir", "hadoop.tmp.dir"); /** * The method creates a {@linkplain TaskInputOutputContext} which can be used * in unit tests. The context serves very limited purpose. You can only * operate with counters, taskAttempId, status and configuration while using * this context. */ public static <KI, VI, KO, VO> TaskInputOutputContext<KI, VI, KO, VO> getTestContext(final Configuration config) { TaskInputOutputContext<KI, VI, KO, VO> context = Mockito.mock(TaskInputOutputContext.class); TestCounters.clearCounters(); final StateHolder holder = new StateHolder(); Mockito.when(context.getCounter(Mockito.any(Enum.class))).then(new Answer<Counter>() { @Override public Counter answer(InvocationOnMock invocation) throws Throwable { Enum<?> counter = (Enum<?>) invocation.getArguments()[0]; return TestCounters.getCounter(counter); } }); Mockito.when(context.getCounter(Mockito.anyString(), Mockito.anyString())).then(new Answer<Counter>() { @Override public Counter answer(InvocationOnMock invocation) throws Throwable { String group = (String) invocation.getArguments()[0]; String name = (String) invocation.getArguments()[1]; return TestCounters.getCounter(group, name); } }); Mockito.when(context.getConfiguration()).thenReturn(config); Mockito.when(context.getTaskAttemptID()).thenReturn(new TaskAttemptID()); Mockito.when(context.getStatus()).then(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return holder.internalStatus; } }); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { holder.internalStatus = (String) invocation.getArguments()[0]; return null; } }).when(context).setStatus(Mockito.anyString()); return context; } static class StateHolder { private String internalStatus; } }
2,420
0
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch/test/TemporaryPath.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import java.io.File; import java.io.IOException; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.rules.ExternalResource; import org.junit.rules.TemporaryFolder; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.google.common.collect.ImmutableSet; import com.google.common.io.Files; import com.google.common.io.Resources; /** * Creates a temporary directory for a test case and destroys it afterwards. * * This provides a temporary directory like JUnit's {@link TemporaryFolder} but * geared towards Hadoop applications. Unlike {@link TemporaryFolder}, it * doesn't create any files or directories except for the root directory itself. * * Also, {@link #getDefaultConfiguration()} provides you with a configuration that * overrides path properties with temporary directories. You have to specify these * properties via the constructor. */ public final class TemporaryPath extends ExternalResource { private final TemporaryFolder tmp = new TemporaryFolder(); private final Set<String> confKeys; /** * Construct {@code TemporaryPath}. * @param confKeys {@link Configuration} keys containing directories to override */ public TemporaryPath(String... confKeys) { if (confKeys != null) { this.confKeys = ImmutableSet.copyOf(confKeys); } else { this.confKeys = ImmutableSet.of(); } } public void create() throws Throwable { tmp.create(); } public void delete() { tmp.delete(); } @Override public Statement apply(Statement base, Description description) { return tmp.apply(base, description); } /** * Get the root directory which will be deleted automatically. */ public File getRootFile() { return tmp.getRoot(); } /** * Get the root directory as a {@link Path}. */ public Path getRootPath() { return toPath(tmp.getRoot()); } /** * Get the root directory as an absolute file name. */ public String getRootFileName() { return tmp.getRoot().getAbsolutePath(); } /** * Get a {@link File} below the temporary directory. */ public File getFile(String fileName) { return new File(getRootFile(), fileName); } /** * Get a {@link Path} below the temporary directory. */ public Path getPath(String fileName) { return toPath(getFile(fileName)); } /** * Get an absolute file name below the temporary directory. */ public String getFileName(String fileName) { return getFile(fileName).getAbsolutePath(); } /** * Copy a classpath resource to {@link File}. */ public File copyResourceFile(String resourceName) throws IOException { String baseName = new File(resourceName).getName(); File dest = new File(tmp.getRoot(), baseName); copy(resourceName, dest); return dest; } /** * Copy a classpath resource to a {@link Path}. */ public Path copyResourcePath(String resourceName) throws IOException { return toPath(copyResourceFile(resourceName)); } /** * Copy a classpath resource returning its absolute file name. */ public String copyResourceFileName(String resourceName) throws IOException { return copyResourceFile(resourceName).getAbsolutePath(); } private static void copy(String resourceName, File dest) throws IOException { Resources.asByteSource(Resources.getResource(resourceName)).copyTo(Files.asByteSink(dest)); } private static Path toPath(File file) { return new Path(file.getAbsolutePath()); } public Configuration getDefaultConfiguration() { return overridePathProperties(new Configuration()); } /** * Set all keys specified in the constructor to temporary directories. */ public Configuration overridePathProperties(Configuration config) { for (String name : confKeys) { config.set(name, getFileName("tmp-" + name)); } return config; } }
2,421
0
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch/test/TestCounters.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; /** * A utility class used during unit testing to update and read counters. */ public class TestCounters { private static Counters COUNTERS = new Counters(); public static Counter getCounter(Enum<?> e) { return COUNTERS.findCounter(e); } public static Counter getCounter(String group, String name) { return COUNTERS.findCounter(group, name); } public static void clearCounters() { COUNTERS = new Counters(); } }
2,422
0
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch/test/DebugLogging.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; /** * Allows direct manipulation of the Hadoop log4j settings to aid in * unit testing. Not recommended for production use. */ public final class DebugLogging { /** * Enables logging Hadoop output to the console using the pattern * '%-4r [%t] %-5p %c %x - %m%n' at the specified {@code Level}. * * @param level The log4j level */ public static void enable(Level level) { enable(level, new ConsoleAppender(new PatternLayout("%-4r [%t] %-5p %c %x - %m%n"))); } /** * Enables logging to the given {@code Appender} at the specified {@code Level}. * * @param level The log4j level * @param appender The log4j appender */ public static void enable(Level level, Appender appender) { Logger hadoopLogger = LogManager.getLogger("org.apache.hadoop"); hadoopLogger.setLevel(level); hadoopLogger.addAppender(appender); } private DebugLogging() { } }
2,423
0
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-test/src/main/java/org/apache/crunch/test/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Utilities for testing Crunch-based applications. */ package org.apache.crunch.test;
2,424
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/TotalBytesByIP.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.crunch.Aggregator; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineResult; import org.apache.crunch.fn.Aggregators; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; @SuppressWarnings("serial") public class TotalBytesByIP extends Configured implements Tool, Serializable { static enum COUNTERS { NO_MATCH, CORRUPT_SIZE } static final String logRegex = "^([\\w.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+) \"([^\"]+)\" \"([^\"]+)\""; public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println(); System.err.println("Two and only two arguments are accepted."); System.err.println("Usage: " + this.getClass().getName() + " [generic options] input output"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(TotalBytesByIP.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(args[0]); // Aggregator used for summing up response size Aggregator<Long> agg = Aggregators.SUM_LONGS(); // Table of (ip, sum(response size)) PTable<String, Long> ipAddrResponseSize = lines .parallelDo(extractIPResponseSize, Writables.tableOf(Writables.strings(), Writables.longs())).groupByKey() .combineValues(agg); pipeline.writeTextFile(ipAddrResponseSize, args[1]); // Execute the pipeline as a MapReduce. PipelineResult result = pipeline.done(); return result.succeeded() ? 0 : 1; } // Function to parse apache log records // Given a standard apache log line, extract the ip address and // request size. Outputs the ip and response size. // // Input: 55.1.3.2 ...... 200 512 .... // Output: (55.1.3.2, 512) DoFn<String, Pair<String, Long>> extractIPResponseSize = new DoFn<String, Pair<String, Long>>() { transient Pattern pattern; public void initialize() { pattern = Pattern.compile(logRegex); } public void process(String line, Emitter<Pair<String, Long>> emitter) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { try { Long requestSize = Long.parseLong(matcher.group(7)); String remoteAddr = matcher.group(1); emitter.emit(Pair.of(remoteAddr, requestSize)); } catch (NumberFormatException e) { // corrupt line, we should increment counter } } } }; public static void main(String[] args) throws Exception { int result = ToolRunner.run(new Configuration(), new TotalBytesByIP(), args); System.exit(result); } }
2,425
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/WordAggregationHBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.List; import com.google.common.collect.Lists; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.Pipeline; import org.apache.crunch.fn.Aggregators; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.io.hbase.HBaseSourceTarget; import org.apache.crunch.io.hbase.HBaseTarget; import org.apache.crunch.io.hbase.HBaseTypes; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * You need to have a HBase instance running. Required dependencies : hbase /!\ * The version should be your version of hbase. <dependency> * <groupId>org.apache.hbase</groupId> <artifactId>hbase</artifactId> * <version>...</version> </dependency> */ @SuppressWarnings("serial") public class WordAggregationHBase extends Configured implements Tool, Serializable { private static final Logger LOG = LoggerFactory.getLogger(WordAggregationHBase.class); // Configuration parameters. Here configured for a hbase instance running // locally private static final String HBASE_CONFIGURATION_ZOOKEEPER_QUORUM = "hbase.zookeeper.quorum"; private static final String HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT = "hbase.zookeeper.property.clientPort"; private static final String hbaseZookeeperQuorum = "localhost"; private static final String hbaseZookeeperClientPort = "2181"; // HBase parameters private static final String TABLE_SOURCE = "list"; private static final String TABLE_TARGET = "aggregation"; private final byte[] COLUMN_FAMILY_SOURCE = Bytes.toBytes("content"); private final byte[] COLUMN_QUALIFIER_SOURCE_PLAY = Bytes.toBytes("play"); private final byte[] COLUMN_QUALIFIER_SOURCE_QUOTE = Bytes.toBytes("quote"); private final byte[] COLUMN_FAMILY_TARGET = Bytes.toBytes("aggregation"); private final byte[] COLUMN_QUALIFIER_TARGET_TEXT = Bytes.toBytes("text"); @Override public int run(String[] args) throws Exception { // We create the test rows first String type1 = "romeo and juliet"; String type2 = "macbeth"; String quote1 = "That which we call a rose By any other word would smell as sweet"; String quote2 = "But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun."; String quote3 = "But first, let me tell ye, if you should leadher in a fool's paradise, as they say,"; String quote4 = "Fair is foul, and foul is fair"; String quote5 = "But screw your courage to the sticking-place, And we'll not fail."; String[] character = { "juliet", "romeo", "nurse", "witch", "macbeth" }; String[] type = { type1, type1, type1, type2, type2 }; String[] quote = { quote1, quote2, quote3, quote4, quote5 }; List<Put> putList = createPuts(Arrays.asList(character), Arrays.asList(type), Arrays.asList(quote)); // We create the tables and fill the source Configuration configuration = getConf(); createTable(configuration, TABLE_SOURCE, Bytes.toString(COLUMN_FAMILY_SOURCE)); createTable(configuration, TABLE_TARGET, Bytes.toString(COLUMN_FAMILY_TARGET)); putInHbase(putList, configuration); // We create the pipeline which will handle most of the job. Pipeline pipeline = new MRPipeline(WordAggregationHBase.class, HBaseConfiguration.create()); // The scan which will retrieve the data from the source in hbase. Scan scan = new Scan(); scan.addColumn(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_PLAY); scan.addColumn(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_QUOTE); // Our hbase source HBaseSourceTarget source = new HBaseSourceTarget(TABLE_SOURCE, scan); // Our source, in a format which can be use by crunch PTable<ImmutableBytesWritable, Result> rawText = pipeline.read(source); // We process the data from the source HTable then concatenate all data // with the same rowkey PTable<String, String> textExtracted = extractText(rawText); PTable<String, String> result = textExtracted.groupByKey() .combineValues(Aggregators.STRING_CONCAT(" ", true)); // We create the collection of puts from the concatenated datas PCollection<Put> resultPut = createPut(result); // We write the puts in hbase, in the target table pipeline.write(resultPut, new HBaseTarget(TABLE_TARGET)); pipeline.done(); return 0; } /** * Put the puts in HBase * * @param putList the puts * @param conf the hbase configuration * @throws IOException */ private static void putInHbase(List<Put> putList, Configuration conf) throws IOException { Connection connection = ConnectionFactory.createConnection(conf); Table htable = connection.getTable(TableName.valueOf(TABLE_SOURCE)); try { htable.put(putList); } finally { htable.close(); connection.close(); } } /** * Create the table if they don't exist * * @param conf the hbase configuration * @param htableName the table name * @param families the column family names * @throws IOException */ private static void createTable(Configuration conf, String htableName, String... families) throws IOException { Connection connection = ConnectionFactory.createConnection(conf); Admin hbase = connection.getAdmin(); try { TableName tableName = TableName.valueOf(htableName); if (!hbase.tableExists(tableName)) { HTableDescriptor desc = new HTableDescriptor(tableName); for (String s : families) { HColumnDescriptor meta = new HColumnDescriptor(s); desc.addFamily(meta); } hbase.createTable(desc); } } finally { hbase.close(); connection.close(); } } /** * Create a list of puts * * @param character the rowkey * @param play the play (in column COLUMN_QUALIFIER_SOURCE_PLAY) * @param quote the quote (in column COLUMN_QUALIFIER_SOURCE_QUOTE) */ private List<Put> createPuts(List<String> character, List<String> play, List<String> quote) { List<Put> list = Lists.newArrayList(); if (character.size() != play.size() || quote.size() != play.size()) { LOG.error("Every list should have the same number of elements"); throw new IllegalArgumentException("Every list should have the same number of elements"); } for (int i = 0; i < character.size(); i++) { Put put = new Put(Bytes.toBytes(character.get(i))); put.addColumn(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_PLAY, Bytes.toBytes(play.get(i))); put.addColumn(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_QUOTE, Bytes.toBytes(quote.get(i))); list.add(put); } return list; } /** * Extract information from hbase * * @param words the source from hbase * @return a {@code PTable} composed of the type of the input as key * and its def as value */ public PTable<String, String> extractText(PTable<ImmutableBytesWritable, Result> words) { return words.parallelDo("Extract text", new DoFn<Pair<ImmutableBytesWritable, Result>, Pair<String, String>>() { @Override public void process(Pair<ImmutableBytesWritable, Result> row, Emitter<Pair<String, String>> emitter) { byte[] type = row.second().getValue(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_PLAY); byte[] def = row.second().getValue(COLUMN_FAMILY_SOURCE, COLUMN_QUALIFIER_SOURCE_QUOTE); if (type != null && def != null) { emitter.emit(new Pair<String, String>(Bytes.toString(type), Bytes.toString(def))); } } }, Writables.tableOf(Writables.strings(), Writables.strings())); } /** * Create puts in order to insert them in hbase. * * @param extractedText * a PTable which contain the data in order to create the puts: * keys of the PTable are rowkeys for the puts, values are the * values for hbase. * @return a PCollection formed by the puts. */ public PCollection<Put> createPut(PTable<String, String> extractedText) { return extractedText.parallelDo("Convert to puts", new DoFn<Pair<String, String>, Put>() { @Override public void process(Pair<String, String> input, Emitter<Put> emitter) { Put put = new Put(Bytes.toBytes(input.first())); put.addColumn(COLUMN_FAMILY_TARGET, COLUMN_QUALIFIER_TARGET_TEXT, Bytes.toBytes(input.second())); emitter.emit(put); } }, HBaseTypes.puts()); } public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); // Configuration hbase conf.set(HBASE_CONFIGURATION_ZOOKEEPER_QUORUM, hbaseZookeeperQuorum); conf.set(HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT, hbaseZookeeperClientPort); ToolRunner.run(conf, new WordAggregationHBase(), args); } }
2,426
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/TotalWordCount.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import java.io.Serializable; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PObject; import org.apache.crunch.PTable; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineResult; import org.apache.crunch.fn.Aggregators; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class TotalWordCount extends Configured implements Tool, Serializable { public int run(String[] args) throws Exception { if (args.length != 1) { System.err.println(); System.err.println("Usage: " + this.getClass().getName() + " [generic options] input"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(TotalWordCount.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(args[0]); // Define a function that splits each line in a PCollection of Strings into // a // PCollection made up of the individual words in the file. PCollection<Long> numberOfWords = lines.parallelDo(new DoFn<String, Long>() { public void process(String line, Emitter<Long> emitter) { emitter.emit((long)line.split("\\s+").length); } }, Writables.longs()); // Indicates the serialization format // The aggregate method groups a collection into a single PObject. PObject<Long> totalCount = numberOfWords.aggregate(Aggregators.SUM_LONGS()).first(); // Execute the pipeline as a MapReduce. PipelineResult result = pipeline.run(); System.out.println("Total number of words: " + totalCount.getValue()); pipeline.done(); return result.succeeded() ? 0 : 1; } public static void main(String[] args) throws Exception { int result = ToolRunner.run(new Configuration(), new TotalWordCount(), args); System.exit(result); } }
2,427
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/SecondarySortExample.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import java.io.Serializable; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.Pipeline; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.lib.SecondarySort; import org.apache.crunch.io.To; import org.apache.crunch.types.avro.Avros; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.common.base.Splitter; @SuppressWarnings("serial") public class SecondarySortExample extends Configured implements Tool, Serializable { static enum COUNTERS { CORRUPT_TIMESTAMP, CORRUPT_LINE } // Input records are comma separated. The first field is grouping record. The // second is the one to sort on (a long in this implementation). The rest is // payload to be sorted. // For example: // one,1,1 // one,2,-3 // two,4,5 // two,2,6 // two,1,7,9 // three,0,-1 // one,-5,10 // one,-10,garbage private static final char SPLIT_ON = ','; private static final Splitter INPUT_SPLITTER = Splitter.on(SPLIT_ON).trimResults().omitEmptyStrings().limit(3); @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println(); System.err.println("Usage: " + this.getClass().getName() + " [generic options] input output"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(SecondarySortExample.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(args[0]); // Define a function that parses each line in a PCollection of Strings into // a pair of pairs, the first of which will be grouped by (first member) and // the sorted by (second memeber). The second pair is payload which can be // passed in an Iterable object. PTable<String, Pair<Long, String>> pairs = lines.parallelDo("extract_records", new DoFn<String, Pair<String, Pair<Long, String>>>() { @Override public void process(String line, Emitter<Pair<String, Pair<Long, String>>> emitter) { int i = 0; String key = ""; long timestamp = 0; String value = ""; for (String element : INPUT_SPLITTER.split(line)) { switch (++i) { case 1: key = element; break; case 2: try { timestamp = Long.parseLong(element); } catch (NumberFormatException e) { System.out.println("Timestamp not in long format '" + line + "'"); this.increment(COUNTERS.CORRUPT_TIMESTAMP); } break; case 3: value = element; break; default: System.err.println("i = " + i + " should never happen!"); break; } } if (i == 3) { Long sortby = new Long(timestamp); emitter.emit(Pair.of(key, Pair.of(sortby, value))); } else { this.increment(COUNTERS.CORRUPT_LINE); } }}, Avros.tableOf(Avros.strings(), Avros.pairs(Avros.longs(), Avros.strings()))); // The output of the above input will be (with one reducer): // one : [[-10,garbage],[-5,10],[1,1],[2,-3]] // three : [[0,-1]] // two : [[1,7,9],[2,6],[4,5]] SecondarySort.sortAndApply(pairs, new DoFn<Pair<String, Iterable<Pair<Long, String>>>, String>() { final StringBuilder sb = new StringBuilder(); @Override public void process(Pair<String, Iterable<Pair<Long, String>>> input, Emitter<String> emitter) { sb.setLength(0); sb.append(input.first()); sb.append(" : ["); boolean first = true; for(Pair<Long, String> pair : input.second()) { if (first) { first = false; } else { sb.append(','); } sb.append(pair); } sb.append("]"); emitter.emit(sb.toString()); } }, Writables.strings()).write(To.textFile(args[1])); // Execute the pipeline as a MapReduce. return pipeline.done().succeeded() ? 0 : 1; } public static void main(String[] args) throws Exception { int exitCode = -1; try { exitCode = ToolRunner.run(new Configuration(), new SecondarySortExample(), args); } catch (Throwable e) { e.printStackTrace(); } System.exit(exitCode); } }
2,428
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/SortExample.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import org.apache.crunch.PCollection; import org.apache.crunch.lib.Sort; import org.apache.crunch.lib.Sort.Order; import org.apache.crunch.util.CrunchTool; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.ToolRunner; /** * Simple Crunch tool for running sorting examples from the command line. */ public class SortExample extends CrunchTool { @Override public int run(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: <input-path> <output-path> <num-reducers>"); return 1; } PCollection<String> in = readTextFile(args[0]); writeTextFile(Sort.sort(in, Integer.valueOf(args[2]), Order.ASCENDING), args[1]); done(); return 0; } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new SortExample(), args); } }
2,429
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/WordCount.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import java.io.Serializable; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineResult; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class WordCount extends Configured implements Tool, Serializable { public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println(); System.err.println("Usage: " + this.getClass().getName() + " [generic options] input output"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(WordCount.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(args[0]); // Define a function that splits each line in a PCollection of Strings into // a // PCollection made up of the individual words in the file. PCollection<String> words = lines.parallelDo(new DoFn<String, String>() { public void process(String line, Emitter<String> emitter) { for (String word : line.split("\\s+")) { emitter.emit(word); } } }, Writables.strings()); // Indicates the serialization format // The count method applies a series of Crunch primitives and returns // a map of the unique words in the input PCollection to their counts. // Best of all, the count() function doesn't need to know anything about // the kind of data stored in the input PCollection. PTable<String, Long> counts = words.count(); // Instruct the pipeline to write the resulting counts to a text file. pipeline.writeTextFile(counts, args[1]); // Execute the pipeline as a MapReduce. PipelineResult result = pipeline.done(); return result.succeeded() ? 0 : 1; } public static void main(String[] args) throws Exception { int result = ToolRunner.run(new Configuration(), new WordCount(), args); System.exit(result); } }
2,430
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Example applications demonstrating various aspects of Crunch. */ package org.apache.crunch.examples;
2,431
0
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch
Create_ds/crunch/crunch-examples/src/main/java/org/apache/crunch/examples/AverageBytesByIP.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.examples; import static org.apache.crunch.fn.Aggregators.SUM_LONGS; import static org.apache.crunch.fn.Aggregators.pairAggregator; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.crunch.Aggregator; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.MapFn; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineResult; import org.apache.crunch.impl.mr.MRPipeline; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; @SuppressWarnings("serial") public class AverageBytesByIP extends Configured implements Tool, Serializable { static enum COUNTERS { NO_MATCH, CORRUPT_SIZE } static final String logRegex = "^([\\w.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+) \"([^\"]+)\" \"([^\"]+)\""; public int run(String[] args) throws Exception { if (args.length != 2) { System.err.println(); System.err.println("Two and only two arguments are accepted."); System.err.println("Usage: " + this.getClass().getName() + " [generic options] input output"); System.err.println(); GenericOptionsParser.printGenericCommandUsage(System.err); return 1; } // Create an object to coordinate pipeline creation and execution. Pipeline pipeline = new MRPipeline(AverageBytesByIP.class, getConf()); // Reference a given text file as a collection of Strings. PCollection<String> lines = pipeline.readTextFile(args[0]); // Aggregator used for summing up response size and count Aggregator<Pair<Long, Long>> agg = pairAggregator(SUM_LONGS(), SUM_LONGS()); // Table of (ip, sum(response size), count) PTable<String, Pair<Long, Long>> remoteAddrResponseSize = lines .parallelDo(extractResponseSize, Writables.tableOf(Writables.strings(), Writables.pairs(Writables.longs(), Writables.longs()))).groupByKey() .combineValues(agg); // Calculate average response size by ip address PTable<String, Double> avgs = remoteAddrResponseSize.parallelDo(calulateAverage, Writables.tableOf(Writables.strings(), Writables.doubles())); // write the result to a text file pipeline.writeTextFile(avgs, args[1]); // Execute the pipeline as a MapReduce. PipelineResult result = pipeline.done(); return result.succeeded() ? 0 : 1; } // Function to calculate the average response size for a given ip address // // Input: (ip, sum(response size), count) // Output: (ip, average response size) MapFn<Pair<String, Pair<Long, Long>>, Pair<String, Double>> calulateAverage = new MapFn<Pair<String, Pair<Long, Long>>, Pair<String, Double>>() { @Override public Pair<String, Double> map(Pair<String, Pair<Long, Long>> arg) { Pair<Long, Long> sumCount = arg.second(); double avg = 0; if (sumCount.second() > 0) { avg = (double) sumCount.first() / (double) sumCount.second(); } return Pair.of(arg.first(), avg); } }; // Function to parse apache log records // Given a standard apache log line, extract the ip address and // response size. Outputs ip and the response size and a count (1) so that // a combiner can be used. // // Input: 55.1.3.2 ...... 200 512 .... // Output: (55.1.3.2, (512, 1)) DoFn<String, Pair<String, Pair<Long, Long>>> extractResponseSize = new DoFn<String, Pair<String, Pair<Long, Long>>>() { transient Pattern pattern; public void initialize() { pattern = Pattern.compile(logRegex); } public void process(String line, Emitter<Pair<String, Pair<Long, Long>>> emitter) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { try { Long responseSize = Long.parseLong(matcher.group(7)); Pair<Long, Long> sumCount = Pair.of(responseSize, 1L); String remoteAddr = matcher.group(1); emitter.emit(Pair.of(remoteAddr, sumCount)); } catch (NumberFormatException e) { this.increment(COUNTERS.CORRUPT_SIZE); } } else { this.increment(COUNTERS.NO_MATCH); } } }; public static void main(String[] args) throws Exception { int result = ToolRunner.run(new Configuration(), new AverageBytesByIP(), args); System.exit(result); } }
2,432
0
Create_ds/crunch/crunch-core/src/test/java/org/apache
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/TupleTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.apache.crunch.types.TupleFactory; import org.junit.Test; public class TupleTest { private String first = "foo"; private Integer second = 1729; private Double third = 64.2; private Boolean fourth = false; private Float fifth = 17.29f; @Test public void testTuple3() { Tuple3<String, Integer, Double> t = new Tuple3<String, Integer, Double>(first, second, third); assertEquals(3, t.size()); assertEquals(first, t.first()); assertEquals(second, t.second()); assertEquals(third, t.third()); assertEquals(first, t.get(0)); assertEquals(second, t.get(1)); assertEquals(third, t.get(2)); try { t.get(-1); fail(); } catch (IndexOutOfBoundsException e) { // expected } } @Test public void testTuple3Equality() { Tuple3<String, Integer, Double> t = new Tuple3<String, Integer, Double>(first, second, third); assertTrue(t.equals(new Tuple3(first, second, third))); assertFalse(t.equals(new Tuple3(first, null, third))); assertFalse((new Tuple3(null, null, null)).equals(t)); assertTrue((new Tuple3(first, null, null)).equals(new Tuple3(first, null, null))); } @Test public void testTuple4() { Tuple4<String, Integer, Double, Boolean> t = new Tuple4<String, Integer, Double, Boolean>(first, second, third, fourth); assertEquals(4, t.size()); assertEquals(first, t.first()); assertEquals(second, t.second()); assertEquals(third, t.third()); assertEquals(fourth, t.fourth()); assertEquals(first, t.get(0)); assertEquals(second, t.get(1)); assertEquals(third, t.get(2)); assertEquals(fourth, t.get(3)); try { t.get(-1); fail(); } catch (IndexOutOfBoundsException e) { // expected } } @Test public void testTuple4Equality() { Tuple4<String, Integer, Double, Boolean> t = new Tuple4<String, Integer, Double, Boolean>(first, second, third, fourth); assertFalse(t.equals(new Tuple3(first, second, third))); assertFalse(t.equals(new Tuple4(first, null, third, null))); assertFalse((new Tuple4(null, null, null, null)).equals(t)); assertTrue((new Tuple4(first, null, third, null)).equals(new Tuple4(first, null, third, null))); } @Test public void testTupleN() { TupleN t = new TupleN(first, second, third, fourth, fifth); assertEquals(5, t.size()); assertEquals(first, t.get(0)); assertEquals(second, t.get(1)); assertEquals(third, t.get(2)); assertEquals(fourth, t.get(3)); assertEquals(fifth, t.get(4)); try { t.get(-1); fail(); } catch (IndexOutOfBoundsException e) { // expected } } @Test public void testTupleNEquality() { TupleN t = new TupleN(first, second, third, fourth, fifth); assertTrue(t.equals(new TupleN(first, second, third, fourth, fifth))); assertFalse(t.equals(new TupleN(first, null, third, null))); assertFalse((new TupleN(null, null, null, null, null)).equals(t)); assertTrue((new TupleN(first, second, third, null, null)).equals(new TupleN(first, second, third, null, null))); } @Test public void testTupleFactory() { checkTuple(TupleFactory.PAIR.makeTuple("a", "b"), Pair.class, "a", "b"); checkTuple(TupleFactory.TUPLE3.makeTuple("a", "b", "c"), Tuple3.class, "a", "b", "c"); checkTuple(TupleFactory.TUPLE4.makeTuple("a", "b", "c", "d"), Tuple4.class, "a", "b", "c", "d"); checkTuple(TupleFactory.TUPLEN.makeTuple("a", "b", "c", "d", "e"), TupleN.class, "a", "b", "c", "d", "e"); checkTuple(TupleFactory.TUPLEN.makeTuple("a", "b"), TupleN.class, "a", "b"); checkTuple(TupleFactory.TUPLEN.makeTuple("a", "b", "c"), TupleN.class, "a", "b", "c"); checkTuple(TupleFactory.TUPLEN.makeTuple("a", "b", "c", "d"), TupleN.class, "a", "b", "c", "d"); checkTuple(TupleFactory.TUPLEN.makeTuple("a", "b", "c", "d", "e"), TupleN.class, "a", "b", "c", "d", "e"); } private void checkTuple(Tuple t, Class<? extends Tuple> type, Object... values) { assertEquals(type, t.getClass()); assertEquals(values.length, t.size()); for (int i = 0; i < values.length; i++) assertEquals(values[i], t.get(i)); } }
2,433
0
Create_ds/crunch/crunch-core/src/test/java/org/apache
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/WriteModeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch; import static org.junit.Assert.assertEquals; import org.apache.crunch.Target.WriteMode; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.crunch.io.To; import org.apache.crunch.test.TemporaryPath; import org.apache.crunch.test.TemporaryPaths; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Rule; import org.junit.Test; import com.google.common.collect.ImmutableList; public class WriteModeTest { @Rule public TemporaryPath tmpDir = TemporaryPaths.create(); @Test(expected=CrunchRuntimeException.class) public void testDefault() throws Exception { run(null, true); } @Test(expected=CrunchRuntimeException.class) public void testDefaultNoRun() throws Exception { run(null, false); } @Test public void testOverwrite() throws Exception { Path p = run(WriteMode.OVERWRITE, true); PCollection<String> lines = MemPipeline.getInstance().readTextFile(p.toString()); assertEquals(ImmutableList.of("some", "string", "values"), ImmutableList.copyOf(lines.materialize())); } @Test(expected=CrunchRuntimeException.class) public void testOverwriteNoRun() throws Exception { run(WriteMode.OVERWRITE, false); } @Test public void testAppend() throws Exception { Path p = run(WriteMode.APPEND, true); PCollection<String> lines = MemPipeline.getInstance().readTextFile(p.toString()); assertEquals(ImmutableList.of("some", "string", "values", "some", "string", "values"), ImmutableList.copyOf(lines.materialize())); } @Test public void testAppendNoRun() throws Exception { Path p = run(WriteMode.APPEND, false); PCollection<String> lines = MemPipeline.getInstance().readTextFile(p.toString()); assertEquals(ImmutableList.of("some", "string", "values", "some", "string", "values"), ImmutableList.copyOf(lines.materialize())); } Path run(WriteMode writeMode, boolean doRun) throws Exception { Path output = tmpDir.getPath("existing"); FileSystem fs = FileSystem.get(tmpDir.getDefaultConfiguration()); if (fs.exists(output)) { fs.delete(output, true); } Pipeline p = MemPipeline.getInstance(); PCollection<String> data = MemPipeline.typedCollectionOf(Avros.strings(), ImmutableList.of("some", "string", "values")); data.write(To.textFile(output)); if (doRun) { p.run(); } if (writeMode == null) { data.write(To.textFile(output)); } else { data.write(To.textFile(output), writeMode); } p.run(); return output; } }
2,434
0
Create_ds/crunch/crunch-core/src/test/java/org/apache
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/PairTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; public class PairTest { @Test public void testPairConstructor() { Pair<String, Integer> pair = new Pair<String, Integer>("brock", 45); test(pair); } @Test public void testPairOf() { Pair<String, Integer> pair = Pair.of("brock", 45); test(pair); } protected void test(Pair<String, Integer> pair) { assertTrue(pair.size() == 2); assertEquals("brock", pair.first()); assertEquals(new Integer(45), pair.second()); assertEquals(Pair.of("brock", 45), pair); assertEquals("brock", pair.get(0)); assertEquals(new Integer(45), pair.get(1)); try { pair.get(-1); fail(); } catch (IndexOutOfBoundsException e) { // expected } } @Test public void testPairComparisons() { assertEquals(0, Pair.of(null, null).compareTo(Pair.of(null, null))); assertEquals(0, Pair.of(1, 2).compareTo(Pair.of(1, 2))); assertTrue(Pair.of(2, "a").compareTo(Pair.of(1, "a")) > 0); assertTrue(Pair.of("a", 2).compareTo(Pair.of("a", 1)) > 0); assertTrue(Pair.of(null, 17).compareTo(Pair.of(null, 29)) < 0); assertTrue(Pair.of(Integer.MIN_VALUE, 0).compareTo(Pair.of((Integer)null, 0)) < 0); assertTrue(Pair.of(0, Integer.MIN_VALUE).compareTo(Pair.of(0, (Integer)null)) < 0); assertTrue(Pair.of(2, "a").compareTo(Pair.of(1, "a")) > 0); assertTrue(Pair.of(new HashValue(2), "a").compareTo(Pair.of(new HashValue(1), "a")) > 0); assertTrue(Pair.of(new HashValue(Integer.MAX_VALUE), "a").compareTo( Pair.of(new HashValue(Integer.MIN_VALUE), "a")) > 0); assertTrue(Pair.of(new HashValue(0), "a").compareTo(Pair.of((HashValue) null, "a")) < 0); // Two value whose hash code is the same but are not equal (via equals) should not compare as the same assertTrue(Pair.of(new HashValue(0, 1), 0).compareTo(Pair.of(new HashValue(0, 2), 0)) != 0); } /** * An object with a known hash value that is not comparable used for testing the comparison logic * within Pair. */ private static final class HashValue { private final int value; private final int additionalValue; // Additional value which is used for equality but not hash code public HashValue(int value) { this(value, 0); } public HashValue(int value, int additionalValue) { this.value = value; this.additionalValue = additionalValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HashValue)) return false; HashValue other = (HashValue) o; if (value != other.value) return false; if (additionalValue != other.additionalValue) return false; return true; } @Override public int hashCode() { return this.value; } } }
2,435
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/SingleUseIterableTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import com.google.common.collect.Lists; public class SingleUseIterableTest { @Test public void testIterator() { List<Integer> values = Lists.newArrayList(1,2,3); SingleUseIterable<Integer> iterable = new SingleUseIterable<Integer>(values); List<Integer> retrievedValues = Lists.newArrayList(iterable); assertEquals(values, retrievedValues); } @Test(expected=IllegalStateException.class) public void testIterator_MultipleCalls() { List<Integer> values = Lists.newArrayList(1,2,3); SingleUseIterable<Integer> iterable = new SingleUseIterable<Integer>(values); // Consume twice Lists.newArrayList(iterable); Lists.newArrayList(iterable); } }
2,436
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/MRPipelineTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.io.IOException; import org.apache.crunch.PipelineExecution; import org.apache.crunch.PipelineResult; import org.apache.crunch.SourceTarget; import org.apache.crunch.impl.dist.collect.PCollectionImpl; import org.apache.crunch.impl.mr.run.RuntimeParameters; import org.apache.crunch.io.ReadableSourceTarget; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MRPipelineTest { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); @Mock private PCollectionImpl<String> pcollection; @Mock private ReadableSourceTarget<String> readableSourceTarget; @Mock private SourceTarget<String> nonReadableSourceTarget; private MRPipeline pipeline; @Before public void setUp() throws IOException { Configuration conf = new Configuration(); conf.set(RuntimeParameters.TMP_DIR, tempDir.getRoot().getAbsolutePath()); pipeline = spy(new MRPipeline(MRPipelineTest.class, conf)); } @Test public void testGetMaterializeSourceTarget_AlreadyMaterialized() { when(pcollection.getMaterializedAt()).thenReturn(readableSourceTarget); assertEquals(readableSourceTarget, pipeline.getMaterializeSourceTarget(pcollection)); } @Test public void testGetMaterializeSourceTarget_NotMaterialized_HasOutput() { when(pcollection.getPType()).thenReturn(Avros.strings()); doReturn(readableSourceTarget).when(pipeline).createIntermediateOutput(Avros.strings()); when(pcollection.getMaterializedAt()).thenReturn(null); assertEquals(readableSourceTarget, pipeline.getMaterializeSourceTarget(pcollection)); } @Test(expected = IllegalArgumentException.class) public void testGetMaterializeSourceTarget_NotMaterialized_NotReadableSourceTarget() { when(pcollection.getPType()).thenReturn(Avros.strings()); doReturn(nonReadableSourceTarget).when(pipeline).createIntermediateOutput(Avros.strings()); when(pcollection.getMaterializedAt()).thenReturn(null); pipeline.getMaterializeSourceTarget(pcollection); } @Test public void testDonePipeline_NoOutputTargets() { PipelineResult res = pipeline.done(); assertTrue(res.succeeded()); assertEquals(PipelineExecution.Status.SUCCEEDED,res.status); } }
2,437
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/plan/JobNameBuilderTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.plan; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class JobNameBuilderTest { private static final Configuration CONF = new Configuration(); @Test public void testBuild() { String pipelineName = "PipelineName"; String nodeName = "outputNode"; DoNode doNode = createDoNode(nodeName); JobNameBuilder jobNameBuilder = new JobNameBuilder(CONF, pipelineName, 1, 1); jobNameBuilder.visit(Lists.newArrayList(doNode)); String jobName = jobNameBuilder.jobSequence(1).build(); assertEquals(String.format("%s: %s ID=1 (1/1)", pipelineName, nodeName), jobName); } @Test public void testNodeNameTooLong() { String pipelineName = "PipelineName"; String nodeName = Strings.repeat("very_long_node_name", 100); DoNode doNode = createDoNode(nodeName); JobNameBuilder jobNameBuilder = new JobNameBuilder(CONF, pipelineName, 1, 1); jobNameBuilder.visit(Lists.newArrayList(doNode)); String jobName = jobNameBuilder.jobSequence(1).build(); assertFalse(jobName.contains(nodeName)); // Tests that the very long node name was shorten } private static DoNode createDoNode(String nodeName) { return DoNode.createOutputNode(nodeName, Writables.strings().getConverter(), Writables.strings()); } }
2,438
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/plan/JobPrototypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.plan; import com.google.common.collect.HashMultimap; import org.apache.crunch.Target; import org.apache.crunch.impl.mr.collect.PGroupedTableImpl; import org.apache.crunch.io.impl.FileTargetImpl; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @RunWith(MockitoJUnitRunner.class) public class JobPrototypeTest { public static final String DFS_REPLICATION = "dfs.replication"; public static final String TEST_INITIAL_DFS_REPLICATION = "42"; public static final String TEST_TMP_DIR_REPLICATION = "1"; @Mock private Path mockPath; @Mock private FileTargetImpl mockTarget; @Mock private FileSystem mockFs; @Mock private PGroupedTableImpl<String, String> mockPgroup; @Mock private Set<NodePath> mockInputs; private JobPrototype jobPrototypeUnderTest; private Configuration testConfiguration = new Configuration(); @Before public void setUp() { testConfiguration.set("dfs.replication.initial", TEST_INITIAL_DFS_REPLICATION); testConfiguration.set("crunch.tmp.dir.replication", TEST_TMP_DIR_REPLICATION); doReturn(new Object[]{}).when(mockInputs).toArray(); jobPrototypeUnderTest= JobPrototype.createMapReduceJob(42, mockPgroup, mockInputs, mockPath); } @Test public void initialReplicationFactorSetForLeafOutputTargets() { jobPrototypeUnderTest.setJobReplication(testConfiguration, true); assertEquals(TEST_TMP_DIR_REPLICATION, testConfiguration.get(DFS_REPLICATION)); } @Test public void userDefinedTmpDirReplicationFactorSetForIntermediateTargets() { jobPrototypeUnderTest.setJobReplication(testConfiguration, false); assertEquals(TEST_INITIAL_DFS_REPLICATION, testConfiguration.get(DFS_REPLICATION)); } @Test public void initialReplicationFactorSetIfUserSpecified() { jobPrototypeUnderTest.handleInitialReplication(testConfiguration); assertEquals(TEST_INITIAL_DFS_REPLICATION, testConfiguration.get("dfs.replication.initial")); } @Test public void initialReplicationFactorUsedFromFileSystem() throws IOException { HashMultimap<Target, NodePath> targetNodePaths = HashMultimap.create(); targetNodePaths.put(mockTarget, new NodePath()); doReturn(mockPath).when(mockTarget).getPath(); doReturn(mockFs).when(mockPath).getFileSystem(any(Configuration.class)); Configuration c = new Configuration(); c.set("dfs.replication", TEST_INITIAL_DFS_REPLICATION); doReturn(c).when(mockFs).getConf(); jobPrototypeUnderTest.addReducePaths(targetNodePaths); testConfiguration = new Configuration(false); jobPrototypeUnderTest.handleInitialReplication(testConfiguration); assertEquals(TEST_INITIAL_DFS_REPLICATION, testConfiguration.get("dfs.replication.initial")); } @Test public void initialReplicationFactorUsedWhenItCannotBeRetrievedFromFileSystem() throws IOException { HashMultimap<Target, NodePath> targetNodePaths = HashMultimap.create(); targetNodePaths.put(mockTarget, new NodePath()); doReturn(mockPath).when(mockTarget).getPath(); doThrow(new IOException()).when(mockPath).getFileSystem(any(Configuration.class)); Configuration c = new Configuration(); c.set("dfs.replication", TEST_INITIAL_DFS_REPLICATION); jobPrototypeUnderTest.addReducePaths(targetNodePaths); testConfiguration = new Configuration(false); jobPrototypeUnderTest.handleInitialReplication(testConfiguration); assertEquals("3", testConfiguration.get("dfs.replication.initial")); //default } }
2,439
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/plan/DotfileWriterTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.plan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.crunch.ParallelDoOptions; import org.apache.crunch.Source; import org.apache.crunch.SourceTarget; import org.apache.crunch.Target; import org.apache.crunch.impl.dist.collect.PCollectionImpl; import org.apache.crunch.impl.mr.collect.InputCollection; import org.apache.crunch.impl.mr.collect.PGroupedTableImpl; import org.apache.crunch.impl.mr.plan.DotfileWriter.MRTaskType; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class DotfileWriterTest { private DotfileWriter dotfileWriter; @Before public void setUp() { dotfileWriter = new DotfileWriter(); } @Test public void testFormatPCollectionNodeDeclaration() { PCollectionImpl<?> pcollectionImpl = mock(PCollectionImpl.class); JobPrototype jobPrototype = mock(JobPrototype.class); when(pcollectionImpl.getName()).thenReturn("collection"); when(pcollectionImpl.getSize()).thenReturn(1024L * 500L); assertEquals("\"collection@" + pcollectionImpl.hashCode() + "@" + jobPrototype.hashCode() + "\" [label=\"collection 0.49 Mb\" shape=box];", dotfileWriter.formatPCollectionNodeDeclaration(pcollectionImpl, jobPrototype)); } @Test public void testFormatPCollectionNodeDeclaration_InputPCollection() { InputCollection<?> inputCollection = mock(InputCollection.class, Mockito.RETURNS_DEEP_STUBS); JobPrototype jobPrototype = mock(JobPrototype.class); when(inputCollection.getName()).thenReturn("input"); when(inputCollection.getSource().toString()).thenReturn("source"); when(inputCollection.getSize()).thenReturn(1024L * 1024L * 1729L); assertEquals("\"source\" [label=\"input 1,729 Mb\" shape=folder];", dotfileWriter.formatPCollectionNodeDeclaration(inputCollection, jobPrototype)); } @Test public void testFormatPGroupedTableImplDeclarationAutomatic() { PGroupedTableImpl<?,?> inputCollection = mock(PGroupedTableImpl.class, Mockito.RETURNS_DEEP_STUBS); JobPrototype jobPrototype = mock(JobPrototype.class); when(inputCollection.getName()).thenReturn("GBK"); when(inputCollection.getSize()).thenReturn(1024L * 1024L * 1729L); when(inputCollection.getNumReduceTasks()).thenReturn(10); String expected = "\"GBK@" + inputCollection.hashCode() + "@" + jobPrototype.hashCode() + "\" [label=\"GBK " + "1,729 Mb (10 Automatic reducers)\" shape=box];"; assertEquals(expected, dotfileWriter.formatPCollectionNodeDeclaration(inputCollection, jobPrototype)); } @Test public void testFormatPGroupedTableImplDeclarationManual() { PGroupedTableImpl<?,?> inputCollection = mock(PGroupedTableImpl.class, Mockito.RETURNS_DEEP_STUBS); JobPrototype jobPrototype = mock(JobPrototype.class); when(inputCollection.getName()).thenReturn("collection"); when(inputCollection.getSize()).thenReturn(1024L * 1024L * 1729L); when(inputCollection.getNumReduceTasks()).thenReturn(50); when(inputCollection.isNumReduceTasksSetByUser()).thenReturn(true); String expected = "\"collection@" + inputCollection.hashCode() + "@" + jobPrototype.hashCode() + "\" [label=\"collection " + "1,729 Mb (50 Manual reducers)\" shape=box];"; assertEquals(expected, dotfileWriter.formatPCollectionNodeDeclaration(inputCollection, jobPrototype)); } @Test public void testFormatTargetNodeDeclaration() { Target target = mock(Target.class); when(target.toString()).thenReturn("target/path"); assertEquals("\"target/path\" [label=\"target/path\" shape=folder];", dotfileWriter.formatTargetNodeDeclaration(target)); } @Test public void testFormatPCollection() { PCollectionImpl<?> pcollectionImpl = mock(PCollectionImpl.class); JobPrototype jobPrototype = mock(JobPrototype.class); when(pcollectionImpl.getName()).thenReturn("collection"); assertEquals("\"collection@" + pcollectionImpl.hashCode() + "@" + jobPrototype.hashCode() + "\"", dotfileWriter.formatPCollection(pcollectionImpl, jobPrototype)); } @Test public void testFormatPCollection_InputCollection() { InputCollection<Object> inputCollection = mock(InputCollection.class); Source<Object> source = mock(Source.class); JobPrototype jobPrototype = mock(JobPrototype.class); when(source.toString()).thenReturn("mocksource"); when(inputCollection.getSource()).thenReturn(source); assertEquals("\"mocksource\"", dotfileWriter.formatPCollection(inputCollection, jobPrototype)); } @Test public void testFormatNodeCollection() { List<String> nodeCollection = Lists.newArrayList("one", "two", "three"); assertEquals("one -> two -> three;", dotfileWriter.formatNodeCollection(nodeCollection)); } @Test public void testFormatNodeCollection_WithStyles() { List<String> nodeCollection = Lists.newArrayList("one", "two"); assertEquals( "one -> two [style=dotted];", dotfileWriter.formatNodeCollection(nodeCollection, ImmutableMap.of("style", "dotted"))); } @Test public void testFormatNodePath() { PCollectionImpl<?> tail = mock(PCollectionImpl.class); PCollectionImpl<?> head = mock(PCollectionImpl.class); JobPrototype jobPrototype = mock(JobPrototype.class); ParallelDoOptions doOptions = ParallelDoOptions.builder().build(); when(tail.getName()).thenReturn("tail"); when(head.getName()).thenReturn("head"); when(tail.getParallelDoOptions()).thenReturn(doOptions); when(head.getParallelDoOptions()).thenReturn(doOptions); NodePath nodePath = new NodePath(tail); nodePath.close(head); assertEquals( Lists.newArrayList("\"head@" + head.hashCode() + "@" + jobPrototype.hashCode() + "\" -> \"tail@" + tail.hashCode() + "@" + jobPrototype.hashCode() + "\";"), dotfileWriter.formatNodePath(nodePath, jobPrototype)); } @Test public void testFormatNodePathWithTargetDependencies() { PCollectionImpl<?> tail = mock(PCollectionImpl.class); PCollectionImpl<?> head = mock(PCollectionImpl.class); SourceTarget<?> srcTarget = mock(SourceTarget.class); JobPrototype jobPrototype = mock(JobPrototype.class); ParallelDoOptions tailOptions = ParallelDoOptions.builder().sourceTargets(srcTarget).build(); ParallelDoOptions headOptions = ParallelDoOptions.builder().build(); when(srcTarget.toString()).thenReturn("target"); when(tail.getName()).thenReturn("tail"); when(head.getName()).thenReturn("head"); when(tail.getParallelDoOptions()).thenReturn(tailOptions); when(head.getParallelDoOptions()).thenReturn(headOptions); NodePath nodePath = new NodePath(tail); nodePath.close(head); assertEquals( ImmutableList.of("\"head@" + head.hashCode() + "@" + jobPrototype.hashCode() + "\" -> \"tail@" + tail.hashCode() + "@" + jobPrototype.hashCode() + "\";", "\"target\" -> \"tail@" + tail.hashCode() + "@" + jobPrototype.hashCode() + "\" [style=dashed];"), dotfileWriter.formatNodePath(nodePath, jobPrototype)); } @Test public void testGetTaskGraphAttributes_Map() { assertEquals("label = Map; color = blue;", dotfileWriter.getTaskGraphAttributes(MRTaskType.MAP)); } @Test public void testGetTaskGraphAttributes_Reduce() { assertEquals("label = Reduce; color = red;", dotfileWriter.getTaskGraphAttributes(MRTaskType.REDUCE)); } @Test public void testLimitNodeNameLength_AlreadyWithinLimit() { String nodeName = "within_limit"; assertEquals(nodeName, DotfileWriter.limitNodeNameLength(nodeName)); } @Test public void testLimitNodeNameLength_OverLimit() { String nodeName = Strings.repeat("x", DotfileWriter.MAX_NODE_NAME_LENGTH + 1); String abbreviated = DotfileWriter.limitNodeNameLength(nodeName); assertEquals(DotfileWriter.MAX_NODE_NAME_LENGTH, abbreviated.length()); assertTrue(abbreviated.startsWith("xxxxx")); } }
2,440
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/exec/CappedExponentialCounterTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.exec; import static org.junit.Assert.assertEquals; import org.junit.Test; public class CappedExponentialCounterTest { @Test public void testGet() { CappedExponentialCounter c = new CappedExponentialCounter(1L, Long.MAX_VALUE); assertEquals(1L, c.get()); assertEquals(2L, c.get()); assertEquals(4L, c.get()); assertEquals(8L, c.get()); } @Test public void testCap() { CappedExponentialCounter c = new CappedExponentialCounter(1L, 2); assertEquals(1L, c.get()); assertEquals(2L, c.get()); assertEquals(2L, c.get()); } }
2,441
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/emit/IntermediateEmitterTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.emit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.apache.crunch.impl.mr.run.RTNode; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.PType; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import com.google.common.collect.Lists; public class IntermediateEmitterTest { private StringWrapper stringWrapper; private PType ptype; @Before public void setUp() { stringWrapper = new StringWrapper("test"); ptype = spy(Avros.reflects(StringWrapper.class)); } @Test public void testEmit_SingleChild() { RTNode singleChild = mock(RTNode.class); IntermediateEmitter emitter = new IntermediateEmitter(ptype, Lists.newArrayList(singleChild), new Configuration(), false); emitter.emit(stringWrapper); ArgumentCaptor<StringWrapper> argumentCaptor = ArgumentCaptor.forClass(StringWrapper.class); verify(singleChild).process(argumentCaptor.capture()); assertSame(stringWrapper, argumentCaptor.getValue()); } @Test public void testEmit_MultipleChildren() { RTNode childA = mock(RTNode.class); RTNode childB = mock(RTNode.class); IntermediateEmitter emitter = new IntermediateEmitter(ptype, Lists.newArrayList(childA, childB), new Configuration(), false); emitter.emit(stringWrapper); ArgumentCaptor<StringWrapper> argumentCaptorA = ArgumentCaptor.forClass(StringWrapper.class); ArgumentCaptor<StringWrapper> argumentCaptorB = ArgumentCaptor.forClass(StringWrapper.class); verify(childA).process(argumentCaptorA.capture()); verify(childB).process(argumentCaptorB.capture()); assertEquals(stringWrapper, argumentCaptorA.getValue()); assertEquals(stringWrapper, argumentCaptorB.getValue()); // Make sure that multiple children means deep copies are performed assertNotSame(stringWrapper, argumentCaptorA.getValue()); assertNotSame(stringWrapper, argumentCaptorB.getValue()); } @Test public void testEmit_MultipleChildrenDisableDeepCopy() { RTNode childA = mock(RTNode.class); RTNode childB = mock(RTNode.class); IntermediateEmitter emitter = new IntermediateEmitter(ptype, Lists.newArrayList(childA, childB), new Configuration(), true); emitter.emit(stringWrapper); ArgumentCaptor<StringWrapper> argumentCaptorA = ArgumentCaptor.forClass(StringWrapper.class); ArgumentCaptor<StringWrapper> argumentCaptorB = ArgumentCaptor.forClass(StringWrapper.class); verify(childA).process(argumentCaptorA.capture()); verify(childB).process(argumentCaptorB.capture()); assertEquals(stringWrapper, argumentCaptorA.getValue()); assertEquals(stringWrapper, argumentCaptorB.getValue()); // Make sure that multiple children without deep copies are the same instance assertSame(stringWrapper, argumentCaptorA.getValue()); assertSame(stringWrapper, argumentCaptorB.getValue()); } }
2,442
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mr/run/UniformHashPartitionerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mr.run; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import org.junit.Test; public class UniformHashPartitionerTest { private static final UniformHashPartitioner INSTANCE = new UniformHashPartitioner(); // Simple test to ensure that the general idea behind this partitioner is working. // We create 100 keys that have exactly the same lower-order bits, and partition them into 10 buckets, // and then verify that every bucket got at least 20% of the keys. The default HashPartitioner would put // everything in the same bucket. @Test public void testGetPartition() { Multiset<Integer> partitionCounts = HashMultiset.create(); final int NUM_PARTITIONS = 10; for (int i = 0; i < 1000; i += 10) { partitionCounts.add(INSTANCE.getPartition(i, i, NUM_PARTITIONS)); } for (int partitionNumber = 0; partitionNumber < NUM_PARTITIONS; partitionNumber++) { assertThat(partitionCounts.count(partitionNumber), greaterThan(5)); } } }
2,443
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/dist/DistributedPipelineTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.dist; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class DistributedPipelineTest { private final String testTempDirPath1 = "/tmp/crunch-1345424622/p1"; private final String testTempDirPath2 = "/tmp/crunch-1345424622/p2"; @Mock private Job mockJob; @Mock private Path mockPath; private Configuration testConfiguration = new Configuration(); @Before public void setUp() { when(mockJob.getConfiguration()).thenReturn(testConfiguration); } @Test public void isTempDirFalseWhenCrunchCreatesNoDirs() { boolean isTmp = DistributedPipeline.isTempDir(mockJob, testTempDirPath1); Assert.assertFalse(isTmp); } @Test public void isTempDirTrueWhenFileIsInTempDir() { testConfiguration.set("crunch.tmp.dirs", "/tmp/crunch-1345424622/p1"); boolean isTmp = DistributedPipeline.isTempDir(mockJob, testTempDirPath1); Assert.assertTrue(isTmp); } @Test public void isTempDirFalseWhenFileIsNotInTempDir() { testConfiguration.set("crunch.tmp.dirs", testTempDirPath1.toString()); boolean isTmp = DistributedPipeline.isTempDir(mockJob, "/user/crunch/iwTV2/"); Assert.assertFalse(isTmp); } @Test public void tempDirsAreStoredInPipelineConf() { DistributedPipeline distributedPipeline = Mockito.mock(DistributedPipeline.class, Mockito.CALLS_REAL_METHODS); Configuration testConfiguration = new Configuration(); distributedPipeline.setConfiguration(testConfiguration); // no temp directory is present at startup Assert.assertEquals( null, distributedPipeline.getConfiguration().get("crunch.tmp.dirs")); // store a temp directory distributedPipeline.storeTempDirLocation(new Path(testTempDirPath1)); Assert.assertEquals( testTempDirPath1.toString(), distributedPipeline.getConfiguration().get("crunch.tmp.dirs")); // store one more temp directory distributedPipeline.storeTempDirLocation(new Path(testTempDirPath2)); Assert.assertEquals( String.format("%s:%s", testTempDirPath1.toString(), testTempDirPath2.toString()), distributedPipeline.getConfiguration().get("crunch.tmp.dirs")); // try to store the first temp directory again, not added again distributedPipeline.storeTempDirLocation(new Path(testTempDirPath1)); Assert.assertEquals( String.format("%s:%s", testTempDirPath1.toString(), testTempDirPath2.toString()), distributedPipeline.getConfiguration().get("crunch.tmp.dirs")); } }
2,444
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/dist
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/dist/collect/DoTableImplTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.dist.collect; import static org.apache.crunch.types.writable.Writables.strings; import static org.apache.crunch.types.writable.Writables.tableOf; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.Pair; import org.apache.crunch.ParallelDoOptions; import org.junit.Test; public class DoTableImplTest { @Test public void testGetSizeInternal_NoScaleFactor() { runScaleTest(100L, 1.0f, 100L); } @Test public void testGetSizeInternal_ScaleFactorBelowZero() { runScaleTest(100L, 0.5f, 50L); } @Test public void testGetSizeInternal_ScaleFactorAboveZero() { runScaleTest(100L, 1.5f, 150L); } private void runScaleTest(long inputSize, float scaleFactor, long expectedScaledSize) { @SuppressWarnings("unchecked") PCollectionImpl<String> parentCollection = (PCollectionImpl<String>) mock(PCollectionImpl.class); when(parentCollection.getPipeline()).thenReturn(null); when(parentCollection.getSize()).thenReturn(inputSize); BaseDoTable<String, String> doTable = new BaseDoTable<String, String>("Scalled table collection", parentCollection, new TableScaledFunction(scaleFactor), tableOf(strings(), strings()), ParallelDoOptions.builder().build()); assertEquals(expectedScaledSize, doTable.getSizeInternal()); verify(parentCollection).getPipeline(); verify(parentCollection).getSize(); verifyNoMoreInteractions(parentCollection); } static class TableScaledFunction extends DoFn<String, Pair<String, String>> { private float scaleFactor; public TableScaledFunction(float scaleFactor) { this.scaleFactor = scaleFactor; } @Override public float scaleFactor() { return scaleFactor; } @Override public void process(String input, Emitter<Pair<String, String>> emitter) { emitter.emit(Pair.of(input, input)); } } }
2,445
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/dist
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/dist/collect/DoCollectionTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.dist.collect; import static org.junit.Assert.assertEquals; import java.util.List; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.ParallelDoOptions; import org.apache.crunch.ReadableData; import org.apache.crunch.types.PType; import org.apache.crunch.types.writable.Writables; import org.junit.Test; public class DoCollectionTest { @Test public void testGetSizeInternal_NoScaleFactor() { runScaleTest(100L, 1.0f, 100L); } @Test public void testGetSizeInternal_ScaleFactorBelowZero() { runScaleTest(100L, 0.5f, 50L); } @Test public void testGetSizeInternal_ScaleFactorAboveZero() { runScaleTest(100L, 1.5f, 150L); } private void runScaleTest(long inputSize, float scaleFactor, long expectedScaledSize) { PCollectionImpl<String> parentCollection = new SizedPCollectionImpl("Sized collection", inputSize); BaseDoCollection<String> doCollection = new BaseDoCollection<String>("Scaled collection", parentCollection, new ScaledFunction(scaleFactor), Writables.strings(), ParallelDoOptions.builder().build()); assertEquals(expectedScaledSize, doCollection.getSizeInternal()); } static class ScaledFunction extends DoFn<String, String> { private float scaleFactor; public ScaledFunction(float scaleFactor) { this.scaleFactor = scaleFactor; } @Override public void process(String input, Emitter<String> emitter) { emitter.emit(input); } @Override public float scaleFactor() { return scaleFactor; } } static class SizedPCollectionImpl extends PCollectionImpl<String> { private long internalSize; public SizedPCollectionImpl(String name, long internalSize) { super(name, null); this.internalSize = internalSize; } @Override public PType getPType() { return null; } @Override public List getParents() { return null; } @Override protected void acceptInternal(Visitor visitor) { } @Override protected ReadableData<String> getReadableDataInternal() { return null; } @Override protected long getSizeInternal() { return internalSize; } @Override public long getLastModifiedAt() { return -1; } } }
2,446
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mem/MemPipelinePCollectionReuseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mem; import static org.junit.Assert.assertEquals; import java.util.Set; import com.google.common.collect.ImmutableSet; import org.apache.crunch.MapFn; import org.apache.crunch.PCollection; import org.apache.crunch.PGroupedTable; import org.apache.crunch.PTable; import org.apache.crunch.fn.IdentityFn; import org.apache.crunch.types.avro.Avros; import org.junit.Test; public class MemPipelinePCollectionReuseTest { /** * Specific test for the situation outlined in CRUNCH-607, which was that deriving two PCollections from the same * PGroupedTable would throw an IllegalStateException from SingleUseIterable. This just ensures that this case * doesn't return. */ @Test public void testGroupedCollectionReuse() { PCollection<String> stringValues = MemPipeline.typedCollectionOf(Avros.strings(), "one", "two", "three"); PGroupedTable<String, String> groupedTable = stringValues.by(IdentityFn.<String>getInstance(), Avros.strings()).groupByKey(); // Here we re-use the grouped table twice, meaning its internal iterators will need to be iterated multiple times PTable<String, Integer> stringLengthTable = groupedTable.mapValues(new MaxStringLengthFn(), Avros.ints()); // Previous to LP-607, this would fail with an IllegalStateException from SingleUseIterable Set<String> keys = ImmutableSet.copyOf(groupedTable.ungroup().join(stringLengthTable).keys().materialize()); assertEquals( ImmutableSet.of("one", "two", "three"), keys); } public static class MaxStringLengthFn extends MapFn<Iterable<String>, Integer> { @Override public Integer map(Iterable<String> input) { int maxLength = Integer.MIN_VALUE; for (String inputString : input) { maxLength = Math.max(maxLength, inputString.length()); } return maxLength; } } }
2,447
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/impl/mem/CountersTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.impl.mem; import org.apache.crunch.MapFn; import org.apache.crunch.PCollection; import org.apache.crunch.Pipeline; import org.apache.crunch.impl.mem.collect.MemCollection; import org.apache.crunch.types.writable.Writables; import org.junit.Test; import java.io.Serializable; import java.util.Arrays; public class CountersTest implements Serializable { @Test public void counterTest() throws Exception { Pipeline pipeline = MemPipeline.getInstance(); // Single row PCollection. PCollection<String> objects = MemPipeline.collectionOf(Arrays.asList(new String[]{"hello world"})); System.out.println("Objects: " + ((MemCollection) objects).getCollection()); // Counter creating Map. PCollection<String> objects2 = objects.parallelDo("Create counters", new MapFn<String, String>() { @Override public String map(String input) { for(int i = 0; i < 200; ++i) { this.increment("testCounter", String.valueOf(i)); } return input; } }, Writables.strings() ); // Run it! pipeline.done(); System.out.println("Objects2: " + ((MemCollection) objects2).getCollection()); } }
2,448
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/MapDeepCopierTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import java.util.Map; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Maps; public class MapDeepCopierTest { @Test public void testDeepCopy() { StringWrapper stringWrapper = new StringWrapper("value"); String key = "key"; Map<String, StringWrapper> map = Maps.newHashMap(); map.put(key, stringWrapper); MapDeepCopier<StringWrapper> deepCopier = new MapDeepCopier<StringWrapper>( Avros.reflects(StringWrapper.class)); deepCopier.initialize(new Configuration()); Map<String, StringWrapper> deepCopy = deepCopier.deepCopy(map); assertEquals(map, deepCopy); assertNotSame(map.get(key), deepCopy.get(key)); } @Test public void testDeepCopy_Null() { Map<String, StringWrapper> map = null; MapDeepCopier<StringWrapper> deepCopier = new MapDeepCopier<StringWrapper>( Avros.reflects(StringWrapper.class)); deepCopier.initialize(new Configuration()); Map<String, StringWrapper> deepCopy = deepCopier.deepCopy(map); assertNull(deepCopy); } }
2,449
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/TupleFactoryTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import org.apache.crunch.Pair; import org.apache.crunch.Tuple; import org.apache.crunch.Tuple3; import org.apache.crunch.Tuple4; import org.apache.crunch.TupleN; import org.junit.Test; public class TupleFactoryTest { @Test public void testGetTupleFactory_Pair() { assertEquals(TupleFactory.PAIR, TupleFactory.getTupleFactory(Pair.class)); } @Test public void testGetTupleFactory_Tuple3() { assertEquals(TupleFactory.TUPLE3, TupleFactory.getTupleFactory(Tuple3.class)); } @Test public void testGetTupleFactory_Tuple4() { assertEquals(TupleFactory.TUPLE4, TupleFactory.getTupleFactory(Tuple4.class)); } @Test public void testGetTupleFactory_TupleN() { assertEquals(TupleFactory.TUPLEN, TupleFactory.getTupleFactory(TupleN.class)); } @Test public void testGetTupleFactory_CustomTupleClass() { TupleFactory<CustomTupleImplementation> customTupleFactory = TupleFactory.create(CustomTupleImplementation.class); assertEquals(customTupleFactory, TupleFactory.getTupleFactory(CustomTupleImplementation.class)); } private static class CustomTupleImplementation implements Tuple { @Override public Object get(int index) { return null; } @Override public int size() { return 0; } } }
2,450
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/CollectionDeepCopierTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import java.util.Collection; import org.apache.crunch.test.Person; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Lists; public class CollectionDeepCopierTest { @Test public void testDeepCopy() { Person person = new Person(); person.age = 42; person.name = "John Smith"; person.siblingnames = Lists.<CharSequence> newArrayList(); Collection<Person> personCollection = Lists.newArrayList(person); CollectionDeepCopier<Person> collectionDeepCopier = new CollectionDeepCopier<Person>( Avros.records(Person.class)); collectionDeepCopier.initialize(new Configuration()); Collection<Person> deepCopyCollection = collectionDeepCopier.deepCopy(personCollection); assertEquals(personCollection, deepCopyCollection); assertNotSame(personCollection.iterator().next(), deepCopyCollection.iterator().next()); } @Test public void testNullDeepCopy() { CollectionDeepCopier<Person> collectionDeepCopier = new CollectionDeepCopier<Person>( Avros.records(Person.class)); collectionDeepCopier.initialize(new Configuration()); Collection<Person> nullCollection = null; assertNull(collectionDeepCopier.deepCopy(nullCollection)); } }
2,451
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/TupleDeepCopierTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import org.apache.crunch.Pair; import org.apache.crunch.test.Person; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Lists; public class TupleDeepCopierTest { @Test public void testDeepCopy_Pair() { Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); Pair<Integer, Person> inputPair = Pair.of(1, person); DeepCopier<Pair> deepCopier = new TupleDeepCopier<Pair>(Pair.class, Avros.ints(), Avros.records(Person.class)); deepCopier.initialize(new Configuration()); Pair<Integer, Person> deepCopyPair = deepCopier.deepCopy(inputPair); assertEquals(inputPair, deepCopyPair); assertNotSame(inputPair.second(), deepCopyPair.second()); } @Test public void testDeepCopy_PairContainingNull() { Pair<Integer, Person> inputPair = Pair.of(1, null); DeepCopier<Pair> deepCopier = new TupleDeepCopier<Pair>(Pair.class, Avros.ints(), Avros.records(Person.class)); deepCopier.initialize(new Configuration()); Pair<Integer, Person> deepCopyPair = deepCopier.deepCopy(inputPair); assertEquals(inputPair, deepCopyPair); } @Test public void testDeepCopy_NullPair() { Pair<Integer, Person> inputPair = null; DeepCopier<Pair> deepCopier = new TupleDeepCopier<Pair>(Pair.class, Avros.ints(), Avros.records(Person.class)); deepCopier.initialize(new Configuration()); Pair<Integer, Person> deepCopyPair = deepCopier.deepCopy(inputPair); assertNull(deepCopyPair); } }
2,452
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/PTypesTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import java.util.UUID; import org.apache.crunch.types.avro.AvroTypeFamily; import org.junit.Test; public class PTypesTest { @Test public void testUUID() throws Exception { UUID uuid = UUID.randomUUID(); PType<UUID> ptype = PTypes.uuid(AvroTypeFamily.getInstance()); assertEquals(uuid, ptype.getInputMapFn().map(ptype.getOutputMapFn().map(uuid))); } }
2,453
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/PTypeUtilsTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Collection; import org.apache.avro.Schema; import org.apache.avro.util.Utf8; import org.apache.crunch.Tuple3; import org.apache.crunch.TupleN; import org.apache.crunch.types.avro.AvroType; import org.apache.crunch.types.avro.AvroTypeFamily; import org.apache.crunch.types.avro.Avros; import org.apache.crunch.types.writable.WritableTypeFamily; import org.apache.crunch.types.writable.Writables; import org.apache.hadoop.io.Text; import org.junit.Assert; import org.junit.Test; public class PTypeUtilsTest { @Test public void testPrimitives() { assertEquals(Avros.strings(), AvroTypeFamily.getInstance().as(Writables.strings())); Assert.assertEquals(Writables.doubles(), WritableTypeFamily.getInstance().as(Avros.doubles())); } @Test public void testTuple3() { PType<Tuple3<String, Float, Integer>> t = Writables.triples(Writables.strings(), Writables.floats(), Writables.ints()); PType<Tuple3<String, Float, Integer>> at = AvroTypeFamily.getInstance().as(t); assertEquals(Avros.strings(), at.getSubTypes().get(0)); assertEquals(Avros.floats(), at.getSubTypes().get(1)); assertEquals(Avros.ints(), at.getSubTypes().get(2)); } @Test public void testTupleN() { PType<TupleN> t = Avros.tuples(Avros.strings(), Avros.floats(), Avros.ints()); PType<TupleN> wt = WritableTypeFamily.getInstance().as(t); assertEquals(Writables.strings(), wt.getSubTypes().get(0)); assertEquals(Writables.floats(), wt.getSubTypes().get(1)); assertEquals(Writables.ints(), wt.getSubTypes().get(2)); } @Test public void testWritableCollections() { PType<Collection<String>> t = Avros.collections(Avros.strings()); t = WritableTypeFamily.getInstance().as(t); assertEquals(Writables.strings(), t.getSubTypes().get(0)); } @Test public void testAvroCollections() { PType<Collection<Double>> t = Writables.collections(Writables.doubles()); t = AvroTypeFamily.getInstance().as(t); assertEquals(Avros.doubles(), t.getSubTypes().get(0)); } @Test public void testAvroRegistered() { AvroType<Utf8> at = new AvroType<Utf8>(Utf8.class, Schema.create(Schema.Type.STRING), NoOpDeepCopier.<Utf8>create()); Avros.register(Utf8.class, at); assertEquals(at, Avros.records(Utf8.class)); } @Test public void testWritableBuiltin() { assertNotNull(Writables.records(Text.class)); } }
2,454
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/WritableDeepCopierTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Test; public class WritableDeepCopierTest { private WritableDeepCopier<Text> deepCopier; @Before public void setUp() { deepCopier = new WritableDeepCopier<Text>(Text.class); } @Test public void testDeepCopy() { Text text = new Text("value"); Text deepCopy = deepCopier.deepCopy(text); assertEquals(text, deepCopy); assertNotSame(text, deepCopy); } @Test public void testDeepCopy_Null() { Text text = null; Text deepCopy = deepCopier.deepCopy(text); assertNull(deepCopy); } }
2,455
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/GenericArrayWritableTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import java.nio.charset.Charset; import java.util.Arrays; import org.apache.crunch.test.Tests; import org.apache.hadoop.io.BytesWritable; import org.junit.Test; public class GenericArrayWritableTest { @Test public void testEmpty() { GenericArrayWritable src = new GenericArrayWritable(); src.set(new BytesWritable[0]); GenericArrayWritable dest = Tests.roundtrip(src, new GenericArrayWritable()); assertThat(dest.get().length, is(0)); } @Test public void testNonEmpty() { GenericArrayWritable src = new GenericArrayWritable(); src.set(new BytesWritable[] { new BytesWritable("foo".getBytes(Charset.forName("UTF-8"))), new BytesWritable("bar".getBytes(Charset.forName("UTF-8"))) }); GenericArrayWritable dest = Tests.roundtrip(src, new GenericArrayWritable()); assertThat(src.get(), not(sameInstance(dest.get()))); assertThat(dest.get().length, is(2)); assertThat(Arrays.asList(dest.get()), hasItems(new BytesWritable("foo".getBytes(Charset.forName("UTF-8"))), new BytesWritable("bar".getBytes(Charset.forName("UTF-8"))))); } @Test public void testNulls() { GenericArrayWritable src = new GenericArrayWritable(); src.set(new BytesWritable[] { new BytesWritable("a".getBytes(Charset.forName("UTF-8"))), null, new BytesWritable("b".getBytes(Charset.forName("UTF-8"))) }); GenericArrayWritable dest = Tests.roundtrip(src, new GenericArrayWritable()); assertThat(src.get(), not(sameInstance(dest.get()))); assertThat(dest.get().length, is(3)); assertThat(Arrays.asList(dest.get()), hasItems(new BytesWritable("a".getBytes(Charset.forName("UTF-8"))), new BytesWritable("b".getBytes(Charset.forName("UTF-8"))), null)); } }
2,456
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/WritableTableTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import org.apache.crunch.Pair; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.junit.Test; public class WritableTableTypeTest { @Test public void testGetDetachedValue() { Integer integerValue = 42; Text textValue = new Text("forty-two"); Pair<Integer, Text> pair = Pair.of(integerValue, textValue); WritableTableType<Integer, Text> tableType = Writables.tableOf(Writables.ints(), Writables.writables(Text.class)); tableType.initialize(new Configuration()); Pair<Integer, Text> detachedPair = tableType.getDetachedValue(pair); assertSame(integerValue, detachedPair.first()); assertEquals(textValue, detachedPair.second()); assertNotSame(textValue, detachedPair.second()); } }
2,457
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/TupleWritableTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TupleWritableTest { @Test public void testSerialization() throws IOException { TupleWritable t1 = new TupleWritable( new Writable[] { new IntWritable(10), null, new Text("hello"), new Text("world") }); TupleWritable t2 = new TupleWritable(); t2.readFields(new DataInputStream(new ByteArrayInputStream(WritableUtils.toByteArray(t1)))); assertTrue(t2.has(0)); assertEquals(new IntWritable(10), t2.get(0)); assertFalse(t2.has(1)); assertNull(t2.get(1)); assertTrue(t2.has(2)); assertEquals(new Text("hello"), t2.get(2)); assertTrue(t2.has(3)); assertEquals(new Text("world"), t2.get(3)); } @Test public void testCompare() throws IOException { doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1) }), new TupleWritable(new Writable[] { new IntWritable(2) }), -1); doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1) }), new TupleWritable(new Writable[] { new IntWritable(1) }), 0); doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1), new IntWritable(1) }), new TupleWritable(new Writable[] { new IntWritable(1), new IntWritable(2) }), -1); doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1), new IntWritable(2) }), new TupleWritable(new Writable[] { new IntWritable(1), new IntWritable(2) }), 0); doTestCompare( new TupleWritable(new Writable[] { null }), new TupleWritable(new Writable[] { new IntWritable(1) }), -1); doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1) }), new TupleWritable(new Writable[] { new Text("1") }), 1); // code for IntWritable is larger than code for Text doTestCompare( new TupleWritable(new Writable[] { new IntWritable(1) }), new TupleWritable(new Writable[] { new IntWritable(1), new IntWritable(2) }), -1); // shorter is less } private void doTestCompare(TupleWritable t1, TupleWritable t2, int result) throws IOException { // test comparing objects TupleWritable.Comparator comparator = TupleWritable.Comparator.getInstance(); assertEquals(result, comparator.compare(t1, t2)); // test comparing buffers DataOutputBuffer buffer1 = new DataOutputBuffer(); DataOutputBuffer buffer2 = new DataOutputBuffer(); t1.write(buffer1); t2.write(buffer2); assertEquals(result, comparator.compare( buffer1.getData(), 0, buffer1.getLength(), buffer2.getData(), 0, buffer2.getLength())); } }
2,458
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/WritableGroupedTableTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import java.util.List; import org.apache.crunch.Pair; import org.apache.crunch.types.PGroupedTableType; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.junit.Test; import com.google.common.collect.Lists; public class WritableGroupedTableTypeTest { @Test public void testGetDetachedValue() { Integer integerValue = 42; Text textValue = new Text("forty-two"); Iterable<Text> inputTextIterable = Lists.newArrayList(textValue); Pair<Integer, Iterable<Text>> pair = Pair.of(integerValue, inputTextIterable); PGroupedTableType<Integer, Text> groupedTableType = Writables.tableOf(Writables.ints(), Writables.writables(Text.class)).getGroupedTableType(); groupedTableType.initialize(new Configuration()); Pair<Integer, Iterable<Text>> detachedPair = groupedTableType.getDetachedValue(pair); assertSame(integerValue, detachedPair.first()); List<Text> textList = Lists.newArrayList(detachedPair.second()); assertEquals(inputTextIterable, textList); assertNotSame(textValue, textList.get(0)); } }
2,459
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/WritablesTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Collection; import com.google.common.collect.Lists; import org.apache.crunch.Pair; import org.apache.crunch.Tuple3; import org.apache.crunch.Tuple4; import org.apache.crunch.TupleN; import org.apache.crunch.types.PTableType; import org.apache.crunch.types.PType; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; import org.junit.Test; public class WritablesTest { @Test public void testNulls() throws Exception { Void n = null; NullWritable nw = NullWritable.get(); testInputOutputFn(Writables.nulls(), n, nw); } @Test public void testStrings() throws Exception { String s = "abc"; Text text = new Text(s); testInputOutputFn(Writables.strings(), s, text); } @Test public void testInts() throws Exception { int j = 55; IntWritable w = new IntWritable(j); testInputOutputFn(Writables.ints(), j, w); } @Test public void testLongs() throws Exception { long j = 55; LongWritable w = new LongWritable(j); testInputOutputFn(Writables.longs(), j, w); } @Test public void testFloats() throws Exception { float j = 55.5f; FloatWritable w = new FloatWritable(j); testInputOutputFn(Writables.floats(), j, w); } @Test public void testDoubles() throws Exception { double j = 55.5d; DoubleWritable w = new DoubleWritable(j); testInputOutputFn(Writables.doubles(), j, w); } @Test public void testBoolean() throws Exception { boolean j = false; BooleanWritable w = new BooleanWritable(j); testInputOutputFn(Writables.booleans(), j, w); } @Test public void testBytes() throws Exception { byte[] bytes = new byte[] { 17, 26, -98 }; BytesWritable bw = new BytesWritable(bytes); ByteBuffer bb = ByteBuffer.wrap(bytes); testInputOutputFn(Writables.bytes(), bb, bw); } @Test public void testCollections() throws Exception { String s = "abc"; Collection<String> j = Lists.newArrayList(); j.add(s); GenericArrayWritable w = new GenericArrayWritable(); Text t = new Text(s); BytesWritable bw = new BytesWritable(WritableUtils.toByteArray(t)); w.set(new BytesWritable[] { bw }); testInputOutputFn(Writables.collections(Writables.strings()), j, w); } @Test public void testPairs() throws Exception { Pair<String, String> j = Pair.of("a", "b"); Text[] t = new Text[] { new Text("a"), new Text("b"), }; TupleWritable w = new TupleWritable(t); testInputOutputFn(Writables.pairs(Writables.strings(), Writables.strings()), j, w); } @Test public void testNestedTables() throws Exception { PTableType<Long, Long> pll = Writables.tableOf(Writables.longs(), Writables.longs()); PTableType<Pair<Long, Long>, String> nest = Writables.tableOf(pll, Writables.strings()); assertNotNull(nest); } @Test public void testPairEquals() throws Exception { PType<Pair<Long, ByteBuffer>> t1 = Writables.pairs(Writables.longs(), Writables.bytes()); PType<Pair<Long, ByteBuffer>> t2 = Writables.pairs(Writables.longs(), Writables.bytes()); assertEquals(t1, t2); assertEquals(t1.hashCode(), t2.hashCode()); } @Test @SuppressWarnings("rawtypes") public void testTriples() throws Exception { Tuple3 j = Tuple3.of("a", "b", "c"); Text[] t = new Text[] { new Text("a"), new Text("b"), new Text("c"), }; TupleWritable w = new TupleWritable(t); WritableType<?, ?> wt = Writables.triples(Writables.strings(), Writables.strings(), Writables.strings()); testInputOutputFn(wt, j, w); } @Test @SuppressWarnings("rawtypes") public void testQuads() throws Exception { Tuple4 j = Tuple4.of("a", "b", "c", "d"); Text[] t = new Text[] { new Text("a"), new Text("b"), new Text("c"), new Text("d"), }; TupleWritable w = new TupleWritable(t); WritableType<?, ?> wt = Writables.quads(Writables.strings(), Writables.strings(), Writables.strings(), Writables.strings()); testInputOutputFn(wt, j, w); } @Test public void testTupleN() throws Exception { TupleN j = new TupleN("a", "b", "c", "d", "e"); Text[] t = new Text[] { new Text("a"), new Text("b"), new Text("c"), new Text("d"), new Text("e"), }; TupleWritable w = new TupleWritable(t); WritableType<?, ?> wt = Writables.tuples(Writables.strings(), Writables.strings(), Writables.strings(), Writables.strings(), Writables.strings()); testInputOutputFn(wt, j, w); } protected static class TestWritable implements WritableComparable<TestWritable> { String left; int right; @Override public void write(DataOutput out) throws IOException { out.writeUTF(left); out.writeInt(right); } @Override public void readFields(DataInput in) throws IOException { left = in.readUTF(); right = in.readInt(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestWritable other = (TestWritable) obj; if (left == null) { if (other.left != null) return false; } else if (!left.equals(other.left)) return false; if (right != other.right) return false; return true; } @Override public int hashCode() { return (left == null ? 0 : left.hashCode()) ^ right; } @Override public int compareTo(TestWritable o) { int cmp = left.compareTo(o.left); if (cmp != 0) return cmp; return Integer.valueOf(right).compareTo(Integer.valueOf(o.right)); } } @Test public void testRecords() throws Exception { TestWritable j = new TestWritable(); j.left = "a"; j.right = 1; TestWritable w = new TestWritable(); w.left = "a"; w.right = 1; WritableType<?, ?> wt = Writables.records(TestWritable.class); testInputOutputFn(wt, j, w); } @Test public void testTableOf() throws Exception { Pair<String, String> j = Pair.of("a", "b"); Pair<Text, Text> w = Pair.of(new Text("a"), new Text("b")); WritableTableType<String, String> wtt = Writables.tableOf(Writables.strings(), Writables.strings()); testInputOutputFn(wtt, j, w); } @Test public void testRegister() throws Exception { WritableType<TestWritable, TestWritable> wt = Writables.writables(TestWritable.class); Writables.register(TestWritable.class, wt); assertSame(Writables.records(TestWritable.class), wt); } @Test public void testRegisterComparable() throws Exception { Writables.registerComparable(TestWritable.class); assertNotNull(Writables.WRITABLE_CODES.inverse().get(TestWritable.class)); // Also try serializing/deserializing from a configuration, just to make sure this works Configuration conf = new Configuration(); Writables.serializeWritableComparableCodes(conf); Writables.WRITABLE_CODES.clear(); Writables.reloadWritableComparableCodes(conf); assertNotNull(Writables.WRITABLE_CODES.inverse().get(TestWritable.class)); } @SuppressWarnings({ "unchecked", "rawtypes" }) protected static void testInputOutputFn(PType ptype, Object java, Object writable) { ptype.getInputMapFn().initialize(); ptype.getOutputMapFn().initialize(); assertEquals(java, ptype.getInputMapFn().map(writable)); assertEquals(writable, ptype.getOutputMapFn().map(java)); } }
2,460
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/writable/WritableTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.writable; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Map; import java.util.UUID; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.crunch.Pair; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.PType; import org.apache.crunch.types.PTypes; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.junit.Test; public class WritableTypeTest { @Test(expected = IllegalStateException.class) public void testGetDetachedValue_NotInitialized() { WritableType<Text, Text> textWritableType = Writables.writables(Text.class); Text value = new Text("test"); // Calling getDetachedValue without first calling initialize should throw an // exception textWritableType.getDetachedValue(value); } @Test public void testGetDetachedValue_CustomWritable() { WritableType<Text, Text> textWritableType = Writables.writables(Text.class); textWritableType.initialize(new Configuration()); Text value = new Text("test"); Text detachedValue = textWritableType.getDetachedValue(value); assertEquals(value, detachedValue); assertNotSame(value, detachedValue); } @Test public void testGetDetachedValue_Collection() { Collection<Text> textCollection = Lists.newArrayList(new Text("value")); WritableType<Collection<Text>, GenericArrayWritable> ptype = Writables .collections(Writables.writables(Text.class)); ptype.initialize(new Configuration()); Collection<Text> detachedCollection = ptype.getDetachedValue(textCollection); assertEquals(textCollection, detachedCollection); assertNotSame(textCollection.iterator().next(), detachedCollection.iterator().next()); } @Test public void testGetDetachedValue_Tuple() { Pair<Text, Text> textPair = Pair.of(new Text("one"), new Text("two")); WritableType<Pair<Text, Text>, TupleWritable> ptype = Writables.pairs( Writables.writables(Text.class), Writables.writables(Text.class)); ptype.initialize(new Configuration()); Pair<Text, Text> detachedPair = ptype.getDetachedValue(textPair); assertEquals(textPair, detachedPair); assertNotSame(textPair.first(), detachedPair.first()); assertNotSame(textPair.second(), detachedPair.second()); } @Test public void testGetDetachedValue_Map() { Map<String, Text> stringTextMap = Maps.newHashMap(); stringTextMap.put("key", new Text("value")); WritableType<Map<String, Text>, MapWritable> ptype = Writables.maps(Writables .writables(Text.class)); ptype.initialize(new Configuration()); Map<String, Text> detachedMap = ptype.getDetachedValue(stringTextMap); assertEquals(stringTextMap, detachedMap); assertNotSame(stringTextMap.get("key"), detachedMap.get("key")); } @Test public void testGetDetachedValue_String() { String s = "test"; WritableType<String, Text> stringType = Writables.strings(); stringType.initialize(new Configuration()); String detached = stringType.getDetachedValue(s); assertSame(s, detached); } @Test public void testGetDetachedValue_Primitive() { WritableType<Integer, IntWritable> intType = Writables.ints(); intType.initialize(new Configuration()); Integer intValue = Integer.valueOf(42); Integer detachedValue = intType.getDetachedValue(intValue); assertSame(intValue, detachedValue); } @Test public void testGetDetachedValue_NonPrimitive() { WritableType<Text, Text> textType = Writables.writables(Text.class); textType.initialize(new Configuration()); Text text = new Text("test"); Text detachedValue = textType.getDetachedValue(text); assertEquals(text, detachedValue); assertNotSame(text, detachedValue); } @Test public void testGetDetachedValue_ImmutableDerived() { PType<UUID> uuidType = PTypes.uuid(WritableTypeFamily.getInstance()); uuidType.initialize(new Configuration()); UUID uuid = new UUID(1L, 1L); UUID detached = uuidType.getDetachedValue(uuid); assertSame(uuid, detached); } @Test public void testGetDetachedValue_MutableDerived() { PType<StringWrapper> jsonType = PTypes.jsonString(StringWrapper.class, WritableTypeFamily.getInstance()); jsonType.initialize(new Configuration()); StringWrapper stringWrapper = new StringWrapper(); stringWrapper.setValue("test"); StringWrapper detachedValue = jsonType.getDetachedValue(stringWrapper); assertNotSame(stringWrapper, detachedValue); assertEquals(stringWrapper, detachedValue); } @Test public void testGetDetachedValue_Bytes() { byte[] buffer = new byte[]{1, 2, 3}; WritableType<ByteBuffer,BytesWritable> byteType = Writables.bytes(); byteType.initialize(new Configuration()); ByteBuffer detachedValue = byteType.getDetachedValue(ByteBuffer.wrap(buffer)); byte[] detachedBuffer = new byte[buffer.length]; detachedValue.get(detachedBuffer); assertArrayEquals(buffer, detachedBuffer); buffer[0] = 99; assertEquals(detachedBuffer[0], 1); } }
2,461
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroModeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.reflect.ReflectData; import org.apache.avro.specific.SpecificData; import org.apache.crunch.io.FormatBundle; import org.apache.hadoop.conf.Configuration; import org.junit.Test; public class AvroModeTest { @Test public void customWithFactory(){ ReaderWriterFactory fakeFactory = new FakeReaderWriterFactory(); AvroMode mode = AvroMode.SPECIFIC.withFactory(fakeFactory); assertThat(mode.getFactory(), is(fakeFactory)); //assert that the original is unchanged assertThat(mode, is(not(AvroMode.SPECIFIC))); assertThat(AvroMode.SPECIFIC.getFactory(), is((ReaderWriterFactory) AvroMode.SPECIFIC)); } @Test public void sameWithFactory(){ AvroMode mode = AvroMode.SPECIFIC.withFactory(AvroMode.SPECIFIC); assertThat(mode.getFactory(), is( (ReaderWriterFactory) AvroMode.SPECIFIC)); } @Test public void getDataSpecific(){ assertThat(AvroMode.SPECIFIC.getData(), is(instanceOf(SpecificData.class))); } @Test public void getDataGeneric(){ assertThat(AvroMode.GENERIC.getData(), is(instanceOf(GenericData.class))); } @Test public void getDataReflect(){ assertThat(AvroMode.REFLECT.getData(), is(instanceOf(ReflectData.class))); } @Test public void configureAndRetrieveSpecific(){ Configuration conf = new Configuration(); AvroMode.SPECIFIC.configure(conf); AvroMode returnedMode = AvroMode.fromConfiguration(conf); assertThat(returnedMode, is(AvroMode.SPECIFIC)); } @Test public void configureAndRetrieveGeneric(){ Configuration conf = new Configuration(); AvroMode.GENERIC.configure(conf); AvroMode returnedMode = AvroMode.fromConfiguration(conf); assertThat(returnedMode, is(AvroMode.GENERIC)); } @Test public void configureShuffleAndRetrieveSpecific(){ Configuration conf = new Configuration(); AvroMode.SPECIFIC.configureShuffle(conf); AvroMode returnedMode = AvroMode.fromShuffleConfiguration(conf); assertThat(returnedMode, is(AvroMode.SPECIFIC)); } @Test public void configureShuffleAndRetrieveGeneric(){ Configuration conf = new Configuration(); AvroMode.GENERIC.configureShuffle(conf); AvroMode returnedMode = AvroMode.fromShuffleConfiguration(conf); assertThat(returnedMode, is(AvroMode.GENERIC)); } @Test public void configureBundleSpecific(){ FormatBundle bundle = FormatBundle.forInput(AvroInputFormat.class); Configuration config = new Configuration(); AvroMode.SPECIFIC.configure(bundle); bundle.configure(config); AvroMode returnedMode = AvroMode.fromConfiguration(config); assertThat(returnedMode.getData(), is(instanceOf(SpecificData.class))); } @Test public void configureBundleGeneric(){ FormatBundle bundle = FormatBundle.forInput(AvroInputFormat.class); Configuration config = new Configuration(); AvroMode.GENERIC.configure(bundle); bundle.configure(config); AvroMode returnedMode = AvroMode.fromConfiguration(config); assertThat(returnedMode.getData(), is(instanceOf(GenericData.class))); } @Test public void configureBundleReflect(){ FormatBundle bundle = FormatBundle.forInput(AvroInputFormat.class); Configuration config = new Configuration(); AvroMode.REFLECT.configure(bundle); bundle.configure(config); AvroMode returnedMode = AvroMode.fromConfiguration(config); assertThat(returnedMode.getData(), is(instanceOf(ReflectData.class))); } @Test public void configureBundleCustomWithFactory(){ ReaderWriterFactory fakeFactory = new FakeReaderWriterFactory(); AvroMode mode = AvroMode.SPECIFIC.withFactory(fakeFactory); FormatBundle bundle = FormatBundle.forInput(AvroInputFormat.class); Configuration config = new Configuration(); mode.configure(bundle); bundle.configure(config); AvroMode returnedMode = AvroMode.fromConfiguration(config); assertThat(returnedMode.getFactory(), is(instanceOf(FakeReaderWriterFactory.class))); } @Test public void configureCustomWithFactory(){ ReaderWriterFactory fakeFactory = new FakeReaderWriterFactory(); AvroMode mode = AvroMode.SPECIFIC.withFactory(fakeFactory); Configuration config = new Configuration(); mode.configure(config); AvroMode returnedMode = AvroMode.fromConfiguration(config); assertThat(returnedMode.getFactory(), is(instanceOf(FakeReaderWriterFactory.class))); } private static class FakeReaderWriterFactory implements ReaderWriterFactory{ @Override public GenericData getData() { return null; } @Override public <D> DatumReader<D> getReader(Schema schema) { return null; } @Override public <D> DatumWriter<D> getWriter(Schema schema) { return null; } } }
2,462
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvrosTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.avro.Schema; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.reflect.ReflectData; import org.apache.avro.util.Utf8; import org.apache.crunch.Pair; import org.apache.crunch.Tuple3; import org.apache.crunch.Tuple4; import org.apache.crunch.TupleN; import org.apache.crunch.test.CrunchTestSupport; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.NoOpDeepCopier; import org.apache.crunch.types.PTableType; import org.apache.crunch.types.PType; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.junit.Test; /** * TODO test Avros.register and Avros.containers */ public class AvrosTest { @Test public void testNulls() throws Exception { Void n = null; testInputOutputFn(Avros.nulls(), n, n); } @Test public void testStrings() throws Exception { String s = "abc"; Utf8 w = new Utf8(s); testInputOutputFn(Avros.strings(), s, w); testInputOutputFn(Avros.strings(), null, null); } @Test public void testInts() throws Exception { int j = 55; testInputOutputFn(Avros.ints(), j, j); } @Test public void testLongs() throws Exception { long j = Long.MAX_VALUE; testInputOutputFn(Avros.longs(), j, j); } @Test public void testFloats() throws Exception { float j = Float.MIN_VALUE; testInputOutputFn(Avros.floats(), j, j); } @Test public void testDoubles() throws Exception { double j = Double.MIN_VALUE; testInputOutputFn(Avros.doubles(), j, j); } @Test public void testBooleans() throws Exception { boolean j = true; testInputOutputFn(Avros.booleans(), j, j); } @Test public void testBytes() throws Exception { byte[] bytes = new byte[] { 17, 26, -98 }; ByteBuffer bb = ByteBuffer.wrap(bytes); testInputOutputFn(Avros.bytes(), bb, bb); testInputOutputFn(Avros.bytes(), null, null); } @Test public void testCollections() throws Exception { Collection<String> j = Lists.newArrayList(); j.add("a"); j.add("b"); Schema collectionSchema = Schema.createArray(Schema.createUnion(ImmutableList.of(Avros.strings().getSchema(), Schema.create(Type.NULL)))); GenericData.Array<Utf8> w = new GenericData.Array<Utf8>(2, collectionSchema); w.add(new Utf8("a")); w.add(new Utf8("b")); testInputOutputFn(Avros.collections(Avros.strings()), j, w); } @Test public void testNestedTables() throws Exception { PTableType<Long, Long> pll = Avros.tableOf(Avros.longs(), Avros.longs()); String schema = Avros.tableOf(pll, Avros.strings()).getSchema().toString(); assertNotNull(schema); } @Test public void testPairs() throws Exception { AvroType<Pair<String, String>> at = Avros.pairs(Avros.strings(), Avros.strings()); Pair<String, String> j = Pair.of("a", "b"); GenericData.Record w = new GenericData.Record(at.getSchema()); w.put(0, new Utf8("a")); w.put(1, new Utf8("b")); testInputOutputFn(at, j, w); } @Test public void testPairEquals() throws Exception { AvroType<Pair<Long, ByteBuffer>> at1 = Avros.pairs(Avros.longs(), Avros.bytes()); AvroType<Pair<Long, ByteBuffer>> at2 = Avros.pairs(Avros.longs(), Avros.bytes()); assertEquals(at1, at2); assertEquals(at1.hashCode(), at2.hashCode()); } @Test @SuppressWarnings("rawtypes") public void testTriples() throws Exception { AvroType at = Avros.triples(Avros.strings(), Avros.strings(), Avros.strings()); Tuple3 j = Tuple3.of("a", "b", "c"); GenericData.Record w = new GenericData.Record(at.getSchema()); w.put(0, new Utf8("a")); w.put(1, new Utf8("b")); w.put(2, new Utf8("c")); testInputOutputFn(at, j, w); } @Test @SuppressWarnings("rawtypes") public void testQuads() throws Exception { AvroType at = Avros.quads(Avros.strings(), Avros.strings(), Avros.strings(), Avros.strings()); Tuple4 j = Tuple4.of("a", "b", "c", "d"); GenericData.Record w = new GenericData.Record(at.getSchema()); w.put(0, new Utf8("a")); w.put(1, new Utf8("b")); w.put(2, new Utf8("c")); w.put(3, new Utf8("d")); testInputOutputFn(at, j, w); } @Test @SuppressWarnings("rawtypes") public void testTupleN() throws Exception { AvroType at = Avros.tuples(Avros.strings(), Avros.strings(), Avros.strings(), Avros.strings(), Avros.strings()); TupleN j = new TupleN("a", "b", "c", "d", "e"); GenericData.Record w = new GenericData.Record(at.getSchema()); w.put(0, new Utf8("a")); w.put(1, new Utf8("b")); w.put(2, new Utf8("c")); w.put(3, new Utf8("d")); w.put(4, new Utf8("e")); testInputOutputFn(at, j, w); } @Test @SuppressWarnings("rawtypes") public void testWritables() throws Exception { AvroType at = Avros.writables(LongWritable.class); TaskInputOutputContext<?, ?, ?, ?> testContext = CrunchTestSupport.getTestContext(new Configuration()); at.getInputMapFn().setContext(testContext); at.getInputMapFn().initialize(); at.getOutputMapFn().setContext(testContext); at.getOutputMapFn().initialize(); LongWritable lw = new LongWritable(1729L); assertEquals(lw, at.getInputMapFn().map(at.getOutputMapFn().map(lw))); } @Test @SuppressWarnings("rawtypes") public void testTableOf() throws Exception { AvroType at = Avros.tableOf(Avros.strings(), Avros.strings()); Pair<String, String> j = Pair.of("a", "b"); org.apache.avro.mapred.Pair w = new org.apache.avro.mapred.Pair(at.getSchema()); w.put(0, new Utf8("a")); w.put(1, new Utf8("b")); // TODO update this after resolving the o.a.a.m.Pair.equals issue initialize(at); assertEquals(j, at.getInputMapFn().map(w)); org.apache.avro.mapred.Pair converted = (org.apache.avro.mapred.Pair) at.getOutputMapFn().map(j); assertEquals(w.key(), converted.key()); assertEquals(w.value(), converted.value()); } private static void initialize(PType ptype) { ptype.getInputMapFn().initialize(); ptype.getOutputMapFn().initialize(); } @SuppressWarnings({ "unchecked", "rawtypes" }) protected static void testInputOutputFn(PType ptype, Object java, Object avro) { initialize(ptype); assertEquals(java, ptype.getInputMapFn().map(avro)); assertEquals(avro, ptype.getOutputMapFn().map(java)); } @Test public void testIsPrimitive_PrimitiveMappedType() { assertTrue(Avros.isPrimitive(Avros.ints())); } @Test public void testIsPrimitive_TruePrimitiveValue() { AvroType truePrimitiveAvroType = new AvroType(int.class, Schema.create(Type.INT), NoOpDeepCopier.create()); assertTrue(Avros.isPrimitive(truePrimitiveAvroType)); } @Test public void testIsPrimitive_False() { assertFalse(Avros.isPrimitive(Avros.reflects(Person.class))); } @Test public void testPairs_Generic() { Schema schema = ReflectData.get().getSchema(IntWritable.class); GenericData.Record recordA = new GenericData.Record(schema); GenericData.Record recordB = new GenericData.Record(schema); AvroType<Pair<Record, Record>> pairType = Avros.pairs(Avros.generics(schema), Avros.generics(schema)); Pair<Record, Record> pair = Pair.of(recordA, recordB); pairType.getOutputMapFn().initialize(); pairType.getInputMapFn().initialize(); Object mapped = pairType.getOutputMapFn().map(pair); Pair<Record, Record> doubleMappedPair = pairType.getInputMapFn().map(mapped); assertEquals(pair, doubleMappedPair); mapped.hashCode(); } @Test public void testPairs_Reflect() { IntWritable intWritableA = new IntWritable(1); IntWritable intWritableB = new IntWritable(2); AvroType<Pair<IntWritable, IntWritable>> pairType = Avros.pairs(Avros.reflects(IntWritable.class), Avros.reflects(IntWritable.class)); Pair<IntWritable, IntWritable> pair = Pair.of(intWritableA, intWritableB); pairType.getOutputMapFn().initialize(); pairType.getInputMapFn().initialize(); Object mapped = pairType.getOutputMapFn().map(pair); Pair<IntWritable, IntWritable> doubleMappedPair = pairType.getInputMapFn().map(mapped); assertEquals(pair, doubleMappedPair); } @Test public void testPairs_Specific() { Person personA = new Person(); Person personB = new Person(); personA.age = 1; personA.name = "A"; personA.siblingnames = Collections.<CharSequence> emptyList(); personB.age = 2; personB.name = "B"; personB.siblingnames = Collections.<CharSequence> emptyList(); AvroType<Pair<Person, Person>> pairType = Avros.pairs(Avros.records(Person.class), Avros.records(Person.class)); Pair<Person, Person> pair = Pair.of(personA, personB); pairType.getOutputMapFn().initialize(); pairType.getInputMapFn().initialize(); Object mapped = pairType.getOutputMapFn().map(pair); Pair<Person, Person> doubleMappedPair = pairType.getInputMapFn().map(mapped); assertEquals(pair, doubleMappedPair); } @Test public void testPairOutputMapFn_VerifyNoObjectReuse() { StringWrapper stringWrapper = new StringWrapper("Test"); Pair<Integer, StringWrapper> pair = Pair.of(1, stringWrapper); AvroType<Pair<Integer, StringWrapper>> pairType = Avros.pairs(Avros.ints(), Avros.reflects(StringWrapper.class)); pairType.getOutputMapFn().initialize(); Object outputMappedValueA = pairType.getOutputMapFn().map(pair); Object outputMappedValueB = pairType.getOutputMapFn().map(pair); assertEquals(outputMappedValueA, outputMappedValueB); assertNotSame(outputMappedValueA, outputMappedValueB); } @Test public void testSpecific_AutoRegisterClassLoader() { AvroMode.setSpecificClassLoader(null); // Initial sanity check assertNull(AvroMode.getSpecificClassLoader()); // Calling Avros.specifics should automatically register a class loader for Avro specifics, // unless there is already a specifics class loader set Avros.specifics(Person.class); assertEquals(Person.class.getClassLoader(), AvroMode.getSpecificClassLoader()); } @Test public void testReflect_AutoRegisterClassLoader() { AvroMode.setSpecificClassLoader(null); // Initial sanity check assertNull(AvroMode.getSpecificClassLoader()); // Calling Avros.specifics should automatically register a class loader for Avro specifics, // unless there is already a specifics class loader set Avros.reflects(ReflectedPerson.class); assertEquals(ReflectedPerson.class.getClassLoader(), AvroMode.getSpecificClassLoader()); } }
2,463
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericData.Record; import org.apache.crunch.Pair; import org.apache.crunch.TupleN; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.PType; import org.apache.crunch.types.PTypes; import org.apache.hadoop.conf.Configuration; import org.junit.Test; public class AvroTypeTest { @Test public void testIsSpecific_SpecificData() { assertTrue(Avros.records(Person.class).hasSpecific()); } @Test public void testIsGeneric_SpecificData() { assertFalse(Avros.records(Person.class).isGeneric()); } @Test public void testIsSpecific_GenericData() { assertFalse(Avros.generics(Person.SCHEMA$).hasSpecific()); } @Test public void testIsGeneric_GenericData() { assertTrue(Avros.generics(Person.SCHEMA$).isGeneric()); } @Test public void testIsSpecific_NonAvroClass() { assertFalse(Avros.ints().hasSpecific()); } @Test public void testIsGeneric_NonAvroClass() { assertFalse(Avros.ints().isGeneric()); } @Test public void testIsSpecific_SpecificAvroTable() { assertTrue(Avros.tableOf(Avros.strings(), Avros.records(Person.class)).hasSpecific()); } @Test public void testIsGeneric_SpecificAvroTable() { assertFalse(Avros.tableOf(Avros.strings(), Avros.records(Person.class)).isGeneric()); } @Test public void testIsSpecific_GenericAvroTable() { assertFalse(Avros.tableOf(Avros.strings(), Avros.generics(Person.SCHEMA$)).hasSpecific()); } @Test public void testIsGeneric_GenericAvroTable() { assertFalse(Avros.tableOf(Avros.strings(), Avros.generics(Person.SCHEMA$)).isGeneric()); } @Test public void testIsReflect_GenericType() { assertFalse(Avros.generics(Person.SCHEMA$).hasReflect()); } @Test public void testIsReflect_SpecificType() { assertFalse(Avros.records(Person.class).hasReflect()); } @Test public void testIsReflect_ReflectSimpleType() { assertTrue(Avros.reflects(StringWrapper.class).hasReflect()); } @Test public void testIsReflect_NonReflectSubType() { assertFalse(Avros.pairs(Avros.ints(), Avros.ints()).hasReflect()); } @Test public void testIsReflect_ReflectSubType() { assertTrue(Avros.pairs(Avros.ints(), Avros.reflects(StringWrapper.class)).hasReflect()); } @Test public void testIsReflect_TableOfNonReflectTypes() { assertFalse(Avros.tableOf(Avros.ints(), Avros.strings()).hasReflect()); } @Test public void testIsReflect_TableWithReflectKey() { assertTrue(Avros.tableOf(Avros.reflects(StringWrapper.class), Avros.ints()).hasReflect()); } @Test public void testIsReflect_TableWithReflectValue() { assertTrue(Avros.tableOf(Avros.ints(), Avros.reflects(StringWrapper.class)).hasReflect()); } @Test public void testReflect_CollectionContainingReflectValue() { assertTrue(Avros.collections(Avros.reflects(StringWrapper.class)).hasReflect()); } @Test public void testReflect_CollectionNotContainingReflectValue() { assertFalse(Avros.collections(Avros.generics(Person.SCHEMA$)).hasReflect()); } @Test public void testStableTupleNames() { AvroType<Pair<Long, Float>> at1 = Avros.pairs(Avros.longs(), Avros.floats()); AvroType<Pair<Long, Float>> at2 = Avros.pairs(Avros.longs(), Avros.floats()); assertEquals(at1.getSchema(), at2.getSchema()); } @Test public void testGetDetachedValue_AlreadyMappedAvroType() { Integer value = 42; AvroType<Integer> intType = Avros.ints(); intType.initialize(new Configuration()); Integer detachedValue = intType.getDetachedValue(value); assertSame(value, detachedValue); } @Test public void testGetDetachedValue_GenericAvroType() { AvroType<Record> genericType = Avros.generics(Person.SCHEMA$); genericType.initialize(new Configuration()); GenericData.Record record = new GenericData.Record(Person.SCHEMA$); record.put("name", "name value"); record.put("age", 42); record.put("siblingnames", Lists.newArrayList()); Record detachedRecord = genericType.getDetachedValue(record); assertEquals(record, detachedRecord); assertNotSame(record, detachedRecord); } private Person createPerson() { Person person = new Person(); person.name = "name value"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); return person; } @Test public void testGetDetachedValue_SpecificAvroType() { AvroType<Person> specificType = Avros.specifics(Person.class); specificType.initialize(new Configuration()); Person person = createPerson(); Person detachedPerson = specificType.getDetachedValue(person); assertEquals(person, detachedPerson); assertNotSame(person, detachedPerson); } @Test(expected = IllegalStateException.class) public void testGetDetachedValue_NotInitialized() { AvroType<Person> specificType = Avros.specifics(Person.class); Person person = createPerson(); specificType.getDetachedValue(person); } @Test public void testGetDetachedValue_ReflectAvroType() { AvroType<ReflectedPerson> reflectType = Avros.reflects(ReflectedPerson.class); reflectType.initialize(new Configuration()); ReflectedPerson rp = new ReflectedPerson(); rp.setName("josh"); rp.setAge(32); rp.setSiblingnames(Lists.<String>newArrayList()); ReflectedPerson detached = reflectType.getDetachedValue(rp); assertEquals(rp, detached); assertNotSame(rp, detached); } @Test public void testGetDetachedValue_Pair() { Person person = createPerson(); AvroType<Pair<Integer, Person>> pairType = Avros.pairs(Avros.ints(), Avros.records(Person.class)); pairType.initialize(new Configuration()); Pair<Integer, Person> inputPair = Pair.of(1, person); Pair<Integer, Person> detachedPair = pairType.getDetachedValue(inputPair); assertEquals(inputPair, detachedPair); assertNotSame(inputPair.second(), detachedPair.second()); } @Test public void testGetDetachedValue_Collection() { Person person = createPerson(); List<Person> personList = Lists.newArrayList(person); AvroType<Collection<Person>> collectionType = Avros.collections(Avros.records(Person.class)); collectionType.initialize(new Configuration()); Collection<Person> detachedCollection = collectionType.getDetachedValue(personList); assertEquals(personList, detachedCollection); Person detachedPerson = detachedCollection.iterator().next(); assertNotSame(person, detachedPerson); } @Test public void testGetDetachedValue_Map() { String key = "key"; Person value = createPerson(); Map<String, Person> stringPersonMap = Maps.newHashMap(); stringPersonMap.put(key, value); AvroType<Map<String, Person>> mapType = Avros.maps(Avros.records(Person.class)); mapType.initialize(new Configuration()); Map<String, Person> detachedMap = mapType.getDetachedValue(stringPersonMap); assertEquals(stringPersonMap, detachedMap); assertNotSame(value, detachedMap.get(key)); } @Test public void testGetDetachedValue_TupleN() { Person person = createPerson(); AvroType<TupleN> ptype = Avros.tuples(Avros.records(Person.class)); ptype.initialize(new Configuration()); TupleN tuple = new TupleN(person); TupleN detachedTuple = ptype.getDetachedValue(tuple); assertEquals(tuple, detachedTuple); assertNotSame(person, detachedTuple.get(0)); } @Test public void testGetDetachedValue_ImmutableDerived() { PType<UUID> uuidType = PTypes.uuid(AvroTypeFamily.getInstance()); uuidType.initialize(new Configuration()); UUID uuid = new UUID(1L, 1L); UUID detached = uuidType.getDetachedValue(uuid); assertSame(uuid, detached); } @Test public void testGetDetachedValue_MutableDerived() { PType<StringWrapper> jsonType = PTypes.jsonString(StringWrapper.class, AvroTypeFamily.getInstance()); jsonType.initialize(new Configuration()); StringWrapper stringWrapper = new StringWrapper(); stringWrapper.setValue("test"); StringWrapper detachedValue = jsonType.getDetachedValue(stringWrapper); assertNotSame(stringWrapper, detachedValue); assertEquals(stringWrapper, detachedValue); } @Test public void testGetDetachedValue_Bytes() { byte[] buffer = new byte[]{1, 2, 3}; AvroType<ByteBuffer> byteType = Avros.bytes(); byteType.initialize(new Configuration()); ByteBuffer detachedValue = byteType.getDetachedValue(ByteBuffer.wrap(buffer)); byte[] detachedBuffer = new byte[buffer.length]; detachedValue.get(detachedBuffer); assertArrayEquals(buffer, detachedBuffer); buffer[0] = 99; assertEquals(detachedBuffer[0], 1); } }
2,464
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/PojoWithPrivateCtor.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; /** * A test helper class to check that Avro reflect support private constructors */ class PojoWithPrivateCtor { private String field; public PojoWithPrivateCtor(String field) { this.field = field; } private PojoWithPrivateCtor() {} public String getField() { return field; } }
2,465
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroGroupedTableTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import java.util.List; import org.apache.crunch.Pair; import org.apache.crunch.test.Person; import org.apache.crunch.types.PGroupedTableType; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Lists; public class AvroGroupedTableTypeTest { @Test public void testGetDetachedValue() { Integer integerValue = 42; Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); Iterable<Person> inputPersonIterable = Lists.newArrayList(person); Pair<Integer, Iterable<Person>> pair = Pair.of(integerValue, inputPersonIterable); PGroupedTableType<Integer, Person> groupedTableType = Avros.tableOf(Avros.ints(), Avros.specifics(Person.class)).getGroupedTableType(); groupedTableType.initialize(new Configuration()); Pair<Integer, Iterable<Person>> detachedPair = groupedTableType.getDetachedValue(pair); assertSame(integerValue, detachedPair.first()); List<Person> personList = Lists.newArrayList(detachedPair.second()); assertEquals(inputPersonIterable, personList); assertNotSame(person, personList.get(0)); } }
2,466
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroDeepCopierTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import com.google.common.collect.Lists; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData.Record; import org.apache.crunch.test.Person; import org.apache.crunch.types.PType; import org.apache.crunch.types.avro.AvroDeepCopier.AvroSpecificDeepCopier; import org.apache.hadoop.conf.Configuration; import org.junit.Test; public class AvroDeepCopierTest { @Test public void testDeepCopySpecific() { Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); Person deepCopyPerson = new AvroSpecificDeepCopier<Person>(Person.SCHEMA$).deepCopy(person); assertEquals(person, deepCopyPerson); assertNotSame(person, deepCopyPerson); } @Test public void testDeepCopySpecific_Null() { assertNull(new AvroSpecificDeepCopier<Person>(Person.SCHEMA$).deepCopy(null)); } @Test public void testDeepCopyGeneric() { Record record = new Record(Person.SCHEMA$); record.put("name", "John Doe"); record.put("age", 42); record.put("siblingnames", Lists.newArrayList()); Record deepCopyRecord = new AvroDeepCopier.AvroGenericDeepCopier(Person.SCHEMA$).deepCopy(record); assertEquals(record, deepCopyRecord); assertNotSame(record, deepCopyRecord); } @Test public void testDeepCopyGeneric_Null() { assertNull(new AvroDeepCopier.AvroGenericDeepCopier(Person.SCHEMA$).deepCopy(null)); } @Test public void testDeepCopyReflect() { ReflectedPerson person = new ReflectedPerson(); person.setName("John Doe"); person.setAge(42); person.setSiblingnames(Lists.<String>newArrayList()); AvroDeepCopier<ReflectedPerson> avroDeepCopier = new AvroDeepCopier.AvroReflectDeepCopier<ReflectedPerson>( Avros.reflects(ReflectedPerson.class).getSchema()); avroDeepCopier.initialize(new Configuration()); ReflectedPerson deepCopyPerson = avroDeepCopier.deepCopy(person); assertEquals(person, deepCopyPerson); assertNotSame(person, deepCopyPerson); } @Test public void testDeepCopyReflect_privateCtor() { Schema schema = Avros.reflects(PojoWithPrivateCtor.class).getSchema(); AvroDeepCopier<PojoWithPrivateCtor> avroDeepCopier = new AvroDeepCopier.AvroReflectDeepCopier<>(schema); avroDeepCopier.initialize(new Configuration()); PojoWithPrivateCtor orig = new PojoWithPrivateCtor("foo"); PojoWithPrivateCtor deepCopy = avroDeepCopier.deepCopy(orig); assertEquals(orig.getField(), deepCopy.getField()); } @Test public void testSerializableReflectPType() throws Exception { ReflectedPerson person = new ReflectedPerson(); person.setName("John Doe"); person.setAge(42); person.setSiblingnames(Lists.<String>newArrayList()); PType<ReflectedPerson> rptype = Avros.reflects(ReflectedPerson.class); rptype.initialize(new Configuration()); ReflectedPerson copy1 = rptype.getDetachedValue(person); assertEquals(copy1, person); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(rptype); oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); rptype = (PType<ReflectedPerson>) ois.readObject(); rptype.initialize(new Configuration()); ReflectedPerson copy2 = rptype.getDetachedValue(person); assertEquals(person, copy2); } @Test public void testDeepCopyReflect_Null() { AvroDeepCopier<ReflectedPerson> avroDeepCopier = new AvroDeepCopier.AvroReflectDeepCopier<ReflectedPerson>( Avros.reflects(ReflectedPerson.class).getSchema()); avroDeepCopier.initialize(new Configuration()); assertNull(avroDeepCopier.deepCopy(null)); } @Test public void testDeepCopy_ByteBuffer() { byte[] bytes = new byte[] { 1, 2, 3 }; ByteBuffer buffer = ByteBuffer.wrap(bytes); ByteBuffer deepCopied = new AvroDeepCopier.AvroByteBufferDeepCopier().INSTANCE.deepCopy(buffer); // Change the original array to make sure we've really got a copy bytes[0] = 0; assertArrayEquals(new byte[] { 1, 2, 3 }, deepCopied.array()); } }
2,467
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/ReflectedPerson.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import java.util.List; /** * A test helper class that conforms to the Person Avro specific data class, to use the Person schema for testing * with reflection-based reading and writing. */ public class ReflectedPerson { private String name; private int age; private List<String> siblingnames; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<String> getSiblingnames() { return siblingnames; } public void setSiblingnames(List<String> siblingnames) { this.siblingnames = siblingnames; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReflectedPerson that = (ReflectedPerson) o; if (age != that.age) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (siblingnames != null ? !siblingnames.equals(that.siblingnames) : that.siblingnames != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; result = 31 * result + (siblingnames != null ? siblingnames.hashCode() : 0); return result; } @Override public String toString() { return "ReflectedPerson{" + "name='" + name + '\'' + ", age=" + age + ", siblingnames=" + siblingnames + '}'; } }
2,468
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroTableTypeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.crunch.Pair; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import com.google.common.collect.Lists; import java.util.List; public class AvroTableTypeTest { @Test public void testGetDetachedValue() { Integer integerValue = 42; Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.<CharSequence> newArrayList(); Pair<Integer, Person> pair = Pair.of(integerValue, person); AvroTableType<Integer, Person> tableType = Avros.tableOf(Avros.ints(), Avros.specifics(Person.class)); tableType.initialize(new Configuration()); Pair<Integer, Person> detachedPair = tableType.getDetachedValue(pair); assertSame(integerValue, detachedPair.first()); assertEquals(person, detachedPair.second()); assertNotSame(person, detachedPair.second()); } @Test public void testUnionValueType() { List<Schema> schemas = Lists.newArrayList(); schemas.add(Schema.create(Schema.Type.BOOLEAN)); schemas.add(Schema.create(Schema.Type.INT)); Schema union = Schema.createUnion(schemas); boolean success = false; try { Avros.tableOf(Avros.longs(), Avros.generics(union)); success = true; } catch (Exception shouldNotBeThrown) { } assertTrue("Union type was properly made nullable", success); } @Test public void testIsReflect_ContainsReflectKey() { assertTrue(Avros.tableOf(Avros.reflects(StringWrapper.class), Avros.ints()).hasReflect()); } @Test public void testIsReflect_ContainsReflectValue() { assertTrue(Avros.tableOf(Avros.ints(), Avros.reflects(StringWrapper.class)).hasReflect()); } @Test public void testReflect_NoReflectKeyOrValue() { assertFalse(Avros.tableOf(Avros.ints(), Avros.ints()).hasReflect()); } }
2,469
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroSpecificDeepCopierClassloaderTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import org.apache.crunch.test.Person; import org.apache.crunch.types.avro.AvroDeepCopier.AvroSpecificDeepCopier; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.collect.Lists; @RunWith(AvroChildClassloaderTestRunner.class) public class AvroSpecificDeepCopierClassloaderTest { @Test public void testDeepCopyWithinChildClassloader() { Person person = new Person(); person.name = "John Doe"; person.age = 42; person.siblingnames = Lists.newArrayList(); Person deepCopyPerson = new AvroSpecificDeepCopier<Person>(Person.SCHEMA$) .deepCopy(person); assertEquals(person, deepCopyPerson); assertNotSame(person, deepCopyPerson); } }
2,470
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/types/avro/AvroChildClassloaderTestRunner.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.types.avro; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; public class AvroChildClassloaderTestRunner extends BlockJUnit4ClassRunner { public AvroChildClassloaderTestRunner(Class<?> clazz) throws InitializationError { super(getFromTestClassloader(clazz)); } private static Class<?> getFromTestClassloader(Class<?> clazz) throws InitializationError { try { ClassLoader testClassLoader = new TestClassLoader(); return Class.forName(clazz.getName(), true, testClassLoader); } catch (ClassNotFoundException e) { throw new InitializationError(e); } } public static class TestClassLoader extends URLClassLoader { private static ClassLoader parentClassLoader; private static URL[] crunchURLs; static { ClassLoader classLoader = getSystemClassLoader(); URL[] urls = null; if (classLoader instanceof URLClassLoader) { urls = ((URLClassLoader) classLoader).getURLs(); } else { String[] pieces = ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator); urls = new URL[pieces.length]; for (int i = 0; i < pieces.length; i++) { try { urls[i] = new File(pieces[i]).toURI().toURL(); } catch (Exception e) { throw new RuntimeException(e); } } } Collection<URL> crunchURLs = new ArrayList<URL>(); Collection<URL> otherURLs = new ArrayList<URL>(); for (URL url : urls) { if (url.getPath().matches("^.*/crunch-?.*/.*$")) { crunchURLs.add(url); } else { otherURLs.add(url); } } TestClassLoader.crunchURLs = crunchURLs.toArray(new URL[crunchURLs.size()]); parentClassLoader = new URLClassLoader(otherURLs.toArray(new URL[otherURLs.size()]), classLoader); } public TestClassLoader() { super(crunchURLs, parentClassLoader); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith("org.junit")) { return getSystemClassLoader().loadClass(name); } return super.loadClass(name); } } }
2,471
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/test/StringWrapper.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import org.apache.crunch.MapFn; /** * Simple String wrapper for testing with Avro reflection. */ public class StringWrapper implements Comparable<StringWrapper> { public static class StringToStringWrapperMapFn extends MapFn<String, StringWrapper> { @Override public StringWrapper map(String input) { return wrap(input); } } public static class StringWrapperToStringMapFn extends MapFn<StringWrapper, String> { @Override public String map(StringWrapper input) { return input.getValue(); } } private String value; public StringWrapper() { this(""); } public StringWrapper(String value) { this.value = value; } @Override public int compareTo(StringWrapper o) { return this.value.compareTo(o.value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StringWrapper other = (StringWrapper) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @Override public String toString() { return "StringWrapper [value=" + value + "]"; } public static StringWrapper wrap(String value) { return new StringWrapper(value); } }
2,472
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/test/CountersTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.test; import static org.junit.Assert.assertEquals; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.hadoop.conf.Configuration; import org.junit.Test; /** * A test to verify using counters inside of a unit test works. :) */ public class CountersTest { public enum CT { ONE, TWO, THREE }; public static class CTFn extends DoFn<String, String> { CTFn() { setContext(CrunchTestSupport.getTestContext(new Configuration())); } @Override public void process(String input, Emitter<String> emitter) { increment(CT.ONE, 1); increment(CT.TWO, 4); increment(CT.THREE, 7); } } @Test public void test() { CTFn fn = new CTFn(); fn.process("foo", null); fn.process("bar", null); assertEquals(2L, TestCounters.getCounter(CT.ONE).getValue()); assertEquals(8L, TestCounters.getCounter(CT.TWO).getValue()); assertEquals(14L, TestCounters.getCounter(CT.THREE).getValue()); } @Test public void secondTest() { CTFn fn = new CTFn(); fn.process("foo", null); fn.process("bar", null); assertEquals(2L, TestCounters.getCounter(CT.ONE).getValue()); assertEquals(8L, TestCounters.getCounter(CT.TWO).getValue()); assertEquals(14L, TestCounters.getCounter(CT.THREE).getValue()); } }
2,473
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/util/PartitionUtilsTest.java
/* * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you 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 org.apache.crunch.util; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.apache.crunch.PCollection; import org.apache.crunch.Pipeline; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PartitionUtilsTest { @Mock private PCollection<String> pcollection; @Mock private Pipeline pipeline; @Test public void testBasic() throws Exception { Configuration conf = new Configuration(); when(pcollection.getSize()).thenReturn(7 * 1000L * 1000L * 1000L); when(pcollection.getPipeline()).thenReturn(pipeline); when(pipeline.getConfiguration()).thenReturn(conf); assertEquals(8, PartitionUtils.getRecommendedPartitions(pcollection)); } @Test public void testBytesPerTask() throws Exception { Configuration conf = new Configuration(); conf.setLong(PartitionUtils.BYTES_PER_REDUCE_TASK, 500L * 1000L * 1000L); when(pcollection.getSize()).thenReturn(7 * 1000L * 1000L * 1000L); when(pcollection.getPipeline()).thenReturn(pipeline); when(pipeline.getConfiguration()).thenReturn(conf); assertEquals(15, PartitionUtils.getRecommendedPartitions(pcollection)); } @Test public void testDefaultMaxRecommended() throws Exception { Configuration conf = new Configuration(); when(pcollection.getSize()).thenReturn(1000 * 1000L * 1000L * 1000L); when(pcollection.getPipeline()).thenReturn(pipeline); when(pipeline.getConfiguration()).thenReturn(conf); assertEquals(500, PartitionUtils.getRecommendedPartitions(pcollection)); } @Test public void testMaxRecommended() throws Exception { Configuration conf = new Configuration(); conf.setInt(PartitionUtils.MAX_REDUCERS, 400); when(pcollection.getSize()).thenReturn(1000 * 1000L * 1000L * 1000L); when(pcollection.getPipeline()).thenReturn(pipeline); when(pipeline.getConfiguration()).thenReturn(conf); assertEquals(400, PartitionUtils.getRecommendedPartitions(pcollection)); } @Test public void testNegativeMaxRecommended() throws Exception { Configuration conf = new Configuration(); conf.setInt(PartitionUtils.MAX_REDUCERS, -1); when(pcollection.getSize()).thenReturn(1000 * 1000L * 1000L * 1000L); when(pcollection.getPipeline()).thenReturn(pipeline); when(pipeline.getConfiguration()).thenReturn(conf); assertEquals(1001, PartitionUtils.getRecommendedPartitions(pcollection)); } }
2,474
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/util/DistCacheTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class DistCacheTest { // A temporary folder used to hold files created for the test. @Rule public TemporaryFolder testFolder = new TemporaryFolder(); // A configuration and lists of paths to use in tests. private Configuration testConf; private String[] testFilePaths; private String[] testFileQualifiedPaths; /** * Setup resources for tests. These include: * <ol> * <li>A Hadoop configuration. * <li>A directory of temporary files that includes 3 .jar files and 1 other * file. * <li>Arrays containing the canonical paths and qualified paths to the test * files. * </ol> */ @Before public void setup() throws IOException { // Create a configuration for tests. testConf = new Configuration(); // Create the test files and add their paths to the list of test file paths. testFilePaths = new String[3]; testFilePaths[0] = testFolder.newFile("jar1.jar").getCanonicalPath(); testFilePaths[1] = testFolder.newFile("jar2.jar").getCanonicalPath(); testFilePaths[2] = testFolder.newFile("jar3.jar").getCanonicalPath(); testFolder.newFile("notJar.other"); // Populate a list of qualified paths from the test file paths. testFileQualifiedPaths = new String[3]; for (int i = 0; i < testFilePaths.length; i++) { testFileQualifiedPaths[i] = "file:" + testFilePaths[i]; } } /** * Tests adding jars one-by-one to a job's configuration. * * @throws IOException * If there is a problem adding the jars. */ @Test public void testAddJar() throws IOException { // Add each valid jar path to the distributed cache configuration, and // verify each was // added correctly in turn. for (int i = 0; i < testFilePaths.length; i++) { DistCache.addJarToDistributedCache(testConf, testFilePaths[i]); assertEquals("tmpjars configuration var does not contain expected value.", StringUtils.join(testFileQualifiedPaths, ",", 0, i + 1), testConf.get("tmpjars")); } } /** * Tests that attempting to add the path to a jar that does not exist to the * configuration throws an exception. * * @throws IOException * If the added jar path does not exist. This exception is expected. */ @Test(expected = IOException.class) public void testAddJarThatDoesntExist() throws IOException { DistCache.addJarToDistributedCache(testConf, "/garbage/doesntexist.jar"); } /** * Tests that adding a directory of jars to the configuration works as * expected. .jar files under the added directory should be added to the * configuration, and all other files should be skipped. * * @throws IOException * If there is a problem adding the jar directory to the * configuration. */ @Test public void testAddJarDirectory() throws IOException { DistCache.addJarDirToDistributedCache(testConf, testFolder.getRoot().getCanonicalPath()); // Throw the added jar paths in a set to detect duplicates. String[] splitJarPaths = StringUtils.split(testConf.get("tmpjars"), ","); Set<String> addedJarPaths = new HashSet<String>(); for (String path : splitJarPaths) { addedJarPaths.add(path); } assertEquals("Incorrect number of jar paths added.", testFilePaths.length, addedJarPaths.size()); // Ensure all expected paths were added. for (int i = 0; i < testFileQualifiedPaths.length; i++) { assertTrue("Expected jar path missing from jar paths added to tmpjars: " + testFileQualifiedPaths[i], addedJarPaths.contains(testFileQualifiedPaths[i])); } } /** * Tests that adding a jar directory that does not exist to the configuration * throws an exception. * * @throws IOException * If the added jar directory does not exist. This exception is * expected. */ @Test(expected = IOException.class) public void testAddJarDirectoryThatDoesntExist() throws IOException { DistCache.addJarDirToDistributedCache(testConf, "/garbage/doesntexist"); } /** * Tests that adding a jar directory that is not a directory to the * configuration throws an exception. * * @throws IOException * If the added jar directory is not a directory. This exception is * expected. */ @Test(expected = IOException.class) public void testAddJarDirectoryNotDirectory() throws IOException { DistCache.addJarDirToDistributedCache(testConf, testFilePaths[0]); } }
2,475
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/SequentialFileNamingSchemeTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class SequentialFileNamingSchemeTest { // The partition id used for testing. This partition id should be ignored by // the SequentialFileNamingScheme. private static final int PARTITION_ID = 42; private SequentialFileNamingScheme namingScheme; private Configuration configuration; @Rule public TemporaryFolder tmpOutputDir = new TemporaryFolder(); @Before public void setUp() throws IOException { configuration = new Configuration(); namingScheme = SequentialFileNamingScheme.getInstance(); } @Test public void testGetMapOutputName_EmptyDirectory() throws IOException { assertEquals("part-m-00000", namingScheme.getMapOutputName(configuration, new Path(tmpOutputDir.getRoot().getAbsolutePath()))); } @Test public void testGetMapOutputName_NonEmptyDirectory() throws IOException { File outputDirectory = tmpOutputDir.getRoot(); new File(outputDirectory, "existing-1").createNewFile(); new File(outputDirectory, "existing-2").createNewFile(); assertEquals("part-m-00002", namingScheme.getMapOutputName(configuration, new Path(outputDirectory.getAbsolutePath()))); } @Test public void testGetReduceOutputName_EmptyDirectory() throws IOException { assertEquals("part-r-00000", namingScheme.getReduceOutputName(configuration, new Path(tmpOutputDir.getRoot() .getAbsolutePath()), PARTITION_ID)); } @Test public void testGetReduceOutputName_NonEmptyDirectory() throws IOException { File outputDirectory = tmpOutputDir.getRoot(); new File(outputDirectory, "existing-1").createNewFile(); new File(outputDirectory, "existing-2").createNewFile(); assertEquals("part-r-00002", namingScheme.getReduceOutputName(configuration, new Path(outputDirectory.getAbsolutePath()), PARTITION_ID)); } }
2,476
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/FromTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io; import static org.junit.Assert.assertEquals; import java.io.IOException; import com.google.common.collect.ImmutableList; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumWriter; import org.apache.crunch.Source; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class FromTest { @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Test(expected=IllegalArgumentException.class) public void testAvroFile_EmptyPathListNotAllowed() { From.avroFile(ImmutableList.<Path>of()); } @Test(expected=IllegalArgumentException.class) public void testTextFile_EmptyPathListNotAllowed() { From.textFile(ImmutableList.<Path>of()); } @Test(expected=IllegalArgumentException.class) public void testFormattedFile_EmptyPathListNotAllowed() { From.formattedFile(ImmutableList.<Path>of(), TextInputFormat.class, LongWritable.class, Text.class); } @Test(expected=IllegalArgumentException.class) public void testSequenceFile_EmptyPathListNotAllowed() { From.sequenceFile(ImmutableList.<Path>of(), LongWritable.class, Text.class); } @Test public void testAvroFile_GlobWithSchemaInferenceIsSupported() throws IOException { Schema schema = SchemaBuilder.record("record") .fields() .endRecord(); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); try (DataFileWriter<GenericRecord> writer = new DataFileWriter<>(datumWriter)) { writer.create(schema, tmp.newFile("1")); writer.append(new GenericData.Record(schema)); } Source<GenericData.Record> source = From.avroFile(new Path(tmp.getRoot().toString() + "/*")); assertEquals(source.getType(), Avros.generics(schema)); } @Test public void testAvroFile_DirectoryWithSchemaInferenceIsSupported() throws IOException { Schema schema = SchemaBuilder.record("record") .fields() .endRecord(); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); try (DataFileWriter<GenericRecord> writer = new DataFileWriter<>(datumWriter)) { writer.create(schema, tmp.newFile("1")); writer.append(new GenericData.Record(schema)); } Source<GenericData.Record> source = From.avroFile(new Path(tmp.getRoot().toString())); assertEquals(source.getType(), Avros.generics(schema)); } @Test public void testAvroFile_FileWithSchemaInferenceIsSupported() throws IOException { Schema schema = SchemaBuilder.record("record") .fields() .endRecord(); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); try (DataFileWriter<GenericRecord> writer = new DataFileWriter<>(datumWriter)) { writer.create(schema, tmp.newFile("1")); writer.append(new GenericData.Record(schema)); } Source<GenericData.Record> source = From.avroFile(new Path(tmp.getRoot().toString(), "1")); assertEquals(source.getType(), Avros.generics(schema)); } }
2,477
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/FormatBundleTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io; import static org.hamcrest.CoreMatchers.is; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.junit.Assert; import org.junit.Test; public class FormatBundleTest { @Test public void testFileSystemConfs() throws Exception { Configuration fsConf = new Configuration(false); fsConf.set(FileSystem.FS_DEFAULT_NAME_KEY, "file:///tmp/foo"); fsConf.set("foo", "bar"); fsConf.set("fs.fake.impl", "FakeFileSystem"); fsConf.set("dfs.overridden", "fsValue"); fsConf.set("dfs.extraOverridden", "fsExtra"); fsConf.set(DFSConfigKeys.DFS_NAMESERVICES, "fs-cluster"); FileSystem fs = FileSystem.newInstance(fsConf); FormatBundle<TextInputFormat> formatBundle = new FormatBundle<>(TextInputFormat.class); formatBundle.setFileSystem(fs); formatBundle.set("dfs.extraOverridden", "extraExtra"); Configuration conf = new Configuration(); conf.set(DFSConfigKeys.DFS_NAMESERVICES, "pipeline-cluster"); conf.set("dfs.overridden", "pipelineValue"); formatBundle.configure(conf); // should be filtered by blacklist Assert.assertFalse(conf.get(FileSystem.FS_DEFAULT_NAME_KEY).equals("hdfs://my-hdfs")); // shouldn't be on whitelist Assert.assertFalse(conf.get("foo") != null); // should get through both blacklist and whitelist Assert.assertEquals("FakeFileSystem", conf.get("fs.fake.impl")); // should use value from fsConf Assert.assertEquals("fsValue", conf.get("dfs.overridden")); // should use value from 'extraConf' Assert.assertEquals("extraExtra", conf.get("dfs.extraOverridden")); // dfs.nameservices should be merged Assert.assertArrayEquals(new String [] {"pipeline-cluster", "fs-cluster"}, conf.getStrings(DFSConfigKeys.DFS_NAMESERVICES)); } @Test public void testRedactedFileSystemConfs() throws Exception { Configuration fsConf = new Configuration(false); fsConf.set("fs.s3a.access.key", "accessKey"); fsConf.set("fs.s3a.secret.key", "secretKey"); fsConf.set("fs.fake.impl", "FakeFileSystem"); FileSystem fs = FileSystem.newInstance(fsConf); FormatBundle<TextInputFormat> formatBundle = new FormatBundle<>(TextInputFormat.class); formatBundle.setFileSystem(fs); Configuration conf = new Configuration(); conf.set("mapreduce.job.redacted-properties", "fs.s3a.access.key,fs.s3a.secret.key"); final FormatBundleTestAppender appender = new FormatBundleTestAppender(); final Logger logger = Logger.getRootLogger(); logger.addAppender(appender); try { Logger.getLogger(FormatBundleTest.class); formatBundle.configure(conf); } finally { logger.removeAppender(appender); } final List<LoggingEvent> log = appender.getLog(); // redacted value: accesskey Assert.assertThat(log.get(0).getMessage().toString(), is("Applied fs.s3a.access.key=*********(redacted) from FS 'file:///'")); // fake non redacted value: fs.fake.impl Assert.assertThat(log.get(1).getMessage().toString(), is("Applied fs.fake.impl=FakeFileSystem from FS 'file:///'")); // redacted value: secretKey Assert.assertThat(log.get(2).getMessage().toString(), is("Applied fs.s3a.secret.key=*********(redacted) from FS 'file:///'")); } class FormatBundleTestAppender extends AppenderSkeleton { private final List<LoggingEvent> log = new ArrayList<>(); @Override public boolean requiresLayout() { return false; } @Override protected void append(final LoggingEvent loggingEvent) { log.add(loggingEvent); } @Override public void close() { } public List<LoggingEvent> getLog() { return new ArrayList<>(log); } } }
2,478
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/CrunchInputsTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io; import java.io.IOException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class CrunchInputsTest { private Job job; private FormatBundle formatBundle; @Before public void setUp() throws IOException { job = new Job(); formatBundle = FormatBundle.forInput(TextInputFormat.class); } @Test public void testAddAndGetPaths() { Path inputPath = new Path("/tmp"); CrunchInputs.addInputPath(job, inputPath, formatBundle, 0); assertEquals( ImmutableMap.of(formatBundle, ImmutableMap.of(0, ImmutableList.of(inputPath))), CrunchInputs.getFormatNodeMap(job)); } @Test public void testAddAndGetPaths_GlobPath() { Path globPath = new Path("/tmp/file{1,2,3}.txt"); CrunchInputs.addInputPath(job, globPath, formatBundle, 0); assertEquals( ImmutableMap.of(formatBundle, ImmutableMap.of(0, ImmutableList.of(globPath))), CrunchInputs.getFormatNodeMap(job)); } @Test public void testAddAndGetPaths_PathUsingSeparators() { Path pathUsingRecordSeparators = new Path("/tmp/,;|.txt"); CrunchInputs.addInputPath(job, pathUsingRecordSeparators, formatBundle, 0); assertEquals( ImmutableMap.of(formatBundle, ImmutableMap.of(0, ImmutableList.of(pathUsingRecordSeparators))), CrunchInputs.getFormatNodeMap(job)); } @Test public void testAddAndGetPaths_FullyQualifiedPath() throws IOException { Path fullyQualifiedPath = new Path("/tmp").makeQualified(FileSystem.getLocal(new Configuration())); System.out.println("Fully qualified: " + fullyQualifiedPath); CrunchInputs.addInputPath(job, fullyQualifiedPath, formatBundle, 0); assertEquals( ImmutableMap.of(formatBundle, ImmutableMap.of(0, ImmutableList.of(fullyQualifiedPath))), CrunchInputs.getFormatNodeMap(job)); } }
2,479
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/SourceTargetHelperTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.crunch.test.TemporaryPath; import org.apache.crunch.test.TemporaryPaths; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RawLocalFileSystem; import org.junit.Rule; import org.junit.Test; public class SourceTargetHelperTest { @Rule public TemporaryPath tmpDir = TemporaryPaths.create(); @Test public void testGetNonexistentPathSize() throws Exception { Path tmpPath = tmpDir.getRootPath(); tmpDir.delete(); FileSystem fs = FileSystem.getLocal(tmpDir.getDefaultConfiguration()); assertEquals(-1L, SourceTargetHelper.getPathSize(fs, tmpPath)); } @Test public void testGetNonExistentPathSize_NonExistantPath() throws IOException { FileSystem mockFs = new MockFileSystem(); assertEquals(-1L, SourceTargetHelper.getPathSize(mockFs, new Path("does/not/exist"))); } /** * Tests for proper recursive size calculation on a path containing a glob pattern. */ @Test public void testGetPathSizeGlobPathRecursive() throws Exception { FileSystem fs = FileSystem.getLocal(tmpDir.getDefaultConfiguration()); // Create a directory structure with 3 files spread across 2 top-level directories and one subdirectory: // foo1/file1 // foo1/subdir/file2 // foo2/file3 Path foo1 = tmpDir.getPath("foo1"); fs.mkdirs(foo1); createFile(fs, new Path(foo1, "file1"), 3); Path subDir = tmpDir.getPath("foo1/subdir"); fs.mkdirs(subDir); createFile(fs, new Path(subDir, "file2"), 5); Path foo2 = tmpDir.getPath("foo2"); fs.mkdirs(foo2); createFile(fs, new Path(foo2, "file3"), 11); // assert total size with glob pattern (3 + 5 + 11 = 19) assertEquals(19, SourceTargetHelper.getPathSize(fs, tmpDir.getPath("foo*"))); } private static void createFile(FileSystem fs, Path path, int size) throws IOException { FSDataOutputStream outputStream = fs.create(path); for (int i = 0; i < size; i++) { outputStream.write(0); } outputStream.close(); } /** * Mock FileSystem that returns null for {@link FileSystem#listStatus(Path)}. */ private static class MockFileSystem extends LocalFileSystem { private static RawLocalFileSystem createConfiguredRawLocalFileSystem() { RawLocalFileSystem fs = new RawLocalFileSystem(); fs.setConf(new Configuration(false)); return fs; } private MockFileSystem() { super(createConfiguredRawLocalFileSystem()); } @Override public FileStatus[] listStatus(Path f) throws IOException { return null; } } }
2,480
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/impl/CrunchJobHooksTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.impl; import static org.junit.Assert.assertEquals; import org.apache.crunch.io.impl.FileTargetImpl; import org.junit.Test; public class CrunchJobHooksTest { @Test public void testExtractPartitionNumber() { assertEquals(0, FileTargetImpl.extractPartitionNumber("out1-r-00000")); assertEquals(10, FileTargetImpl.extractPartitionNumber("out2-r-00010")); assertEquals(99999, FileTargetImpl.extractPartitionNumber("out3-r-99999")); } @Test public void testExtractPartitionNumber_WithSuffix() { assertEquals(10, FileTargetImpl.extractPartitionNumber("out2-r-00010.avro")); } @Test(expected = IllegalArgumentException.class) public void testExtractPartitionNumber_MapOutputFile() { FileTargetImpl.extractPartitionNumber("out1-m-00000"); } }
2,481
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/impl/FileTargetImplTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.impl; import org.apache.commons.io.FileUtils; import org.apache.crunch.Target; import org.apache.crunch.io.SequentialFileNamingScheme; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.hasItem; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class FileTargetImplTest { @Rule public TemporaryFolder TMP = new TemporaryFolder(); @Test public void testHandleOutputsMovesFilesToDestination() throws Exception { java.nio.file.Path testWorkingPath = TMP.newFolder().toPath(); java.nio.file.Path testDestinationPath = TMP.newFolder().toPath(); FileTargetImpl fileTarget = new FileTargetImpl( new Path(testDestinationPath.toAbsolutePath().toString()), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()); Map<String, String> partToContent = new HashMap<>(); partToContent.put("part-m-00000", "test1"); partToContent.put("part-m-00001", "test2"); Collection<String> expectedContent = partToContent.values(); for(Map.Entry<String, String> entry: partToContent.entrySet()){ File part = new File(testWorkingPath.toAbsolutePath().toString(), entry.getKey()); FileUtils.writeStringToFile(part, entry.getValue()); } fileTarget.handleOutputs(new Configuration(), new Path(testWorkingPath.toAbsolutePath().toString()), -1); Set<String> fileContents = new HashSet<>(); for (String fileName : partToContent.keySet()) { fileContents.add(FileUtils.readFileToString(testDestinationPath.resolve(fileName).toFile())); } assertThat(expectedContent.size(), is(fileContents.size())); for(String content: expectedContent){ assertThat(fileContents, hasItem(content)); } } @Test public void testEquality() { Target target = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()); Target target2 = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()); assertEquals(target, target2); assertEquals(target.hashCode(), target2.hashCode()); } @Test public void testEqualityWithExtraConf() { Target target = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).outputConf("key", "value"); Target target2 = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).outputConf("key", "value"); assertEquals(target, target2); assertEquals(target.hashCode(), target2.hashCode()); } @Test public void testEqualityWithFileSystem() { Path path = new Path("/path"); Path qualifiedPath = path.makeQualified(URI.create("scheme://cluster"), new Path("/")); FileSystem fs = mock(FileSystem.class); when(fs.makeQualified(path)).thenReturn(qualifiedPath); Configuration conf = new Configuration(false); conf.set("key", "value"); when(fs.getConf()).thenReturn(conf); Target target = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs); Target target2 = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs); assertEquals(target, target2); assertEquals(target.hashCode(), target2.hashCode()); } @Test public void testInequality() { Target target = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()); Target target2 = new FileTargetImpl(new Path("/path2"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()); assertThat(target, is(not(target2))); assertThat(target.hashCode(), is(not(target2.hashCode()))); } @Test public void testInequalityWithExtraConf() { Target target = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).outputConf("key", "value"); Target target2 = new FileTargetImpl(new Path("/path"), SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).outputConf("key", "value2"); assertThat(target, is(not(target2))); assertThat(target.hashCode(), is(not(target2.hashCode()))); } @Test public void testInequalityWithFileSystemURI() { Path path = new Path("/path"); Path qualifiedPath = path.makeQualified(URI.create("scheme://cluster"), new Path("/")); Path qualifiedPath2 = path.makeQualified(URI.create("scheme://cluster2"), new Path("/")); FileSystem fs = mock(FileSystem.class); FileSystem fs2 = mock(FileSystem.class); when(fs.makeQualified(path)).thenReturn(qualifiedPath); when(fs2.makeQualified(path)).thenReturn(qualifiedPath2); when(fs.getConf()).thenReturn(new Configuration(false)); when(fs2.getConf()).thenReturn(new Configuration(false)); Target target = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs); Target target2 = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs2); assertThat(target, is(not(target2))); assertThat(target.hashCode(), is(not(target2.hashCode()))); } @Test public void testInequalityWithFileSystemConf() { Path path = new Path("/path"); Path qualifiedPath = path.makeQualified(URI.create("scheme://cluster"), new Path("/")); FileSystem fs = mock(FileSystem.class); FileSystem fs2 = mock(FileSystem.class); when(fs.makeQualified(path)).thenReturn(qualifiedPath); when(fs2.makeQualified(path)).thenReturn(qualifiedPath); Configuration conf = new Configuration(false); conf.set("key", "value"); Configuration conf2 = new Configuration(false); conf2.set("key", "value2"); when(fs.getConf()).thenReturn(conf); when(fs2.getConf()).thenReturn(conf2); Target target = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs); Target target2 = new FileTargetImpl(path, SequenceFileOutputFormat.class, SequentialFileNamingScheme.getInstance()).fileSystem(fs2); assertThat(target, is(not(target2))); assertThat(target.hashCode(), is(not(target2.hashCode()))); } }
2,482
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/avro/AvroFileReaderFactoryTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.reflect.ReflectData; import org.apache.avro.reflect.ReflectDatumReader; import org.apache.avro.specific.SpecificDatumReader; import org.apache.crunch.Pair; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.avro.AvroType; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Lists; public class AvroFileReaderFactoryTest { private File avroFile; @Before public void setUp() throws IOException { avroFile = File.createTempFile("test", ".av"); } @After public void tearDown() { avroFile.delete(); } private void populateGenericFile(List<GenericRecord> genericRecords, Schema outputSchema) throws IOException { FileOutputStream outputStream = new FileOutputStream(this.avroFile); GenericDatumWriter<GenericRecord> genericDatumWriter = new GenericDatumWriter<GenericRecord>(outputSchema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(genericDatumWriter); dataFileWriter.create(outputSchema, outputStream); for (GenericRecord record : genericRecords) { dataFileWriter.append(record); } dataFileWriter.close(); outputStream.close(); } private static <T> AvroFileReaderFactory<T> createFileReaderFactory(AvroType<T> avroType) { return new AvroFileReaderFactory<T>(avroType); } @Test public void testRead_GenericReader() throws IOException { GenericRecord savedRecord = new GenericData.Record(Person.SCHEMA$); savedRecord.put("name", "John Doe"); savedRecord.put("age", 42); savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane")); populateGenericFile(Lists.newArrayList(savedRecord), Person.SCHEMA$); AvroFileReaderFactory<GenericData.Record> genericReader = createFileReaderFactory(Avros.generics(Person.SCHEMA$)); Iterator<GenericData.Record> recordIterator = genericReader.read(FileSystem.getLocal(new Configuration()), new Path(this.avroFile.getAbsolutePath())); GenericRecord genericRecord = recordIterator.next(); assertEquals(savedRecord, genericRecord); assertFalse(recordIterator.hasNext()); } @Test public void testRead_SpecificReader() throws IOException { GenericRecord savedRecord = new GenericData.Record(Person.SCHEMA$); savedRecord.put("name", "John Doe"); savedRecord.put("age", 42); savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane")); populateGenericFile(Lists.newArrayList(savedRecord), Person.SCHEMA$); AvroFileReaderFactory<Person> genericReader = createFileReaderFactory(Avros.records(Person.class)); Iterator<Person> recordIterator = genericReader.read(FileSystem.getLocal(new Configuration()), new Path( this.avroFile.getAbsolutePath())); Person expectedPerson = new Person(); expectedPerson.age = 42; expectedPerson.name = "John Doe"; List<CharSequence> siblingNames = Lists.newArrayList(); siblingNames.add("Jimmy"); siblingNames.add("Jane"); expectedPerson.siblingnames = siblingNames; Person person = recordIterator.next(); assertEquals(expectedPerson, person); assertFalse(recordIterator.hasNext()); } @Test public void testRead_ReflectReader() throws IOException { Schema reflectSchema = ReflectData.get().getSchema(StringWrapper.class); GenericRecord savedRecord = new GenericData.Record(reflectSchema); savedRecord.put("value", "stringvalue"); populateGenericFile(Lists.newArrayList(savedRecord), reflectSchema); AvroFileReaderFactory<StringWrapper> genericReader = createFileReaderFactory(Avros.reflects(StringWrapper.class)); Iterator<StringWrapper> recordIterator = genericReader.read(FileSystem.getLocal(new Configuration()), new Path( this.avroFile.getAbsolutePath())); StringWrapper stringWrapper = recordIterator.next(); assertEquals("stringvalue", stringWrapper.getValue()); assertFalse(recordIterator.hasNext()); } @Test public void testCreateDatumReader_Generic() { DatumReader<GenericData.Record> datumReader = AvroFileReaderFactory.createDatumReader(Avros.generics(Person.SCHEMA$)); assertEquals(GenericDatumReader.class, datumReader.getClass()); } @Test public void testCreateDatumReader_Reflect() { DatumReader<StringWrapper> datumReader = AvroFileReaderFactory.createDatumReader(Avros .reflects(StringWrapper.class)); assertEquals(ReflectDatumReader.class, datumReader.getClass()); } @Test public void testCreateDatumReader_Specific() { DatumReader<Person> datumReader = AvroFileReaderFactory.createDatumReader(Avros.records(Person.class)); assertEquals(SpecificDatumReader.class, datumReader.getClass()); } @Test public void testCreateDatumReader_ReflectAndSpecific() { Assume.assumeTrue(Avros.CAN_COMBINE_SPECIFIC_AND_REFLECT_SCHEMAS); DatumReader<Pair<Person, StringWrapper>> datumReader = AvroFileReaderFactory.createDatumReader(Avros.pairs( Avros.records(Person.class), Avros.reflects(StringWrapper.class))); assertEquals(ReflectDatumReader.class, datumReader.getClass()); } @Test(expected = IllegalStateException.class) public void testCreateDatumReader_ReflectAndSpecific_NotSupported() { Assume.assumeTrue(!Avros.CAN_COMBINE_SPECIFIC_AND_REFLECT_SCHEMAS); AvroFileReaderFactory.createDatumReader(Avros.pairs(Avros.records(Person.class), Avros.reflects(StringWrapper.class))); } }
2,483
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/avro/AvroFileSourceTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.avro; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.mapred.AvroJob; import org.apache.crunch.io.CrunchInputs; import org.apache.crunch.io.FormatBundle; import org.apache.crunch.test.Person; import org.apache.crunch.test.StringWrapper; import org.apache.crunch.types.avro.AvroType; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.junit.After; import org.junit.Before; import org.junit.Test; public class AvroFileSourceTest { private Job job; File tempFile; @Before public void setUp() throws IOException { job = new Job(); tempFile = File.createTempFile("test", ".avr"); } @After public void tearDown() { tempFile.delete(); } @Test public void testConfigureJob_SpecificData() throws IOException { AvroType<Person> avroSpecificType = Avros.records(Person.class); AvroFileSource<Person> personFileSource = new AvroFileSource<Person>(new Path(tempFile.getAbsolutePath()), avroSpecificType); FormatBundle bundle = personFileSource.getBundle(); bundle.configure(job.getConfiguration()); assertFalse(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, true)); assertEquals(Person.SCHEMA$.toString(), job.getConfiguration().get(AvroJob.INPUT_SCHEMA)); } @Test public void testConfigureJob_GenericData() throws IOException { AvroType<Record> avroGenericType = Avros.generics(Person.SCHEMA$); AvroFileSource<Record> personFileSource = new AvroFileSource<Record>(new Path(tempFile.getAbsolutePath()), avroGenericType); FormatBundle bundle = personFileSource.getBundle(); bundle.configure(job.getConfiguration()); assertFalse(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, true)); } @Test public void testConfigureJob_ReflectData() throws IOException { AvroType<StringWrapper> avroReflectType = Avros.reflects(StringWrapper.class); AvroFileSource<StringWrapper> personFileSource = new AvroFileSource<StringWrapper>(new Path( tempFile.getAbsolutePath()), avroReflectType); FormatBundle bundle = personFileSource.getBundle(); bundle.configure(job.getConfiguration()); assertTrue(job.getConfiguration().getBoolean(AvroJob.INPUT_IS_REFLECT, false)); } }
2,484
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text/xml/XmlRecordReaderTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.text.xml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.crunch.impl.mr.run.RuntimeParameters; import org.apache.crunch.io.text.xml.XmlInputFormat.XmlRecordReader; import org.apache.crunch.test.TemporaryPath; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /** * {@link XmlRecordReader} Test. * */ public class XmlRecordReaderTest { @Rule public transient TemporaryPath tmpDir = new TemporaryPath(RuntimeParameters.TMP_DIR, "hadoop.tmp.dir"); private Configuration conf; private String xmlFile; private long xmlFileLength; @Before public void before() throws IOException { xmlFile = tmpDir.copyResourceFileName("xmlSourceSample3.xml"); xmlFileLength = getFileLength(xmlFile); conf = new org.apache.hadoop.conf.Configuration(); conf.set(XmlInputFormat.START_TAG_KEY, "<PLANT"); conf.set(XmlInputFormat.END_TAG_KEY, "</PLANT>"); } @Test public void testStartOffsets() throws Exception { /* * The xmlSourceSample3.xml file byte ranges: * * 50-252 - first PLANT element. * * 254-454 - second PLANT element. * * 456-658 - third PLANT element. */ assertEquals("Starting from offset 0 should read all elements", 3, readXmlElements(createSplit(0, xmlFileLength))); assertEquals("Offset is in the middle of the first element. Should read only the remaining 2 elements", 2, readXmlElements(createSplit(100, xmlFileLength))); assertEquals("Offset is in the middle of the second element. Should read only the remaining 1 element", 1, readXmlElements(createSplit(300, xmlFileLength))); assertEquals("Offset is in the middle of the third element. Should read no elements", 0, readXmlElements(createSplit(500, xmlFileLength))); } @Test public void readThroughSplitEnd() throws IOException, InterruptedException { // Third element starts at position: 456 and has length: 202 assertEquals("Split starts before the 3rd element and ends in the middle of the 3rd element.", 1, readXmlElements(createSplit(300, ((456 - 300) + 202 / 2)))); assertEquals("Split starts and ends before the 3rd element.", 0, readXmlElements(createSplit(300, (456 - 300)))); } private FileSplit createSplit(long offset, long length) { return new FileSplit(new Path(xmlFile), offset, length, new String[] {}); } private long readXmlElements(FileSplit split) throws IOException, InterruptedException { int elementCount = 0; XmlRecordReader xmlRecordReader = new XmlRecordReader(split, conf); try { long lastKey = 0; while (xmlRecordReader.nextKeyValue()) { elementCount++; assertTrue(xmlRecordReader.getCurrentKey().get() > lastKey); lastKey = xmlRecordReader.getCurrentKey().get(); assertTrue(xmlRecordReader.getCurrentValue().getLength() > 0); } } finally { xmlRecordReader.close(); } return elementCount; } private long getFileLength(String fileName) throws FileNotFoundException, IOException { return new File(fileName).length(); } }
2,485
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text/csv/CSVRecordIteratorTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.text.csv; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.apache.crunch.test.TemporaryPath; import org.apache.crunch.test.TemporaryPaths; import org.junit.Rule; import org.junit.Test; public class CSVRecordIteratorTest { @Rule public transient TemporaryPath tmpDir = TemporaryPaths.create(); @Test public void testVanillaCSV() throws IOException { String[] expectedFileContents = { "1,2,3,4", "5,6,7,8", "9,10,11", "12,13,14" }; String vanillaCSVFile = tmpDir.copyResourceFileName("vanilla.csv"); File vanillaFile = new File(vanillaCSVFile); InputStream inputStream = new FileInputStream(vanillaFile); CSVRecordIterator csvRecordIterator = new CSVRecordIterator(inputStream); ArrayList<String> fileContents = new ArrayList<String>(5); while (csvRecordIterator.hasNext()) { fileContents.add(csvRecordIterator.next()); } for (int i = 0; i < expectedFileContents.length; i++) { assertEquals(expectedFileContents[i], fileContents.get(i)); } } @Test public void testCSVWithNewlines() throws IOException { String[] expectedFileContents = { "\"Champion, Mac\",\"1234 Hoth St.\n\tApartment 101\n\tAtlanta, GA\n\t64086\",\"30\",\"M\",\"5/28/2010 12:00:00 AM\",\"Just some guy\"", "\"Champion, Mac\",\"5678 Tatooine Rd. Apt 5, Mobile, AL 36608\",\"30\",\"M\",\"Some other date\",\"short description\"" }; String csvWithNewlines = tmpDir.copyResourceFileName("withNewlines.csv"); File fileWithNewlines = new File(csvWithNewlines); InputStream inputStream = new FileInputStream(fileWithNewlines); CSVRecordIterator csvRecordIterator = new CSVRecordIterator(inputStream); ArrayList<String> fileContents = new ArrayList<String>(2); while (csvRecordIterator.hasNext()) { fileContents.add(csvRecordIterator.next()); } for (int i = 0; i < expectedFileContents.length; i++) { assertEquals(expectedFileContents[i], fileContents.get(i)); } } }
2,486
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text/csv/CSVLineReaderTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.text.csv; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.crunch.test.TemporaryPath; import org.apache.crunch.test.TemporaryPaths; import org.apache.hadoop.io.Text; import org.junit.Rule; import org.junit.Test; public class CSVLineReaderTest { @Rule public transient TemporaryPath tmpDir = TemporaryPaths.create(); @Test public void testVariousUTF8Characters() throws IOException { final String variousCharacters = "€Abبώиב¥£€¢₡₢₣₤₥₦§₧₨₩₪₫₭₮漢Ä©óíßä"; final String utf8Junk = tmpDir.copyResourceFileName("UTF8.csv"); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(utf8Junk)); final CSVLineReader csvLineReader = new CSVLineReader(fileInputStream); final Text readText = new Text(); csvLineReader.readCSVLine(readText); assertEquals(variousCharacters, readText.toString()); } finally { fileInputStream.close(); } } /** * This is effectively a mirror the address tests, but using Chinese * characters, even for the quotation marks and escape characters. * * @throws IOException */ @Test public void testBrokenLineParsingInChinese() throws IOException { final String[] expectedChineseLines = { "您好我叫马克,我从亚拉巴马州来,我是软件工程师,我二十八岁", "我有一个宠物,它是一个小猫,它六岁,它很漂亮", "我喜欢吃饭,“我觉得这个饭最好\n*蛋糕\n*包子\n*冰淇淋\n*啤酒“,他们都很好,我也很喜欢奶酪但它是不健康的", "我是男的,我的头发很短,我穿蓝色的裤子,“我穿黑色的、“衣服”" }; final String chineseLines = tmpDir.copyResourceFileName("brokenChineseLines.csv"); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(chineseLines)); final CSVLineReader csvLineReader = new CSVLineReader(fileInputStream, CSVLineReader.DEFAULT_BUFFER_SIZE, CSVLineReader.DEFAULT_INPUT_FILE_ENCODING, '“', '”', '、', CSVLineReader.DEFAULT_MAXIMUM_RECORD_SIZE); for (int i = 0; i < expectedChineseLines.length; i++) { final Text readText = new Text(); csvLineReader.readCSVLine(readText); assertEquals(expectedChineseLines[i], readText.toString()); } } finally { fileInputStream.close(); } } @Test(expected = IOException.class) public void testMalformedBrokenLineParsingInChinese() throws IOException { final String[] expectedChineseLines = { "您好我叫马克,我从亚拉巴马州来,我是软件工程师,我二十八岁", "我有一个宠物,它是一个小猫,它六岁,它很漂亮", "我喜欢吃饭,“我觉得这个饭最好\n*蛋糕\n*包子\n*冰淇淋\n*啤酒“,他们都很好,我也很喜欢奶酪但它是不健康的", "我是男的,我的头发很短,我穿蓝色的裤子,“我穿黑色的、“衣服”" }; final String chineseLines = tmpDir.copyResourceFileName("brokenChineseLines.csv"); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(chineseLines)); final CSVLineReader csvLineReader = new CSVLineReader(fileInputStream, CSVLineReader.DEFAULT_BUFFER_SIZE, CSVLineReader.DEFAULT_INPUT_FILE_ENCODING, '“', '”', '、', 5); for (int i = 0; i < expectedChineseLines.length; i++) { final Text readText = new Text(); csvLineReader.readCSVLine(readText); assertEquals(expectedChineseLines[i], readText.toString()); } } finally { fileInputStream.close(); } } }
2,487
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/text/csv/CSVInputFormatTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 org.apache.crunch.io.text.csv; import org.apache.hadoop.conf.Configuration; import org.junit.After; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class CSVInputFormatTest { @Rule public final ExpectedException exception = ExpectedException.none(); private final Configuration configuration = new Configuration(); private final CSVInputFormat csvInputFormat = new CSVInputFormat(); @After public void clearConfiguration() { configuration.clear(); } @Test public void testDefaultConfiguration() { csvInputFormat.setConf(configuration); csvInputFormat.configure(); Assert.assertEquals(CSVLineReader.DEFAULT_BUFFER_SIZE, csvInputFormat.bufferSize); Assert.assertEquals(CSVLineReader.DEFAULT_INPUT_FILE_ENCODING, csvInputFormat.inputFileEncoding); Assert.assertEquals(CSVLineReader.DEFAULT_QUOTE_CHARACTER, csvInputFormat.openQuoteChar); Assert.assertEquals(CSVLineReader.DEFAULT_QUOTE_CHARACTER, csvInputFormat.closeQuoteChar); Assert.assertEquals(CSVLineReader.DEFAULT_ESCAPE_CHARACTER, csvInputFormat.escapeChar); Assert.assertEquals(CSVLineReader.DEFAULT_MAXIMUM_RECORD_SIZE, csvInputFormat.maximumRecordSize); } @Test public void testReasonableConfiguration() { configuration.set(CSVFileSource.CSV_INPUT_FILE_ENCODING, "UTF8"); configuration.set(CSVFileSource.CSV_CLOSE_QUOTE_CHAR, "C"); configuration.set(CSVFileSource.CSV_OPEN_QUOTE_CHAR, "O"); configuration.set(CSVFileSource.CSV_ESCAPE_CHAR, "E"); configuration.setInt(CSVFileSource.CSV_BUFFER_SIZE, 1000); configuration.setInt(CSVFileSource.MAXIMUM_RECORD_SIZE, 10001); csvInputFormat.setConf(configuration); csvInputFormat.configure(); Assert.assertEquals(1000, csvInputFormat.bufferSize); Assert.assertEquals("UTF8", csvInputFormat.inputFileEncoding); Assert.assertEquals('O', csvInputFormat.openQuoteChar); Assert.assertEquals('C', csvInputFormat.closeQuoteChar); Assert.assertEquals('E', csvInputFormat.escapeChar); Assert.assertEquals(10001, csvInputFormat.maximumRecordSize); } @Test public void testMaximumRecordSizeFallbackConfiguration() { configuration.set(CSVFileSource.CSV_INPUT_FILE_ENCODING, "UTF8"); configuration.set(CSVFileSource.CSV_CLOSE_QUOTE_CHAR, "C"); configuration.set(CSVFileSource.CSV_OPEN_QUOTE_CHAR, "O"); configuration.set(CSVFileSource.CSV_ESCAPE_CHAR, "E"); configuration.setInt(CSVFileSource.CSV_BUFFER_SIZE, 1000); configuration.setInt(CSVFileSource.INPUT_SPLIT_SIZE, 10002); csvInputFormat.setConf(configuration); csvInputFormat.configure(); Assert.assertEquals(1000, csvInputFormat.bufferSize); Assert.assertEquals("UTF8", csvInputFormat.inputFileEncoding); Assert.assertEquals('O', csvInputFormat.openQuoteChar); Assert.assertEquals('C', csvInputFormat.closeQuoteChar); Assert.assertEquals('E', csvInputFormat.escapeChar); Assert.assertEquals(10002, csvInputFormat.maximumRecordSize); } }
2,488
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/io/parquet/AvroParquetFileReaderFactoryTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.io.parquet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericRecord; import org.apache.crunch.test.Person; import org.apache.crunch.test.TemporaryPath; import org.apache.crunch.test.TemporaryPaths; import org.apache.crunch.types.avro.AvroType; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.parquet.avro.AvroParquetWriter; public class AvroParquetFileReaderFactoryTest { private File parquetFile; @Rule public transient TemporaryPath tmpDir = TemporaryPaths.create(); @Before public void setUp() throws IOException { parquetFile = tmpDir.getFile("test.avro.parquet"); } @After public void tearDown() { parquetFile.delete(); } private void populateGenericFile(List<GenericRecord> genericRecords, Schema schema) throws IOException { AvroParquetWriter<GenericRecord> writer = new AvroParquetWriter<GenericRecord>( new Path(parquetFile.getPath()), schema); for (GenericRecord record : genericRecords) { writer.write(record); } writer.close(); } private <T> AvroParquetFileReaderFactory<T> createFileReaderFactory(AvroType<T> avroType) { return new AvroParquetFileReaderFactory<T>(avroType); } @Test public void testProjection() throws IOException { String genericSchemaJson = Person.SCHEMA$.toString().replace("Person", "GenericPerson"); Schema genericPersonSchema = new Schema.Parser().parse(genericSchemaJson); GenericRecord savedRecord = new Record(genericPersonSchema); savedRecord.put("name", "John Doe"); savedRecord.put("age", 42); savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane")); populateGenericFile(Lists.newArrayList(savedRecord), genericPersonSchema); Schema projection = Schema.createRecord("projection", null, null, false); projection.setFields(Lists.newArrayList(cloneField(genericPersonSchema.getField("name")))); AvroParquetFileReaderFactory<Record> genericReader = createFileReaderFactory(Avros.generics(projection)); Iterator<Record> recordIterator = genericReader.read(FileSystem.getLocal(new Configuration()), new Path(this.parquetFile.getAbsolutePath())); GenericRecord genericRecord = recordIterator.next(); assertEquals(savedRecord.get("name"), genericRecord.get("name")); assertNull(genericRecord.get("age")); assertFalse(recordIterator.hasNext()); } public static Schema.Field cloneField(Schema.Field field) { return new Schema.Field(field.name(), field.schema(), field.doc(), field.defaultVal()); } }
2,489
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/hadoop/mapreduce/lib
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/hadoop/mapreduce/lib/jobcontrol/CrunchJobControlTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.hadoop.mapreduce.lib.jobcontrol; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.apache.crunch.Pipeline; import org.apache.crunch.PipelineCallable; import org.apache.crunch.Target; import org.apache.crunch.impl.mr.MRJob; import org.apache.crunch.impl.mr.plan.JobNameBuilder; import org.apache.crunch.impl.mr.run.RuntimeParameters; import org.apache.crunch.io.To; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Job; import org.junit.Test; import java.io.IOException; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CrunchJobControlTest { @Test public void testMaxRunningJobs() throws IOException, InterruptedException { Configuration conf = new Configuration(); conf.setInt(RuntimeParameters.MAX_RUNNING_JOBS, 2); CrunchJobControl jobControl = new CrunchJobControl(conf, "group", ImmutableMap.<PipelineCallable<?>, Set<Target>>of()); CrunchControlledJob job1 = createJob(1); CrunchControlledJob job2 = createJob(2); CrunchControlledJob job3 = createJob(3); // Submit job1 and job2. jobControl.addJob(job1); jobControl.addJob(job2); jobControl.pollJobStatusAndStartNewOnes(); verify(job1).submit(); verify(job2).submit(); // Add job3 and expect it is pending. jobControl.addJob(job3); jobControl.pollJobStatusAndStartNewOnes(); verify(job3, never()).submit(); // Expect job3 is submitted after job1 is done. setSuccess(job1); jobControl.pollJobStatusAndStartNewOnes(); verify(job3).submit(); } private static class IncrementingPipelineCallable extends PipelineCallable<Void> { private String name; private boolean executed; public IncrementingPipelineCallable(String name) { this.name = name; } @Override public Status call() { executed = true; return Status.SUCCESS; } public boolean isExecuted() { return executed; } @Override public Void getOutput(Pipeline pipeline) { return null; } } @Test public void testSequentialDo() throws IOException, InterruptedException { Target t1 = To.textFile("foo"); Target t2 = To.textFile("bar"); Target t3 = To.textFile("baz"); IncrementingPipelineCallable first = new IncrementingPipelineCallable("first"); IncrementingPipelineCallable second = new IncrementingPipelineCallable("second"); IncrementingPipelineCallable third = new IncrementingPipelineCallable("third"); CrunchControlledJob job1 = createJob(1, ImmutableSet.of(t1)); CrunchControlledJob job2 = createJob(2, ImmutableSet.of(t2)); CrunchControlledJob job3 = createJob(3, ImmutableSet.of(t3)); Configuration conf = new Configuration(); Map<PipelineCallable<?>, Set<Target>> pipelineCallables = Maps.newHashMap(); pipelineCallables.put(first, ImmutableSet.<Target>of()); pipelineCallables.put(second, ImmutableSet.<Target>of(t1)); pipelineCallables.put(third, ImmutableSet.<Target>of(t2, t3)); CrunchJobControl jobControl = new CrunchJobControl(conf, "group", pipelineCallables); jobControl.addJob(job1); jobControl.addJob(job2); jobControl.addJob(job3); jobControl.pollJobStatusAndStartNewOnes(); verify(job1).submit(); verify(job2).submit(); verify(job3).submit(); assertTrue(first.isExecuted()); setSuccess(job1); jobControl.pollJobStatusAndStartNewOnes(); assertTrue(second.isExecuted()); setSuccess(job2); jobControl.pollJobStatusAndStartNewOnes(); assertFalse(third.isExecuted()); setSuccess(job3); jobControl.pollJobStatusAndStartNewOnes(); assertTrue(third.isExecuted()); } private CrunchControlledJob createJob(int jobID) { return createJob(jobID, ImmutableSet.<Target>of()); } private CrunchControlledJob createJob(int jobID, Set<Target> targets) { Job mrJob = mock(Job.class); when(mrJob.getConfiguration()).thenReturn(new Configuration()); CrunchControlledJob job = new CrunchControlledJob( jobID, mrJob, new JobNameBuilder(mrJob.getConfiguration(), "test", 1, 1), targets, mock(CrunchControlledJob.Hook.class), mock(CrunchControlledJob.Hook.class)); return spy(job); } private void setSuccess(CrunchControlledJob job) throws IOException, InterruptedException { when(job.checkState()).thenReturn(MRJob.State.SUCCESS); when(job.getJobState()).thenReturn(MRJob.State.SUCCESS); } }
2,490
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/AvroIndexedRecordPartitionerTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import static org.junit.Assert.assertEquals; import org.apache.avro.Schema; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapred.AvroValue; import org.apache.crunch.lib.join.JoinUtils.AvroIndexedRecordPartitioner; import org.junit.Before; import org.junit.Test; public class AvroIndexedRecordPartitionerTest { private AvroIndexedRecordPartitioner avroPartitioner; @Before public void setUp() { avroPartitioner = new AvroIndexedRecordPartitioner(); } @Test public void testGetPartition() { IndexedRecord indexedRecord = new MockIndexedRecord(3); AvroKey<IndexedRecord> avroKey = new AvroKey<IndexedRecord>(indexedRecord); assertEquals(3, avroPartitioner.getPartition(avroKey, new AvroValue<Object>(), 5)); assertEquals(1, avroPartitioner.getPartition(avroKey, new AvroValue<Object>(), 2)); } @Test public void testGetPartition_NegativeHashValue() { IndexedRecord indexedRecord = new MockIndexedRecord(-3); AvroKey<IndexedRecord> avroKey = new AvroKey<IndexedRecord>(indexedRecord); assertEquals(1, avroPartitioner.getPartition(avroKey, new AvroValue<Object>(), 5)); assertEquals(1, avroPartitioner.getPartition(avroKey, new AvroValue<Object>(), 2)); } @Test public void testGetPartition_IntegerMinValue() { IndexedRecord indexedRecord = new MockIndexedRecord(Integer.MIN_VALUE); AvroKey<IndexedRecord> avroKey = new AvroKey<IndexedRecord>(indexedRecord); assertEquals(151558288, avroPartitioner.getPartition(avroKey, new AvroValue<Object>(), Integer.MAX_VALUE)); } /** * Mock implementation of IndexedRecord to give us control over the hashCode. */ static class MockIndexedRecord implements IndexedRecord { private Integer value; public MockIndexedRecord(Integer value) { this.value = value; } @Override public int hashCode() { return value.hashCode(); } @Override public Schema getSchema() { throw new UnsupportedOperationException(); } @Override public Object get(int arg0) { return this.value; } @Override public void put(int arg0, Object arg1) { throw new UnsupportedOperationException(); } } }
2,491
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/SecondarySortTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import static org.apache.crunch.types.avro.Avros.*; import static org.junit.Assert.assertEquals; import org.apache.crunch.DoFn; import org.apache.crunch.Emitter; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.MemPipeline; import org.junit.Test; import com.google.common.collect.ImmutableList; public class SecondarySortTest { @Test public void testInMemory() throws Exception { PTable<Long, Pair<Long, String>> input = MemPipeline.typedTableOf(tableOf(longs(), pairs(longs(), strings())), 1729L, Pair.of(17L, "a"), 100L, Pair.of(29L, "b"), 1729L, Pair.of(29L, "c")); PCollection<String> letters = SecondarySort.sortAndApply(input, new StringifyFn(), strings()); assertEquals(ImmutableList.of("b", "ac"), letters.materialize()); } private static class StringifyFn extends DoFn<Pair<Long, Iterable<Pair<Long, String>>>, String> { @Override public void process(Pair<Long, Iterable<Pair<Long, String>>> input, Emitter<String> emitter) { StringBuilder sb = new StringBuilder(); for (Pair<Long, String> p : input.second()) { sb.append(p.second()); } emitter.emit(sb.toString()); } } }
2,492
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/PTablesTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import com.google.common.collect.ImmutableMap; import org.apache.crunch.PTable; import org.apache.crunch.impl.mem.MemPipeline; import org.junit.Test; import java.util.Map; import static org.apache.crunch.types.avro.Avros.longs; import static org.apache.crunch.types.avro.Avros.strings; import static org.apache.crunch.types.avro.Avros.tableOf; import static org.junit.Assert.assertEquals; public class PTablesTest { @Test public void testSwapKeyValue() { PTable<String, Long> table = MemPipeline.typedTableOf(tableOf(strings(), longs()), "hello", 14L, "goodbye", 21L); PTable<Long, String> actual = PTables.swapKeyValue(table); Map<Long, String> expected = ImmutableMap.of(14L, "hello", 21L, "goodbye"); assertEquals(expected, actual.materializeToMap()); } }
2,493
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/CartesianTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.List; import org.apache.crunch.PCollection; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.crunch.types.writable.Writables; import org.junit.Test; import com.google.common.collect.Lists; public class CartesianTest { @Test public void testCartesianCollection_SingleValues() { PCollection<String> letters = MemPipeline.typedCollectionOf(Writables.strings(), "a", "b"); PCollection<Integer> ints = MemPipeline.typedCollectionOf(Writables.ints(), 1, 2); PCollection<Pair<String, Integer>> cartesianProduct = Cartesian.cross(letters, ints); @SuppressWarnings("unchecked") List<Pair<String, Integer>> expectedResults = Lists.newArrayList(Pair.of("a", 1), Pair.of("a", 2), Pair.of("b", 1), Pair.of("b", 2)); List<Pair<String, Integer>> actualResults = Lists.newArrayList(cartesianProduct.materialize()); Collections.sort(actualResults); assertEquals(expectedResults, actualResults); } @Test public void testCartesianCollection_Tables() { PTable<String, Integer> leftTable = MemPipeline.typedTableOf( Writables.tableOf(Writables.strings(), Writables.ints()), "a", 1, "b", 2); PTable<String, Float> rightTable = MemPipeline.typedTableOf( Writables.tableOf(Writables.strings(), Writables.floats()), "A", 1.0f, "B", 2.0f); PTable<Pair<String, String>, Pair<Integer, Float>> cartesianProduct = Cartesian.cross(leftTable, rightTable); List<Pair<Pair<String, String>, Pair<Integer, Float>>> expectedResults = Lists.newArrayList(); expectedResults.add(Pair.of(Pair.of("a", "A"), Pair.of(1, 1.0f))); expectedResults.add(Pair.of(Pair.of("a", "B"), Pair.of(1, 2.0f))); expectedResults.add(Pair.of(Pair.of("b", "A"), Pair.of(2, 1.0f))); expectedResults.add(Pair.of(Pair.of("b", "B"), Pair.of(2, 2.0f))); List<Pair<Pair<String, String>, Pair<Integer, Float>>> actualResults = Lists.newArrayList(cartesianProduct .materialize()); Collections.sort(actualResults); assertEquals(expectedResults, actualResults); } }
2,494
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/QuantilesTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.crunch.lib.Quantiles.Result; import org.junit.Test; import java.util.Map; import static org.apache.crunch.types.avro.Avros.*; import static org.junit.Assert.assertEquals; public class QuantilesTest { private static <T> Quantiles.Result<T> result(long count, Pair<Double, T>... quantiles) { return new Quantiles.Result<T>(count, Lists.newArrayList(quantiles)); } @Test public void testQuantilesExact() { PTable<String, Integer> testTable = MemPipeline.typedTableOf( tableOf(strings(), ints()), "a", 5, "a", 2, "a", 3, "a", 4, "a", 1); Map<String, Result<Integer>> actualS = Quantiles.distributed(testTable, 0, 0.5, 1.0).materializeToMap(); Map<String, Result<Integer>> actualM = Quantiles.inMemory(testTable, 0, 0.5, 1.0).materializeToMap(); Map<String, Result<Integer>> expected = ImmutableMap.of( "a", result(5, Pair.of(0.0, 1), Pair.of(0.5, 3), Pair.of(1.0, 5)) ); assertEquals(expected, actualS); assertEquals(expected, actualM); } @Test public void testQuantilesBetween() { PTable<String, Integer> testTable = MemPipeline.typedTableOf( tableOf(strings(), ints()), "a", 5, "a", 2, // We expect the 0.5 to correspond to this element, according to the "nearest rank" %ile definition. "a", 4, "a", 1); Map<String, Result<Integer>> actualS = Quantiles.distributed(testTable, 0.5).materializeToMap(); Map<String, Result<Integer>> actualM = Quantiles.inMemory(testTable, 0.5).materializeToMap(); Map<String, Result<Integer>> expected = ImmutableMap.of( "a", result(4, Pair.of(0.5, 2)) ); assertEquals(expected, actualS); assertEquals(expected, actualM); } @Test public void testQuantilesNines() { PTable<String, Integer> testTable = MemPipeline.typedTableOf( tableOf(strings(), ints()), "a", 10, "a", 20, "a", 30, "a", 40, "a", 50, "a", 60, "a", 70, "a", 80, "a", 90, "a", 100); Map<String, Result<Integer>> actualS = Quantiles.distributed(testTable, 0.9, 0.99).materializeToMap(); Map<String, Result<Integer>> actualM = Quantiles.inMemory(testTable, 0.9, 0.99).materializeToMap(); Map<String, Result<Integer>> expected = ImmutableMap.of( "a", result(10, Pair.of(0.9, 90), Pair.of(0.99, 100)) ); assertEquals(expected, actualS); assertEquals(expected, actualM); } @Test public void testQuantilesLessThanOrEqual() { PTable<String, Integer> testTable = MemPipeline.typedTableOf( tableOf(strings(), ints()), "a", 10, "a", 20, "a", 30, "a", 40, "a", 50, "a", 60, "a", 70, "a", 80, "a", 90, "a", 100); Map<String, Result<Integer>> actualS = Quantiles.distributed(testTable, 0.5).materializeToMap(); Map<String, Result<Integer>> actualM = Quantiles.inMemory(testTable, 0.5).materializeToMap(); Map<String, Result<Integer>> expected = ImmutableMap.of( "a", result(10, Pair.of(0.5, 50)) ); assertEquals(expected, actualS); assertEquals(expected, actualM); } }
2,495
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/MapredTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.crunch.MapFn; import org.apache.crunch.PTable; import org.apache.crunch.Pair; import org.apache.crunch.types.avro.Avros; import org.apache.crunch.types.writable.Writables; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.junit.Before; import org.junit.Test; public class MapredTest implements Serializable { private static class TestMapper implements Mapper<IntWritable, Text, Text, LongWritable> { @Override public void configure(JobConf arg0) { } @Override public void close() throws IOException { } @Override public void map(IntWritable k, Text v, OutputCollector<Text, LongWritable> out, Reporter reporter) throws IOException { reporter.getCounter("written", "out").increment(1L); out.collect(new Text(v), new LongWritable(v.getLength())); } } private static class TestReducer implements Reducer<IntWritable, Text, Text, LongWritable> { @Override public void configure(JobConf arg0) { } @Override public void close() throws IOException { } @Override public void reduce(IntWritable key, Iterator<Text> iter, OutputCollector<Text, LongWritable> out, Reporter reporter) throws IOException { boolean hasBall = false; String notBall = ""; while (iter.hasNext()) { String next = iter.next().toString(); if ("ball".equals(next)) { reporter.getCounter("foo", "bar").increment(1); hasBall = true; } else { notBall = next; } } out.collect(new Text(notBall), hasBall ? new LongWritable(1L) : new LongWritable(0L)); } } private static Pair<Text, LongWritable> $(String one, int two) { return Pair.of(new Text(one), new LongWritable(two)); } @Before public void setUp() { MemPipeline.clearCounters(); } @Test public void testMapper() throws Exception { PTable<Integer, String> in = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 1, "foot", 2, "ball", 3, "bazzar"); PTable<IntWritable, Text> two = in.parallelDo(new MapFn<Pair<Integer, String>, Pair<IntWritable, Text>>() { @Override public Pair<IntWritable, Text> map(Pair<Integer, String> input) { return Pair.of(new IntWritable(input.first()), new Text(input.second())); } }, Writables.tableOf(Writables.writables(IntWritable.class), Writables.writables(Text.class))); PTable<Text, LongWritable> out = Mapred.map(two, TestMapper.class, Text.class, LongWritable.class); assertEquals(ImmutableList.of($("foot", 4), $("ball", 4), $("bazzar", 6)), Lists.newArrayList(out.materialize())); } @Test public void testReducer() throws Exception { PTable<Integer, String> in = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 1, "foot", 1, "ball", 2, "base", 2, "ball", 3, "basket", 3, "ball", 4, "hockey"); PTable<IntWritable, Text> two = in.parallelDo(new MapFn<Pair<Integer, String>, Pair<IntWritable, Text>>() { @Override public Pair<IntWritable, Text> map(Pair<Integer, String> input) { return Pair.of(new IntWritable(input.first()), new Text(input.second())); } }, Writables.tableOf(Writables.writables(IntWritable.class), Writables.writables(Text.class))); PTable<Text, LongWritable> out = Mapred.reduce(two.groupByKey(), TestReducer.class, Text.class, LongWritable.class); assertEquals(ImmutableList.of($("foot", 1), $("base", 1), $("basket", 1), $("hockey", 0)), Lists.newArrayList(out.materialize())); assertEquals(3, MemPipeline.getCounters().findCounter("foo", "bar").getValue()); } }
2,496
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/DoFnsTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import com.google.common.base.Strings; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Lists; import org.apache.avro.util.Utf8; import org.apache.crunch.DoFn; import org.apache.crunch.MapFn; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.emit.InMemoryEmitter; import org.apache.crunch.test.Employee; import org.apache.crunch.types.avro.Avros; import org.apache.hadoop.conf.Configuration; import org.junit.Test; import java.util.Collection; import java.util.Iterator; import static org.junit.Assert.assertEquals; public class DoFnsTest { private static class AvroIterable implements Iterable<Employee> { @Override public Iterator<Employee> iterator() { final Employee rec = new Employee(new Utf8("something"), 10000, new Utf8("")); return new AbstractIterator<Employee>() { private int n = 0; @Override protected Employee computeNext() { n++; if (n > 3) return endOfData(); rec.setDepartment(new Utf8(Strings.repeat("*", n))); return rec; } }; } } private static class CollectingMapFn extends MapFn<Pair<String, Iterable<Employee>>, Collection<Employee>> { @Override public Collection<Employee> map(Pair<String, Iterable<Employee>> input) { return Lists.newArrayList(input.second()); } } @Test public void testDetach() { Collection<Employee> expected = Lists.newArrayList( new Employee(new Utf8("something"), 10000, new Utf8("*")), new Employee(new Utf8("something"), 10000, new Utf8("**")), new Employee(new Utf8("something"), 10000, new Utf8("***")) ); DoFn<Pair<String, Iterable<Employee>>, Collection<Employee>> doFn = DoFns.detach(new CollectingMapFn(), Avros.specifics(Employee.class)); Pair<String, Iterable<Employee>> input = Pair.of("key", (Iterable<Employee>) new AvroIterable()); InMemoryEmitter<Collection<Employee>> emitter = new InMemoryEmitter<Collection<Employee>>(); doFn.configure(new Configuration()); doFn.initialize(); doFn.process(input, emitter); doFn.cleanup(emitter); assertEquals(expected, emitter.getOutput().get(0)); } }
2,497
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/TupleWritablePartitionerTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import static org.junit.Assert.assertEquals; import org.apache.crunch.lib.join.JoinUtils.TupleWritablePartitioner; import org.apache.crunch.types.writable.TupleWritable; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import org.junit.Before; import org.junit.Test; public class TupleWritablePartitionerTest { private TupleWritablePartitioner tupleWritableParitioner; @Before public void setUp() { tupleWritableParitioner = new TupleWritablePartitioner(); } @Test public void testGetPartition() { IntWritable intWritable = new IntWritable(3); BytesWritable bw = new BytesWritable(WritableUtils.toByteArray(intWritable)); TupleWritable key = new TupleWritable(new Writable[] { bw }); assertEquals(4, tupleWritableParitioner.getPartition(key, NullWritable.get(), 5)); assertEquals(0, tupleWritableParitioner.getPartition(key, NullWritable.get(), 2)); } }
2,498
0
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/SortTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.crunch.lib; import com.google.common.collect.ImmutableList; import org.apache.crunch.PCollection; import org.apache.crunch.Pair; import org.apache.crunch.impl.mem.MemPipeline; import org.junit.Test; import static org.apache.crunch.types.avro.Avros.longs; import static org.apache.crunch.types.avro.Avros.pairs; import static org.apache.crunch.types.avro.Avros.strings; import static org.junit.Assert.assertEquals; public class SortTest { @Test public void testInMemoryReverseAvro() throws Exception { PCollection<Pair<String, Long>> pc = MemPipeline.typedCollectionOf(pairs(strings(), longs()), Pair.of("a", 1L), Pair.of("c", 7L), Pair.of("b", 10L)); PCollection<Pair<String, Long>> sorted = Sort.sortPairs(pc, Sort.ColumnOrder.by(2, Sort.Order.DESCENDING)); assertEquals(ImmutableList.of(Pair.of("b", 10L), Pair.of("c", 7L), Pair.of("a", 1L)), ImmutableList.copyOf(sorted.materialize())); } }
2,499