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-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/SampleTest.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.List;
import java.util.Map;
import org.apache.crunch.PCollection;
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.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
public class SampleTest {
private PCollection<Pair<String, Double>> values = MemPipeline.typedCollectionOf(
Writables.pairs(Writables.strings(), Writables.doubles()),
ImmutableList.of(
Pair.of("foo", 200.0),
Pair.of("bar", 400.0),
Pair.of("baz", 100.0),
Pair.of("biz", 100.0)));
@Test
public void testWRS() throws Exception {
Map<String, Integer> histogram = Maps.newHashMap();
for (int i = 0; i < 100; i++) {
PCollection<String> sample = Sample.weightedReservoirSample(values, 1, 1729L + i);
for (String s : sample.materialize()) {
if (!histogram.containsKey(s)) {
histogram.put(s, 1);
} else {
histogram.put(s, 1 + histogram.get(s));
}
}
}
Map<String, Integer> expected = ImmutableMap.of(
"foo", 24, "bar", 51, "baz", 13, "biz", 12);
assertEquals(expected, histogram);
}
@Test
public void testSample() {
PCollection<Integer> pcollect = MemPipeline.collectionOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Iterable<Integer> sample = Sample.sample(pcollect, 123998L, 0.2).materialize();
List<Integer> sampleValues = ImmutableList.copyOf(sample);
assertEquals(ImmutableList.of(6, 7), sampleValues);
}
}
| 2,500 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/ChannelsTest.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 static org.junit.Assert.assertTrue;
import java.util.Collection;
import org.apache.crunch.PCollection;
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.ImmutableList;
public class ChannelsTest {
/**
* Test that non-null values in a PCollection<Pair<>> are split properly into
* a Pair<PCollection<>,PCollection<>>
*/
@Test
public void split() {
// Test that any combination of values and nulls are handled properly
final PCollection<Pair<String, String>> pCollection = MemPipeline.typedCollectionOf(
Writables.pairs(Writables.strings(), Writables.strings()),
ImmutableList.of(Pair.of("One", (String) null), Pair.of((String) null, "Two"), Pair.of("Three", "Four"),
Pair.of((String) null, (String) null)));
final Pair<PCollection<String>, PCollection<String>> splitPCollection = Channels.split(pCollection);
final Collection<String> firstCollection = splitPCollection.first().asCollection().getValue();
assertEquals(2, firstCollection.size());
assertTrue(firstCollection.contains("One"));
assertTrue(firstCollection.contains("Three"));
final Collection<String> secondCollection = splitPCollection.second().asCollection().getValue();
assertEquals(2, secondCollection.size());
assertTrue(secondCollection.contains("Two"));
assertTrue(secondCollection.contains("Four"));
}
}
| 2,501 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/DistinctTest.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.Arrays;
import java.util.List;
import org.apache.crunch.PCollection;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.types.avro.Avros;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
public class DistinctTest {
private static final List<Integer> DATA = Arrays.asList(
17, 29, 17, 29, 17, 29, 36, 45, 17, 45, 36, 29
);
@Test
public void testDistinct() {
PCollection<Integer> input = MemPipeline.typedCollectionOf(Avros.ints(), DATA);
Iterable<Integer> unique = Distinct.distinct(input).materialize();
assertEquals(ImmutableSet.copyOf(DATA), ImmutableSet.copyOf(unique));
}
@Test
public void testDistinctFlush() {
PCollection<Integer> input = MemPipeline.typedCollectionOf(Avros.ints(), DATA);
Iterable<Integer> unique = Distinct.distinct(input, 2).materialize();
assertEquals(ImmutableSet.copyOf(DATA), ImmutableSet.copyOf(unique));
}
}
| 2,502 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/TopListTest.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.PCollection;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mem.MemPipeline;
import org.junit.Test;
import java.util.Collection;
import java.util.Map;
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 TopListTest {
private <T> Collection<T> collectionOf(T... elements) {
return Lists.newArrayList(elements);
}
@Test
public void testTopNYbyX() {
PTable<String, String> data = MemPipeline.typedTableOf(tableOf(strings(), strings()),
"a", "x",
"a", "x",
"a", "x",
"a", "y",
"a", "y",
"a", "z",
"b", "x",
"b", "x",
"b", "z");
Map<String, Collection<Pair<Long, String>>> actual = TopList.topNYbyX(data, 2).materializeToMap();
Map<String, Collection<Pair<Long, String>>> expected = ImmutableMap.of(
"a", collectionOf(Pair.of(3L, "x"), Pair.of(2L, "y")),
"b", collectionOf(Pair.of(2L, "x"), Pair.of(1L, "z")));
assertEquals(expected, actual);
}
@Test
public void testGlobalToplist() {
PCollection<String> data = MemPipeline.typedCollectionOf(strings(), "a", "a", "a", "b", "b", "c", "c", "c", "c");
Map<String, Long> actual = TopList.globalToplist(data).materializeToMap();
Map<String, Long> expected = ImmutableMap.of("c", 4L, "a", 3L, "b", 2L);
assertEquals(expected, actual);
}
}
| 2,503 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/AverageTest.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.*;
import static org.junit.Assert.assertEquals;
public class AverageTest {
@Test
public void testMeanValue() {
PTable<String, Integer> testTable = MemPipeline.typedTableOf(
tableOf(strings(), ints()),
"a", 2,
"a", 10,
"b", 3,
"c", 3,
"c", 4,
"c", 5);
Map<String, Double> actual = Average.meanValue(testTable).materializeToMap();
Map<String, Double> expected = ImmutableMap.of(
"a", 6.0,
"b", 3.0,
"c", 4.0
);
assertEquals(expected, actual);
}
}
| 2,504 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/MapreduceTest.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.MapFn;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class MapreduceTest {
private static class TestMapper extends Mapper<IntWritable, Text, IntWritable, Text> {
@Override
protected void map(IntWritable k, Text v, Mapper<IntWritable, Text, IntWritable, Text>.Context ctxt) {
try {
ctxt.write(new IntWritable(v.getLength()), v);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static class TestReducer extends Reducer<IntWritable, Text, Text, LongWritable> {
protected void reduce(IntWritable key, Iterable<Text> values,
org.apache.hadoop.mapreduce.Reducer<IntWritable, Text, Text, LongWritable>.Context ctxt) {
boolean hasBall = false;
String notBall = "";
for (Text t : values) {
String next = t.toString();
if ("ball".equals(next)) {
hasBall = true;
ctxt.getCounter("foo", "bar").increment(1);
} else {
notBall = next;
}
}
try {
ctxt.write(new Text(notBall), hasBall ? new LongWritable(1L) : new LongWritable(0L));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static Pair<Text, LongWritable> $1(String one, int two) {
return Pair.of(new Text(one), new LongWritable(two));
}
private static Pair<IntWritable, Text> $2(int one, String two) {
return Pair.of(new IntWritable(one), new Text(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<IntWritable, Text> out = Mapreduce.map(two, TestMapper.class, IntWritable.class, Text.class);
assertEquals(ImmutableList.of($2(4, "foot"), $2(4, "ball"), $2(6, "bazzar")),
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 = Mapreduce.reduce(two.groupByKey(), TestReducer.class, Text.class, LongWritable.class);
assertEquals(ImmutableList.of($1("foot", 1), $1("base", 1), $1("basket", 1), $1("hockey", 0)),
Lists.newArrayList(out.materialize()));
assertEquals(3, MemPipeline.getCounters().findCounter("foo", "bar").getValue());
}
}
| 2,505 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/JoinFnTestBase.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.join;
import static org.mockito.Mockito.mock;
import java.util.List;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.test.StringWrapper;
import org.apache.hadoop.conf.Configuration;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Lists;
public abstract class JoinFnTestBase {
private JoinFn<StringWrapper, StringWrapper, String> joinFn;
private Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter;
// Avoid warnings on generic Emitter mock
@SuppressWarnings("unchecked")
@Before
public void setUp() {
joinFn = getJoinFn();
joinFn.setContext(CrunchTestSupport.getTestContext(new Configuration()));
joinFn.initialize();
emitter = mock(Emitter.class);
}
@Test
public void testJoin() {
StringWrapper key = new StringWrapper();
StringWrapper leftValue = new StringWrapper();
key.setValue("left-only");
leftValue.setValue("left-only-left");
joinFn.join(key, 0, createValuePairList(leftValue, null), emitter);
key.setValue("both");
leftValue.setValue("both-left");
joinFn.join(key, 0, createValuePairList(leftValue, null), emitter);
joinFn.join(key, 1, createValuePairList(null, "both-right"), emitter);
key.setValue("right-only");
joinFn.join(key, 1, createValuePairList(null, "right-only-right"), emitter);
checkOutput(emitter);
}
protected abstract void checkOutput(Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter);
protected abstract JoinFn<StringWrapper, StringWrapper, String> getJoinFn();
protected List<Pair<StringWrapper, String>> createValuePairList(StringWrapper leftValue, String rightValue) {
Pair<StringWrapper, String> valuePair = Pair.of(leftValue, rightValue);
List<Pair<StringWrapper, String>> valuePairList = Lists.newArrayList();
valuePairList.add(valuePair);
return valuePairList;
}
}
| 2,506 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/BrokenLeftAndOuterJoinTest.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.join;
import static org.apache.crunch.test.StringWrapper.wrap;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.apache.crunch.test.CrunchTestSupport;
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.Lists;
public class BrokenLeftAndOuterJoinTest {
List<Pair<StringWrapper, String>> createValuePairList(StringWrapper leftValue, String rightValue) {
Pair<StringWrapper, String> valuePair = Pair.of(leftValue, rightValue);
List<Pair<StringWrapper, String>> valuePairList = Lists.newArrayList();
valuePairList.add(valuePair);
return valuePairList;
}
@Test
public void testOuterJoin() {
JoinFn<StringWrapper, StringWrapper, String> joinFn = new LeftOuterJoinFn<StringWrapper, StringWrapper, String>(
Avros.reflects(StringWrapper.class),
Avros.reflects(StringWrapper.class));
joinFn.setContext(CrunchTestSupport.getTestContext(new Configuration()));
joinFn.initialize();
Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter = mock(Emitter.class);
StringWrapper key = new StringWrapper();
StringWrapper leftValue = new StringWrapper();
key.setValue("left-only");
leftValue.setValue("left-only-left");
joinFn.join(key, 0, createValuePairList(leftValue, null), emitter);
key.setValue("right-only");
joinFn.join(key, 1, createValuePairList(null, "right-only-right"), emitter);
verify(emitter).emit(Pair.of(wrap("left-only"), Pair.of(wrap("left-only-left"), (String) null)));
verifyNoMoreInteractions(emitter);
}
@Test
public void testFullJoin() {
JoinFn<StringWrapper, StringWrapper, String> joinFn = new FullOuterJoinFn<StringWrapper, StringWrapper, String>(
Avros.reflects(StringWrapper.class),
Avros.reflects(StringWrapper.class));
joinFn.setContext(CrunchTestSupport.getTestContext(new Configuration()));
joinFn.initialize();
Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter = mock(Emitter.class);
StringWrapper key = new StringWrapper();
StringWrapper leftValue = new StringWrapper();
key.setValue("left-only");
leftValue.setValue("left-only-left");
joinFn.join(key, 0, createValuePairList(leftValue, null), emitter);
key.setValue("right-only");
joinFn.join(key, 1, createValuePairList(null, "right-only-right"), emitter);
verify(emitter).emit(Pair.of(wrap("left-only"), Pair.of(wrap("left-only-left"), (String) null)));
verify(emitter).emit(Pair.of(wrap("right-only"), Pair.of((StringWrapper)null, "right-only-right")));
verifyNoMoreInteractions(emitter);
}
}
| 2,507 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/RightOuterJoinFnTest.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.join;
import static org.apache.crunch.test.StringWrapper.wrap;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.types.avro.Avros;
public class RightOuterJoinFnTest extends JoinFnTestBase {
@Override
protected void checkOutput(Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter) {
verify(emitter).emit(Pair.of(wrap("both"), Pair.of(wrap("both-left"), "both-right")));
verify(emitter).emit(
Pair.of(wrap("right-only"), Pair.of((StringWrapper) null, "right-only-right")));
verifyNoMoreInteractions(emitter);
}
@Override
protected JoinFn<StringWrapper, StringWrapper, String> getJoinFn() {
return new RightOuterJoinFn<StringWrapper, StringWrapper, String>(
Avros.reflects(StringWrapper.class),
Avros.reflects(StringWrapper.class));
}
}
| 2,508 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/OneToManyJoinTest.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.join;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.apache.crunch.MapFn;
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.avro.Avros;
import org.junit.Test;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class OneToManyJoinTest {
@Test
public void testOneToMany() {
PTable<Integer, String> left = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()),
1, "one", 2, "two");
PTable<Integer, String> right = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()),
1, "1A", 1, "1B", 2, "2A", 2, "2B");
PCollection<Pair<String, String>> joined = OneToManyJoin.oneToManyJoin(left, right, new StringJoinFn(),
Avros.pairs(Avros.strings(), Avros.strings()));
List<Pair<String, String>> expected = ImmutableList.of(Pair.of("one", "1A,1B"), Pair.of("two", "2A,2B"));
assertEquals(expected, Lists.newArrayList(joined.materialize()));
}
@Test
public void testOneToMany_UnmatchedOnRightSide() {
PTable<Integer, String> left = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 1, "one", 2,
"two");
PTable<Integer, String> right = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 2, "2A", 2, "2B");
PCollection<Pair<String, String>> joined = OneToManyJoin.oneToManyJoin(left, right, new StringJoinFn(),
Avros.pairs(Avros.strings(), Avros.strings()));
List<Pair<String, String>> expected = ImmutableList.of(Pair.of("two", "2A,2B"));
assertEquals(expected, Lists.newArrayList(joined.materialize()));
}
@Test
public void testOneToMany_UnmatchedLeftSide() {
PTable<Integer, String> left = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 2, "two");
PTable<Integer, String> right = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 1, "1A", 1,
"1B", 2, "2A", 2, "2B");
PCollection<Pair<String, String>> joined = OneToManyJoin.oneToManyJoin(left, right, new StringJoinFn(),
Avros.pairs(Avros.strings(), Avros.strings()));
List<Pair<String, String>> expected = ImmutableList.of(Pair.of("two", "2A,2B"));
assertEquals(expected, Lists.newArrayList(joined.materialize()));
}
@Test
public void testOneToMany_MultipleValuesForSameKeyOnLeft() {
PTable<Integer, String> left = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()),
1, "one", 2, "two", 1, "oneExtra");
PTable<Integer, String> right = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()),
1, "1A", 1, "1B", 2, "2A", 2, "2B");
PCollection<Pair<String, String>> joined = OneToManyJoin.oneToManyJoin(left, right, new StringJoinFn(),
Avros.pairs(Avros.strings(), Avros.strings()));
List<Pair<String, String>> expected = ImmutableList.of(Pair.of("one", "1A,1B"), Pair.of("two", "2A,2B"));
assertEquals(expected, Lists.newArrayList(joined.materialize()));
}
static class StringJoinFn extends MapFn<Pair<String, Iterable<String>>, Pair<String, String>> {
@Override
public Pair<String, String> map(Pair<String, Iterable<String>> input) {
increment("counters", "inputcount");
return Pair.of(input.first(), Joiner.on(',').join(input.second()));
}
}
}
| 2,509 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/LeftOuterJoinTest.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.join;
import static org.apache.crunch.test.StringWrapper.wrap;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.types.avro.Avros;
public class LeftOuterJoinTest extends JoinFnTestBase {
@Override
protected void checkOutput(Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> emitter) {
verify(emitter)
.emit(Pair.of(wrap("left-only"), Pair.of(wrap("left-only-left"), (String) null)));
verify(emitter).emit(Pair.of(wrap("both"), Pair.of(wrap("both-left"), "both-right")));
verifyNoMoreInteractions(emitter);
}
@Override
protected JoinFn<StringWrapper, StringWrapper, String> getJoinFn() {
return new LeftOuterJoinFn<StringWrapper, StringWrapper, String>(
Avros.reflects(StringWrapper.class),
Avros.reflects(StringWrapper.class));
}
}
| 2,510 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/lib/join/InnerJoinFnTest.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.join;
import static org.apache.crunch.test.StringWrapper.wrap;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.types.avro.Avros;
public class InnerJoinFnTest extends JoinFnTestBase {
protected void checkOutput(Emitter<Pair<StringWrapper, Pair<StringWrapper, String>>> joinEmitter) {
verify(joinEmitter).emit(Pair.of(wrap("both"), Pair.of(wrap("both-left"), "both-right")));
verifyNoMoreInteractions(joinEmitter);
}
@Override
protected JoinFn<StringWrapper, StringWrapper, String> getJoinFn() {
return new InnerJoinFn<StringWrapper, StringWrapper, String>(
Avros.reflects(StringWrapper.class),
Avros.reflects(StringWrapper.class));
}
}
| 2,511 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/FilterFnTest.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.fn;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.apache.crunch.FilterFn;
import org.junit.Test;
import com.google.common.base.Predicates;
public class FilterFnTest {
private static final FilterFn<String> TRUE = FilterFns.<String>ACCEPT_ALL();
private static final FilterFn<String> FALSE = FilterFns.<String>REJECT_ALL();
@Test
public void testAcceptAll() {
assertThat(TRUE.accept(""), is(true));
assertThat(TRUE.accept("foo"), is(true));
}
@Test
public void testRejectAll() {
assertThat(FALSE.accept(""), is(false));
assertThat(FALSE.accept("foo"), is(false));
Predicates.or(Predicates.alwaysFalse(), Predicates.alwaysTrue());
}
@Test
public void testAnd() {
assertThat(FilterFns.and(TRUE, TRUE).accept("foo"), is(true));
assertThat(FilterFns.and(TRUE, FALSE).accept("foo"), is(false));
}
@Test
@SuppressWarnings("unchecked")
public void testGeneric() {
assertThat(FilterFns.and(TRUE).accept("foo"), is(true));
assertThat(FilterFns.and(FALSE).accept("foo"), is(false));
assertThat(FilterFns.and(FALSE, FALSE, FALSE).accept("foo"), is(false));
assertThat(FilterFns.and(TRUE, TRUE, FALSE).accept("foo"), is(false));
assertThat(FilterFns.and(FALSE, FALSE, FALSE, FALSE).accept("foo"), is(false));
}
@Test
public void testOr() {
assertThat(FilterFns.or(FALSE, TRUE).accept("foo"), is(true));
assertThat(FilterFns.or(TRUE, FALSE).accept("foo"), is(true));
}
@Test
@SuppressWarnings("unchecked")
public void testOrGeneric() {
assertThat(FilterFns.or(TRUE).accept("foo"), is(true));
assertThat(FilterFns.or(FALSE).accept("foo"), is(false));
assertThat(FilterFns.or(TRUE, FALSE, TRUE).accept("foo"), is(true));
assertThat(FilterFns.or(FALSE, FALSE, TRUE).accept("foo"), is(true));
assertThat(FilterFns.or(FALSE, FALSE, FALSE).accept("foo"), is(false));
}
@Test
public void testNot() {
assertThat(FilterFns.not(TRUE).accept("foo"), is(false));
assertThat(FilterFns.not(FALSE).accept("foo"), is(true));
}
}
| 2,512 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/NotFnTest.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.fn;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.crunch.Emitter;
import org.apache.crunch.FilterFn;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import org.junit.Before;
import org.junit.Test;
public class NotFnTest {
private FilterFn<Integer> base;
private FilterFn<Integer> notFn;
@Before
public void setUp() {
base = mock(FilterFn.class);
notFn = FilterFns.not(base);
}
@Test
public void testSetContext() {
TaskInputOutputContext<?, ?, ?, ?> context = mock(TaskInputOutputContext.class);
notFn.setContext(context);
verify(base).setContext(context);
}
@Test
public void testAccept_True() {
when(base.accept(1)).thenReturn(true);
assertFalse(notFn.accept(1));
}
@Test
public void testAccept_False() {
when(base.accept(1)).thenReturn(false);
assertTrue(notFn.accept(1));
}
@Test
public void testCleanupEmitterOfT() {
notFn.cleanup(mock(Emitter.class));
verify(base).cleanup();
}
}
| 2,513 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/ExtractKeyFnTest.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.fn;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.Iterables;
import org.apache.crunch.MapFn;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mem.emit.InMemoryEmitter;
import org.junit.Test;
@SuppressWarnings("serial")
public class ExtractKeyFnTest {
protected static final MapFn<String, Integer> mapFn = new MapFn<String, Integer>() {
@Override
public Integer map(String input) {
return input.hashCode();
}
};
protected static final ExtractKeyFn<Integer, String> one = new ExtractKeyFn<Integer, String>(mapFn);
@Test
public void test() {
InMemoryEmitter<Pair<Integer, String>> emitter = InMemoryEmitter.create();
one.process("boza", emitter);
assertEquals(Pair.of("boza".hashCode(), "boza"), Iterables.getOnlyElement(emitter.getOutput()));
}
}
| 2,514 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/PairMapTest.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.fn;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Iterables;
import org.apache.crunch.MapFn;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mem.emit.InMemoryEmitter;
import org.junit.Test;
@SuppressWarnings("serial")
public class PairMapTest {
static final MapFn<String, Integer> one = new MapFn<String, Integer>() {
@Override
public Integer map(String input) {
return 1;
}
};
static final MapFn<String, Integer> two = new MapFn<String, Integer>() {
@Override
public Integer map(String input) {
return 2;
}
};
@Test
public void testPairMap() {
InMemoryEmitter<Pair<Integer, Integer>> emitter = InMemoryEmitter.create();
PairMapFn<String, String, Integer, Integer> fn = new PairMapFn<String, String, Integer, Integer>(one, two);
fn.process(Pair.of("a", "b"), emitter);
Pair<Integer, Integer> pair = Iterables.getOnlyElement(emitter.getOutput());
assertTrue(pair.first() == 1);
assertTrue(pair.second() == 2);
}
}
| 2,515 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/OrFnTest.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.fn;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.crunch.Emitter;
import org.apache.crunch.FilterFn;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import org.junit.Before;
import org.junit.Test;
public class OrFnTest {
private FilterFn<Integer> fnA;
private FilterFn<Integer> fnB;
private FilterFn<Integer> orFn;
@Before
public void setUp() {
fnA = mock(FilterFn.class);
fnB = mock(FilterFn.class);
orFn = FilterFns.or(fnA, fnB);
}
@Test
public void testSetContext() {
TaskInputOutputContext<?, ?, ?, ?> context = mock(TaskInputOutputContext.class);
orFn.setContext(context);
verify(fnA).setContext(context);
verify(fnB).setContext(context);
}
@Test
public void testAccept_True() {
when(fnA.accept(1)).thenReturn(false);
when(fnB.accept(1)).thenReturn(true);
assertTrue(orFn.accept(1));
}
@Test
public void testAccept_False() {
when(fnA.accept(1)).thenReturn(false);
when(fnB.accept(1)).thenReturn(false);
assertFalse(orFn.accept(1));
}
@Test
public void testCleanupEmitterOfT() {
orFn.cleanup(mock(Emitter.class));
verify(fnA).cleanup();
verify(fnB).cleanup();
}
}
| 2,516 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/AggregatorsTest.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.fn;
import static org.apache.crunch.fn.Aggregators.*;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import org.apache.crunch.Aggregator;
import org.apache.crunch.CombineFn;
import org.apache.crunch.Pair;
import org.apache.crunch.Tuple3;
import org.apache.crunch.Tuple4;
import org.apache.crunch.TupleN;
import org.apache.crunch.impl.mem.emit.InMemoryEmitter;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
public class AggregatorsTest {
@Test
public void testSums2() {
assertThat(sapply(SUM_INTS(), 1, 2, 3, -4), is(2));
assertThat(sapply(SUM_LONGS(), 1L, 2L, 3L, -4L, 5000000000L), is(5000000002L));
assertThat(sapply(SUM_FLOATS(), 1f, 2f, 3f, -4f), is(2f));
assertThat(sapply(SUM_DOUBLES(), 0.1, 0.2, 0.3), is(closeTo(0.6, 0.00001)));
assertThat(sapply(SUM_BIGINTS(), bigInt("7"), bigInt("3")), is(bigInt("10")));
assertThat(sapply(SUM_BIGDECIMALS(), bigDecimal("1.122"), bigDecimal("0.654")), is(bigDecimal("1.776")));
}
@Test
public void testSums() {
assertThat(sapply(SUM_LONGS(), 29L, 17L, 1729L), is(1775L));
assertThat(sapply(SUM_LONGS(), 29L, 7L, 1729L), is(1765L));
assertThat(sapply(SUM_INTS(), 29, 17, 1729), is(1775));
assertThat(sapply(SUM_FLOATS(), 29f, 17f, 1729f), is(1775.0f));
assertThat(sapply(SUM_DOUBLES(), 29.0, 17.0, 1729.0), is(1775.0));
assertThat(sapply(SUM_BIGINTS(), bigInt("29"), bigInt("17"), bigInt("1729")), is(bigInt("1775")));
assertThat(sapply(SUM_BIGDECIMALS(), bigDecimal("29.987"), bigDecimal("17.876"), bigDecimal("1729.876")), is(bigDecimal("1777.739")));
}
@Test
public void testMax() {
assertThat(sapply(MAX_LONGS(), 29L, 17L, 1729L), is(1729L));
assertThat(sapply(MAX_INTS(), 29, 17, 1729), is(1729));
assertThat(sapply(MAX_FLOATS(), 29f, 17f, 1729f), is(1729.0f));
assertThat(sapply(MAX_DOUBLES(), 29.0, 17.0, 1729.0), is(1729.0));
assertThat(sapply(MAX_FLOATS(), 29f, 1745f, 17f, 1729f), is(1745.0f));
assertThat(sapply(MAX_BIGINTS(), bigInt("29"), bigInt("17"), bigInt("1729")), is(bigInt("1729")));
assertThat(sapply(MAX_BIGDECIMALS(), bigDecimal("29.987"), bigDecimal("17.876"), bigDecimal("1729.876")), is(bigDecimal("1729.876")));
assertThat(sapply(Aggregators.<String>MAX_COMPARABLES(), "b", "a", "d", "c"), is("d"));
}
@Test
public void testMin() {
assertThat(sapply(MIN_LONGS(), 29L, 17L, 1729L), is(17L));
assertThat(sapply(MIN_INTS(), 29, 17, 1729), is(17));
assertThat(sapply(MIN_FLOATS(), 29f, 17f, 1729f), is(17.0f));
assertThat(sapply(MIN_DOUBLES(), 29.0, 17.0, 1729.0), is(17.0));
assertThat(sapply(MIN_INTS(), 29, 170, 1729), is(29));
assertThat(sapply(MIN_BIGINTS(), bigInt("29"), bigInt("17"), bigInt("1729")), is(bigInt("17")));
assertThat(sapply(MIN_BIGDECIMALS(), bigDecimal("29.987"), bigDecimal("17.876"), bigDecimal("1729.876")), is(bigDecimal("17.876")));
assertThat(sapply(Aggregators.<String>MIN_COMPARABLES(), "b", "a", "d", "c"), is("a"));
}
@Test
public void testMaxN() {
assertThat(apply(MAX_INTS(2), 17, 34, 98, 29, 1009), is(ImmutableList.of(98, 1009)));
assertThat(apply(MAX_N(1, String.class), "b", "a"), is(ImmutableList.of("b")));
assertThat(apply(MAX_N(3, String.class), "b", "a", "d", "c"), is(ImmutableList.of("b", "c", "d")));
assertThat(apply(MAX_N(2, Integer.class), 1, 2, 3, 3), is(ImmutableList.of(3, 3)));
}
@Test
public void testMaxUniqueN() {
assertThat(apply(MAX_UNIQUE_N(2, Integer.class), 1, 2, 3, 3), is(ImmutableList.of(2, 3)));
}
@Test
public void testMinN() {
assertThat(apply(MIN_INTS(2), 17, 34, 98, 29, 1009), is(ImmutableList.of(17, 29)));
assertThat(apply(MIN_N(1, String.class), "b", "a"), is(ImmutableList.of("a")));
assertThat(apply(MIN_N(3, String.class), "b", "a", "d", "c"), is(ImmutableList.of("a", "b", "c")));
assertThat(apply(MIN_N(2, Integer.class), 1, 1, 2, 3), is(ImmutableList.of(1, 1)));
}
@Test
public void testMinUniqueN() {
assertThat(apply(MIN_UNIQUE_N(2, Integer.class), 3, 2, 1, 1), is(ImmutableList.of(1, 2)));
}
@Test
public void testFirstN() {
assertThat(apply(Aggregators.<Integer>FIRST_N(2), 17, 34, 98, 29, 1009), is(ImmutableList.of(17, 34)));
}
@Test
public void testLastN() {
assertThat(apply(Aggregators.<Integer>LAST_N(2), 17, 34, 98, 29, 1009), is(ImmutableList.of(29, 1009)));
}
@Test
public void testUniqueElements() {
assertThat(ImmutableSet.copyOf(apply(Aggregators.<Integer>UNIQUE_ELEMENTS(), 17, 29, 29, 16, 17)),
is(ImmutableSet.of(17, 29, 16)));
Iterable<Integer> samp = apply(Aggregators.<Integer>SAMPLE_UNIQUE_ELEMENTS(2), 17, 29, 16, 17, 29, 16);
assertThat(Iterables.size(samp), is(2));
assertThat(ImmutableSet.copyOf(samp).size(), is(2)); // check that the two elements are unique
}
@Test
public void testPairs() {
List<Pair<Long, Double>> input = ImmutableList.of(Pair.of(1720L, 17.29), Pair.of(9L, -3.14));
Aggregator<Pair<Long, Double>> a = Aggregators.pairAggregator(SUM_LONGS(), MIN_DOUBLES());
assertThat(sapply(a, input), is(Pair.of(1729L, -3.14)));
}
@Test
public void testPairsTwoLongs() {
List<Pair<Long, Long>> input = ImmutableList.of(Pair.of(1720L, 1L), Pair.of(9L, 19L));
Aggregator<Pair<Long, Long>> a = Aggregators.pairAggregator(SUM_LONGS(), SUM_LONGS());
assertThat(sapply(a, input), is(Pair.of(1729L, 20L)));
}
@Test
public void testTrips() {
List<Tuple3<Float, Double, Double>> input = ImmutableList.of(Tuple3.of(17.29f, 12.2, 0.1),
Tuple3.of(3.0f, 1.2, 3.14), Tuple3.of(-1.0f, 14.5, -0.98));
Aggregator<Tuple3<Float, Double, Double>> a = Aggregators.tripAggregator(
MAX_FLOATS(), MAX_DOUBLES(), MIN_DOUBLES());
List<Tuple3<Float, BigDecimal, BigDecimal>> input1 = ImmutableList.of(Tuple3.of(17.29f, bigDecimal("12.2"), bigDecimal("0.1")),
Tuple3.of(3.0f, bigDecimal("1.2"), bigDecimal("3.14")), Tuple3.of(-1.0f, bigDecimal("14.5"), bigDecimal("-0.98")));
Aggregator<Tuple3<Float, BigDecimal, BigDecimal>> b = Aggregators.tripAggregator(
MAX_FLOATS(), MAX_BIGDECIMALS(), MIN_BIGDECIMALS());
assertThat(sapply(a, input), is(Tuple3.of(17.29f, 14.5, -0.98)));
assertThat(sapply(b, input1), is(Tuple3.of(17.29f, bigDecimal("14.5"), bigDecimal("-0.98"))));
}
@Test
public void testQuads() {
List<Tuple4<Float, Double, Double, Integer>> input = ImmutableList.of(Tuple4.of(17.29f, 12.2, 0.1, 1),
Tuple4.of(3.0f, 1.2, 3.14, 2), Tuple4.of(-1.0f, 14.5, -0.98, 3));
Aggregator<Tuple4<Float, Double, Double, Integer>> a = Aggregators.quadAggregator(
MAX_FLOATS(), MAX_DOUBLES(), MIN_DOUBLES(), SUM_INTS());
List<Tuple4<BigDecimal, Double, Double, Integer>> input1 = ImmutableList.of(Tuple4.of(bigDecimal("17.29"), 12.2, 0.1, 1),
Tuple4.of(bigDecimal("3.0"), 1.2, 3.14, 2), Tuple4.of(bigDecimal("-1.0"), 14.5, -0.98, 3));
Aggregator<Tuple4<BigDecimal, Double, Double, Integer>> b = Aggregators.quadAggregator(
MAX_BIGDECIMALS(), MAX_DOUBLES(), MIN_DOUBLES(), SUM_INTS());
assertThat(sapply(a, input), is(Tuple4.of(17.29f, 14.5, -0.98, 6)));
assertThat(sapply(b, input1), is(Tuple4.of(bigDecimal("17.29"), 14.5, -0.98, 6)));
}
@Test
public void testTupleN() {
List<TupleN> input = ImmutableList.of(new TupleN(1, 3.0, 1, 2.0, 4L), new TupleN(4, 17.0, 1, 9.7, 12L));
Aggregator<TupleN> a = Aggregators.tupleAggregator(
MIN_INTS(), SUM_DOUBLES(), MAX_INTS(), MIN_DOUBLES(), MAX_LONGS());
assertThat(sapply(a, input), is(new TupleN(1, 20.0, 1, 2.0, 12L)));
}
@Test
public void testConcatenation() {
assertThat(sapply(STRING_CONCAT("", true), "foo", "foobar", "bar"), is("foofoobarbar"));
assertThat(sapply(STRING_CONCAT("/", false), "foo", "foobar", "bar"), is("foo/foobar/bar"));
assertThat(sapply(STRING_CONCAT(" ", true), " ", ""), is(" "));
assertThat(sapply(STRING_CONCAT(" ", true), Arrays.asList(null, "")), is(""));
assertThat(sapply(STRING_CONCAT(" ", true, 20, 3), "foo", "foobar", "bar"), is("foo bar"));
assertThat(sapply(STRING_CONCAT(" ", true, 10, 6), "foo", "foobar", "bar"), is("foo foobar"));
assertThat(sapply(STRING_CONCAT(" ", true, 9, 6), "foo", "foobar", "bar"), is("foo bar"));
}
@Test(expected = NullPointerException.class)
public void testConcatenationNullException() {
sapply(STRING_CONCAT(" ", false), Arrays.asList(null, "" ));
}
private static <T> T sapply(Aggregator<T> a, T... values) {
return sapply(a, ImmutableList.copyOf(values));
}
private static <T> T sapply(Aggregator<T> a, Iterable<T> values) {
return Iterables.getOnlyElement(apply(a, values));
}
private static <T> ImmutableList<T> apply(Aggregator<T> a, T... values) {
return apply(a, ImmutableList.copyOf(values));
}
private static <T> ImmutableList<T> apply(Aggregator<T> a, Iterable<T> values) {
CombineFn<String, T> fn = Aggregators.toCombineFn(a);
InMemoryEmitter<Pair<String, T>> e1 = new InMemoryEmitter<Pair<String,T>>();
fn.process(Pair.of("", values), e1);
// and a second time to make sure Aggregator.reset() works
InMemoryEmitter<Pair<String, T>> e2 = new InMemoryEmitter<Pair<String,T>>();
fn.process(Pair.of("", values), e2);
assertEquals(getValues(e1), getValues(e2));
return getValues(e1);
}
private static <K, V> ImmutableList<V> getValues(InMemoryEmitter<Pair<K, V>> emitter) {
return ImmutableList.copyOf(
Iterables.transform(emitter.getOutput(), new Function<Pair<K, V>, V>() {
@Override
public V apply(Pair<K, V> input) {
return input.second();
}
}));
}
private static BigInteger bigInt(String value) {
return new BigInteger(value);
}
private static BigDecimal bigDecimal(String value) {
return new BigDecimal(value);
}
}
| 2,517 |
0 |
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/test/java/org/apache/crunch/fn/AndFnTest.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.fn;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.crunch.Emitter;
import org.apache.crunch.FilterFn;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import org.junit.Before;
import org.junit.Test;
public class AndFnTest {
private FilterFn<Integer> fnA;
private FilterFn<Integer> fnB;
private FilterFn<Integer> andFn;
@Before
public void setUp() {
fnA = mock(FilterFn.class);
fnB = mock(FilterFn.class);
andFn = FilterFns.and(fnA, fnB);
}
@Test
public void testSetContext() {
TaskInputOutputContext<?, ?, ?, ?> context = mock(TaskInputOutputContext.class);
andFn.setContext(context);
verify(fnA).setContext(context);
verify(fnB).setContext(context);
}
@Test
public void testAccept_False() {
when(fnA.accept(1)).thenReturn(true);
when(fnB.accept(1)).thenReturn(false);
assertFalse(andFn.accept(1));
}
@Test
public void testAccept_True() {
when(fnA.accept(1)).thenReturn(true);
when(fnB.accept(1)).thenReturn(true);
assertTrue(andFn.accept(1));
}
@Test
public void testCleanup() {
andFn.cleanup(mock(Emitter.class));
verify(fnA).cleanup();
verify(fnB).cleanup();
}
}
| 2,518 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/LongPipelinePlannerIT.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.apache.crunch.types.avro.Avros.*;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.MaterializableIterable;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
import java.util.Locale;
/**
* Verifies that complex plans execute dependent jobs in the correct sequence.
*/
public class LongPipelinePlannerIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMR() throws Exception {
run(new MRPipeline(LongPipelinePlannerIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("shakes.txt"),
tmpDir.getFileName("output"));
}
public static void run(Pipeline p, String input, String output) {
PCollection<String> in = p.readTextFile(input);
PCollection<String> toLower = in.parallelDo("tolower", new DoFn<String, String>() {
@Override
public void process(String input, Emitter<String> emitter) {
emitter.emit(input.toLowerCase(Locale.ENGLISH));
}
}, strings());
PTable<Integer, String> keyedLower = toLower.parallelDo("keyed", new MapFn<String, Pair<Integer, String>>() {
@Override
public Pair<Integer, String> map(String input) {
return Pair.of(input.length(), input);
}
}, tableOf(ints(), strings())).groupByKey().ungroup();
PCollection<String> iso = keyedLower.groupByKey().parallelDo("iso", new DoFn<Pair<Integer, Iterable<String>>, String>() {
@Override
public void process(Pair<Integer, Iterable<String>> input, Emitter<String> emitter) {
for (String s : input.second()) {
emitter.emit(s);
}
}
}, strings());
ReadableData<String> isoRD = iso.asReadable(true);
ParallelDoOptions.Builder builder = ParallelDoOptions.builder().sourceTargets(isoRD.getSourceTargets());
PTable<Integer, String> splitMap = keyedLower.parallelDo("split-map",
new MapFn<Pair<Integer, String>, Pair<Integer, String>>() {
@Override
public Pair<Integer, String> map(Pair<Integer, String> input) {
return input;
}
}, tableOf(ints(), strings()), builder.build());
PTable<Integer, String> splitReduce = splitMap.groupByKey().parallelDo("split-reduce",
new DoFn<Pair<Integer, Iterable<String>>, Pair<Integer, String>>() {
@Override
public void process(Pair<Integer, Iterable<String>> input,
Emitter<Pair<Integer, String>> emitter) {
emitter.emit(Pair.of(input.first(), input.second().iterator().next()));
}
}, tableOf(ints(), strings()));
PTable<Integer, String> splitReduceResetKeys = splitReduce.parallelDo("reset",
new MapFn<Pair<Integer, String>, Pair<Integer, String>>() {
@Override
public Pair<Integer, String> map(Pair<Integer, String> input) {
return Pair.of(input.first() - 1, input.second());
}
}, tableOf(ints(), strings()));
PTable<Integer, String> intersections = splitReduceResetKeys.groupByKey().ungroup();
PCollection<String> merged = intersections.values();
PCollection<String> upper = merged.parallelDo("toupper", new MapFn<String, String>() {
@Override
public String map(String input) {
return input.toUpperCase(Locale.ENGLISH);
}
}, strings());
p.writeTextFile(upper, output);
p.done();
}
}
| 2,519 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CleanTextIT.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 java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.crunch.hadoop.mapreduce.lib.jobcontrol.CrunchControlledJob;
import org.apache.crunch.impl.mr.MRJob;
import org.apache.crunch.impl.mr.MRPipeline;
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.junit.Rule;
import org.junit.Test;
import com.google.common.io.Files;
/**
*
*/
public class CleanTextIT {
private static final int LINES_IN_SHAKES = 3285;
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
static DoFn<String, String> CLEANER = new DoFn<String, String>() {
@Override
public void process(String input, Emitter<String> emitter) {
emitter.emit(input.toLowerCase());
}
};
static DoFn<String, String> SPLIT = new DoFn<String, String>() {
@Override
public void process(String input, Emitter<String> emitter) {
for (String word : input.split("\\S+")) {
if (!word.isEmpty()) {
emitter.emit(word);
}
}
}
};
@Test
public void testMapSideOutputs() throws Exception {
MRPipeline pipeline = new MRPipeline(CleanTextIT.class, tmpDir.getDefaultConfiguration());
JobHook prepareOne = new JobHook();
JobHook prepareTwo = new JobHook();
JobHook completed = new JobHook();
pipeline.addPrepareHook(prepareOne).addPrepareHook(prepareTwo).addCompletionHook(completed);
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
PCollection<String> cleanShakes = shakespeare.parallelDo(CLEANER, Avros.strings());
File cso = tmpDir.getFile("cleanShakes");
cleanShakes.write(To.textFile(cso.getAbsolutePath()));
File wc = tmpDir.getFile("wordCounts");
cleanShakes.parallelDo(SPLIT, Avros.strings()).count().write(To.textFile(wc.getAbsolutePath()));
pipeline.done();
File cleanFile = new File(cso, "part-m-00000");
List<String> lines = Files.readLines(cleanFile, Charset.defaultCharset());
assertEquals(LINES_IN_SHAKES, lines.size());
assertEquals(1, prepareOne.called);
assertEquals(1, prepareTwo.called);
assertEquals(1, completed.called);
}
static class JobHook implements CrunchControlledJob.Hook {
int called = 0;
@Override
public void run(MRJob job) throws IOException {
called++;
}
}
}
| 2,520 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MapsIT.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.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.Map;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
public class MapsIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritables() throws Exception {
run(WritableTypeFamily.getInstance(), tmpDir);
}
@Test
public void testAvros() throws Exception {
run(AvroTypeFamily.getInstance(), tmpDir);
}
public static void run(PTypeFamily typeFamily, TemporaryPath tmpDir) throws Exception {
Pipeline pipeline = new MRPipeline(MapsIT.class, tmpDir.getDefaultConfiguration());
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
Iterable<Pair<String, Map<String, Long>>> output = shakespeare
.parallelDo(new DoFn<String, Pair<String, Map<String, Long>>>() {
@Override
public void process(String input, Emitter<Pair<String, Map<String, Long>>> emitter) {
String last = null;
for (String word : input.toLowerCase().split("\\W+")) {
if (!word.isEmpty()) {
String firstChar = word.substring(0, 1);
if (last != null) {
Map<String, Long> cc = ImmutableMap.of(firstChar, 1L);
emitter.emit(Pair.of(last, cc));
}
last = firstChar;
}
}
}
}, typeFamily.tableOf(typeFamily.strings(), typeFamily.maps(typeFamily.longs()))).groupByKey()
.combineValues(new CombineFn<String, Map<String, Long>>() {
@Override
public void process(Pair<String, Iterable<Map<String, Long>>> input,
Emitter<Pair<String, Map<String, Long>>> emitter) {
Map<String, Long> agg = Maps.newHashMap();
for (Map<String, Long> in : input.second()) {
for (Map.Entry<String, Long> e : in.entrySet()) {
if (!agg.containsKey(e.getKey())) {
agg.put(e.getKey(), e.getValue());
} else {
agg.put(e.getKey(), e.getValue() + agg.get(e.getKey()));
}
}
}
emitter.emit(Pair.of(input.first(), agg));
}
}).materialize();
boolean passed = false;
for (Pair<String, Map<String, Long>> v : output) {
if (v.first().equals("k") && v.second().get("n") == 8L) {
passed = true;
break;
}
}
pipeline.done();
assertThat(passed, is(true));
}
}
| 2,521 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MapPObjectIT.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 java.io.IOException;
import java.util.Map;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.pobject.MapPObject;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class MapPObjectIT {
static final ImmutableList<Pair<Integer, String>> kvPairs = ImmutableList.of(Pair.of(0, "a"), Pair.of(1, "b"),
Pair.of(2, "c"), Pair.of(3, "e"));
public void assertMatches(Map<Integer, String> m) {
for (Map.Entry<Integer, String> e : m.entrySet()) {
assertEquals(kvPairs.get(e.getKey()).second(), e.getValue());
}
}
private static class Set1Mapper extends MapFn<String, Pair<Integer, String>> {
@Override
public Pair<Integer, String> map(String input) {
int k = -1;
if (input.equals("a"))
k = 0;
else if (input.equals("b"))
k = 1;
else if (input.equals("c"))
k = 2;
else if (input.equals("e"))
k = 3;
return Pair.of(k, input);
}
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMemMapPObject() {
PTable<Integer, String> table = MemPipeline.tableOf(kvPairs);
PObject<Map<Integer, String>> map = new MapPObject<Integer, String>(table);
assertMatches(map.getValue());
}
@Test
public void testMemAsMap() {
PTable<Integer, String> table = MemPipeline.tableOf(kvPairs);
assertMatches(table.asMap().getValue());
}
private PTable<Integer, String> getMRPTable() throws IOException {
Pipeline p = new MRPipeline(MaterializeToMapIT.class, tmpDir.getDefaultConfiguration());
String inputFile = tmpDir.copyResourceFileName("set1.txt");
PCollection<String> c = p.readTextFile(inputFile);
PTypeFamily tf = c.getTypeFamily();
PTable<Integer, String> table = c.parallelDo(new Set1Mapper(), tf.tableOf(tf.ints(),
tf.strings()));
return table;
}
@Test
public void testMRMapPObject() throws IOException {
PTable<Integer, String> table = getMRPTable();
PObject<Map<Integer, String>> map = new MapPObject<Integer, String>(table);
assertMatches(map.getValue());
}
@Test
public void testMRAsMap() throws IOException {
PTable<Integer, String> table = getMRPTable();
assertMatches(table.asMap().getValue());
}
}
| 2,522 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/WordCountIT.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 java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.apache.crunch.fn.Aggregators;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.To;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.PTypes;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.mapred.ShuffleConsumerPlugin;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class WordCountIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
enum WordCountStats {
ANDS
}
public static PTable<String, Long> wordCount(PCollection<String> words, PTypeFamily typeFamily) {
return Aggregate.count(words.parallelDo(new DoFn<String, String>() {
@Override
public void process(String input, Emitter<String> emitter) {
List<String> words = Arrays.asList(input.split("\\s+"));
for (String word : words) {
if ("and".equals(word)) {
increment(WordCountStats.ANDS);
}
emitter.emit(word);
}
}
}, typeFamily.strings()));
}
public static PTable<String, Long> substr(PTable<String, Long> ptable) {
return ptable.parallelDo(new DoFn<Pair<String, Long>, Pair<String, Long>>() {
@Override
public void process(Pair<String, Long> input, Emitter<Pair<String, Long>> emitter) {
if (!input.first().isEmpty()) {
emitter.emit(Pair.of(input.first().substring(0, 1), input.second()));
}
}
}, ptable.getPTableType());
}
public static PTable<String, BigDecimal> convDecimal(PCollection<String> ptable) {
return ptable.parallelDo(new DoFn<String, Pair<String, BigDecimal>>() {
@Override
public void process(String input, Emitter<Pair<String, BigDecimal>> emitter) {
emitter.emit(Pair.of(input.split("~")[0], new BigDecimal(input.split("~")[1])));
}
}, Writables.tableOf(Writables.strings(), PTypes.bigDecimal(WritableTypeFamily.getInstance())));
}
private boolean runSecond = false;
private boolean useToOutput = false;
private boolean testBigDecimal = false;
@Test
public void testWritables() throws IOException {
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testWritablesWithSecond() throws IOException {
runSecond = true;
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testWritablesWithSecondUseToOutput() throws IOException {
runSecond = true;
useToOutput = true;
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testWritablesForBigDecimal() throws IOException {
runSecond = false;
useToOutput = true;
testBigDecimal = true;
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testAvro() throws IOException {
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
@Test
public void testAvroWithSecond() throws IOException {
runSecond = true;
run(new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
@Test
public void testWithTopWritable() throws IOException {
runWithTop(WritableTypeFamily.getInstance());
}
@Test
public void testWithTopAvro() throws IOException {
runWithTop(AvroTypeFamily.getInstance());
}
public void runWithTop(PTypeFamily tf) throws IOException {
Pipeline pipeline = new MRPipeline(WordCountIT.class, tmpDir.getDefaultConfiguration());
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.read(At.textFile(inputPath, tf.strings()));
PTable<String, Long> wordCount = wordCount(shakespeare, tf);
List<Pair<String, Long>> top5 = Lists.newArrayList(Aggregate.top(wordCount, 5, true).materialize());
assertEquals(
ImmutableList.of(Pair.of("", 1345L), Pair.of("the", 528L), Pair.of("and", 375L), Pair.of("I", 314L),
Pair.of("of", 314L)), top5);
}
public void run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
String outputPath = tmpDir.getFileName("output");
PCollection<String> shakespeare = pipeline.read(At.textFile(inputPath, typeFamily.strings()));
PTable<String, Long> wordCount = wordCount(shakespeare, typeFamily);
if (useToOutput) {
wordCount.write(To.textFile(outputPath));
} else {
pipeline.writeTextFile(wordCount, outputPath);
}
if (runSecond) {
String substrPath = tmpDir.getFileName("substr");
PTable<String, Long> we = substr(wordCount).groupByKey().combineValues(Aggregators.SUM_LONGS());
pipeline.writeTextFile(we, substrPath);
}
PTable<String, BigDecimal> bd = null;
if (testBigDecimal) {
String decimalInputPath = tmpDir.copyResourceFileName("bigdecimal.txt");
PCollection<String> testBd = pipeline.read(At.textFile(decimalInputPath, typeFamily.strings()));
bd = convDecimal(testBd).groupByKey().combineValues(Aggregators.SUM_BIGDECIMALS());
}
PipelineResult res = pipeline.done();
assertTrue(res.succeeded());
List<PipelineResult.StageResult> stageResults = res.getStageResults();
if (testBigDecimal) {
assertEquals(1, stageResults.size());
assertEquals(
ImmutableList.of(Pair.of("A", bigDecimal("3.579")), Pair.of("B", bigDecimal("11.579")),
Pair.of("C", bigDecimal("15.642"))), Lists.newArrayList(bd.materialize()));
} else if (runSecond) {
assertEquals(2, stageResults.size());
} else {
assertEquals(1, stageResults.size());
assertEquals(375, stageResults.get(0).getCounterValue(WordCountStats.ANDS));
}
File outputFile = new File(outputPath, "part-r-00000");
List<String> lines = Files.readLines(outputFile, Charset.defaultCharset());
boolean passed = false;
for (String line : lines) {
if (line.startsWith("Macbeth\t") || line.startsWith("[Macbeth,")) {
passed = true;
break;
}
}
assertTrue(passed);
}
private static BigDecimal bigDecimal(String value) {
return new BigDecimal(value);
}
}
| 2,523 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/BreakpointIT.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 org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.exec.MRExecutor;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BreakpointIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testNoBreakpoint() throws Exception {
run(new MRPipeline(BreakpointIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("shakes.txt"),
tmpDir.getFileName("out1"),
tmpDir.getFileName("out2"),
false);
}
@Test
public void testBreakpoint() throws Exception {
run(new MRPipeline(BreakpointIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("shakes.txt"),
tmpDir.getFileName("out1"),
tmpDir.getFileName("out2"),
true);
}
public static void run(MRPipeline pipeline, String input, String out1, String out2, boolean breakpoint)
throws Exception {
// Read a line from a file to get a PCollection.
PCollection<String> pCol1 = pipeline.read(From.textFile(input));
// Create a PTable from PCollection
PTable<String, Integer> pTable1 = pCol1.parallelDo(new DoFn<String, Pair<String, Integer>>() {
@Override
public void process(final String s, final Emitter<Pair<String, Integer>> emitter) {
for (int i = 0; i < 10; i++) {
emitter.emit(new Pair<String, Integer>(s, i));
}
}
}, Writables.tableOf(Writables.strings(), Writables.ints()));
// Do a groupByKey
PGroupedTable<String, Integer> pGrpTable1 = pTable1.groupByKey();
// Select from PGroupedTable
PTable<String, Integer> selectFromPTable1 = pGrpTable1.parallelDo(
new DoFn<Pair<String, Iterable<Integer>>, Pair<String, Integer>>() {
@Override
public void process(final Pair<String, Iterable<Integer>> input,
final Emitter<Pair<String, Integer>> emitter) {
emitter.emit(new Pair<String, Integer>(input.first(), input.second().iterator().next()));
}
}, Writables.tableOf(Writables.strings(), Writables.ints()));
// Process selectFromPTable1 once
final PTable<String, String> pTable2 = selectFromPTable1.parallelDo(new DoFn<Pair<String, Integer>, Pair<String, String>>() {
@Override
public void process(final Pair<String, Integer> input, final Emitter<Pair<String, String>> emitter) {
final Integer newInt = input.second() + 5;
increment("job", "table2");
emitter.emit(new Pair<String, String>(newInt.toString(), input.first()));
}
}, Writables.tableOf(Writables.strings(), Writables.strings()));
// Process selectFromPTable1 once more
PTable<String, String> pTable3 = selectFromPTable1.parallelDo(new DoFn<Pair<String, Integer>, Pair<String, String>>() {
@Override
public void process(final Pair<String, Integer> input, final Emitter<Pair<String, String>> emitter) {
final Integer newInt = input.second() + 10;
increment("job", "table3");
emitter.emit(new Pair<String, String>(newInt.toString(), input.first()));
}
}, Writables.tableOf(Writables.strings(), Writables.strings()));
// Union pTable2 and pTable3 and set a breakpoint
PTable<String, String> pTable4 = pTable2.union(pTable3);
if (breakpoint) {
pTable4.materialize();
}
// Write keys
pTable4.keys().write(To.textFile(out1));
// Group values
final PGroupedTable<String, String> pGrpTable3 = pTable4.groupByKey();
// Write values
pGrpTable3.ungroup().write(To.textFile(out2));
MRExecutor exec = pipeline.plan();
// Count the number of map processing steps in this pipeline
int mapsCount = 0;
for (String line : exec.getPlanDotFile().split("\n")) {
if (line.contains(" subgraph ") && line.contains("-map\" {")) {
mapsCount++;
}
}
assertEquals(breakpoint ? 1 : 2, mapsCount);
}
}
| 2,524 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/PCollectionGetSizeIT.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 com.google.common.collect.Lists.newArrayList;
import static org.apache.crunch.io.At.sequenceFile;
import static org.apache.crunch.io.At.textFile;
import static org.apache.crunch.types.writable.Writables.strings;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.apache.crunch.fn.FilterFns;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
public class PCollectionGetSizeIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
private String emptyInputPath;
private String nonEmptyInputPath;
private String outputPath;
@Before
public void setUp() throws IOException {
emptyInputPath = tmpDir.copyResourceFileName("emptyTextFile.txt");
nonEmptyInputPath = tmpDir.copyResourceFileName("set1.txt");
outputPath = tmpDir.getFileName("output");
}
@Test
public void testGetSizeOfEmptyInput_MRPipeline() throws IOException {
testCollectionGetSizeOfEmptyInput(new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration()));
}
@Test
public void testGetSizeOfEmptyInput_MemPipeline() throws IOException {
testCollectionGetSizeOfEmptyInput(MemPipeline.getInstance());
}
private void testCollectionGetSizeOfEmptyInput(Pipeline pipeline) throws IOException {
assertThat(pipeline.read(textFile(emptyInputPath)).getSize(), is(0L));
}
@Test
public void testMaterializeEmptyInput_MRPipeline() throws IOException {
testMaterializeEmptyInput(new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration()));
}
@Test
public void testMaterializeEmptyImput_MemPipeline() throws IOException {
testMaterializeEmptyInput(MemPipeline.getInstance());
}
private void testMaterializeEmptyInput(Pipeline pipeline) throws IOException {
assertThat(newArrayList(pipeline.readTextFile(emptyInputPath).materialize().iterator()).size(), is(0));
}
@Test
public void testGetSizeOfEmptyIntermediatePCollection_MRPipeline() throws IOException {
PCollection<String> emptyIntermediate = createPesistentEmptyIntermediate(
new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration()));
assertThat(emptyIntermediate.getSize(), is(0L));
}
@Test
@Ignore("GetSize of a DoCollection is only an estimate based on scale factor, so we can't count on it being reported as 0")
public void testGetSizeOfEmptyIntermediatePCollection_NoSave_MRPipeline() throws IOException {
PCollection<String> data = new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration())
.readTextFile(nonEmptyInputPath);
PCollection<String> emptyPCollection = data.filter(FilterFns.<String>REJECT_ALL());
assertThat(emptyPCollection.getSize(), is(0L));
}
@Test
public void testGetSizeOfEmptyIntermediatePCollection_MemPipeline() {
PCollection<String> emptyIntermediate = createPesistentEmptyIntermediate(MemPipeline.getInstance());
assertThat(emptyIntermediate.getSize(), is(0L));
}
@Test
public void testMaterializeOfEmptyIntermediatePCollection_MRPipeline() throws IOException {
PCollection<String> emptyIntermediate = createPesistentEmptyIntermediate(
new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration()));
assertThat(newArrayList(emptyIntermediate.materialize()).size(), is(0));
}
@Test
public void testMaterializeOfEmptyIntermediatePCollection_MemPipeline() {
PCollection<String> emptyIntermediate = createPesistentEmptyIntermediate(MemPipeline.getInstance());
assertThat(newArrayList(emptyIntermediate.materialize()).size(), is(0));
}
private PCollection<String> createPesistentEmptyIntermediate(Pipeline pipeline) {
PCollection<String> data = pipeline.readTextFile(nonEmptyInputPath);
PCollection<String> emptyPCollection = data.filter(FilterFns.<String>REJECT_ALL());
emptyPCollection.write(sequenceFile(outputPath, strings()));
pipeline.run();
return pipeline.read(sequenceFile(outputPath, strings()));
}
@Test(expected = IllegalStateException.class)
public void testExpectExceptionForGettingSizeOfNonExistingFile_MRPipeline() throws IOException {
new MRPipeline(this.getClass(), tmpDir.getDefaultConfiguration()).readTextFile("non_existing.file").getSize();
}
@Test(expected = IllegalStateException.class)
public void testExpectExceptionForGettingSizeOfNonExistingFile_MemPipeline() {
MemPipeline.getInstance().readTextFile("non_existing.file").getSize();
}
}
| 2,525 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MaterializeIT.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 java.io.IOException;
import java.util.List;
import com.google.common.collect.Iterables;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.MaterializableIterable;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class MaterializeIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMaterializeInput_Writables() throws IOException {
runMaterializeInput(new MRPipeline(MaterializeIT.class, tmpDir.getDefaultConfiguration()),
WritableTypeFamily.getInstance());
}
@Test
public void testMaterializeInput_Avro() throws IOException {
runMaterializeInput(new MRPipeline(MaterializeIT.class, tmpDir.getDefaultConfiguration()),
AvroTypeFamily.getInstance());
}
@Test
public void testMaterializeInput_InMemoryWritables() throws IOException {
runMaterializeInput(MemPipeline.getInstance(), WritableTypeFamily.getInstance());
}
@Test
public void testMaterializeInput_InMemoryAvro() throws IOException {
runMaterializeInput(MemPipeline.getInstance(), AvroTypeFamily.getInstance());
}
@Test
public void testMaterializeEmptyIntermediate() throws IOException {
runMaterializeEmptyIntermediate(
new MRPipeline(MaterializeIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testMaterializeEmptyIntermediate_InMemory() throws IOException {
runMaterializeEmptyIntermediate(MemPipeline.getInstance());
}
@Test(expected = CrunchRuntimeException.class)
public void testMaterializeFailure() throws IOException {
runMaterializeWithFailure(
new MRPipeline(MaterializeIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testMaterializeNoFailure() throws IOException {
Configuration conf = tmpDir.getDefaultConfiguration();
conf.setBoolean("crunch.empty.materialize.on.failure", true);
runMaterializeWithFailure(new MRPipeline(MaterializeIT.class, conf));
}
public void runMaterializeInput(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
List<String> expectedContent = Lists.newArrayList("b", "c", "a", "e");
String inputPath = tmpDir.copyResourceFileName("set1.txt");
PCollection<String> lines = pipeline.readTextFile(inputPath);
assertEquals(expectedContent, Lists.newArrayList(lines.materialize()));
pipeline.done();
}
public void runMaterializeEmptyIntermediate(Pipeline pipeline)
throws IOException {
String inputPath = tmpDir.copyResourceFileName("set1.txt");
PCollection<String> empty = pipeline.readTextFile(inputPath).filter(new FilterAll<String>(false));
assertTrue(Iterables.isEmpty(empty.materialize()));
pipeline.done();
}
public void runMaterializeWithFailure(Pipeline pipeline) throws IOException {
String inputPath = tmpDir.copyResourceFileName("set1.txt");
PCollection<String> empty = pipeline.readTextFile(inputPath).filter(new FilterAll<String>(true));
empty.materialize().iterator();
pipeline.done();
}
static class FilterAll<T> extends FilterFn<T> {
private final boolean throwException;
public FilterAll(boolean throwException) {
this.throwException = throwException;
}
@Override
public boolean accept(T input) {
if (throwException) {
throw new RuntimeException("This is an exception");
}
return false;
}
}
static class StringToStringWrapperPersonPairMapFn extends MapFn<String, Pair<StringWrapper, Person>> {
@Override
public Pair<StringWrapper, Person> map(String input) {
Person person = new Person();
person.name = input;
person.age = 42;
person.siblingnames = Lists.<CharSequence> newArrayList();
return Pair.of(new StringWrapper(input), person);
}
}
@Test
public void testMaterializeAvroPersonAndReflectsPair_GroupedTable() throws IOException {
Assume.assumeTrue(Avros.CAN_COMBINE_SPECIFIC_AND_REFLECT_SCHEMAS);
Pipeline pipeline = new MRPipeline(MaterializeIT.class);
MaterializableIterable<Pair<StringWrapper, Person>> mi = (MaterializableIterable) pipeline
.readTextFile(tmpDir.copyResourceFileName("set1.txt"))
.parallelDo(new StringToStringWrapperPersonPairMapFn(),
Avros.pairs(Avros.reflects(StringWrapper.class), Avros.records(Person.class)))
.materialize();
// We just need to make sure this doesn't crash
assertEquals(4, Iterables.size(mi));
assertTrue(mi.getPipelineResult().succeeded());
}
}
| 2,526 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/ExternalFilesystemIT.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.apache.hadoop.hdfs.MiniDFSCluster.HDFS_MINIDFS_BASEDIR;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.io.IOUtils;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSCluster.Builder;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
/**
* Tests reading and writing from a FileSystem for which the Configuration is separate from the Pipeline's
* Configuration.
*/
public class ExternalFilesystemIT {
@ClassRule
public static TemporaryPath tmpDir1 = TemporaryPaths.create();
@ClassRule
public static TemporaryPath tmpDir2 = TemporaryPaths.create();
@ClassRule
public static TemporaryPath tmpDir3 = TemporaryPaths.create();
private static FileSystem dfsCluster1;
private static FileSystem dfsCluster2;
private static FileSystem defaultFs;
private static Collection<MiniDFSCluster> miniDFSClusters = new ArrayList<>();
@BeforeClass
public static void setup() throws Exception {
dfsCluster1 = createHaMiniClusterFs("cluster1", tmpDir1);
dfsCluster2 = createHaMiniClusterFs("cluster2", tmpDir2);
defaultFs = createHaMiniClusterFs("default", tmpDir3);
}
@AfterClass
public static void teardown() throws IOException {
dfsCluster1.close();
dfsCluster2.close();
defaultFs.close();
for (MiniDFSCluster miniDFSCluster : miniDFSClusters) {
miniDFSCluster.shutdown();
}
}
@Test
public void testReadWrite() throws Exception {
// write a test file outside crunch
Path path = new Path("hdfs://cluster1/input.txt");
String testString = "Hello world!";
try (PrintWriter printWriter = new PrintWriter(dfsCluster1.create(path, true))) {
printWriter.println(testString);
}
// assert it can be read back using a Pipeline with config that doesn't know the FileSystem
Iterable<String> strings = new MRPipeline(getClass(), minimalConfiguration())
.read(From.textFile(path).fileSystem(dfsCluster1)).materialize();
Assert.assertEquals(testString, concatStrings(strings));
// write output with crunch using a Pipeline with config that doesn't know the FileSystem
MRPipeline pipeline = new MRPipeline(getClass(), minimalConfiguration());
PCollection<String> input = pipeline.read(From.textFile("hdfs://cluster1/input.txt").fileSystem(dfsCluster1));
pipeline.write(input, To.textFile("hdfs://cluster2/output").fileSystem(dfsCluster2));
pipeline.run();
// assert the output was written correctly
try (FSDataInputStream inputStream = dfsCluster2.open(new Path("hdfs://cluster2/output/part-m-00000"))) {
String readValue = IOUtils.toString(inputStream).trim();
Assert.assertEquals(testString, readValue);
}
// make sure the clusters aren't getting mixed up
Assert.assertFalse(dfsCluster1.exists(new Path("/output")));
}
/**
* Tests that multiple calls to fileSystem() on Source, Target, or SourceTarget results in
* IllegalStateException
*/
@Test
public void testResetFileSystem() {
Source<String> source = From.textFile("/data").fileSystem(defaultFs);
try {
source.fileSystem(dfsCluster1);
Assert.fail("Expected an IllegalStateException");
} catch (IllegalStateException e) { }
Target target = To.textFile("/data").fileSystem(defaultFs);
try {
target.fileSystem(dfsCluster1);
Assert.fail("Expected an IllegalStateException");
} catch (IllegalStateException e) { }
SourceTarget<String> sourceTarget = target.asSourceTarget(source.getType());
try {
sourceTarget.fileSystem(dfsCluster1);
Assert.fail("Expected an IllegalStateException");
} catch (IllegalStateException e) { }
}
/**
* Tests when supplied Filesystem is not in agreement with Path. For example, Path is "hdfs://cluster1/data"
* but FileSystem is hdfs://cluster2.
*/
@Test
public void testWrongFs() {
Source<String> source = From.textFile("hdfs://cluster1/data");
try {
source.fileSystem(dfsCluster2);
Assert.fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
Target target = To.textFile("hdfs://cluster1/data");
try {
target.fileSystem(dfsCluster2);
Assert.fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
SourceTarget<String> sourceTarget = target.asSourceTarget(source.getType());
try {
sourceTarget.fileSystem(dfsCluster2);
Assert.fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
}
private static String concatStrings(Iterable<String> strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
/**
* Creates a minimal configuration pointing to an HA HDFS default filesystem to ensure
* that configuration for external filesystems used in Sources and Targets doesn't mess up
* dfs.nameservices on the Pipeline, which could cause the default filesystem to become
* unresolveable.
*
* @return a minimal configuration with an HDFS HA default fs
*/
private static Configuration minimalConfiguration() {
Configuration minimalConfiguration = new Configuration(false);
minimalConfiguration.addResource(defaultFs.getConf());
minimalConfiguration.set("fs.defaultFS", "hdfs://default");
// exposes bugs hidden by filesystem cache
minimalConfiguration.set("fs.hdfs.impl.disable.cache", "true");
return minimalConfiguration;
}
private static Configuration getDfsConf(String nsName, MiniDFSCluster cluster) {
Configuration conf = new Configuration(false);
conf.set("dfs.nameservices", nsName);
conf.set("dfs.client.failover.proxy.provider." + nsName,
"org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
conf.set("dfs.ha.namenodes." + nsName, "nn1");
conf.set("dfs.namenode.rpc-address." + nsName + ".nn1", "localhost:" + cluster.getNameNodePort());
return conf;
}
private static FileSystem createHaMiniClusterFs(String clusterName, TemporaryPath temporaryPath)
throws IOException {
Configuration conf = new Configuration();
conf.set(HDFS_MINIDFS_BASEDIR, temporaryPath.getRootFileName());
MiniDFSCluster cluster = new Builder(conf).build();
miniDFSClusters.add(cluster);
return FileSystem.get(URI.create("hdfs://" + clusterName), getDfsConf(clusterName, cluster));
}
}
| 2,527 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/PipelineCallableIT.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 com.google.common.collect.ImmutableMap;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class PipelineCallableIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMRShakes() throws Exception {
run(new MRPipeline(PipelineCallableIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("shakes.txt"), false /* fail */);
}
@Test
public void testFailure() throws Exception {
run(new MRPipeline(PipelineCallableIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("shakes.txt"), true /* fail */);
}
public static int INC1 = 0;
public static int INC2 = 0;
public static void run(Pipeline p, final String input, final boolean fail) {
PTable<String, Long> top3 = p.sequentialDo(new PipelineCallable<PCollection<String>>() {
@Override
public Status call() {
INC1 = 17;
return fail ? Status.FAILURE : Status.SUCCESS;
}
@Override
public PCollection<String> getOutput(Pipeline pipeline) {
return pipeline.readTextFile(input);
}
}.named("first"))
.sequentialDo("onInput", new PipelineCallable<PCollection<String>>() {
@Override
protected PCollection<String> getOutput(Pipeline pipeline) {
return getOnlyPCollection();
}
@Override
public Status call() throws Exception {
return Status.SUCCESS;
}
})
.count()
.sequentialDo("label", new PipelineCallable<PTable<String, Long>>() {
@Override
public Status call() {
INC2 = 29;
if (getPCollection("label") != null) {
return Status.SUCCESS;
}
return Status.FAILURE;
}
@Override
public PTable<String, Long> getOutput(Pipeline pipeline) {
return (PTable<String, Long>) getOnlyPCollection();
}
}.named("second"))
.top(3);
if (fail) {
assertFalse(p.run().succeeded());
} else {
Map<String, Long> counts = top3.materializeToMap();
assertEquals(ImmutableMap.of("", 697L, "Enter.", 7L, "Exeunt.", 21L), counts);
assertEquals(17, INC1);
assertEquals(29, INC2);
}
p.done();
}
}
| 2,528 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CombineReduceIT.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 org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Multiset;
/**
* Tests for two phase (combine and reduce) CombineFns.
*/
public class CombineReduceIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
private String docsPath;
@Before
public void setUp() throws Exception {
docsPath = tmpDir.copyResourceFileName("docs.txt");
}
static class CountCombiner extends CombineFn<String,Long> {
private final int stringLengthLimit;
public CountCombiner(int stringLengthLimit) {
this.stringLengthLimit = stringLengthLimit;
}
@Override
public void process(Pair<String, Iterable<Long>> input, Emitter<Pair<String, Long>> emitter) {
String key = input.first();
if (key.length() <= stringLengthLimit) {
long sum = 0L;
for (Long countValue : input.second()) {
sum += countValue;
}
emitter.emit(Pair.of(key, sum));
} else {
for (Long countValue : input.second()) {
emitter.emit(Pair.of(key, countValue));
}
}
}
}
@Test
public void testCombineValues_NoCombineOrReduceOfLongWords() throws Exception {
Iterable<Pair<String, Long>> mrResult = run(
new MRPipeline(CombineReduceIT.class, tmpDir.getDefaultConfiguration()),
docsPath, false, false);
Iterable<Pair<String, Long>> memResult = run(
MemPipeline.getInstance(), docsPath, false, false);
Multiset<Pair<String, Long>> mrResultSet = ImmutableMultiset.copyOf(mrResult);
Multiset<Pair<String, Long>> memResultSet = ImmutableMultiset.copyOf(memResult);
assertEquals(mrResultSet, memResultSet);
// Words with more than 3 characters shouldn't be combined at all
assertTrue(mrResultSet.contains(Pair.of("this", 1L)));
assertEquals(5, mrResultSet.count(Pair.of("this", 1L)));
}
@Test
public void testCombineValues_OnlyReduceLongWords() throws Exception {
Iterable<Pair<String, Long>> mrResult = run(
new MRPipeline(CombineReduceIT.class, tmpDir.getDefaultConfiguration()),
docsPath, false, true);
Iterable<Pair<String, Long>> memResult = run(
MemPipeline.getInstance(), docsPath, false, true);
Multiset<Pair<String, Long>> mrResultSet = ImmutableMultiset.copyOf(mrResult);
Multiset<Pair<String, Long>> memResultSet = ImmutableMultiset.copyOf(memResult);
assertEquals(mrResultSet, memResultSet);
// All words should be combined, although longer words will only
// have been combined in the reduce phase
assertTrue(mrResultSet.contains(Pair.of("this", 5L)));
assertEquals(1, mrResultSet.count(Pair.of("this", 5L)));
}
@Test
public void testCombineValues_CombineAndReduceLongWords() throws Exception {
Iterable<Pair<String, Long>> mrResult = run(
new MRPipeline(CombineReduceIT.class, tmpDir.getDefaultConfiguration()),
docsPath, true, true);
Iterable<Pair<String, Long>> memResult = run(
MemPipeline.getInstance(), docsPath, true, true);
Multiset<Pair<String, Long>> mrResultSet = ImmutableMultiset.copyOf(mrResult);
Multiset<Pair<String, Long>> memResultSet = ImmutableMultiset.copyOf(memResult);
assertEquals(mrResultSet, memResultSet);
// All words should be combined, both in the combiner and reducer
assertTrue(mrResultSet.contains(Pair.of("this", 5L)));
assertEquals(1, mrResultSet.count(Pair.of("this", 5L)));
}
public static Iterable<Pair<String, Long>> run(Pipeline p, String inputPath, boolean combineLongWords, boolean reduceLongWords)
throws Exception {
return p.read(From.textFile(inputPath))
.parallelDo("split", new DoFn<String, Pair<String, Long>>() {
@Override
public void process(String input, Emitter<Pair<String, Long>> emitter) {
for (String word : input.split("\\s+")) {
emitter.emit(Pair.of(word, 1L));
}
}
}, Avros.tableOf(Avros.strings(), Avros.longs()))
.groupByKey()
.combineValues(
new CountCombiner(combineLongWords ? Integer.MAX_VALUE : 3),
new CountCombiner(reduceLongWords ? Integer.MAX_VALUE : 3))
.materialize();
}
}
| 2,529 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/SingleUseIterableExceptionIT.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 org.apache.crunch.impl.mr.MRPipeline;
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.junit.Rule;
import org.junit.Test;
public class SingleUseIterableExceptionIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
static class ReduceFn extends MapFn<Iterable<String>, String> {
@Override
public String map(Iterable<String> input) {
input.iterator();
throw new CrunchRuntimeException("Exception");
}
}
@Test
public void testException() throws Exception {
run(new MRPipeline(SingleUseIterableExceptionIT.class),
tmpDir.copyResourceFileName("shakes.txt"),
tmpDir.getFileName("out"));
}
public static void run(MRPipeline p, String input, String output) {
PCollection<String> shakes = p.readTextFile(input);
shakes.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
if (input.length() > 5) {
return Pair.of(input.substring(0, 5), input);
} else {
return Pair.of("__SHORT__", input);
}
}
}, Avros.tableOf(Avros.strings(), Avros.strings()))
.groupByKey()
.mapValues(new ReduceFn(), Avros.strings())
.write(To.textFile(output));
p.done();
}
}
| 2,530 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/EmitNullAvroIT.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 java.io.Serializable;
import java.nio.ByteBuffer;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.avro.AvroFileTarget;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.test.Person;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
public class EmitNullAvroIT extends CrunchTestSupport implements Serializable {
@Test
public void testNullableAvroPTable() throws Exception {
// This test fails if values are not nullable
final Pipeline p = new MRPipeline(EmitNullAvroIT.class, tempDir.getDefaultConfiguration());
final Path outDir = tempDir.getPath("out");
final PCollection<String> input = p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")));
input.parallelDo(new MapFn<String, Pair<String, Person>>() {
@Override
public Pair<String, Person> map(final String input) {
return new Pair<String, Person>("first name", null);
}
}, Avros.tableOf(Avros.strings(), Avros.records(Person.class)))
.write(new AvroFileTarget(outDir), Target.WriteMode.APPEND);
p.done();
}
@Test
public void testNullableAvroPTable_ByteBuffer() throws Exception {
final Pipeline p = new MRPipeline(EmitNullAvroIT.class, tempDir.getDefaultConfiguration());
final Path outDir = tempDir.getPath("out");
final PCollection<String> input = p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")));
input.parallelDo(new MapFn<String, Pair<String, ByteBuffer>>() {
@Override
public Pair<String, ByteBuffer> map(final String input) {
return new Pair<String, ByteBuffer>("first name", null);
}
}, Avros.tableOf(Avros.strings(), Avros.bytes()))
.groupByKey()
.write(new AvroFileTarget(outDir), Target.WriteMode.APPEND);
p.done();
}
}
| 2,531 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/PObjectsIT.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 java.io.IOException;
import java.lang.Integer;
import java.lang.Iterable;
import java.lang.String;
import java.util.Iterator;
import org.apache.crunch.PCollection;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.pobject.PObjectImpl;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class PObjectsIT {
private static final Integer LINES_IN_SHAKES = 3285;
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
/**
* A mock PObject that should map PCollections of strings to an integer count of the number of
* elements in the underlying PCollection.
*/
public static class MockPObjectImpl extends PObjectImpl<String, Integer> {
private int numProcessCalls;
public MockPObjectImpl(PCollection<String> collect) {
super(collect);
numProcessCalls = 0;
}
@Override
public Integer process(Iterable<String> input) {
numProcessCalls++;
int i = 0;
Iterator<String> itr = input.iterator();
while (itr.hasNext()) {
i++;
itr.next();
}
return i;
}
public int getNumProcessCalls() {
return numProcessCalls;
}
}
@Test
public void testMRPipeline() throws IOException {
run(new MRPipeline(PObjectsIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testInMemoryPipeline() throws IOException {
run(MemPipeline.getInstance());
}
public void run(Pipeline pipeline) throws IOException {
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
MockPObjectImpl lineCount = new MockPObjectImpl(shakespeare);
// Get the line count once and verify it's correctness.
assertEquals("Incorrect number of lines counted from PCollection.", LINES_IN_SHAKES,
lineCount.getValue());
// And do it again.
assertEquals("Incorrect number of lines counted from PCollection.", LINES_IN_SHAKES,
lineCount.getValue());
// Make sure process was called only once because the PObject's value was cached after the
// first call.
assertEquals("Process on PObject not called exactly 1 times.", 1,
lineCount.getNumProcessCalls());
}
}
| 2,532 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/StageResultsCountersIT.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.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.crunch.PipelineResult.StageResult;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class StageResultsCountersIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
public static HashSet<String> SPECIAL_KEYWORDS = Sets.newHashSet("AND", "OR", "NOT");
public static String KEYWORDS_COUNTER_GROUP = "KEYWORDS_COUNTER_GROUP";
@After
public void after() {
MemPipeline.clearCounters();
}
@Test
public void testStageResultsCountersMRWritables() throws Exception {
testSpecialKeywordCount(new MRPipeline(StageResultsCountersIT.class, tmpDir.getDefaultConfiguration()),
WritableTypeFamily.getInstance());
}
@Test
public void testStageResultsCountersMRAvro() throws Exception {
testSpecialKeywordCount(new MRPipeline(StageResultsCountersIT.class, tmpDir.getDefaultConfiguration()),
AvroTypeFamily.getInstance());
}
@Test
public void testStageResultsCountersMemWritables() throws Exception {
testSpecialKeywordCount(MemPipeline.getInstance(), WritableTypeFamily.getInstance());
}
@Test
public void testStageResultsCountersMemAvro() throws Exception {
testSpecialKeywordCount(MemPipeline.getInstance(), AvroTypeFamily.getInstance());
}
public void testSpecialKeywordCount(Pipeline pipeline, PTypeFamily tf) throws Exception {
String rowsInputPath = tmpDir.copyResourceFileName("shakes.txt");
PipelineResult result = coutSpecialKeywords(pipeline, rowsInputPath, tf);
assertTrue(result.succeeded());
Map<String, Long> keywordsMap = countersToMap(result.getStageResults(), KEYWORDS_COUNTER_GROUP);
assertThat(keywordsMap, is((Map<String, Long>) ImmutableMap.of("NOT", 145L, "AND", 544L, "OR", 37L)));
}
private static PipelineResult coutSpecialKeywords(Pipeline pipeline, String inputFileName, PTypeFamily tf) {
pipeline.read(From.textFile(inputFileName)).parallelDo(new DoFn<String, Void>() {
@Override
public void process(String text, Emitter<Void> emitter) {
if (!StringUtils.isBlank(text)) {
String[] tokens = text.toUpperCase().split("\\s");
for (String token : tokens) {
if (SPECIAL_KEYWORDS.contains(token)) {
increment(KEYWORDS_COUNTER_GROUP, token);
}
}
}
}
}, tf.nulls()).materialize(); // TODO can we avoid the materialize ?
return pipeline.done();
}
private static Map<String, Long> countersToMap(List<StageResult> stages, String counterGroupName) {
Map<String, Long> countersMap = Maps.newHashMap();
for (StageResult sr : stages) {
for (String counterName : sr.getCounterNames().get(counterGroupName)) {
countersMap.put(sr.getCounterDisplayName(counterGroupName, counterName),
sr.getCounterValue(counterGroupName, counterName));
}
}
return countersMap;
}
}
| 2,533 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/IterableReuseProtectionIT.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 java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* Verify that calling the iterator method on a Reducer-based Iterable
* is forcefully disallowed.
*/
public class IterableReuseProtectionIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
public void checkIteratorReuse(Pipeline pipeline) throws IOException {
Iterable<String> values = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"))
.by(IdentityFn.<String>getInstance(), Writables.strings())
.groupByKey()
.combineValues(new TestIterableReuseFn())
.values().materialize();
List<String> valueList = Lists.newArrayList(values);
Collections.sort(valueList);
assertEquals(Lists.newArrayList("a", "b", "c", "e"), valueList);
}
@Test
public void testIteratorReuse_MRPipeline() throws IOException {
checkIteratorReuse(new MRPipeline(IterableReuseProtectionIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testIteratorReuse_InMemoryPipeline() throws IOException {
checkIteratorReuse(MemPipeline.getInstance());
}
static class TestIterableReuseFn extends CombineFn<String, String> {
@Override
public void process(Pair<String, Iterable<String>> input, Emitter<Pair<String, String>> emitter) {
StringBuilder combinedBuilder = new StringBuilder();
for (String v : input.second()) {
combinedBuilder.append(v);
}
try {
input.second().iterator();
throw new RuntimeException("Second call to iterator should throw an exception");
} catch (IllegalStateException e) {
// Expected situation
}
emitter.emit(Pair.of(input.first(), combinedBuilder.toString()));
}
}
}
| 2,534 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/PageRankIT.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 java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.PTypes;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class PageRankIT {
private static List<String> URLS = ImmutableList.of(
"www.A.com www.B.com",
"www.A.com www.C.com",
"www.A.com www.D.com",
"www.A.com www.E.com",
"www.B.com www.D.com",
"www.B.com www.E.com",
"www.C.com www.D.com",
"www.D.com www.B.com",
"www.E.com www.A.com",
"www.F.com www.B.com",
"www.F.com www.C.com");
public static class PageRankData {
public float score;
public float lastScore;
public List<String> urls;
public PageRankData() {
}
public PageRankData(float score, float lastScore, Iterable<String> urls) {
this.score = score;
this.lastScore = lastScore;
this.urls = Lists.newArrayList(urls);
}
public PageRankData next(float newScore) {
return new PageRankData(newScore, score, urls);
}
public float propagatedScore() {
return score / urls.size();
}
@Override
public String toString() {
return score + " " + lastScore + " " + urls;
}
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testAvroReflect() throws Exception {
PTypeFamily tf = AvroTypeFamily.getInstance();
PType<PageRankData> prType = Avros.reflects(PageRankData.class);
run(new MRPipeline(PageRankIT.class, tmpDir.getDefaultConfiguration()),
prType, tf);
}
@Test
public void testAvroMReflectInMemory() throws Exception {
PTypeFamily tf = AvroTypeFamily.getInstance();
PType<PageRankData> prType = Avros.reflects(PageRankData.class);
run(MemPipeline.getInstance(), prType, tf);
}
@Test
public void testAvroJSON() throws Exception {
PTypeFamily tf = AvroTypeFamily.getInstance();
PType<PageRankData> prType = PTypes.jsonString(PageRankData.class, tf);
run(new MRPipeline(PageRankIT.class, tmpDir.getDefaultConfiguration()),
prType, tf);
}
@Test
public void testWritablesJSON() throws Exception {
PTypeFamily tf = WritableTypeFamily.getInstance();
PType<PageRankData> prType = PTypes.jsonString(PageRankData.class, tf);
run(new MRPipeline(PageRankIT.class, tmpDir.getDefaultConfiguration()),
prType, tf);
}
public static PTable<String, PageRankData> pageRank(PTable<String, PageRankData> input, final float d) {
PTypeFamily ptf = input.getTypeFamily();
PTable<String, Float> outbound = input.parallelDo(new DoFn<Pair<String, PageRankData>, Pair<String, Float>>() {
@Override
public void process(Pair<String, PageRankData> input, Emitter<Pair<String, Float>> emitter) {
PageRankData prd = input.second();
for (String link : prd.urls) {
emitter.emit(Pair.of(link, prd.propagatedScore()));
}
}
}, ptf.tableOf(ptf.strings(), ptf.floats()));
return input.cogroup(outbound).mapValues(
new MapFn<Pair<Collection<PageRankData>, Collection<Float>>, PageRankData>() {
@Override
public PageRankData map(Pair<Collection<PageRankData>, Collection<Float>> input) {
PageRankData prd = Iterables.getOnlyElement(input.first());
Collection<Float> propagatedScores = input.second();
float sum = 0.0f;
for (Float s : propagatedScores) {
sum += s;
}
return prd.next(d + (1.0f - d) * sum);
}
}, input.getValueType());
}
public static void run(Pipeline pipeline,
PType<PageRankData> prType, PTypeFamily ptf) throws Exception {
PTable<String, PageRankData> scores = pipeline.create(URLS, ptf.strings())
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] urls = input.split("\\s+");
return Pair.of(urls[0], urls[1]);
}
}, ptf.tableOf(ptf.strings(), ptf.strings())).groupByKey()
.mapValues(new MapFn<Iterable<String>, PageRankData>() {
@Override
public PageRankData map(Iterable<String> input) {
return new PageRankData(1.0f, 0.0f, input);
}
}, prType);
Float delta = 1.0f;
while (delta > 0.01) {
scores = pageRank(scores, 0.5f);
scores.materialize().iterator(); // force the write
delta = Aggregate.max(scores.parallelDo(new MapFn<Pair<String, PageRankData>, Float>() {
@Override
public Float map(Pair<String, PageRankData> input) {
PageRankData prd = input.second();
return Math.abs(prd.score - prd.lastScore);
}
}, ptf.floats())).getValue();
}
assertEquals(0.0048, delta, 0.001);
}
}
| 2,535 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CollectionsLengthIT.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 java.io.IOException;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class CollectionsLengthIT {
public static final Long LINES_IN_SHAKESPEARE = 3285L;
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritables() throws IOException {
run(new MRPipeline(CollectionsIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testAvro() throws IOException {
run(new MRPipeline(CollectionsIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
@Test
public void testInMemoryWritables() throws IOException {
run(MemPipeline.getInstance(), WritableTypeFamily.getInstance());
}
@Test
public void testInMemoryAvro() throws IOException {
run(MemPipeline.getInstance(), AvroTypeFamily.getInstance());
}
public void run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
Long length = shakespeare.length().getValue();
assertEquals("Incorrect length for Shakespeare PCollection.", LINES_IN_SHAKESPEARE, length);
}
}
| 2,536 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/ConfigurationIT.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 org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
public class ConfigurationIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
private static final String KEY = "key";
private static DoFn<String, String> CONFIG_FN = new DoFn<String, String>() {
private String value;
@Override
public void configure(Configuration conf) {
this.value = conf.get(KEY, "none");
}
@Override
public void process(String input, Emitter<String> emitter) {
emitter.emit(value);
}
};
@Test
public void testRun() throws Exception {
run(new MRPipeline(ConfigurationIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("set1.txt"), "testapalooza");
}
private static void run(Pipeline p, String input, String expected) throws Exception {
Iterable<String> mat = p.read(From.textFile(input))
.parallelDo("conf", CONFIG_FN, Writables.strings(), ParallelDoOptions.builder().conf(KEY, expected).build())
.materialize();
for (String v : mat) {
if (!expected.equals(v)) {
Assert.fail("Unexpected value: " + v);
}
}
p.done();
}
}
| 2,537 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/FirstElementPObjectIT.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 java.io.IOException;
import java.lang.String;
import org.apache.crunch.PCollection;
import org.apache.crunch.PObject;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.pobject.FirstElementPObject;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class FirstElementPObjectIT {
private static final String FIRST_SHAKESPEARE_LINE =
"The Tragedie of Macbeth";
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMRPipeline() throws IOException {
run(new MRPipeline(FirstElementPObjectIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testInMemoryPipeline() throws IOException {
run(MemPipeline.getInstance());
}
public void run(Pipeline pipeline) throws IOException {
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
PObject<String> firstLine = new FirstElementPObject<String>(shakespeare);
String first = firstLine.getValue();
assertEquals("First line in Shakespeare is wrong.", FIRST_SHAKESPEARE_LINE, first);
}
}
| 2,538 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CheckpointIT.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 org.apache.crunch.Target.WriteMode;
import org.apache.crunch.impl.mr.MRPipeline;
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.Path;
import org.junit.Rule;
import org.junit.Test;
public class CheckpointIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testCheckpoints() throws Exception {
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
Thread.sleep(2000);
Pipeline p = new MRPipeline(CheckpointIT.class);
String inter = tmpDir.getFileName("intermediate");
PipelineResult one = run(p, tmpDir, inputPath, inter, false);
assertTrue(one.succeeded());
assertEquals(2, one.getStageResults().size());
PipelineResult two = run(p, tmpDir, inputPath, inter, false);
assertTrue(two.succeeded());
assertEquals(1, two.getStageResults().size());
}
@Test
public void testUnsuccessfulCheckpoint() throws Exception {
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
Pipeline p = new MRPipeline(CheckpointIT.class);
String inter = tmpDir.getFileName("intermediate");
PipelineResult one = run(p, tmpDir, inputPath, inter, true);
assertFalse(one.succeeded());
PipelineResult two = run(p, tmpDir, inputPath, inter, false);
assertTrue(two.succeeded());
assertEquals(2, two.getStageResults().size());
}
@Test
public void testModifiedFileCheckpoint() throws Exception {
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
Pipeline p = new MRPipeline(CheckpointIT.class);
Path inter = tmpDir.getPath("intermediate");
PipelineResult one = run(p, tmpDir, inputPath, inter.toString(), false);
assertTrue(one.succeeded());
assertEquals(2, one.getStageResults().size());
// Update the input path
inputPath = tmpDir.copyResourceFileName("shakes.txt");
PipelineResult two = run(p, tmpDir, inputPath, inter.toString(), false);
assertTrue(two.succeeded());
assertEquals(2, two.getStageResults().size());
}
public static PipelineResult run(Pipeline pipeline, TemporaryPath tmpDir,
String shakesInputPath, String intermediatePath,
final boolean fail) {
PCollection<String> shakes = pipeline.readTextFile(shakesInputPath);
PTable<String, Long> cnts = shakes.parallelDo("split words", new DoFn<String, String>() {
@Override
public void process(String line, Emitter<String> emitter) {
if (fail) {
throw new RuntimeException("Failure!");
}
for (String word : line.split("\\s+")) {
emitter.emit(word);
}
}
}, Avros.strings()).count();
cnts.write(To.avroFile(intermediatePath), WriteMode.CHECKPOINT);
PTable<String, Long> singleCounts = cnts.keys().count();
singleCounts.write(To.textFile(tmpDir.getFileName("singleCounts")), WriteMode.OVERWRITE);
return pipeline.run();
}
}
| 2,539 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/UnionResultsIT.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 java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.writable.Writables;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class UnionResultsIT extends CrunchTestSupport implements Serializable {
static class StringLengthMapFn extends MapFn<String, Pair<String, Long>> {
@Override
public Pair<String, Long> map(String input) {
return new Pair<String, Long>(input, 10L);
}
}
/**
* Tests combining a GBK output with a map-only job output into a single
* unioned collection.
*/
@Test
public void testUnionOfGroupedOutputAndNonGroupedOutput() throws IOException {
String inputPath = tempDir.copyResourceFileName("set1.txt");
String inputPath2 = tempDir.copyResourceFileName("set2.txt");
Pipeline pipeline = new MRPipeline(UnionResultsIT.class);
PCollection<String> set1Lines = pipeline.read(At.textFile(inputPath, Writables.strings()));
PCollection<Pair<String, Long>> set1Lengths = set1Lines.parallelDo(new StringLengthMapFn(),
Writables.pairs(Writables.strings(), Writables.longs()));
PCollection<Pair<String, Long>> set2Counts = pipeline.read(At.textFile(inputPath2, Writables.strings())).count();
PCollection<Pair<String, Long>> union = set1Lengths.union(set2Counts);
List<Pair<String, Long>> unionValues = Lists.newArrayList(union.materialize());
assertEquals(7, unionValues.size());
Set<Pair<String, Long>> expectedPairs = Sets.newHashSet();
expectedPairs.add(Pair.of("b", 10L));
expectedPairs.add(Pair.of("c", 10L));
expectedPairs.add(Pair.of("a", 10L));
expectedPairs.add(Pair.of("e", 10L));
expectedPairs.add(Pair.of("a", 1L));
expectedPairs.add(Pair.of("c", 1L));
expectedPairs.add(Pair.of("d", 1L));
assertEquals(expectedPairs, Sets.newHashSet(unionValues));
}
}
| 2,540 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CollectionsIT.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.assertTrue;
import java.io.IOException;
import java.util.Collection;
import org.apache.crunch.fn.Aggregators.SimpleAggregator;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
@SuppressWarnings("serial")
public class CollectionsIT {
private static class AggregateStringListFn extends SimpleAggregator<Collection<String>> {
private final Collection<String> rtn = Lists.newArrayList();
@Override
public void reset() {
rtn.clear();
}
@Override
public void update(Collection<String> values) {
rtn.addAll(values);
}
@Override
public Iterable<Collection<String>> results() {
return ImmutableList.of(rtn);
}
}
private static PTable<String, Collection<String>> listOfCharcters(PCollection<String> lines, PTypeFamily typeFamily) {
return lines.parallelDo(new DoFn<String, Pair<String, Collection<String>>>() {
@Override
public void process(String line, Emitter<Pair<String, Collection<String>>> emitter) {
for (String word : line.split("\\s+")) {
Collection<String> characters = Lists.newArrayList();
for (char c : word.toCharArray()) {
characters.add(String.valueOf(c));
}
emitter.emit(Pair.of(word, characters));
}
}
}, typeFamily.tableOf(typeFamily.strings(), typeFamily.collections(typeFamily.strings())))
.groupByKey().combineValues(new AggregateStringListFn());
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritables() throws IOException {
run(new MRPipeline(CollectionsIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testAvro() throws IOException {
run(new MRPipeline(CollectionsIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
@Test
public void testInMemoryWritables() throws IOException {
run(MemPipeline.getInstance(), WritableTypeFamily.getInstance());
}
@Test
public void testInMemoryAvro() throws IOException {
run(MemPipeline.getInstance(), AvroTypeFamily.getInstance());
}
public void run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
Iterable<Pair<String, Collection<String>>> lines = listOfCharcters(shakespeare, typeFamily).materialize();
boolean passed = false;
for (Pair<String, Collection<String>> line : lines) {
if (line.first().startsWith("yellow")) {
passed = true;
break;
}
}
pipeline.done();
assertTrue(passed);
}
}
| 2,541 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/TextPairIT.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.assertTrue;
import java.io.IOException;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.junit.Rule;
import org.junit.Test;
public class TextPairIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritables() throws IOException {
run(new MRPipeline(TextPairIT.class, tmpDir.getDefaultConfiguration()));
}
private static final String CANARY = "Writables.STRING_TO_TEXT";
public static PCollection<Pair<String, String>> wordDuplicate(PCollection<String> words) {
return words.parallelDo("my word duplicator", new DoFn<String, Pair<String, String>>() {
public void process(String line, Emitter<Pair<String, String>> emitter) {
for (String word : line.split("\\W+")) {
if (word.length() > 0) {
Pair<String, String> pair = Pair.of(CANARY, word);
emitter.emit(pair);
}
}
}
}, Writables.pairs(Writables.strings(), Writables.strings()));
}
public void run(Pipeline pipeline) throws IOException {
String input = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.read(From.textFile(input));
Iterable<Pair<String, String>> lines = pipeline.materialize(wordDuplicate(shakespeare));
boolean passed = false;
for (Pair<String, String> line : lines) {
if (line.first().contains(CANARY)) {
passed = true;
break;
}
}
pipeline.done();
assertTrue(passed);
}
}
| 2,542 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MultiStagePlanningIT.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 com.google.common.base.Splitter;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.join.BloomFilterJoinStrategy;
import org.apache.crunch.lib.join.JoinType;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
import java.io.Serializable;
import java.util.Iterator;
import static org.apache.crunch.types.avro.Avros.strings;
import static org.apache.crunch.types.avro.Avros.tableOf;
import static org.junit.Assert.assertTrue;
public class MultiStagePlanningIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMultiStagePlanning() throws Exception {
Pipeline pipeline = new MRPipeline(MRPipelineIT.class, tmpDir.getDefaultConfiguration());
String customersFile = tmpDir.copyResourceFileName("customers.txt");
String ordersFile = tmpDir.copyResourceFileName("orders.txt");
String addressesFile = tmpDir.copyResourceFileName("addresses.txt");
PTable<String, String> customersTable = pipeline.readTextFile(customersFile)
.parallelDo("Split customers", new StringToPairMapFn(), tableOf(strings(), strings()));
PTable<String, String> ordersTable = pipeline.readTextFile(ordersFile)
.parallelDo("Split orders", new StringToPairMapFn(), tableOf(strings(), strings()));
PTable<String, String> assignedOrders = new BloomFilterJoinStrategy<String, String, String>(5)
.join(customersTable, ordersTable, JoinType.INNER_JOIN)
.parallelDo(new MapFn<Pair<String, Pair<String, String>>, Pair<String, String>>() {
@Override
public Pair<String, String> map(Pair<String, Pair<String, String>> input) {
return Pair.of(input.first(), input.second().second());
}
}, tableOf(strings(), strings()));
PTable<String, String> addressesTable = pipeline.readTextFile(addressesFile)
.parallelDo("Split addresses", new StringToPairMapFn(), tableOf(strings(), strings()))
.filter(new FilterFn<Pair<String, String>>() {
@Override
public boolean accept(Pair<String, String> input) {
// This is odd but it is the simpler way of simulating this would take longer than
// the other branch with the Bloom Filter ...
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
});
addressesTable.materialize();
PTable<String, Pair<String, String>> orderAddresses = assignedOrders.join(addressesTable);
orderAddresses.materialize();
PipelineResult result = pipeline.run();
assertTrue(result != null && result.succeeded());
}
private static class StringToPairMapFn extends MapFn<String, Pair<String, String>> {
private transient Splitter splitter;
@Override
public void initialize() {
super.initialize();
splitter = Splitter.on('|');
}
@Override
public Pair<String, String> map(String input) {
Iterator<String> split = splitter.split(input).iterator();
return Pair.of(split.next(), split.next());
}
}
}
| 2,543 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/TfIdfIT.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.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.seq.SeqFileSourceTarget;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.lib.Join;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.apache.hadoop.fs.Path;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
@SuppressWarnings("serial")
public class TfIdfIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
// total number of documents, should calculate
protected static final double N = 2;
@Test
public void testWritablesSingleRun() throws IOException {
run(new MRPipeline(TfIdfIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), true);
}
@Test
public void testWritablesMultiRun() throws IOException {
run(new MRPipeline(TfIdfIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), false);
}
/**
* This method should generate a TF-IDF score for the input.
*/
public PTable<String, Collection<Pair<String, Double>>> generateTFIDF(PCollection<String> docs, Path termFreqPath,
PTypeFamily ptf) throws IOException {
/*
* Input: String Input title text
*
* Output: PTable<Pair<String, String>, Long> Pair<Pair<word, title>, count
* in title>
*/
PTable<Pair<String, String>, Long> tf = Aggregate.count(docs.parallelDo("term document frequency",
new DoFn<String, Pair<String, String>>() {
@Override
public void process(String doc, Emitter<Pair<String, String>> emitter) {
String[] kv = doc.split("\t");
String title = kv[0];
String text = kv[1];
for (String word : text.split("\\W+")) {
if (word.length() > 0) {
Pair<String, String> pair = Pair.of(word.toLowerCase(), title);
emitter.emit(pair);
}
}
}
}, ptf.pairs(ptf.strings(), ptf.strings())));
tf.write(new SeqFileSourceTarget<Pair<Pair<String, String>, Long>>(termFreqPath, tf.getPType()));
/*
* Input: Pair<Pair<String, String>, Long> Pair<Pair<word, title>, count in
* title>
*
* Output: PTable<String, Long> PTable<word, # of docs containing word>
*/
PTable<String, Long> n = Aggregate.count(tf.parallelDo("little n (# of docs contain word)",
new DoFn<Pair<Pair<String, String>, Long>, String>() {
@Override
public void process(Pair<Pair<String, String>, Long> input, Emitter<String> emitter) {
emitter.emit(input.first().first());
}
}, ptf.strings()));
/*
* Input: Pair<Pair<String, String>, Long> Pair<Pair<word, title>, count in
* title>
*
* Output: PTable<String, Pair<String, Long>> PTable<word, Pair<title, count
* in title>>
*/
PTable<String, Collection<Pair<String, Long>>> wordDocumentCountPair = tf.parallelDo(
"transform wordDocumentPairCount",
new DoFn<Pair<Pair<String, String>, Long>, Pair<String, Collection<Pair<String, Long>>>>() {
Collection<Pair<String, Long>> buffer;
String key;
@Override
public void process(Pair<Pair<String, String>, Long> input,
Emitter<Pair<String, Collection<Pair<String, Long>>>> emitter) {
Pair<String, String> wordDocumentPair = input.first();
if (!wordDocumentPair.first().equals(key)) {
flush(emitter);
key = wordDocumentPair.first();
buffer = Lists.newArrayList();
}
buffer.add(Pair.of(wordDocumentPair.second(), input.second()));
}
protected void flush(Emitter<Pair<String, Collection<Pair<String, Long>>>> emitter) {
if (buffer != null) {
emitter.emit(Pair.of(key, buffer));
buffer = null;
}
}
@Override
public void cleanup(Emitter<Pair<String, Collection<Pair<String, Long>>>> emitter) {
flush(emitter);
}
}, ptf.tableOf(ptf.strings(), ptf.collections(ptf.pairs(ptf.strings(), ptf.longs()))));
PTable<String, Pair<Long, Collection<Pair<String, Long>>>> joinedResults = Join.join(n, wordDocumentCountPair);
/*
* Input: Pair<String, Pair<Long, Collection<Pair<String, Long>>> Pair<word,
* Pair<# of docs containing word, Collection<Pair<title, term frequency>>>
*
* Output: Pair<String, Collection<Pair<String, Double>>> Pair<word,
* Collection<Pair<title, tfidf>>>
*/
return joinedResults
.mapValues(
new MapFn<Pair<Long, Collection<Pair<String, Long>>>, Collection<Pair<String, Double>>>() {
@Override
public Collection<Pair<String, Double>> map(
Pair<Long, Collection<Pair<String, Long>>> input) {
Collection<Pair<String, Double>> tfidfs = Lists.newArrayList();
double n = input.first();
double idf = Math.log(N / n);
for (Pair<String, Long> tf : input.second()) {
double tfidf = tf.second() * idf;
tfidfs.add(Pair.of(tf.first(), tfidf));
}
return tfidfs;
}
}, ptf.collections(ptf.pairs(ptf.strings(), ptf.doubles())));
}
public void run(Pipeline pipeline, PTypeFamily typeFamily, boolean singleRun) throws IOException {
String inputFile = tmpDir.copyResourceFileName("docs.txt");
String outputPath1 = tmpDir.getFileName("output1");
String outputPath2 = tmpDir.getFileName("output2");
Path tfPath = tmpDir.getPath("termfreq");
PCollection<String> docs = pipeline.readTextFile(inputFile);
PTable<String, Collection<Pair<String, Double>>> results = generateTFIDF(docs, tfPath, typeFamily);
pipeline.writeTextFile(results, outputPath1);
if (!singleRun) {
pipeline.run();
}
PTable<String, Collection<Pair<String, Double>>> uppercased = results.mapKeys(
new MapFn<String, String>() {
@Override
public String map(String k1) {
return k1.toUpperCase();
}
}, results.getKeyType());
pipeline.writeTextFile(uppercased, outputPath2);
pipeline.done();
// Check the lowercase version...
File outputFile = new File(outputPath1, "part-r-00000");
List<String> lines = Files.readLines(outputFile, Charset.defaultCharset());
boolean passed = false;
for (String line : lines) {
if (line.startsWith("[the") && line.contains("B,0.6931471805599453")) {
passed = true;
break;
}
}
assertTrue(passed);
// ...and the uppercase version
outputFile = new File(outputPath2, "part-r-00000");
lines = Files.readLines(outputFile, Charset.defaultCharset());
passed = false;
for (String line : lines) {
if (line.startsWith("[THE") && line.contains("B,0.6931471805599453")) {
passed = true;
break;
}
}
assertTrue(passed);
}
}
| 2,544 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/DependentSourcesIT.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.apache.crunch.types.avro.Avros.strings;
import static org.apache.crunch.types.avro.Avros.tableOf;
import java.util.List;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRJob;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.MRPipelineExecution;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.materialize.MaterializableIterable;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
public class DependentSourcesIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testRun() throws Exception {
run(new MRPipeline(DependentSourcesIT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourcePath("shakes.txt"),
tmpDir.getFileName("out"));
}
public static void run(MRPipeline p, Path inputPath, String out) throws Exception {
PCollection<String> in = p.read(From.textFile(inputPath));
PTable<String, String> op = in.parallelDo("op1", new DoFn<String, Pair<String, String>>() {
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
if (input.length() > 5) {
emitter.emit(Pair.of(input.substring(0, 3), input));
}
}
}, tableOf(strings(), strings()));
ReadableData<Pair<String, String>> rd = op.asReadable(true);
op = op.parallelDo("op2", IdentityFn.<Pair<String,String>>getInstance(), tableOf(strings(), strings()),
ParallelDoOptions.builder().sourceTargets(rd.getSourceTargets()).build());
PCollection<String> output = op.values();
output.write(To.textFile(out));
MRPipelineExecution exec = p.runAsync();
exec.waitUntilDone();
List<MRJob> jobs = exec.getJobs();
Assert.assertEquals(2, jobs.size());
Assert.assertEquals(0, jobs.get(0).getJob().getNumReduceTasks());
Assert.assertEquals(0, jobs.get(1).getJob().getNumReduceTasks());
}
}
| 2,545 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/Breakpoint2IT.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.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.MRPipelineExecution;
import org.apache.crunch.impl.mr.exec.MRExecutor;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.lib.Join;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.junit.Rule;
import org.junit.Test;
public class Breakpoint2IT {
private static final class PTableTransform extends DoFn<String, Pair<String, Integer>> {
@Override
public void process(final String s, final Emitter<Pair<String, Integer>> emitter) {
for (int i = 0; i < 10; i++) {
emitter.emit(new Pair<String, Integer>(s, i));
}
}
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testNoBreakpoint() throws Exception {
run(new MRPipeline(Breakpoint2IT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("letters.txt"),
tmpDir.copyResourceFileName("urls.txt"),
tmpDir.copyResourceFileName("docs.txt"),
tmpDir.getFileName("out1"),
tmpDir.getFileName("out2"),
false);
}
@Test
public void testBreakpoint() throws Exception {
run(new MRPipeline(Breakpoint2IT.class, tmpDir.getDefaultConfiguration()),
tmpDir.copyResourceFileName("letters.txt"),
tmpDir.copyResourceFileName("urls.txt"),
tmpDir.copyResourceFileName("docs.txt"),
tmpDir.getFileName("out1"),
tmpDir.getFileName("out2"),
true);
}
public static void run(MRPipeline pipeline, String input1, String input2, String input3,
String out1, String out2, boolean breakpoint) throws Exception {
// Read a line from a file to get a PCollection.
PCollection<String> pCol1 = pipeline.read(From.textFile(input1));
PCollection<String> pCol2 = pipeline.read(From.textFile(input2));
PCollection<String> pCol3 = pipeline.read(From.textFile(input3));
// Create PTables from the PCollections
PTable<String, Integer> pTable1 = pCol1.parallelDo("Transform pCol1 to PTable", new PTableTransform(),
Writables.tableOf(Writables.strings(), Writables.ints()));
if (breakpoint) {
pTable1.materialize();
}
PTable<String, Integer> pTable2 = pCol2.parallelDo("Transform pCol2 to PTable", new PTableTransform(),
Writables.tableOf(Writables.strings(), Writables.ints()));
PTable<String, Integer> pTable3 = pCol3.parallelDo("Transform pCol3 to PTable", new PTableTransform(),
Writables.tableOf(Writables.strings(), Writables.ints()));
// Perform joins to pTable1
PTable<String, Pair<Integer, Integer>> join1 = Join.leftJoin(pTable1, pTable2);
PTable<String, Pair<Integer, Integer>> join2 = Join.rightJoin(pTable1, pTable3);
// Write joins
join1.keys().write(To.textFile(out1));
join2.keys().write(To.textFile(out2));
MRPipelineExecution exec = pipeline.runAsync();
int fnCount = 0;
for (String line : exec.getPlanDotFile().split("\n")) {
if (line.contains("label=\"Transform pCol1 to PTable 0 Mb\"")) {
fnCount++;
}
}
assertEquals(breakpoint ? 1 : 2, fnCount);
exec.waitUntilDone();
}
}
| 2,546 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/RecordDropIT.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 com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
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 java.util.List;
import static org.junit.Assert.assertEquals;
public class RecordDropIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMultiReadCount() throws Exception {
int numReads = 10;
MRPipeline p = new MRPipeline(RecordDropIT.class, tmpDir.getDefaultConfiguration());
Path shakes = tmpDir.copyResourcePath("shakes.txt");
TableSource<LongWritable, Text> src = From.formattedFile(shakes,
TextInputFormat.class, LongWritable.class, Text.class);
PTable<LongWritable, Text> in = p.read(src);
List<Iterable<Integer>> values = Lists.newArrayList();
for (int i = 0; i < numReads; i++) {
PCollection<Integer> cnt = in.parallelDo(new LineCountFn<Pair<LongWritable, Text>>(), Writables.ints());
values.add(cnt.materialize());
}
int index = 0;
for (Iterable<Integer> iter : values) {
assertEquals("Checking index = " + index, 3285, Iterables.getFirst(iter, 0).intValue());
index++;
}
p.done();
}
public static class LineCountFn<T> extends DoFn<T, Integer> {
private int count = 0;
@Override
public void process(T input, Emitter<Integer> emitter) {
count++;
}
@Override
public void cleanup(Emitter<Integer> emitter) {
emitter.emit(count);
}
}
}
| 2,547 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CollectionPObjectIT.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 java.io.IOException;
import java.lang.String;
import java.util.Collection;
import org.apache.crunch.PCollection;
import org.apache.crunch.PObject;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.materialize.pobject.CollectionPObject;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class CollectionPObjectIT {
private static final int LINES_IN_SHAKES = 3285;
private static final String FIRST_SHAKESPEARE_LINE =
"The Tragedie of Macbeth";
private static final String LAST_SHAKESPEARE_LINE =
"FINIS. THE TRAGEDIE OF MACBETH.";
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testPObjectMRPipeline() throws IOException {
runPObject(new MRPipeline(CollectionPObjectIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testAsCollectionMRPipeline() throws IOException {
runAsCollection(new MRPipeline(CollectionPObjectIT.class, tmpDir.getDefaultConfiguration()));
}
@Test
public void testPObjectMemPipeline() throws IOException {
runPObject(MemPipeline.getInstance());
}
@Test
public void testAsCollectionMemPipeline() throws IOException {
runAsCollection(MemPipeline.getInstance());
}
private PCollection<String> getPCollection(Pipeline pipeline) throws IOException {
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakespeare = pipeline.readTextFile(shakesInputPath);
return shakespeare;
}
private void verifyLines(String[] lines) {
assertEquals("Not enough lines in Shakespeare.", LINES_IN_SHAKES, lines.length);
assertEquals("First line in Shakespeare is wrong.", FIRST_SHAKESPEARE_LINE, lines[0]);
assertEquals("Last line in Shakespeare is wrong.", LAST_SHAKESPEARE_LINE,
lines[lines.length - 1]);
}
public void runPObject(Pipeline pipeline) throws IOException {
PCollection<String> shakespeare = getPCollection(pipeline);
PObject<Collection<String>> linesP = new CollectionPObject<String>(shakespeare);
String[] lines = new String[LINES_IN_SHAKES];
lines = linesP.getValue().toArray(lines);
verifyLines(lines);
}
public void runAsCollection(Pipeline pipeline) throws IOException {
PCollection<String> shakespeare = getPCollection(pipeline);
String[] lines = new String[LINES_IN_SHAKES];
lines = shakespeare.asCollection().getValue().toArray(lines);
verifyLines(lines);
}
}
| 2,548 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/PTableKeyValueIT.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 java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Lists;
@RunWith(value = Parameterized.class)
public class PTableKeyValueIT implements Serializable {
private static final long serialVersionUID = 4374227704751746689L;
private transient PTypeFamily typeFamily;
private transient MRPipeline pipeline;
private transient String inputFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
pipeline = new MRPipeline(PTableKeyValueIT.class, tmpDir.getDefaultConfiguration());
inputFile = tmpDir.copyResourceFileName("set1.txt");
}
@After
public void tearDown() {
pipeline.done();
}
public PTableKeyValueIT(PTypeFamily typeFamily) {
this.typeFamily = typeFamily;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { WritableTypeFamily.getInstance() }, { AvroTypeFamily.getInstance() } };
return Arrays.asList(data);
}
@Test
public void testKeysAndValues() throws Exception {
PCollection<String> collection = pipeline.read(At.textFile(inputFile, typeFamily.strings()));
PTable<String, String> table = collection.parallelDo(new DoFn<String, Pair<String, String>>() {
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
emitter.emit(Pair.of(input.toUpperCase(), input));
}
}, typeFamily.tableOf(typeFamily.strings(), typeFamily.strings()));
PCollection<String> keys = table.keys();
PCollection<String> values = table.values();
ArrayList<String> keyList = Lists.newArrayList(keys.materialize().iterator());
ArrayList<String> valueList = Lists.newArrayList(values.materialize().iterator());
Assert.assertEquals(keyList.size(), valueList.size());
for (int i = 0; i < keyList.size(); i++) {
Assert.assertEquals(keyList.get(i), valueList.get(i).toUpperCase());
}
}
}
| 2,549 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/TermFrequencyIT.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.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Locale;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.ReadableSource;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class TermFrequencyIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testTermFrequencyWithNoTransform() throws IOException {
run(new MRPipeline(TermFrequencyIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), false);
}
@Test
public void testTermFrequencyWithTransform() throws IOException {
run(new MRPipeline(TermFrequencyIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), true);
}
@Test
public void testTermFrequencyNoTransformInMemory() throws IOException {
run(MemPipeline.getInstance(), WritableTypeFamily.getInstance(), false);
}
@Test
public void testTermFrequencyWithTransformInMemory() throws IOException {
run(MemPipeline.getInstance(), WritableTypeFamily.getInstance(), true);
}
public void run(Pipeline pipeline, PTypeFamily typeFamily, boolean transformTF) throws IOException {
String input = tmpDir.copyResourceFileName("docs.txt");
File transformedOutput = tmpDir.getFile("transformed-output");
File tfOutput = tmpDir.getFile("tf-output");
PCollection<String> docs = pipeline.readTextFile(input);
PTypeFamily ptf = docs.getTypeFamily();
/*
* Input: String Input title text
*
* Output: PTable<Pair<String, String>, Long> Pair<Pair<word, title>, count
* in title>
*/
PTable<Pair<String, String>, Long> tf = Aggregate.count(docs.parallelDo("term document frequency",
new DoFn<String, Pair<String, String>>() {
@Override
public void process(String doc, Emitter<Pair<String, String>> emitter) {
String[] kv = doc.split("\t");
String title = kv[0];
String text = kv[1];
for (String word : text.split("\\W+")) {
if (!word.isEmpty()) {
Pair<String, String> pair = Pair.of(word.toLowerCase(Locale.ENGLISH), title);
emitter.emit(pair);
}
}
}
}, ptf.pairs(ptf.strings(), ptf.strings())));
if (transformTF) {
/*
* Input: Pair<Pair<String, String>, Long> Pair<Pair<word, title>, count
* in title>
*
* Output: PTable<String, Pair<String, Long>> PTable<word, Pair<title,
* count in title>>
*/
PTable<String, Pair<String, Long>> wordDocumentCountPair = tf.parallelDo("transform wordDocumentPairCount",
new MapFn<Pair<Pair<String, String>, Long>, Pair<String, Pair<String, Long>>>() {
@Override
public Pair<String, Pair<String, Long>> map(Pair<Pair<String, String>, Long> input) {
Pair<String, String> wordDocumentPair = input.first();
return Pair.of(wordDocumentPair.first(), Pair.of(wordDocumentPair.second(), input.second()));
}
}, ptf.tableOf(ptf.strings(), ptf.pairs(ptf.strings(), ptf.longs())));
pipeline.writeTextFile(wordDocumentCountPair, transformedOutput.getAbsolutePath());
}
SourceTarget<String> st = At.textFile(tfOutput.getAbsolutePath());
pipeline.write(tf, st);
pipeline.run();
// test the case we should see
Iterable<String> lines = ((ReadableSource<String>) st).read(pipeline.getConfiguration());
boolean passed = false;
for (String line : lines) {
if ("[well,A]\t0".equals(line)) {
fail("Found " + line + " but well is in Document A 1 time");
}
if ("[well,A]\t1".equals(line)) {
passed = true;
}
}
assertTrue(passed);
pipeline.done();
}
}
| 2,550 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MRPipelineIT.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 java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.Map;
import com.google.common.io.Files;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.crunch.PipelineResult.StageResult;
import org.apache.crunch.fn.FilterFns;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.plan.PlanningParameters;
import org.apache.crunch.io.FormatBundle;
import org.apache.crunch.io.To;
import org.apache.crunch.io.text.TextFileTarget;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.Converter;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.junit.Rule;
import org.junit.Test;
public class MRPipelineIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void materializedColShouldBeWritten() throws Exception {
File textFile = tmpDir.copyResourceFile("shakes.txt");
Pipeline pipeline = new MRPipeline(MRPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> genericCollection = pipeline.readTextFile(textFile.getAbsolutePath());
pipeline.run();
PCollection<String> filter = genericCollection.filter("Filtering data", FilterFns.<String>ACCEPT_ALL());
filter.materialize();
pipeline.run();
File file = tmpDir.getFile("output.txt");
Target outFile = To.textFile(file.getAbsolutePath());
PCollection<String> write = filter.write(outFile);
write.materialize();
pipeline.run();
}
@Test
public void testPGroupedTableToMultipleOutputs() throws IOException{
Pipeline pipeline = new MRPipeline(MRPipelineIT.class, tmpDir.getDefaultConfiguration());
PGroupedTable<String, String> groupedLineTable = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt")).by(IdentityFn.<String>getInstance(), Writables.strings()).groupByKey();
PTable<String, String> ungroupedTableA = groupedLineTable.ungroup();
PTable<String, String> ungroupedTableB = groupedLineTable.ungroup();
File outputDirA = tmpDir.getFile("output_a");
File outputDirB = tmpDir.getFile("output_b");
pipeline.writeTextFile(ungroupedTableA, outputDirA.getAbsolutePath());
pipeline.writeTextFile(ungroupedTableB, outputDirB.getAbsolutePath());
PipelineResult result = pipeline.done();
for(StageResult stageResult : result.getStageResults()){
assertTrue(stageResult.getStageName().length() > 1);
assertTrue(stageResult.getStageId().length() > 1);
}
// Verify that output from a single PGroupedTable can be sent to multiple collections
assertTrue(new File(outputDirA, "part-r-00000").exists());
assertTrue(new File(outputDirB, "part-r-00000").exists());
}
@Test
public void testWritingOfDotfile() throws IOException {
File dotfileDir = Files.createTempDir();
Pipeline pipeline = new MRPipeline(MRPipelineIT.class, tmpDir.getDefaultConfiguration());
pipeline.getConfiguration().set(PlanningParameters.PIPELINE_DOTFILE_OUTPUT_DIR, dotfileDir.getAbsolutePath());
PCollection<String> lines = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
pipeline.write(
lines.parallelDo(IdentityFn.<String>getInstance(), Writables.strings()),
To.textFile(tmpDir.getFile("output").getAbsolutePath()));
pipeline.done();
File[] files = dotfileDir.listFiles((FileFilter)new SuffixFileFilter(".dot"));
assertEquals(1, files.length);
String fileName = files[0].getName();
String fileNamePrefix = URLEncoder.encode(pipeline.getName(), "UTF-8");
fileNamePrefix = (fileNamePrefix.length() < 150) ? fileNamePrefix : fileNamePrefix.substring(0, 150);
assertTrue("DOT file name '" + fileName + "' did not start with the pipeline name '" + fileNamePrefix + "'.",
fileName.startsWith(fileNamePrefix));
String regex = ".*_\\d{4}-\\d{2}-\\d{2}_\\d{2}\\.\\d{2}\\.\\d{2}\\.\\d{3}_jobplan\\.dot";
assertTrue("DOT file name '" + fileName + "' did not match regex '" + regex + "'.", fileName.matches(regex));
}
@Test
public void testJobCredentials() throws IOException {
Pipeline pipeline = new MRPipeline(MRPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> lines = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
pipeline.write(lines, new SecretTextFileTarget(tmpDir.getFile("output").getAbsolutePath()));
PipelineResult pipelineResult = pipeline.done();
assertTrue(pipelineResult.succeeded());
}
private static class SecretTextFileTarget extends TextFileTarget {
public SecretTextFileTarget(String path) {
super(path);
}
@Override
public Target outputConf(String key, String value) {
return super.outputConf(key, value);
}
@Override
public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) {
Converter converter = ptype.getConverter();
Class keyClass = converter.getKeyClass();
Class valueClass = converter.getValueClass();
FormatBundle fb = FormatBundle.forOutput(SecretTextOutputFormat.class);
configureForMapReduce(job, keyClass, valueClass, fb, outputPath, name);
job.getCredentials().addSecretKey(new Text("secret"), "myPassword".getBytes());
}
}
private static class SecretTextOutputFormat extends TextOutputFormat {
@Override
public RecordWriter getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {
byte[] secret = job.getCredentials().getSecretKey(new Text("secret"));
assertEquals("job credentials did not match", "myPassword", new String(secret));
return super.getRecordWriter(job);
}
}
}
| 2,551 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/UnionIT.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.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.Map;
import org.apache.crunch.fn.Aggregators;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.test.Tests;
import org.apache.crunch.types.avro.Avros;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultiset;
public class UnionIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
private MRPipeline pipeline;
private PCollection<String> words1;
private PCollection<String> words2;
@Before
public void setUp() throws IOException {
pipeline = new MRPipeline(UnionIT.class, tmpDir.getDefaultConfiguration());
words1 = pipeline.readTextFile(tmpDir.copyResourceFileName(Tests.resource(this, "src1.txt")));
words2 = pipeline.readTextFile(tmpDir.copyResourceFileName(Tests.resource(this, "src2.txt")));
}
@After
public void tearDown() {
pipeline.done();
}
@Test
public void testUnion() throws Exception {
IdentityFn<String> identity = IdentityFn.getInstance();
words1 = words1.parallelDo(identity, Avros.strings());
words2 = words2.parallelDo(identity, Avros.strings());
PCollection<String> union = words1.union(words2);
ImmutableMultiset<String> actual = ImmutableMultiset.copyOf(union.materialize());
assertThat(actual.elementSet().size(), is(3));
assertThat(actual.count("a1"), is(4));
assertThat(actual.count("b2"), is(2));
assertThat(actual.count("c3"), is(2));
}
@Test
public void testTableUnion() throws IOException {
PTable<String, String> words1ByFirstLetter = byFirstLetter(words1);
PTable<String, String> words2ByFirstLetter = byFirstLetter(words2);
PTable<String, String> union = words1ByFirstLetter.union(words2ByFirstLetter);
ImmutableMultiset<Pair<String, String>> actual = ImmutableMultiset.copyOf(union.materialize());
assertThat(actual.elementSet().size(), is(3));
assertThat(actual.count(Pair.of("a", "1")), is(4));
assertThat(actual.count(Pair.of("b", "2")), is(2));
assertThat(actual.count(Pair.of("c", "3")), is(2));
}
@Test
public void testUnionThenGroupByKey() throws IOException {
PCollection<String> union = words1.union(words2);
PGroupedTable<String, String> grouped = byFirstLetter(union).groupByKey();
Map<String, String> actual = grouped.combineValues(Aggregators.STRING_CONCAT("", true))
.materializeToMap();
Map<String, String> expected = ImmutableMap.of("a", "1111", "b", "22", "c", "33");
assertThat(actual, is(expected));
}
@Test
public void testTableUnionThenGroupByKey() throws IOException {
PTable<String, String> words1ByFirstLetter = byFirstLetter(words1);
PTable<String, String> words2ByFirstLetter = byFirstLetter(words2);
PTable<String, String> union = words1ByFirstLetter.union(words2ByFirstLetter);
PGroupedTable<String, String> grouped = union.groupByKey();
Map<String, String> actual = grouped.combineValues(Aggregators.STRING_CONCAT("", true))
.materializeToMap();
Map<String, String> expected = ImmutableMap.of("a", "1111", "b", "22", "c", "33");
assertThat(actual, is(expected));
}
private static PTable<String, String> byFirstLetter(PCollection<String> values) {
return values.parallelDo("byFirstLetter", new FirstLetterKeyFn(),
Avros.tableOf(Avros.strings(), Avros.strings()));
}
private static class FirstLetterKeyFn extends DoFn<String, Pair<String, String>> {
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
if (input.length() > 1) {
emitter.emit(Pair.of(input.substring(0, 1), input.substring(1)));
}
}
}
}
| 2,552 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/DeepCopyCustomTuplesIT.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.apache.crunch.types.avro.Avros.*;
import static org.junit.Assert.assertEquals;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Iterables;
/**
*
*/
public class DeepCopyCustomTuplesIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
public static class PID extends Pair<Integer, String> {
public PID(Integer first, String second) {
super(first, second);
}
}
private static PType<PID> pids = tuples(PID.class, ints(), strings());
@Test
public void testDeepCopyCustomTuple() throws Exception {
Pipeline p = new MRPipeline(DeepCopyCustomTuplesIT.class, tmpDir.getDefaultConfiguration());
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakes = p.readTextFile(shakesInputPath);
Iterable<String> out = shakes
.parallelDo(new PreProcFn(), tableOf(ints(), pairs(ints(), pids)))
.groupByKey()
.parallelDo(new PostProcFn(), strings())
.materialize();
assertEquals(59, Iterables.size(out));
p.done();
}
private static class PreProcFn extends MapFn<String, Pair<Integer, Pair<Integer, PID>>> {
private int counter = 0;
@Override
public Pair<Integer, Pair<Integer, PID>> map(String input) {
return Pair.of(counter++, Pair.of(counter++, new PID(input.length(), input)));
}
};
private static class PostProcFn extends DoFn<Pair<Integer, Iterable<Pair<Integer, PID>>>, String> {
@Override
public void process(Pair<Integer, Iterable<Pair<Integer, PID>>> input, Emitter<String> emitter) {
for (Pair<Integer, PID> p : input.second()) {
if (p.second().first() > 0 && p.second().first() < 10) {
emitter.emit(p.second().second());
}
}
}
}
}
| 2,553 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/EnumPairIT.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 java.io.IOException;
import java.io.Serializable;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypes;
import org.apache.crunch.types.writable.Writables;
import org.junit.Rule;
import org.junit.Test;
public class EnumPairIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
enum etypes {
type1,
}
@Test
public void testEnumPTypes() throws IOException {
String inputFile1 = tmpDir.copyResourceFileName("set1.txt");
Pipeline pipeline = new MRPipeline(EnumPairIT.class);
PCollection<String> set1 = pipeline.readTextFile(inputFile1);
PTable<String, etypes> data = set1.parallelDo(new DoFn<String, Pair<String, etypes>>() {
@Override
public void process(String input, Emitter<Pair<String, etypes>> emitter) {
emitter.emit(new Pair<String, etypes>(input, etypes.type1));
}
}, Writables.tableOf(Writables.strings(), PTypes.enums(etypes.class, set1.getTypeFamily())));
Iterable<Pair<String, etypes>> materialized = data.materialize();
pipeline.run();
for (Pair<String, etypes> pair : materialized) {
assertEquals(etypes.type1, pair.second());
}
}
}
| 2,554 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/CancelJobsIT.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 java.io.IOException;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
/**
*
*/
public class CancelJobsIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testRun() throws Exception {
PipelineExecution pe = run();
pe.waitUntilDone();
PipelineResult pr = pe.getResult();
assertEquals(PipelineExecution.Status.SUCCEEDED, pe.getStatus());
assertEquals(2, pr.getStageResults().size());
}
@Test
public void testGet() throws Exception {
PipelineExecution pe = run();
PipelineResult pr = pe.get();
assertEquals(PipelineExecution.Status.SUCCEEDED, pe.getStatus());
assertEquals(2, pr.getStageResults().size());
}
@Test
public void testKill() throws Exception {
PipelineExecution pe = run();
pe.kill();
pe.waitUntilDone();
assertEquals(PipelineExecution.Status.KILLED, pe.getStatus());
}
@Test
public void testKillGet() throws Exception {
PipelineExecution pe = run();
pe.kill();
PipelineResult res = pe.get();
assertFalse(res.succeeded());
assertEquals(PipelineExecution.Status.KILLED, pe.getStatus());
}
@Test
public void testCancelNoInterrupt() throws Exception {
PipelineExecution pe = run();
pe.cancel(false);
pe.waitUntilDone();
assertEquals(PipelineExecution.Status.SUCCEEDED, pe.getStatus());
}
@Test
public void testCancelMayInterrupt() throws Exception {
PipelineExecution pe = run();
pe.cancel(true);
pe.waitUntilDone();
assertEquals(PipelineExecution.Status.KILLED, pe.getStatus());
}
@Test
public void testKillMultipleTimes() throws Exception {
PipelineExecution pe = run();
for (int i = 0; i < 10; i++) {
pe.kill();
}
pe.waitUntilDone();
assertEquals(PipelineExecution.Status.KILLED, pe.getStatus());
}
@Test
public void testKillAfterDone() throws Exception {
PipelineExecution pe = run();
pe.waitUntilDone();
assertEquals(PipelineExecution.Status.SUCCEEDED, pe.getStatus());
pe.kill(); // expect no-op
assertEquals(PipelineExecution.Status.SUCCEEDED, pe.getStatus());
}
public PipelineExecution run() throws IOException {
String shakes = tmpDir.copyResourceFileName("shakes.txt");
String out = tmpDir.getFileName("cancel");
Pipeline p = new MRPipeline(CancelJobsIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> words = p.readTextFile(shakes);
p.write(words.count().top(20), To.textFile(out));
return p.runAsync(); // need to hack to slow down job start up if this test becomes flaky.
}
}
| 2,555 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/EmptyPCollectionIT.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 com.google.common.collect.Iterables;
import org.apache.crunch.fn.Aggregators;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.writable.Writables;
import org.junit.Test;
import java.io.Serializable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class EmptyPCollectionIT extends CrunchTestSupport implements Serializable {
private static class SplitFn extends DoFn<String, Pair<String, Long>> {
@Override
public void process(String input, Emitter<Pair<String, Long>> emitter) {
for (String word : input.split("\\s+")) {
emitter.emit(Pair.of(word, 1L));
}
}
}
@Test
public void testEmptyMR() throws Exception {
MRPipeline p = new MRPipeline(EmptyPCollectionIT.class, tempDir.getDefaultConfiguration());
assertTrue(Iterables.isEmpty(p.emptyPCollection(Writables.strings())
.parallelDo(new SplitFn(), Writables.tableOf(Writables.strings(), Writables.longs()))
.groupByKey()
.combineValues(Aggregators.SUM_LONGS())
.materialize()));
p.done();
}
@Test
public void testUnionWithEmptyMR() throws Exception {
MRPipeline p = new MRPipeline(EmptyPCollectionIT.class, tempDir.getDefaultConfiguration());
assertFalse(Iterables.isEmpty(p.emptyPCollection(Writables.strings())
.parallelDo(new SplitFn(), Writables.tableOf(Writables.strings(), Writables.longs()))
.union(
p.read(From.textFile(tempDir.copyResourceFileName("shakes.txt")))
.parallelDo(new SplitFn(), Writables.tableOf(Writables.strings(), Writables.longs())))
.groupByKey()
.combineValues(Aggregators.SUM_LONGS())
.materialize()));
p.done();
}
@Test
public void testUnionTableWithEmptyMR() throws Exception {
MRPipeline p = new MRPipeline(EmptyPCollectionIT.class, tempDir.getDefaultConfiguration());
assertFalse(Iterables.isEmpty(p.emptyPTable(Writables.tableOf(Writables.strings(), Writables.longs()))
.union(
p.read(From.textFile(tempDir.copyResourceFileName("shakes.txt")))
.parallelDo(new SplitFn(), Writables.tableOf(Writables.strings(), Writables.longs())))
.groupByKey()
.combineValues(Aggregators.SUM_LONGS())
.materialize()));
p.done();
}
}
| 2,556 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/UnionFromSameSourceIT.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 java.io.IOException;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTableType;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.writable.Writables;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* Collection of tests re-using the same PCollection in various unions.
*/
public class UnionFromSameSourceIT {
private static final int NUM_ELEMENTS = 4;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
private Pipeline pipeline;
private PType<String> elementType = Writables.strings();
private PTableType<String, String> tableType = Writables.tableOf(Writables.strings(),
Writables.strings());
@Before
public void setUp() {
pipeline = new MRPipeline(UnionFromSameSourceIT.class, tmpDir.getDefaultConfiguration());
}
@Test
public void testUnion_SingleRead() throws IOException {
PCollection<String> strings = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
PCollection<String> union = strings.union(strings.parallelDo(IdentityFn.<String> getInstance(),
strings.getPType()));
assertEquals(NUM_ELEMENTS * 2, getCount(union));
}
@Test
public void testUnion_TwoReads() throws IOException {
PCollection<String> stringsA = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
PCollection<String> stringsB = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
PCollection<String> union = stringsA.union(stringsB);
assertEquals(NUM_ELEMENTS * 2, getCount(union));
}
@Test
public void testDoubleUnion_EndingWithGBK() throws IOException {
runDoubleUnionPipeline(true);
}
@Test
public void testDoubleUnion_EndingWithoutGBK() throws IOException {
runDoubleUnionPipeline(false);
}
private void runDoubleUnionPipeline(boolean endWithGBK) throws IOException {
PCollection<String> strings = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"));
PTable<String, String> tableA = strings.parallelDo("to table A", new ToTableFn(), tableType);
PTable<String, String> tableB = strings.parallelDo("to table B", new ToTableFn(), tableType);
PGroupedTable<String, String> groupedTable = tableA.union(tableB).groupByKey();
PCollection<String> ungrouped = groupedTable.parallelDo("ungroup before union",
new FromGroupedTableFn(), elementType).union(
strings.parallelDo("fake id", IdentityFn.<String> getInstance(), elementType));
PTable<String, String> table = ungrouped.parallelDo("union back to table", new ToTableFn(),
tableType);
if (endWithGBK) {
table = table.groupByKey().ungroup();
}
assertEquals(3 * NUM_ELEMENTS, getCount(table));
}
private int getCount(PCollection<?> pcollection) {
int cnt = 0;
for (Object v : pcollection.materialize()) {
cnt++;
}
return cnt;
}
private static class ToTableFn extends MapFn<String, Pair<String, String>> {
@Override
public Pair<String, String> map(String input) {
return Pair.of(input, input);
}
}
private static class FromGroupedTableFn extends DoFn<Pair<String, Iterable<String>>, String> {
@Override
public void process(Pair<String, Iterable<String>> input, Emitter<String> emitter) {
for (String value : input.second()) {
emitter.emit(value);
}
}
}
}
| 2,557 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MaterializeToMapIT.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 java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import org.apache.commons.lang.SerializationUtils;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class MaterializeToMapIT {
static final ImmutableList<Pair<Integer, String>> kvPairs = ImmutableList.of(Pair.of(0, "a"), Pair.of(1, "b"),
Pair.of(2, "c"), Pair.of(3, "e"));
public static void assertMatches(Map<Integer, String> m) {
for (Map.Entry<Integer,String> entry : m.entrySet()) {
assertEquals(kvPairs.get(entry.getKey()).second(), entry.getValue());
}
}
@Test
public void testMemMaterializeToMap() {
assertMatches(MemPipeline.tableOf(kvPairs).materializeToMap());
}
private static class Set1Mapper extends MapFn<String, Pair<Integer, String>> {
@Override
public Pair<Integer, String> map(String input) {
int k = -1;
if (input.equals("a")) {
k = 0;
} else if (input.equals("b")) {
k = 1;
} else if (input.equals("c")) {
k = 2;
} else if (input.equals("e")) {
k = 3;
}
return Pair.of(k, input);
}
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testMRMaterializeToMap() throws IOException {
Pipeline p = new MRPipeline(MaterializeToMapIT.class, tmpDir.getDefaultConfiguration());
String inputFile = tmpDir.copyResourceFileName("set1.txt");
PCollection<String> c = p.readTextFile(inputFile);
PTypeFamily tf = c.getTypeFamily();
PTable<Integer, String> t = c.parallelDo(new Set1Mapper(), tf.tableOf(tf.ints(), tf.strings()));
Map<Integer, String> m = t.materializeToMap();
assertMatches(m);
Map<Integer, String> mclone = (Map<Integer, String>) SerializationUtils.clone((Serializable) m);
assertMatches(mclone);
}
}
| 2,558 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/TupleNClassCastBugIT.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 java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.io.Files;
public class TupleNClassCastBugIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
public static PCollection<TupleN> mapGroupDo(PCollection<String> lines, PTypeFamily ptf) {
PTable<String, TupleN> mapped = lines.parallelDo(new MapFn<String, Pair<String, TupleN>>() {
@Override
public Pair<String, TupleN> map(String line) {
String[] columns = line.split("\\t");
String docId = columns[0];
String docLine = columns[1];
return Pair.of(docId, new TupleN(docId, docLine));
}
}, ptf.tableOf(ptf.strings(), ptf.tuples(ptf.strings(), ptf.strings())));
return mapped.groupByKey().parallelDo(new DoFn<Pair<String, Iterable<TupleN>>, TupleN>() {
@Override
public void process(Pair<String, Iterable<TupleN>> input, Emitter<TupleN> tupleNEmitter) {
for (TupleN tuple : input.second()) {
tupleNEmitter.emit(tuple);
}
}
}, ptf.tuples(ptf.strings(), ptf.strings()));
}
@Test
public void testWritables() throws IOException {
run(new MRPipeline(TupleNClassCastBugIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testAvro() throws IOException {
run(new MRPipeline(TupleNClassCastBugIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
public void run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
String outputPath = tmpDir.getFileName("output");
PCollection<String> docLines = pipeline.readTextFile(inputPath);
pipeline.writeTextFile(mapGroupDo(docLines, typeFamily), outputPath);
pipeline.done();
// *** We are not directly testing the output, we are looking for a
// ClassCastException
// *** which is thrown in a different thread during the reduce phase. If all
// is well
// *** the file will exist and have six lines. Otherwise the bug is present.
File outputFile = new File(outputPath, "part-r-00000");
List<String> lines = Files.readLines(outputFile, Charset.defaultCharset());
int lineCount = 0;
for (String line : lines) {
lineCount++;
}
assertEquals(6, lineCount);
}
}
| 2,559 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/MultipleOutputIT.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.assertFalse;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.crunch.PipelineResult.StageResult;
import org.apache.crunch.fn.Aggregators;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.CrunchOutputs;
import org.apache.crunch.io.To;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
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.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class MultipleOutputIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
public static PCollection<String> evenCountLetters(PCollection<String> words, PTypeFamily typeFamily) {
return words.parallelDo("even", new FilterFn<String>() {
@Override
public boolean accept(String input) {
return input.length() % 2 == 0;
}
}, typeFamily.strings());
}
public static PCollection<String> oddCountLetters(PCollection<String> words, PTypeFamily typeFamily) {
return words.parallelDo("odd", new FilterFn<String>() {
@Override
public boolean accept(String input) {
return input.length() % 2 != 0;
}
}, typeFamily.strings());
}
public static PTable<String, Long> substr(PTable<String, Long> ptable) {
return ptable.parallelDo(new DoFn<Pair<String, Long>, Pair<String, Long>>() {
public void process(Pair<String, Long> input, Emitter<Pair<String, Long>> emitter) {
if (input.first().length() > 0) {
emitter.emit(Pair.of(input.first().substring(0, 1), input.second()));
}
}
}, ptable.getPTableType());
}
@Test
public void testWritables() throws IOException {
run(new MRPipeline(MultipleOutputIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance());
}
@Test
public void testAvro() throws IOException {
run(new MRPipeline(MultipleOutputIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance());
}
@Test
public void testParallelDosFused() throws IOException {
PipelineResult result = run(new MRPipeline(MultipleOutputIT.class, tmpDir.getDefaultConfiguration()),
WritableTypeFamily.getInstance());
// Ensure our multiple outputs were fused into a single job.
assertEquals("parallel Dos not fused into a single job", 1, result.getStageResults().size());
}
@Test
public void testCountersEnabled() throws IOException {
PipelineResult result = run(new MRPipeline(MultipleOutputIT.class, tmpDir.getDefaultConfiguration()),
WritableTypeFamily.getInstance());
assertEquals(1, result.getStageResults().size());
StageResult stageResult = result.getStageResults().get(0);
String counterGroup = CrunchOutputs.class.getName();
assertEquals(3, stageResult.getCounterNames().get(counterGroup).size());
assertEquals(1l, stageResult.getCounterValue(counterGroup, "out1"));
assertEquals(1l, stageResult.getCounterValue(counterGroup, "out2"));
assertEquals(0l, stageResult.getCounterValue(counterGroup, "out3"));
}
@Test
public void testCountersDisabled() throws IOException {
Configuration configuration = tmpDir.getDefaultConfiguration();
configuration.setBoolean(CrunchOutputs.CRUNCH_DISABLE_OUTPUT_COUNTERS, true);
PipelineResult result = run(new MRPipeline(MultipleOutputIT.class, configuration),
WritableTypeFamily.getInstance());
assertEquals(1, result.getStageResults().size());
StageResult stageResult = result.getStageResults().get(0);
assertFalse(stageResult.getCounterNames().containsKey(CrunchOutputs.CRUNCH_OUTPUTS));
}
public PipelineResult run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String inputPath = tmpDir.copyResourceFileName("letters.txt");
String outputPathEven = tmpDir.getFileName("even");
String outputPathOdd = tmpDir.getFileName("odd");
String outputPathReduce = tmpDir.getFileName("reduce");
PCollection<String> words = pipeline.read(At.textFile(inputPath, typeFamily.strings()));
PCollection<String> evenCountWords = evenCountLetters(words, typeFamily);
PCollection<String> oddCountWords = oddCountLetters(words, typeFamily);
pipeline.writeTextFile(evenCountWords, outputPathEven);
pipeline.writeTextFile(oddCountWords, outputPathOdd);
evenCountWords.by(new FirstLetterFn(), typeFamily.strings())
.groupByKey()
.combineValues(Aggregators.<String>FIRST_N(10))
.write(To.textFile(outputPathReduce));
PipelineResult result = pipeline.done();
checkFileContents(outputPathEven, Arrays.asList("bb"));
checkFileContents(outputPathOdd, Arrays.asList("a"));
checkNotEmpty(outputPathReduce);
return result;
}
static class FirstLetterFn extends MapFn<String, String> {
@Override
public String map(String input) {
return input.substring(0, 1);
}
}
/**
* Mutates the state of an input and then emits the mutated object.
*/
static class AppendFn extends DoFn<StringWrapper, StringWrapper> {
private String value;
public AppendFn(String value) {
this.value = value;
}
@Override
public void process(StringWrapper input, Emitter<StringWrapper> emitter) {
input.setValue(input.getValue() + value);
emitter.emit(input);
}
}
/**
* Fusing multiple pipelines has a risk of running into object reuse bugs.
* This test verifies that mutating the state of an object that is passed
* through multiple streams of a pipeline doesn't allow one stream to affect
* another.
*/
@Test
public void testFusedMappersObjectReuseBug() throws IOException {
Pipeline pipeline = new MRPipeline(MultipleOutputIT.class, tmpDir.getDefaultConfiguration());
PCollection<StringWrapper> stringWrappers = pipeline.readTextFile(tmpDir.copyResourceFileName("set2.txt"))
.parallelDo(new StringWrapper.StringToStringWrapperMapFn(), Avros.reflects(StringWrapper.class));
PCollection<String> stringsA = stringWrappers.parallelDo(new AppendFn("A"), stringWrappers.getPType())
.parallelDo(new StringWrapper.StringWrapperToStringMapFn(), Writables.strings());
PCollection<String> stringsB = stringWrappers.parallelDo(new AppendFn("B"), stringWrappers.getPType())
.parallelDo(new StringWrapper.StringWrapperToStringMapFn(), Writables.strings());
String outputA = tmpDir.getFileName("stringsA");
String outputB = tmpDir.getFileName("stringsB");
pipeline.writeTextFile(stringsA, outputA);
pipeline.writeTextFile(stringsB, outputB);
PipelineResult pipelineResult = pipeline.done();
// Make sure fusing did actually occur
assertEquals(1, pipelineResult.getStageResults().size());
checkFileContents(outputA, Lists.newArrayList("cA", "dA", "aA"));
checkFileContents(outputB, Lists.newArrayList("cB", "dB", "aB"));
}
private void checkNotEmpty(String filePath) throws IOException {
File dir = new File(filePath);
File[] partFiles = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith("part");
}
});
assertTrue(partFiles.length > 0);
assertTrue(Files.readLines(partFiles[0], Charset.defaultCharset()).size() > 0);
}
private void checkFileContents(String filePath, List<String> expected) throws IOException {
File outputFile = new File(filePath, "part-m-00000");
List<String> lines = Files.readLines(outputFile, Charset.defaultCharset());
assertEquals(expected, lines);
}
}
| 2,560 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mr
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mr/plan/DotfilesIT.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 java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
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.io.At;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.apache.hadoop.conf.Configuration;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.io.Files;
public class DotfilesIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Rule
public TemporaryPath dotfileDir = TemporaryPaths.create();
enum WordCountStats {
ANDS
}
public static PTable<String, Long> wordCount(PCollection<String> words, PTypeFamily typeFamily) {
return Aggregate.count(words.parallelDo(new DoFn<String, String>() {
@Override
public void process(String line, Emitter<String> emitter) {
for (String word : line.split("\\s+")) {
emitter.emit(word);
if ("and".equals(word)) {
increment(WordCountStats.ANDS);
}
}
}
}, typeFamily.strings()));
}
@Test
public void testPlanDotfileWithOutputDir() throws Throwable {
Configuration conf = tmpDir.getDefaultConfiguration();
DotfileUtil.setPipelineDotfileOutputDir(conf, dotfileDir.getRootFileName());
run(new MRPipeline(DotfilesIT.class, conf), WritableTypeFamily.getInstance());
String[] dotfileNames = dotfileNames(dotfileDir.getRootFile());
assertEquals(1, dotfileNames.length);
assertTrue(containsFileEndingWith(dotfileNames, "jobplan.dot"));
assertTrue("PlanDotfile should always be present in the Configuration",
conf.get(PlanningParameters.PIPELINE_PLAN_DOTFILE).length() > 0);
}
@Test
public void testPlanDotfileWithoutOutputDir() throws Throwable {
Configuration conf = tmpDir.getDefaultConfiguration();
run(new MRPipeline(DotfilesIT.class, conf), WritableTypeFamily.getInstance());
String[] dotfileNames = dotfileNames(dotfileDir.getRootFile());
assertEquals(0, dotfileNames.length);
assertTrue("PlanDotfile should always be present in the Configuration",
conf.get(PlanningParameters.PIPELINE_PLAN_DOTFILE).length() > 0);
}
@Test
public void testDebugDotfiles() throws Throwable {
Configuration conf = tmpDir.getDefaultConfiguration();
DotfileUtil.setPipelineDotfileOutputDir(conf, dotfileDir.getRootFileName());
DotfileUtil.enableDebugDotfiles(conf);
run(new MRPipeline(DotfilesIT.class, conf), WritableTypeFamily.getInstance());
String[] dotfileNames = dotfileNames(dotfileDir.getRootFile());
assertEquals(6, dotfileNames.length);
assertTrue(containsFileEndingWith(dotfileNames, "jobplan.dot"));
assertTrue(containsFileEndingWith(dotfileNames, "split_graph_plan.dot"));
assertTrue(containsFileEndingWith(dotfileNames, "split_graph_with_components_plan.dot"));
assertTrue(containsFileEndingWith(dotfileNames, "rt_plan.dot"));
assertTrue(containsFileEndingWith(dotfileNames, "base_graph_plan.dot"));
assertTrue(containsFileEndingWith(dotfileNames, "lineage_plan.dot"));
assertTrue("PlanDotfile should always be present in the Configuration",
conf.get(PlanningParameters.PIPELINE_PLAN_DOTFILE).length() > 0);
}
@Test
public void testDebugDotfilesEnabledButNoOutputDirSet() throws Throwable {
Configuration conf = tmpDir.getDefaultConfiguration();
DotfileUtil.enableDebugDotfiles(conf);
run(new MRPipeline(DotfilesIT.class, conf), WritableTypeFamily.getInstance());
String[] dotfileNames = dotfileNames(dotfileDir.getRootFile());
assertEquals(0, dotfileNames.length);
assertTrue("PlanDotfile should always be present in the Configuration",
conf.get(PlanningParameters.PIPELINE_PLAN_DOTFILE).length() > 0);
}
public void run(Pipeline pipeline, PTypeFamily typeFamily) throws IOException {
String inputPath = tmpDir.copyResourceFileName("shakes.txt");
String outputPath = tmpDir.getFileName("output");
PCollection<String> shakespeare = pipeline.read(At.textFile(inputPath, typeFamily.strings()));
PTable<String, Long> wordCount = wordCount(shakespeare, typeFamily);
pipeline.writeTextFile(wordCount, outputPath);
PipelineResult res = pipeline.done();
assertTrue(res.succeeded());
List<PipelineResult.StageResult> stageResults = res.getStageResults();
assertEquals(1, stageResults.size());
assertEquals(375, stageResults.get(0).getCounterValue(WordCountStats.ANDS));
File outputFile = new File(outputPath, "part-r-00000");
List<String> lines = Files.readLines(outputFile, Charset.defaultCharset());
boolean passed = false;
for (String line : lines) {
if (line.startsWith("Macbeth\t") || line.startsWith("[Macbeth,")) {
passed = true;
break;
}
}
assertTrue(passed);
}
private boolean containsFileEndingWith(String[] fileNames, String suffix) {
for (String fn : fileNames) {
if (fn.endsWith(suffix))
return true;
}
return false;
}
private String[] dotfileNames(File rootDir) {
File[] dotfileFiles = rootDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".dot");
}
});
String[] fileNames = new String[dotfileFiles.length];
int i = 0;
for (File file : dotfileFiles) {
fileNames[i++] = file.getName();
}
return fileNames;
}
}
| 2,561 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mr
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mr/exec/MRExecutorIT.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 org.apache.commons.lang.time.StopWatch;
import org.apache.crunch.CrunchRuntimeException;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.PipelineExecution;
import org.apache.crunch.impl.mr.MRJob;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.MRPipelineExecution;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.mapreduce.Job;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
import static org.apache.crunch.types.writable.Writables.longs;
import static org.apache.crunch.types.writable.Writables.strings;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class MRExecutorIT {
private static class SleepForeverFn extends DoFn<Long, Long> {
@Override
public void process(Long input, Emitter<Long> emitter) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
throw new CrunchRuntimeException(e);
}
}
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
/**
* Tests that the pipeline should be stopped immediately when one of the jobs
* get failed. The rest of running jobs should be killed.
*/
@Test
public void testStopPipelineImmediatelyOnJobFailure() throws Exception {
String inPath = tmpDir.copyResourceFileName("shakes.txt");
MRPipeline pipeline = new MRPipeline(MRExecutorIT.class);
// Issue two jobs that sleep forever.
PCollection<String> in = pipeline.read(From.textFile(inPath));
for (int i = 0; i < 2; i++) {
in.count()
.values()
.parallelDo(new SleepForeverFn(), longs())
.write(To.textFile(tmpDir.getPath("out_" + i)));
}
MRPipelineExecution exec = pipeline.runAsync();
// Wait until both of the two jobs are submitted.
List<MRJob> jobs = exec.getJobs();
assertEquals(2, jobs.size());
StopWatch watch = new StopWatch();
watch.start();
int numOfJobsSubmitted = 0;
while (numOfJobsSubmitted < 2 && watch.getTime() < 10000) {
numOfJobsSubmitted = 0;
for (MRJob job : jobs) {
if (job.getJobState() == MRJob.State.RUNNING) {
numOfJobsSubmitted++;
}
}
Thread.sleep(100);
}
assertEquals(2, numOfJobsSubmitted);
// Kill one of them.
Job job0 = jobs.get(0).getJob();
job0.killJob();
// Expect the pipeline exits and the other job is killed.
StopWatch watch2 = new StopWatch();
watch2.start();
Job job1 = jobs.get(1).getJob();
while (!job1.isComplete() && watch2.getTime() < 10000) {
Thread.sleep(100);
}
assertTrue(job1.isComplete());
assertEquals(PipelineExecution.Status.FAILED, exec.getStatus());
}
}
| 2,562 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/dist
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/dist/collect/FailIT.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 org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.PipelineExecution;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.writable.Writables;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class FailIT extends CrunchTestSupport {
static class InverseFn extends MapFn<String, Integer> {
@Override
public Integer map(String input) {
int c = 0;
return 1 / c;
}
};
@Test
public void testKill() throws Exception {
Pipeline pipeline = new MRPipeline(FailIT.class, tempDir.getDefaultConfiguration());
PCollection<String> p = pipeline.readTextFile(tempDir.copyResourceFileName("shakes.txt"));
PCollection<Integer> result = p.parallelDo(new InverseFn(), Writables.ints());
result.cache();
PipelineExecution execution = pipeline.runAsync();
while (!execution.isDone() && !execution.isCancelled()
&& execution.getStatus() != PipelineExecution.Status.FAILED
&& execution.getResult() == null) {
try {
Thread.sleep(1000);
System.out.println("Job Status: " + execution.getStatus().toString());
} catch (InterruptedException e) {
System.err.println("ABORTING");
e.printStackTrace();
try {
execution.kill();
execution.waitUntilDone();
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
throw new RuntimeException(e);
}
}
System.out.println("Finished running job.");
assertEquals(PipelineExecution.Status.FAILED, execution.getStatus());
}
}
| 2,563 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/dist
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/dist/collect/UnionCollectionIT.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.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.crunch.PCollection;
import org.apache.crunch.PTableKeyValueIT;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(value = Parameterized.class)
public class UnionCollectionIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
private static final Logger LOG = LoggerFactory.getLogger(UnionCollectionIT.class);
private PTypeFamily typeFamily;
private Pipeline pipeline;
private PCollection<String> union;
private ArrayList<String> EXPECTED = Lists.newArrayList("a", "a", "b", "c", "c", "d", "e");
private Class pipelineClass;
@Before
@SuppressWarnings("unchecked")
public void setUp() throws IOException {
String inputFile1 = tmpDir.copyResourceFileName("set1.txt");
String inputFile2 = tmpDir.copyResourceFileName("set2.txt");
if (pipelineClass == null) {
pipeline = MemPipeline.getInstance();
} else {
pipeline = new MRPipeline(pipelineClass, tmpDir.getDefaultConfiguration());
}
PCollection<String> firstCollection = pipeline.read(At.textFile(inputFile1, typeFamily.strings()));
PCollection<String> secondCollection = pipeline.read(At.textFile(inputFile2, typeFamily.strings()));
LOG.info("Test fixture: [ {} : {}] First: {}, Second: {}", new Object[]{pipeline.getClass().getSimpleName()
,typeFamily.getClass().getSimpleName(), Lists.newArrayList(firstCollection.materialize().iterator()),
Lists.newArrayList(secondCollection.materialize().iterator())});
union = secondCollection.union(firstCollection);
}
@Parameters
public static Collection<Object[]> data() throws IOException {
Object[][] data = new Object[][] { { WritableTypeFamily.getInstance(), PTableKeyValueIT.class },
{ WritableTypeFamily.getInstance(), null }, { AvroTypeFamily.getInstance(), PTableKeyValueIT.class },
{ AvroTypeFamily.getInstance(), null } };
return Arrays.asList(data);
}
public UnionCollectionIT(PTypeFamily typeFamily, Class pipelineClass) {
this.typeFamily = typeFamily;
this.pipelineClass = pipelineClass;
}
@Test
public void unionMaterializeShouldNotThrowNPE() throws Exception {
checkMaterialized(union.materialize());
checkMaterialized(pipeline.materialize(union));
}
private void checkMaterialized(Iterable<String> materialized) {
List<String> materializedValues = Lists.newArrayList(materialized.iterator());
Collections.sort(materializedValues);
LOG.info("Materialized union: {}", materializedValues);
assertEquals(EXPECTED, materializedValues);
}
@Test
public void unionWriteShouldNotThrowNPE() throws IOException {
String outputPath1 = tmpDir.getFileName("output1");
String outputPath2 = tmpDir.getFileName("output2");
String outputPath3 = tmpDir.getFileName("output3");
if (typeFamily == AvroTypeFamily.getInstance()) {
union.write(To.avroFile(outputPath1));
pipeline.write(union, To.avroFile(outputPath2));
pipeline.run();
checkFileContents(outputPath1);
checkFileContents(outputPath2);
} else {
union.write(To.textFile(outputPath1));
pipeline.write(union, To.textFile(outputPath2));
pipeline.writeTextFile(union, outputPath3);
pipeline.run();
checkFileContents(outputPath1);
checkFileContents(outputPath2);
checkFileContents(outputPath3);
}
}
private void checkFileContents(String filePath) throws IOException {
List<String> fileContentValues = (typeFamily != AvroTypeFamily.getInstance())? Lists
.newArrayList(pipeline.read(At.textFile(filePath, typeFamily.strings())).materialize().iterator()) : Lists
.newArrayList(pipeline.read(At.avroFile(filePath, Avros.strings())).materialize().iterator());
Collections.sort(fileContentValues);
LOG.info("Saved Union: {}", fileContentValues);
assertEquals(EXPECTED, fileContentValues);
}
}
| 2,564 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mem/MemPipelineUTF8IT.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 java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.Target.WriteMode;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.text.TextFileTarget;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
public class MemPipelineUTF8IT {
@Rule
public TemporaryPath baseTmpDir = TemporaryPaths.create();
private static void writeFile(String text, String filename) throws IOException {
Files.write(text, new File(filename), Charsets.UTF_8);
}
@Test
public void testText() throws Exception {
final String infilename = baseTmpDir.getFileName("input");
final String memOutFilename = baseTmpDir.getFileName("memPipelineOut");
final String mrOutFilename = baseTmpDir.getFileName("mrPipelineOut");
final String expected = "súper";
new File(infilename).getParentFile().mkdirs();
writeFile(expected, infilename);
Pipeline memPipeline = MemPipeline.getInstance();
PCollection<String> memPColl = memPipeline.readTextFile(infilename);
Target memTarget = new TextFileTarget(memOutFilename);
memPipeline.write(memPColl, memTarget, WriteMode.OVERWRITE);
memPipeline.run();
File outDir = new File(memOutFilename);
File actualMemOut = null;
for (File f : outDir.listFiles()) {
String name = f.getName();
if (name.contains("out") && name.endsWith(".txt")) {
actualMemOut = f;
break;
}
}
String actualMemText = Files.readFirstLine(actualMemOut, Charsets.UTF_8);
Pipeline mrPipeline = new MRPipeline(getClass());
PCollection<String> mrPColl = mrPipeline.readTextFile(infilename);
Target mrTarget = new TextFileTarget(mrOutFilename);
mrPipeline.write(mrPColl, mrTarget, WriteMode.OVERWRITE);
mrPipeline.run();
String actualMrText = Files.readFirstLine(new File(mrOutFilename + "/part-m-00000"), Charsets.UTF_8);
Assert.assertEquals("MR file mismatch", expected, actualMrText);
Assert.assertEquals("Mem file mismatch", expected, actualMemText);
}
}
| 2,565 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/impl/mem/MemPipelineFileReadingWritingIT.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 static org.junit.Assert.assertFalse;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.impl.mem.collect.MemTable;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.io.avro.AvroFileReaderFactory;
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.crunch.types.writable.Writables;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Reader;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.Text;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
public class MemPipelineFileReadingWritingIT {
@Rule
public TemporaryPath baseTmpDir = TemporaryPaths.create();
private File inputFile;
private File outputDir;
private static final Collection<String> EXPECTED_COLLECTION = Lists.newArrayList("hello", "world");
@SuppressWarnings("unchecked")
private static final Collection<Pair<Integer, String>> EXPECTED_TABLE = Lists.newArrayList(
Pair.of(1, "hello"),
Pair.of(2, "world"));
@Before
public void setUp() throws IOException {
inputFile = baseTmpDir.getFile("test-read");
outputDir = baseTmpDir.getFile("test-write");
}
private File getOutputFile(File outputDir, String wildcardFilter) {
File[] files = outputDir.listFiles((FilenameFilter)new WildcardFileFilter(wildcardFilter));
System.out.println(Arrays.asList(files));
assertEquals(1, files.length);
return files[0];
}
@Test
public void testMemPipelineFileWriter() throws Exception {
File outputDir = baseTmpDir.getFile("mempipe");
Pipeline p = MemPipeline.getInstance();
PCollection<String> lines = MemPipeline.collectionOf("hello", "world");
p.writeTextFile(lines, outputDir.toString());
p.done();
File outputFile = getOutputFile(outputDir, "*.txt");
List<String> txt = Files.readLines(outputFile, Charsets.UTF_8);
assertEquals(ImmutableList.of("hello", "world"), txt);
}
private void createTestSequenceFile(final File seqFile) throws IOException {
SequenceFile.Writer writer = null;
writer = new Writer(FileSystem.getLocal(baseTmpDir.getDefaultConfiguration()),
baseTmpDir.getDefaultConfiguration(),
new Path(seqFile.toString()),
IntWritable.class, Text.class);
writer.append(new IntWritable(1), new Text("hello"));
writer.append(new IntWritable(2), new Text("world"));
writer.close();
}
@Test
public void testMemPipelineReadSequenceFile() throws IOException {
// set up input
createTestSequenceFile(inputFile);
// read from sequence file
final PCollection<Pair<Integer, String>> readCollection = MemPipeline.getInstance().read(
From.sequenceFile(inputFile.toString(),
Writables.tableOf(
Writables.ints(),
Writables.strings())));
// assert read same as written.
assertEquals(EXPECTED_TABLE, Lists.newArrayList(readCollection.materialize()));
}
@Test
public void testMemPipelineWriteSequenceFile_PCollection() throws IOException {
// write
PCollection<String> collection = MemPipeline.typedCollectionOf(Writables.strings(), EXPECTED_COLLECTION);
final Target target = To.sequenceFile(outputDir.toString());
MemPipeline.getInstance().write(collection, target);
// read
final SequenceFile.Reader reader = new Reader(FileSystem.getLocal(
baseTmpDir.getDefaultConfiguration()),
new Path(getOutputFile(outputDir, "*.seq").toString()),
baseTmpDir.getDefaultConfiguration());
final List<String> actual = Lists.newArrayList();
final NullWritable key = NullWritable.get();
final Text value = new Text();
while (reader.next(key, value)) {
actual.add(value.toString());
}
reader.close();
// assert read same as written
assertEquals(EXPECTED_COLLECTION, actual);
}
@Test
public void testMemPipelineWriteSequenceFile_PTable() throws IOException {
// write
final MemTable<Integer, String> collection = new MemTable<Integer, String>(EXPECTED_TABLE, //
Writables.tableOf(
Writables.ints(),
Writables.strings()), "test input");
final Target target = To.sequenceFile(outputDir.toString());
MemPipeline.getInstance().write(collection, target);
// read
final SequenceFile.Reader reader = new Reader(FileSystem.getLocal(baseTmpDir
.getDefaultConfiguration()), new Path(getOutputFile(outputDir, "*.seq").toString()),
baseTmpDir.getDefaultConfiguration());
final List<Pair<Integer, String>> actual = Lists.newArrayList();
final IntWritable key = new IntWritable();
final Text value = new Text();
while (reader.next(key, value)) {
actual.add(Pair.of(key.get(), value.toString()));
}
reader.close();
// assert read same as written
assertEquals(EXPECTED_TABLE, actual);
}
@Test
public void testMemPipelineWriteAvroFile_SpecificRecords() throws IOException {
AvroType<Person> ptype = Avros.specifics(Person.class);
PCollection<Person> collection = MemPipeline.typedCollectionOf(
ptype,
Person.newBuilder()
.setName("A")
.setAge(1)
.setSiblingnames(ImmutableList.<CharSequence>of())
.build(),
Person.newBuilder()
.setName("B")
.setAge(2)
.setSiblingnames(ImmutableList.<CharSequence>of())
.build());
MemPipeline.getInstance().write(collection, To.avroFile(outputDir.getPath()));
Iterator<Person> itr = new AvroFileReaderFactory<Person>(ptype).read(
FileSystem.getLocal(baseTmpDir.getDefaultConfiguration()),
new Path(getOutputFile(outputDir, "*.avro").getPath()));
assertEquals(2, Iterators.size(itr));
}
@Test
public void testMemPipelineWriteAvroFile_ReflectRecords() throws IOException {
AvroType<SimpleBean> ptype = Avros.reflects(SimpleBean.class);
PCollection<SimpleBean> collection = MemPipeline.typedCollectionOf(
ptype,
new SimpleBean(1),
new SimpleBean(2));
MemPipeline.getInstance().write(collection, To.avroFile(outputDir.getPath()));
Iterator<SimpleBean> itr = new AvroFileReaderFactory<SimpleBean>(ptype).read(
FileSystem.getLocal(baseTmpDir.getDefaultConfiguration()),
new Path(getOutputFile(outputDir, "*.avro").getPath()));
assertEquals(2, Iterators.size(itr));
}
@Test
public void testMemPipelineWriteAvroFile_GenericRecords() throws IOException {
AvroType<GenericData.Record> ptype = Avros.generics(Person.SCHEMA$);
GenericData.Record record = new GenericRecordBuilder(ptype.getSchema())
.set("name", "A")
.set("age", 1)
.set("siblingnames", ImmutableList.of())
.build();
PCollection<GenericData.Record> collection = MemPipeline.typedCollectionOf(
ptype, record);
MemPipeline.getInstance().write(collection, To.avroFile(outputDir.getPath()));
Iterator<GenericData.Record> itr = new AvroFileReaderFactory<GenericData.Record>(ptype).read(
FileSystem.getLocal(baseTmpDir.getDefaultConfiguration()),
new Path(getOutputFile(outputDir, "*.avro").getPath()));
assertEquals(record, itr.next());
assertFalse(itr.hasNext());
}
@Test
public void testMemPipelineWriteAvroFile_Tuples() throws IOException {
AvroType<Pair<String, Long>> at = Avros.pairs(Avros.strings(), Avros.longs());
Set<Pair<String, Long>> data = ImmutableSet.of(Pair.of("a", 1L), Pair.of("b", 2L), Pair.of("c", 3L));
PCollection < Pair < String, Long >> pc = MemPipeline.typedCollectionOf(at, data);
pc.write(To.avroFile(outputDir.getPath()));
Iterable<Pair<String, Long>> it = MemPipeline.getInstance().read(
at.getDefaultFileSource(new Path(outputDir.getPath()))).materialize();
assertEquals(data, Sets.newHashSet(it));
}
static class SimpleBean {
public int value;
public SimpleBean() {
this(0);
}
public SimpleBean(int value) {
this.value = value;
}
}
}
| 2,566 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/types
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/types/avro/SafeAvroSerializationIT.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 java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;
import org.apache.crunch.MapFn;
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.io.At;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.junit.Rule;
import org.junit.Test;
@SuppressWarnings("serial")
public class SafeAvroSerializationIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
/**
* Test to prove CRUNCH-316 has been fixed
*/
@Test
public void testMapBufferTooSmallException() throws IOException {
Configuration configuration = tmpDir.getDefaultConfiguration();
// small io.sort.mb to make the test run faster with less resources
configuration.set("io.sort.mb", "1");
Pipeline pipeline = new MRPipeline(SafeAvroSerializationIT.class,
configuration);
Schema schema = new Schema.Parser().parse(tmpDir
.copyResourceFile("CRUNCH-316.avsc"));
PTable<String, GenericData.Record> leftSide = pipeline.read(
At.avroFile(
new Path(populateLeftSide(schema).getAbsolutePath()),
Avros.generics(schema))).by(
new MapFn<GenericData.Record, String>() {
@Override
public String map(GenericData.Record input) {
return (String) input.get("tag").toString();
}
}, Avros.strings());
PTable<String, String> rightSide = pipeline.read(
At.avroFile(new Path(populateRightSide().getAbsolutePath()),
Avros.strings())).by(new MapFn<String, String>() {
@Override
public String map(String input) {
return input;
}
}, Avros.strings());
PTable<String, org.apache.crunch.Pair<GenericData.Record, String>> joinedTable = leftSide
.join(rightSide);
// if CRUNCH-316 isn't fixed, this will result in an
// ArrayIndexOutOfBoundsException in the reduce
Collection<Pair<String, Pair<Record, String>>> joinRows = joinedTable
.asCollection().getValue();
assertEquals(1, joinRows.size());
Pair<String, Pair<Record, String>> firstRow = joinRows.iterator()
.next();
assertEquals("c", firstRow.first());
assertEquals("c", firstRow.second().first().get("tag").toString());
assertEquals(createString('c', 40),
firstRow.second().first().get("data1").toString());
assertEquals(null, firstRow.second().first().get("data2"));
assertEquals("c", firstRow.second().second());
}
private File populateLeftSide(Schema schema) throws IOException {
File file = tmpDir.getFile("leftSide.avro");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(
schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(
datumWriter);
dataFileWriter.create(schema, file);
GenericRecord record = new GenericData.Record(schema);
// RECORD 1
record.put("tag", "b");
record.put("data1", createString('b', 996100));
// buffer space has to run out on a write of less than 512 bytes for the
// issue to occur
record.put("data2", createString('b', 250));
dataFileWriter.append(record);
// RECORD 2 -- this record will be corrupted with overflow from RECORD 1
record.put("tag", "c");
record.put("data1", createString('c', 40));
record.put("data2", null);
dataFileWriter.append(record);
dataFileWriter.close();
return file;
}
private File populateRightSide() throws IOException {
File file = tmpDir.getFile("rightSide.avro");
DatumWriter<String> datumWriter = new GenericDatumWriter<String>(Avros
.strings().getSchema());
DataFileWriter<String> dataFileWriter = new DataFileWriter<String>(
datumWriter);
dataFileWriter.create(Avros.strings().getSchema(), file);
// will join successfully to RECORD 2 from left side
dataFileWriter.append("c");
dataFileWriter.close();
return file;
}
private static String createString(Character ch, int len) {
StringBuilder buffer = new StringBuilder(len);
for (int i = 0; i < len; i++) {
buffer.append(ch);
}
return buffer.toString();
}
}
| 2,567 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/test/TemporaryPaths.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.impl.mr.run.RuntimeParameters;
import org.apache.hadoop.conf.Configuration;
/**
* Utilities for working with {@link TemporaryPath}.
*/
public final class TemporaryPaths {
/**
* Static factory returning a {@link TemporaryPath} with adjusted
* {@link Configuration} properties.
*/
public static TemporaryPath create() {
return new TemporaryPath(RuntimeParameters.TMP_DIR, "hadoop.tmp.dir");
}
private TemporaryPaths() {
// nothing
}
}
| 2,568 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/test/Tests.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 com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Collection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.hadoop.io.Writable;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.google.common.io.Resources;
/**
* Utilities for integration tests.
*/
public final class Tests {
private Tests() {
// nothing
}
/**
* Get the path to and integration test resource file, as per naming convention.
*
* @param testCase The executing test case instance
* @param resourceName The file name of the resource
* @return The path to the resource (never null)
* @throws IllegalArgumentException Thrown if the resource doesn't exist
*/
public static String pathTo(Object testCase, String resourceName) {
String qualifiedName = resource(testCase, resourceName);
return Resources.getResource(qualifiedName).getFile();
}
/**
* This doesn't check whether the resource exists!
*
* @param testCase
* @param resourceName
* @return The path to the resource (never null)
*/
public static String resource(Object testCase, String resourceName) {
checkNotNull(testCase);
checkNotNull(resourceName);
// Note: We append "Data" because otherwise Eclipse would complain about the
// the case's class name clashing with the resource directory's name.
return testCase.getClass().getName().replaceAll("\\.", "/") + "Data/" + resourceName;
}
/**
* Return our two types of {@link Pipeline}s for a JUnit Parameterized test.
*
* @param testCase The executing test case's class
* @return The collection to return from a {@link Parameters} provider method
*/
public static Collection<Object[]> pipelinesParams(Class<?> testCase) {
return ImmutableList.copyOf(
new Object[][] { { MemPipeline.getInstance() }, { new MRPipeline(testCase) }
});
}
/**
* Serialize the given Writable into a byte array.
*
* @param value The instance to serialize
* @return The serialized data
*/
public static byte[] serialize(Writable value) {
checkNotNull(value);
try {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
value.write(out);
return out.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("cannot serialize", e);
}
}
/**
* Serialize the src Writable into a byte array, then deserialize it into dest.
* @param src The instance to serialize
* @param dest The instance to deserialize into
* @return dest, for convenience
*/
public static <T extends Writable> T roundtrip(Writable src, T dest) {
checkNotNull(src);
checkNotNull(dest);
checkArgument(src != dest, "src and dest may not be the same instance");
try {
byte[] data = serialize(src);
dest.readFields(ByteStreams.newDataInput(data));
} catch (IOException e) {
throw new IllegalStateException("cannot deserialize", e);
}
return dest;
}
}
| 2,569 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/CombineFileIT.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 com.google.common.io.Files;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.test.Tests;
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 java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CombineFileIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testCombine() throws Exception {
final File srcFiles = tmpDir.getFile("srcs");
File outputFiles = tmpDir.getFile("out");
assertTrue(srcFiles.mkdir());
File src1 = tmpDir.copyResourceFile(Tests.resource(this, "src1.txt"));
File src2 = tmpDir.copyResourceFile(Tests.resource(this, "src2.txt"));
Files.copy(src1, new File(srcFiles, "src1.txt"));
Files.copy(src2, new File(srcFiles, "src2.txt"));
MRPipeline p = new MRPipeline(CombineFileIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> in = p.readTextFile(srcFiles.getAbsolutePath());
PCollection<Pair<String, String>> out = in.parallelDo(
new IdentityPlusPathFn(srcFiles), Avros.pairs(Avros.strings(), Avros.strings()));
out.write(To.textFile(outputFiles.getAbsolutePath()));
p.done();
assertEquals(4, outputFiles.listFiles().length);
// verify "crunch.split.file" is being handled correctly
FileSystem fs = FileSystem.get(tmpDir.getDefaultConfiguration());
Path qualifiedSourcePath = fs.makeQualified(new Path(srcFiles.getAbsolutePath()));
Iterable<Pair<String, String>> materialized = out.materialize();
for (Pair<String, String> pair : materialized) {
Path path = new Path(pair.first());
String text = pair.second();
assertEquals(qualifiedSourcePath, path.getParent());
String fileName = path.getName();
// make sure filename is correct for each record
String[] parts = text.split(",");
switch (fileName) {
case "src1.txt":
assertEquals("1", parts[1].substring(0, 1));
break;
case "src2.txt":
assertEquals("2", parts[1].substring(0, 1));
break;
default:
fail("unexpected filename: " + fileName);
}
}
}
private static class IdentityPlusPathFn extends DoFn<String, Pair<String, String>> {
private final File srcFiles;
public IdentityPlusPathFn(File srcFiles) {
this.srcFiles = srcFiles;
}
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
String filePath = getConfiguration().get("crunch.split.file");
assertNotNull(filePath);
emitter.emit(Pair.of(filePath, input));
}
}
}
| 2,570 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/NLineInputIT.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 com.google.common.collect.ImmutableList;
import org.apache.crunch.CreateOptions;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.conf.Configuration;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
public class NLineInputIT {
private static List<String> URLS = ImmutableList.of(
"www.A.com www.B.com",
"www.A.com www.C.com",
"www.A.com www.D.com",
"www.A.com www.E.com",
"www.B.com www.D.com",
"www.B.com www.E.com",
"www.C.com www.D.com",
"www.D.com www.B.com",
"www.E.com www.A.com",
"www.F.com www.B.com",
"www.F.com www.C.com");
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testNLine() throws Exception {
Configuration conf = new Configuration(tmpDir.getDefaultConfiguration());
conf.setInt("io.sort.mb", 10);
Pipeline pipeline = new MRPipeline(NLineInputIT.class, conf);
PCollection<String> urls = pipeline.create(URLS, Writables.strings(),
CreateOptions.parallelism(6));
assertEquals(new Integer(2),
urls.parallelDo(new LineCountFn(), Avros.ints()).max().getValue());
}
private static class LineCountFn extends DoFn<String, Integer> {
private int lineCount = 0;
@Override
public void initialize() {
this.lineCount = 0;
}
@Override
public void process(String input, Emitter<Integer> emitter) {
lineCount++;
}
@Override
public void cleanup(Emitter<Integer> emitter) {
emitter.emit(lineCount);
}
}
}
| 2,571 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/ToolRunnerIT.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.nio.charset.Charset;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.seq.SeqFileTarget;
import org.apache.crunch.io.text.TextFileTableSource;
import org.apache.crunch.io.text.TextFileTarget;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import static org.apache.crunch.types.writable.Writables.strings;
import static org.apache.crunch.types.writable.Writables.tableOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class ToolRunnerIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Rule
public TestName testName = new TestName();
@Test
public void textRunWithToolRunner() throws Exception {
Configuration config = tmpDir.getDefaultConfiguration();
String output = tmpDir.getFileName(testName.getMethodName());
assertThat(ToolRunner.run(config, new FakeTextTool(), new String[]{tmpDir.copyResourceFileName("urls.txt"), output}), is(0));
FileSystem fs = FileSystem.get(config);
FileStatus fileStatus = fs.getFileStatus(new Path(output));
assertTrue(fileStatus.isDir());
}
@Test
public void textRunWithoutToolRunner() throws Exception {
Configuration config = tmpDir.getDefaultConfiguration();
String output = tmpDir.getFileName(testName.getMethodName());
FakeTextTool tool = new FakeTextTool();
tool.setConf(config);
assertThat(tool.run(new String[]{tmpDir.copyResourceFileName("urls.txt"), output}), is(0));
FileSystem fs = FileSystem.get(config);
FileStatus fileStatus = fs.getFileStatus(new Path(output));
assertTrue(fileStatus.isDir());
}
@Test
public void sequenceRunWithToolRunner() throws Exception {
Configuration config = tmpDir.getDefaultConfiguration();
String output = tmpDir.getFileName(testName.getMethodName());
assertThat(ToolRunner.run(config, new FakeSequenceTool(), new String[]{tmpDir.copyResourceFileName("urls.txt"), output}), is(0));
FileSystem fs = FileSystem.get(config);
FileStatus fileStatus = fs.getFileStatus(new Path(output));
assertTrue(fileStatus.isDir());
}
@Test
public void sequenceRunWithoutToolRunner() throws Exception {
Configuration config = tmpDir.getDefaultConfiguration();
String output = tmpDir.getFileName(testName.getMethodName());
FakeSequenceTool tool = new FakeSequenceTool();
tool.setConf(config);
assertThat(tool.run(new String[]{tmpDir.copyResourceFileName("urls.txt"), output}), is(0));
FileSystem fs = FileSystem.get(config);
FileStatus fileStatus = fs.getFileStatus(new Path(output));
assertTrue(fileStatus.isDir());
}
private static class FakeTextTool implements Tool, Configurable {
private Configuration config;
@Override
public int run(String[] strings) throws Exception {
String urlsFile = strings[0];
String outFile = strings[1];
Pipeline pipeline = new MRPipeline(ToolRunnerIT.class, getConf());
PCollection<String> urls = pipeline.read(
new TextFileTableSource<String, String>(urlsFile, tableOf(strings(), strings()))).values();
pipeline.write(urls, new TextFileTarget(outFile));
pipeline.done();
PCollection<String> stringPCollection = pipeline.readTextFile(outFile);
assertThat(stringPCollection.length().getValue(), is(greaterThan(0L)));
return 0;
}
@Override
public void setConf(Configuration entries) {
config = entries;
}
@Override
public Configuration getConf() {
return config;
}
}
private static class FakeSequenceTool implements Tool, Configurable {
private Configuration config;
@Override
public int run(String[] strings) throws Exception {
String urlsFile = strings[0];
String outFile = strings[1];
Pipeline pipeline = new MRPipeline(ToolRunnerIT.class, getConf());
PCollection<String> urls = pipeline.read(
new TextFileTableSource<String, String>(urlsFile, tableOf(strings(), strings()))).values();
PType<BytesWritable> bwType = Writables.writables(BytesWritable.class);
urls.parallelDo(new ByteConvertFn(), Writables.pairs(bwType, bwType));
pipeline.write(urls, new SeqFileTarget(outFile));
pipeline.done();
PCollection<Pair<BytesWritable, BytesWritable>> stringPCollection =
pipeline.read(From.sequenceFile(outFile, BytesWritable.class, BytesWritable.class));
assertThat(stringPCollection.length().getValue(), is(greaterThan(0L)));
return 0;
}
@Override
public void setConf(Configuration entries) {
config = entries;
}
@Override
public Configuration getConf() {
return config;
}
}
public static class ByteConvertFn extends MapFn<String, Pair<BytesWritable, BytesWritable>> {
@Override
public Pair<BytesWritable, BytesWritable> map(String input) {
BytesWritable bw = new BytesWritable(input.getBytes(Charset.forName("UTF-8")));
return Pair.of(bw, bw);
}
}
}
| 2,572 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/CompressIT.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 org.apache.crunch.PCollection;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CompressIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testCompressText() throws Exception {
String urlsFile = tmpDir.copyResourceFileName("urls.txt");
String out = tmpDir.getFileName("out");
MRPipeline p = new MRPipeline(CompressIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> in = p.readTextFile(urlsFile);
in.write(Compress.gzip(To.textFile(out)));
p.done();
assertTrue(checkDirContainsExt(out, ".gz"));
}
@Test
public void testCompressAvro() throws Exception {
String urlsFile = tmpDir.copyResourceFileName("urls.txt");
String out = tmpDir.getFileName("out");
MRPipeline p = new MRPipeline(CompressIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> in = p.read(From.textFile(urlsFile, Avros.strings()));
in.write(Compress.snappy(To.avroFile(out)));
p.done();
FileSystem fs = FileSystem.get(tmpDir.getDefaultConfiguration());
FileStatus fstat = fs.getFileStatus(new Path(out, "part-m-00000.avro"));
assertEquals(176, fstat.getLen());
}
private boolean checkDirContainsExt(String dir, String ext) throws Exception {
File directory = new File(dir);
for (File f : directory.listFiles()) {
if (f.getName().endsWith(ext)) {
return true;
}
}
return false;
}
}
| 2,573 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/CompositePathIterableIT.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 static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.apache.crunch.io.text.TextFileReaderFactory;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
public class CompositePathIterableIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testCreate_FilePresent() throws IOException {
String inputFilePath = tmpDir.copyResourceFileName("set1.txt");
Configuration conf = new Configuration();
LocalFileSystem local = FileSystem.getLocal(conf);
Iterable<String> iterable = CompositePathIterable.create(local, new Path(inputFilePath),
new TextFileReaderFactory<String>(Writables.strings()));
assertEquals(Lists.newArrayList("b", "c", "a", "e"), Lists.newArrayList(iterable));
}
@Test
public void testCreate_DirectoryPresentButNoFiles() throws IOException {
Path emptyInputDir = tmpDir.getRootPath();
Configuration conf = new Configuration();
LocalFileSystem local = FileSystem.getLocal(conf);
Iterable<String> iterable = CompositePathIterable.create(local, emptyInputDir,
new TextFileReaderFactory<String>(Writables.strings()));
assertTrue(Lists.newArrayList(iterable).isEmpty());
}
@Test(expected = IOException.class)
public void testCreate_DirectoryNotPresent() throws IOException {
File nonExistentDir = tmpDir.getFile("not-there");
// Sanity check
assertFalse(nonExistentDir.exists());
Configuration conf = new Configuration();
LocalFileSystem local = FileSystem.getLocal(conf);
CompositePathIterable.create(local, new Path(nonExistentDir.getAbsolutePath()), new TextFileReaderFactory<String>(
Writables.strings()));
}
@Test
public void testCreate_HiddenFiles() throws IOException {
File file = tmpDir.copyResourceFile("set1.txt");
assertTrue(file.renameTo(new File(tmpDir.getRootFile(), "_set1.txt")));
file = tmpDir.copyResourceFile("set1.txt");
assertTrue(file.renameTo(new File(tmpDir.getRootFile(), ".set1.txt")));
Path emptyInputDir = tmpDir.getRootPath();
Configuration conf = new Configuration();
LocalFileSystem local = FileSystem.getLocal(conf);
Iterable<String> iterable = CompositePathIterable.create(local, emptyInputDir,
new TextFileReaderFactory<String>(Writables.strings()));
assertTrue(Lists.newArrayList(iterable).isEmpty());
}
}
| 2,574 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/TextFileTableIT.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.apache.crunch.types.writable.Writables.*;
import static org.junit.Assert.assertEquals;
import java.util.Set;
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.io.text.TextFileTableSource;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableSet;
/**
*
*/
public class TextFileTableIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testTextFileTable() throws Exception {
String urlsFile = tmpDir.copyResourceFileName("urls.txt");
Pipeline pipeline = new MRPipeline(TextFileTableIT.class, tmpDir.getDefaultConfiguration());
PTable<String, String> urls = pipeline.read(
new TextFileTableSource<String, String>(urlsFile, tableOf(strings(), strings())));
Set<Pair<String, Long>> cnts = ImmutableSet.copyOf(urls.keys().count().materialize());
assertEquals(ImmutableSet.of(Pair.of("www.A.com", 4L), Pair.of("www.B.com", 2L),
Pair.of("www.C.com", 1L), Pair.of("www.D.com", 1L), Pair.of("www.E.com", 1L),
Pair.of("www.F.com", 2L)), cnts);
}
}
| 2,575 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/FormattedFileIT.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 com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
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.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
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 java.util.List;
import static org.junit.Assert.assertEquals;
public class FormattedFileIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testReadFormattedFile() throws Exception {
String urlsFile = tmpDir.copyResourceFileName("urls.txt");
Pipeline p = new MRPipeline(FormattedFileIT.class, tmpDir.getDefaultConfiguration());
PTable<LongWritable, Text> urls = p.read(From.formattedFile(urlsFile,
TextInputFormat.class, LongWritable.class, Text.class));
List<String> expect = ImmutableList.of("A", "A", "A", "B", "B", "C", "D", "E", "F", "F", "");
List<String> actual = Lists.newArrayList(Iterables.transform(urls.materialize(),
new Function<Pair<LongWritable, Text>, String>() {
@Override
public String apply(Pair<LongWritable, Text> pair) {
String str = pair.second().toString();
if (str.isEmpty()) {
return str;
}
return str.substring(4, 5);
}
}));
assertEquals(expect, actual);
p.done();
}
}
| 2,576 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroKeyValueIT.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 java.io.IOException;
import java.io.Serializable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapred.AvroValue;
import org.apache.avro.mapred.AvroWrapper;
import org.apache.avro.mapred.Pair;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.avro.mapreduce.AvroKeyValueOutputFormat;
import org.apache.crunch.PTable;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.test.Person;
import org.apache.crunch.types.PTableType;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.avro.ReflectedPerson;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.junit.Test;
/**
* Tests for verifying behavior with Avro produced using the org.apache.avro.mapred.*
* and org.apache.avro.mapreduce.* APIs.
*/
public class AvroKeyValueIT extends CrunchTestSupport implements Serializable {
@Test
public void testInputFromMapReduceKeyValueFile_Generic() throws InterruptedException, IOException, ClassNotFoundException {
Path keyValuePath = produceMapReduceOutputFile();
Pipeline pipeline = new MRPipeline(AvroKeyValueIT.class, tempDir.getDefaultConfiguration());
PTable<Person, Integer> personTable = pipeline.read(
From.avroTableFile(keyValuePath, Avros.tableOf(Avros.specifics(Person.class), Avros.ints())));
org.apache.crunch.Pair<Person, Integer> firstEntry = Iterables.getFirst(personTable.materialize(), null);
assertEquals("a", firstEntry.first().getName().toString());
assertEquals(Integer.valueOf(1), firstEntry.second());
pipeline.done();
}
@Test
public void testInputFromMapRedKeyValueFile_Specific() throws IOException {
Path keyValuePath = produceMapRedOutputFile();
Pipeline pipeline = new MRPipeline(AvroKeyValueIT.class, tempDir.getDefaultConfiguration());
PTable<Person, Integer> personTable = pipeline.read(
From.avroTableFile(keyValuePath, Avros.keyValueTableOf(Avros.specifics(Person.class), Avros.ints())));
org.apache.crunch.Pair<Person, Integer> firstEntry = Iterables.getFirst(personTable.materialize(), null);
assertEquals("a", firstEntry.first().getName().toString());
assertEquals(Integer.valueOf(1), firstEntry.second());
// Verify that deep copying on this PType works as well
PTableType<Person, Integer> tableType = Avros.keyValueTableOf(Avros.specifics(Person.class), Avros.ints());
tableType.initialize(tempDir.getDefaultConfiguration());
org.apache.crunch.Pair<Person, Integer> detachedPair = tableType.getDetachedValue(firstEntry);
assertEquals(firstEntry, detachedPair);
pipeline.done();
}
@Test
public void testInputFromMapRedKeyValueFile_Reflect() throws IOException {
Path keyValuePath = produceMapRedOutputFile();
Pipeline pipeline = new MRPipeline(AvroKeyValueIT.class, tempDir.getDefaultConfiguration());
PTable<ReflectedPerson, Integer> personTable = pipeline.read(
From.avroTableFile(keyValuePath, Avros.keyValueTableOf(Avros.reflects(ReflectedPerson.class), Avros.ints())));
org.apache.crunch.Pair<ReflectedPerson, Integer> firstEntry = Iterables.getFirst(personTable.materialize(), null);
assertEquals("a", firstEntry.first().getName().toString());
assertEquals(Integer.valueOf(1), firstEntry.second());
// Verify that deep copying on this PType works as well
PTableType<ReflectedPerson, Integer> tableType =
Avros.keyValueTableOf(Avros.reflects(ReflectedPerson.class), Avros.ints());
tableType.initialize(tempDir.getDefaultConfiguration());
org.apache.crunch.Pair<ReflectedPerson, Integer> detachedPair = tableType.getDetachedValue(firstEntry);
assertEquals(firstEntry, detachedPair);
pipeline.done();
}
/**
* Produces an Avro file using the org.apache.avro.mapred.* API.
*/
private Path produceMapRedOutputFile() throws IOException {
JobConf conf = new JobConf(tempDir.getDefaultConfiguration(), AvroKeyValueIT.class);
org.apache.avro.mapred.AvroJob.setOutputSchema(
conf,
Pair.getPairSchema(Person.SCHEMA$, Schema.create(Schema.Type.INT)));
conf.setMapperClass(MapRedPersonMapper.class);
conf.setNumReduceTasks(0);
conf.setInputFormat(org.apache.hadoop.mapred.TextInputFormat.class);
Path outputPath = new Path(tempDir.getFileName("mapreduce_output"));
org.apache.hadoop.mapred.FileInputFormat.setInputPaths(conf, tempDir.copyResourcePath("letters.txt"));
org.apache.hadoop.mapred.FileOutputFormat.setOutputPath(conf, outputPath);
RunningJob runningJob = JobClient.runJob(conf);
runningJob.waitForCompletion();
return outputPath;
}
/**
* Produces an Avro file using the org.apache.avro.mapreduce.* API.
*/
private Path produceMapReduceOutputFile() throws IOException, ClassNotFoundException, InterruptedException {
Job job = new Job(tempDir.getDefaultConfiguration());
job.setJarByClass(AvroKeyValueIT.class);
job.setJobName("Color Count");
Path outputPath = new Path(tempDir.getFileName("mapreduce_output"));
FileInputFormat.setInputPaths(job, tempDir.copyResourcePath("letters.txt"));
FileOutputFormat.setOutputPath(job, outputPath);
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(MapReducePersonMapper.class);
job.setNumReduceTasks(0);
AvroJob.setOutputKeySchema(job, Person.SCHEMA$);
AvroJob.setOutputValueSchema(job, Schema.create(Schema.Type.INT));
job.setOutputFormatClass(AvroKeyValueOutputFormat.class);
boolean success = job.waitForCompletion(true);
if (!success) {
throw new RuntimeException("Job failed");
}
return outputPath;
}
public static class MapReducePersonMapper extends
Mapper<LongWritable, Text, AvroKey<Person>, AvroValue<Integer>> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
Person person = Person.newBuilder()
.setName(value.toString())
.setAge(value.toString().length())
.setSiblingnames(ImmutableList.<CharSequence>of())
.build();
context.write(
new AvroKey<Person>(person),
new AvroValue<Integer>(1));
}
}
public static class MapRedPersonMapper implements org.apache.hadoop.mapred.Mapper<LongWritable, Text, AvroWrapper<Pair<Person,Integer>>, NullWritable> {
@Override
public void map(LongWritable key, Text value, OutputCollector<AvroWrapper<Pair<Person,Integer>>, NullWritable> outputCollector, Reporter reporter) throws IOException {
Person person = Person.newBuilder()
.setName(value.toString())
.setAge(value.toString().length())
.setSiblingnames(ImmutableList.<CharSequence>of())
.build();
outputCollector.collect(
new AvroWrapper<Pair<Person, Integer>>(new Pair<Person, Integer>(person, 1)),
NullWritable.get());
}
@Override
public void close() throws IOException {
}
@Override
public void configure(JobConf entries) {
}
}
}
| 2,577 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/TextToAvroIT.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 org.apache.crunch.CrunchRuntimeException;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.Rule;
import org.junit.Test;
public class TextToAvroIT {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test(expected=CrunchRuntimeException.class)
public void testTextToAvro() throws Exception {
String shakes = tmpDir.copyResourceFileName("shakes.txt");
Pipeline pipeline = new MRPipeline(TextToAvroIT.class, tmpDir.getDefaultConfiguration());
pipeline.read(From.textFile(shakes)).write(To.avroFile("output"));
pipeline.run();
}
}
| 2,578 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroModeIT.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 com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Random;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.crunch.Aggregator;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.MapFn;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Source;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.AvroMode;
import org.apache.crunch.types.avro.AvroType;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AvroModeIT implements Serializable {
public static final Schema GENERIC_SCHEMA = new Schema.Parser().parse("{\n" +
" \"name\": \"mystring\",\n" +
" \"type\": \"record\",\n" +
" \"fields\": [\n" +
" { \"name\": \"text\", \"type\": \"string\" }\n" +
" ]\n" +
"}");
public static final class FloatArray {
private final float[] values;
public FloatArray() {
this(null);
}
public FloatArray(float[] values) {
this.values = values;
}
float[] getValues() {
return values;
}
}
public static AvroType<float[]> FLOAT_ARRAY = Avros.derived(float[].class,
new MapFn<FloatArray, float[]>() {
@Override
public float[] map(FloatArray input) {
return input.getValues();
}
},
new MapFn<float[], FloatArray>() {
@Override
public FloatArray map(float[] input) {
return new FloatArray(input);
}
}, Avros.reflects(FloatArray.class));
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testGenericReflectConflict() throws IOException {
final Random rand = new Random();
rand.setSeed(12345);
Configuration conf = new Configuration();
Pipeline pipeline = new MRPipeline(AvroModeIT.class, conf);
Source<GenericData.Record> source = From.avroFile(
tmpDir.copyResourceFileName("strings-100.avro"),
Avros.generics(GENERIC_SCHEMA));
PTable<Long, float[]> mapPhase = pipeline
.read(source)
.parallelDo(new DoFn<GenericData.Record, Pair<Long, float[]>>() {
@Override
public void process(GenericData.Record input, Emitter<Pair<Long, float[]>> emitter) {
emitter.emit(Pair.of(
Long.valueOf(input.get("text").toString().length()),
new float[] {rand.nextFloat(), rand.nextFloat()}));
}
}, Avros.tableOf(Avros.longs(), FLOAT_ARRAY));
PTable<Long, float[]> result = mapPhase
.groupByKey()
.combineValues(new Aggregator<float[]>() {
float[] accumulator = null;
@Override
public Iterable<float[]> results() {
return ImmutableList.of(accumulator);
}
@Override
public void initialize(Configuration conf) {
}
@Override
public void reset() {
this.accumulator = null;
}
@Override
public void update(float[] value) {
if (accumulator == null) {
accumulator = Arrays.copyOf(value, 2);
} else {
for (int i = 0; i < value.length; i += 1) {
accumulator[i] += value[i];
}
}
}
});
pipeline.writeTextFile(result, tmpDir.getFileName("unused"));
Assert.assertTrue("Should succeed", pipeline.done().succeeded());
}
}
| 2,579 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroPipelineIT.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.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
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.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.io.FileUtils;
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.Target;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.To;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
public class AvroPipelineIT implements Serializable {
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = tmpDir.getFile("test.avro");
}
private void populateGenericFile(List<GenericRecord> genericRecords, Schema schema) throws IOException {
FileOutputStream outputStream = new FileOutputStream(this.avroFile);
GenericDatumWriter<GenericRecord> genericDatumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(genericDatumWriter);
dataFileWriter.create(schema, outputStream);
for (GenericRecord record : genericRecords) {
dataFileWriter.append(record);
}
dataFileWriter.close();
outputStream.close();
}
@Test
public void toTextShouldWriteAvroDataAsDatumText() throws Exception {
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$);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
File outputFile = tmpDir.getFile("output");
Target textFile = To.textFile(outputFile.getAbsolutePath());
pipeline.write(genericCollection, textFile);
pipeline.run();
Person person = genericCollection.materialize().iterator().next();
String outputString = FileUtils.readFileToString(new File(outputFile, "part-m-00000"));
assertTrue(outputString.contains(person.toString()));
}
@Test
public void genericWithReflection() throws Exception {
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$);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
PTable<Long, StringWrapper> pt = genericCollection.parallelDo(new MapFn<Person, Pair<Long, StringWrapper>>() {
@Override
public Pair<Long, StringWrapper> map(Person input) {
return Pair.of(1L, new StringWrapper(input.getName().toString()));
}
}, Avros.tableOf(Avros.longs(), Avros.reflects(StringWrapper.class)))
.groupByKey()
.ungroup();
List<Pair<Long, StringWrapper>> ret = Lists.newArrayList(pt.materialize());
pipeline.done();
assertEquals(1, ret.size());
}
}
| 2,580 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroMemPipelineIT.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 java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Record;
import org.apache.crunch.MapFn;
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.io.At;
import org.apache.crunch.io.To;
import org.apache.crunch.lib.PTables;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class AvroMemPipelineIT implements Serializable {
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = tmpDir.getFile("test.avro");
}
@Test
public void testMemPipelineWithSpecificRecord() {
Person writeRecord = createSpecificRecord();
final PCollection<Person> writeCollection = MemPipeline.getInstance().create(
ImmutableList.of(writeRecord), Avros.specifics(Person.class));
writeCollection.write(To.avroFile(avroFile.getAbsolutePath()));
PCollection<Person> readCollection = MemPipeline.getInstance().read(
At.avroFile(avroFile.getAbsolutePath(), Avros.records(Person.class)));
Person readRecord = readCollection.materialize().iterator().next();
assertEquals(writeRecord, readRecord);
}
private Person createSpecificRecord() {
List<CharSequence> siblingnames = Lists.newArrayList();
return new Person("John", 41, siblingnames);
}
@Test
public void testMemPipelineWithGenericRecord() {
PType<GenericData.Record> ptype = Avros.generics(Person.SCHEMA$);
GenericData.Record writeRecord = createGenericRecord("John Doe");
final PCollection<GenericData.Record> writeCollection = MemPipeline.typedCollectionOf(
ptype,
writeRecord);
writeCollection.write(To.avroFile(avroFile.getAbsolutePath()));
PCollection<Record> readCollection = MemPipeline.getInstance().read(
At.avroFile(avroFile.getAbsolutePath(), Avros.generics(writeRecord.getSchema())));
Record readRecord = readCollection.materialize().iterator().next();
assertEquals(writeRecord, readRecord);
}
@Test
public void testMemPipelineWithReflectionRecord() {
String writeRecord = "John Doe";
final PCollection<String> writeCollection = MemPipeline.typedCollectionOf(
Avros.strings(),
writeRecord);
writeCollection.write(To.avroFile(avroFile.getAbsolutePath()));
PCollection<? extends String> readCollection = MemPipeline.getInstance().read(
At.avroFile(avroFile.getAbsolutePath(), Avros.reflects(writeRecord.getClass())));
Object readRecord = readCollection.materialize().iterator().next();
assertEquals(writeRecord, readRecord.toString());
}
@Test
public void testMemPipelineWithMultiplePaths() {
PType<GenericData.Record> ptype = Avros.generics(Person.SCHEMA$);
GenericData.Record writeRecord1 = createGenericRecord("John Doe");
final PCollection<GenericData.Record> writeCollection1 = MemPipeline.typedCollectionOf(
ptype,
writeRecord1);
writeCollection1.write(To.avroFile(avroFile.getAbsolutePath()));
File avroFile2 = tmpDir.getFile("test2.avro");
GenericData.Record writeRecord2 = createGenericRecord("Jane Doe");
final PCollection<GenericData.Record> writeCollection2 = MemPipeline.typedCollectionOf(
ptype,
writeRecord2);
writeCollection2.write(To.avroFile(avroFile2.getAbsolutePath()));
List<Path> paths = Lists.newArrayList(new Path(avroFile.getAbsolutePath()),
new Path(avroFile2.getAbsolutePath()));
PCollection<Record> readCollection = MemPipeline.getInstance().read(
new AvroFileSource<Record>(paths, Avros.generics(writeRecord1.getSchema())));
Set<Record> readSet = Sets.newHashSet(readCollection.materialize());
assertEquals(Sets.newHashSet(writeRecord1, writeRecord2), readSet);
}
private GenericData.Record createGenericRecord(String name) {
GenericData.Record savedRecord = new GenericData.Record(Person.SCHEMA$);
savedRecord.put("name", name);
savedRecord.put("age", 42);
savedRecord.put("siblingnames", Lists.newArrayList("Jimmy"));
return savedRecord;
}
@Test
public void testMemPipelineWithPTable() {
String writeRecord = "John Doe";
final PCollection<String> collection = MemPipeline.typedCollectionOf(
Avros.strings(),
writeRecord);
PTable<Integer, String> writeCollection = collection.by(new MapFn<String, Integer>() {
@Override
public Integer map(String input) {
return input.length();
}
}, Avros.ints());
writeCollection.write(To.avroFile(avroFile.getAbsolutePath()));
PCollection<Pair<Integer, String>> readCollection = MemPipeline.getInstance().read(
At.avroFile(avroFile.getAbsolutePath(),
Avros.tableOf(Avros.ints(), Avros.strings())));
Map<Integer, String> map = PTables.asPTable(readCollection).asMap().getValue();
assertEquals(writeRecord, map.get(writeRecord.length()));
}
}
| 2,581 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroReflectIT.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 java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.fn.IdentityFn;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.avro.Avros;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
public class AvroReflectIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testReflection() throws IOException {
Pipeline pipeline = new MRPipeline(AvroReflectIT.class, tmpDir.getDefaultConfiguration());
PCollection<StringWrapper> stringWrapperCollection = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"))
.parallelDo(new MapFn<String, StringWrapper>() {
@Override
public StringWrapper map(String input) {
StringWrapper stringWrapper = new StringWrapper();
stringWrapper.setValue(input);
return stringWrapper;
}
}, Avros.reflects(StringWrapper.class));
List<StringWrapper> stringWrappers = Lists.newArrayList(stringWrapperCollection.materialize());
pipeline.done();
assertEquals(Lists.newArrayList(new StringWrapper("b"), new StringWrapper("c"), new StringWrapper("a"),
new StringWrapper("e")), stringWrappers);
}
// Verify that running with a combination of reflect and specific schema
// doesn't crash
@Test
public void testCombinationOfReflectionAndSpecific() throws IOException {
Assume.assumeTrue(Avros.CAN_COMBINE_SPECIFIC_AND_REFLECT_SCHEMAS);
Pipeline pipeline = new MRPipeline(AvroReflectIT.class, tmpDir.getDefaultConfiguration());
PCollection<Pair<StringWrapper, Person>> hybridPairCollection = pipeline.readTextFile(
tmpDir.copyResourceFileName("set1.txt")).parallelDo(new MapFn<String, Pair<StringWrapper, Person>>() {
@Override
public Pair<StringWrapper, Person> map(String input) {
Person person = new Person();
person.name = input;
person.age = 42;
person.siblingnames = Lists.<CharSequence> newArrayList(input);
return Pair.of(new StringWrapper(input), person);
}
}, Avros.pairs(Avros.reflects(StringWrapper.class), Avros.records(Person.class)));
PCollection<Pair<String, Long>> countCollection = Aggregate.count(hybridPairCollection).parallelDo(
new MapFn<Pair<Pair<StringWrapper, Person>, Long>, Pair<String, Long>>() {
@Override
public Pair<String, Long> map(Pair<Pair<StringWrapper, Person>, Long> input) {
return Pair.of(input.first().first().getValue(), input.second());
}
}, Avros.pairs(Avros.strings(), Avros.longs()));
List<Pair<String, Long>> materialized = Lists.newArrayList(countCollection.materialize());
List<Pair<String, Long>> expected = Lists.newArrayList(Pair.of("a", 1L), Pair.of("b", 1L), Pair.of("c", 1L),
Pair.of("e", 1L));
Collections.sort(materialized);
assertEquals(expected, materialized);
pipeline.done();
}
private static PType<String> STRING_PTYPE = Avros.derived(String.class,
new MapFn<StringWrapper, String>() { public String map(StringWrapper in) { return in.getValue(); }},
new MapFn<String, StringWrapper>() { public StringWrapper map(String out) { return new StringWrapper(out); }},
Avros.reflects(StringWrapper.class));
@Test
public void testDerivedReflection() throws Exception {
Pipeline pipeline = new MRPipeline(AvroReflectIT.class, tmpDir.getDefaultConfiguration());
PCollection<String> stringWrapperCollection = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"))
.parallelDo(IdentityFn.<String>getInstance(), STRING_PTYPE);
List<String> strings = Lists.newArrayList(stringWrapperCollection.materialize());
pipeline.done();
assertEquals(Lists.newArrayList("b", "c", "a", "e"), strings);
}
@Test
public void testWrappedDerivedReflection() throws Exception {
Pipeline pipeline = new MRPipeline(AvroReflectIT.class, tmpDir.getDefaultConfiguration());
PCollection<Pair<Long, String>> stringWrapperCollection = pipeline.readTextFile(tmpDir.copyResourceFileName("set1.txt"))
.parallelDo(new MapFn<String, Pair<Long, String>>() {
@Override
public Pair<Long, String> map(String input) {
return Pair.of(1L, input);
}
}, Avros.pairs(Avros.longs(), STRING_PTYPE));
List<Pair<Long, String>> pairs = Lists.newArrayList(stringWrapperCollection.materialize());
pipeline.done();
assertEquals(pairs.size(), 4);
assertEquals(Pair.of(1L, "a"), pairs.get(2));
}
}
| 2,582 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroFileSourceTargetIT.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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import com.google.common.collect.ImmutableList;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.reflect.ReflectData;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
@SuppressWarnings("serial")
public class AvroFileSourceTargetIT implements Serializable {
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = getTmpFile("test.avro");
}
private File getTmpFile(String file){
return tmpDir.getFile(file);
}
private void populateGenericFile(File outFile, List<GenericRecord> genericRecords, Schema schema) throws IOException {
FileOutputStream outputStream = new FileOutputStream(outFile);
GenericDatumWriter<GenericRecord> genericDatumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(genericDatumWriter);
dataFileWriter.create(schema, outputStream);
for (GenericRecord record : genericRecords) {
dataFileWriter.append(record);
}
dataFileWriter.close();
outputStream.close();
}
@Test
public void testSpecific() 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(avroFile, Lists.newArrayList(savedRecord), Person.SCHEMA$);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
List<Person> personList = Lists.newArrayList(genericCollection.materialize());
Person expectedPerson = new Person();
expectedPerson.setName("John Doe");
expectedPerson.setAge(42);
List<CharSequence> siblingNames = Lists.newArrayList();
siblingNames.add("Jimmy");
siblingNames.add("Jane");
expectedPerson.setSiblingnames(siblingNames);
assertEquals(Lists.newArrayList(expectedPerson), Lists.newArrayList(personList));
}
@Test
public void testMaterializeAppendMode() throws IOException {
File parentPath = getTmpFile("existing");
parentPath.mkdir();
File existingRecordsFile = new File(parentPath, "test.avro");
GenericRecord savedRecord = new GenericData.Record(Person.SCHEMA$);
savedRecord.put("name", "John Doe");
savedRecord.put("age", 42);
savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane"));
populateGenericFile(existingRecordsFile, Lists.newArrayList(savedRecord), Person.SCHEMA$);
GenericRecord secondRecord = new GenericData.Record(Person.SCHEMA$);
secondRecord.put("name", "Admiral Ackbar");
secondRecord.put("age", 37);
secondRecord.put("siblingnames", Lists.newArrayList("Itsa", "Trap"));
File newRecordsParent = getTmpFile("new");
newRecordsParent.mkdir();
File newRecordsFile = new File(newRecordsParent, "test.avro");
populateGenericFile(newRecordsFile, Lists.newArrayList(secondRecord), Person.SCHEMA$);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> people = pipeline.read(At.avroFile(newRecordsParent.getAbsolutePath(),
Avros.records(Person.class)));
pipeline.write(people, To.avroFile(parentPath.getAbsolutePath()), Target.WriteMode.APPEND);
pipeline.run();
List<Person> personList = Lists.newArrayList(people.materialize());
Person expectedPerson = new Person();
expectedPerson.setName("Admiral Ackbar");
expectedPerson.setAge(37);
List<CharSequence> siblingNames = Lists.newArrayList();
siblingNames.add("Itsa");
siblingNames.add("Trap");
expectedPerson.setSiblingnames(siblingNames);
assertEquals(Lists.newArrayList(expectedPerson), Lists.newArrayList(personList));
pipeline.done();
}
@Test
public void testReadAsGeneric() 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(avroFile, Lists.newArrayList(savedRecord), Person.SCHEMA$);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<GenericData.Record> genericCollection = pipeline.read(From.avroFile(
new Path(avroFile.getAbsolutePath()),
tmpDir.getDefaultConfiguration()));
List<GenericData.Record> personList = Lists.newArrayList(genericCollection.materialize());
assertEquals(Lists.newArrayList(savedRecord), Lists.newArrayList(personList));
}
@Test
public void testGeneric() throws IOException {
String genericSchemaJson = Person.SCHEMA$.toString().replace("Person", "GenericPerson");
Schema genericPersonSchema = new Schema.Parser().parse(genericSchemaJson);
GenericRecord savedRecord = new GenericData.Record(genericPersonSchema);
savedRecord.put("name", "John Doe");
savedRecord.put("age", 42);
savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane"));
populateGenericFile(avroFile, Lists.newArrayList(savedRecord), genericPersonSchema);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Record> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.generics(genericPersonSchema)));
List<Record> recordList = Lists.newArrayList(genericCollection.materialize());
assertEquals(Lists.newArrayList(savedRecord), Lists.newArrayList(recordList));
}
@Test
public void testGenericCreate() throws IOException {
String genericSchemaJson = Person.SCHEMA$.toString().replace("Person", "GenericPerson");
Schema genericPersonSchema = new Schema.Parser().parse(genericSchemaJson);
GenericData.Record savedRecord = new GenericData.Record(genericPersonSchema);
savedRecord.put("name", "John Doe");
savedRecord.put("age", 42);
savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane"));
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Record> genericCollection = pipeline.create(ImmutableList.of(savedRecord),
Avros.generics(genericPersonSchema));
List<Record> recordList = Lists.newArrayList(genericCollection.materialize());
assertEquals(Lists.newArrayList(savedRecord), Lists.newArrayList(recordList));
}
@Test
public void testReflect() throws IOException {
Schema pojoPersonSchema = ReflectData.get().getSchema(StringWrapper.class);
GenericRecord savedRecord = new GenericData.Record(pojoPersonSchema);
savedRecord.put("value", "stringvalue");
populateGenericFile(avroFile, Lists.newArrayList(savedRecord), pojoPersonSchema);
Pipeline pipeline = new MRPipeline(AvroFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<StringWrapper> stringValueCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.reflects(StringWrapper.class)));
List<StringWrapper> recordList = Lists.newArrayList(stringValueCollection.materialize());
assertEquals(1, recordList.size());
StringWrapper stringWrapper = recordList.get(0);
assertEquals("stringvalue", stringWrapper.getValue());
}
}
| 2,583 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroPathPerKeyIT.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 com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.crunch.MapFn;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.fn.FilterFns;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import java.io.Serializable;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class AvroPathPerKeyIT extends CrunchTestSupport implements Serializable {
@Test
public void testOutputFilePerKey() throws Exception {
Pipeline p = new MRPipeline(AvroPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], p[1]);
}
}, Avros.tableOf(Avros.strings(), Avros.strings()))
.groupByKey()
.write(new AvroPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
FileStatus[] aStat = fs.listStatus(new Path(outDir, "A"));
assertEquals(1, aStat.length);
assertEquals("part-r-00000.avro", aStat[0].getPath().getName());
FileStatus[] bStat = fs.listStatus(new Path(outDir, "B"));
assertEquals(1, bStat.length);
assertEquals("part-r-00000.avro", bStat[0].getPath().getName());
}
@Test
public void testOutputFilePerKey_NothingToOutput() throws Exception {
Pipeline p = new MRPipeline(AvroPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], p[1]);
}
}, Avros.tableOf(Avros.strings(), Avros.strings()))
.filter(FilterFns.<Pair<String, String>>REJECT_ALL())
.groupByKey()
.write(new AvroPathPerKeyTarget(outDir));
p.done();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
assertFalse(fs.exists(outDir));
}
@Test
public void testOutputFilePerKey_Directories() throws Exception {
Pipeline p = new MRPipeline(AvroPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0] + "/child", p[1]);
}
}, Avros.tableOf(Avros.strings(), Avros.strings()))
.groupByKey()
.write(new AvroPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
Path aParent = new Path(outDir, "A");
FileStatus[] aParentStat = fs.listStatus(aParent);
assertEquals(1, aParentStat.length);
assertEquals("child", aParentStat[0].getPath().getName());
FileStatus[] aChildStat = fs.listStatus(new Path(aParent, "child"));
assertEquals(1, aChildStat.length);
assertEquals("part-r-00000.avro", aChildStat[0].getPath().getName());
Path bParent = new Path(outDir, "B");
FileStatus[] bParentStat = fs.listStatus(bParent);
assertEquals(1, bParentStat.length);
assertEquals("child", bParentStat[0].getPath().getName());
FileStatus[] bChildStat = fs.listStatus(new Path(bParent, "child"));
assertEquals(1, bChildStat.length);
assertEquals("part-r-00000.avro", bChildStat[0].getPath().getName());
}
}
| 2,584 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/avro/AvroWritableIT.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.apache.crunch.types.avro.Avros.ints;
import static org.apache.crunch.types.avro.Avros.tableOf;
import static org.apache.crunch.types.avro.Avros.writables;
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import java.util.Map;
import org.apache.crunch.CombineFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.io.DoubleWritable;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Maps;
/**
* Verify handling of both a ByteBuffer and byte array as input from an Avro job (depending
* on the version of Avro being used).
*/
public class AvroWritableIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testAvroBasedWritablePipeline() throws Exception {
String customersInputPath = tmpDir.copyResourceFileName("customers.txt");
Pipeline pipeline = new MRPipeline(AvroWritableIT.class, tmpDir.getDefaultConfiguration());
pipeline.enableDebug();
PCollection<String> customerLines = pipeline.readTextFile(customersInputPath);
Map<Integer, DoubleWritable> outputMap = customerLines.parallelDo(
new MapFn<String, Pair<Integer, DoubleWritable>>() {
@Override
public Pair<Integer, DoubleWritable> map(String input) {
int len = input.length();
return Pair.of(len, new DoubleWritable(len));
}
}, tableOf(ints(), writables(DoubleWritable.class)))
.groupByKey()
.combineValues(new CombineFn<Integer, DoubleWritable>() {
@Override
public void process(Pair<Integer, Iterable<DoubleWritable>> input,
Emitter<Pair<Integer, DoubleWritable>> emitter) {
double sum = 0.0;
for (DoubleWritable dw : input.second()) {
sum += dw.get();
}
emitter.emit(Pair.of(input.first(), new DoubleWritable(sum)));
}
})
.materializeToMap();
Map<Integer, DoubleWritable> expectedMap = Maps.newHashMap();
expectedMap.put(17, new DoubleWritable(17.0));
expectedMap.put(16, new DoubleWritable(16.0));
expectedMap.put(12, new DoubleWritable(24.0));
assertEquals(expectedMap, outputMap);
pipeline.done();
}
}
| 2,585 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/text/TextPathPerKeyIT.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;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.crunch.MapFn;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.fn.FilterFns;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.Compress;
import org.apache.crunch.io.From;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import java.io.IOException;
import java.io.Serializable;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class TextPathPerKeyIT extends CrunchTestSupport implements Serializable {
@Test
public void testOutputFilePerKey() throws Exception {
Pipeline p = new MRPipeline(this.getClass(), tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
PTable<String, String> pTable = p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], p[1]);
}
}, Writables.tableOf(Writables.strings(), Writables.strings()));
pTable.groupByKey()
.write(new TextPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
FileStatus[] aStat = fs.listStatus(new Path(outDir, "A"));
assertEquals(1, aStat.length);
assertEquals("part-r-00000", aStat[0].getPath().getName());
FileStatus[] bStat = fs.listStatus(new Path(outDir, "B"));
assertEquals(1, bStat.length);
assertEquals("part-r-00000", bStat[0].getPath().getName());
}
@Test
public void testOutputFilePerKeyMapOnlyJob() throws Exception {
Pipeline p = new MRPipeline(this.getClass(), tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
PTable<String, String> pTable = p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], p[1]);
}
}, Writables.tableOf(Writables.strings(), Writables.strings()));
pTable.write(new TextPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
FileStatus[] aStat = fs.listStatus(new Path(outDir, "A"));
assertEquals(1, aStat.length);
assertEquals("part-m-00000", aStat[0].getPath().getName());
FileStatus[] bStat = fs.listStatus(new Path(outDir, "B"));
assertEquals(1, bStat.length);
assertEquals("part-m-00000", bStat[0].getPath().getName());
}
@Test
public void testOutputFilePerKeyWithNestedSubFoldersAndCompression() throws Exception {
Pipeline p = new MRPipeline(this.getClass(), tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
PTable<String, String> pTable = p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0] + "/dir", p[1]);
}
}, Writables.tableOf(Writables.strings(), Writables.strings()));
pTable.groupByKey()
.write(new TextPathPerKeyTarget(outDir));
Path outDir2 = tempDir.getPath("out2");
pTable.groupByKey()
.write(Compress.gzip(new TextPathPerKeyTarget(outDir2)));
p.done();
assertSubDirs(outDir, "");
assertSubDirs(outDir2, ".gz");
}
private void assertSubDirs(Path outDir, String extension) throws IOException {
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
FileStatus[] aStat = fs.listStatus(new Path(outDir, "A"));
assertEquals(1, aStat.length);
assertEquals("dir", aStat[0].getPath().getName());
FileStatus[] aDirStat = fs.listStatus(aStat[0].getPath());
assertEquals("part-r-00000" + extension, aDirStat[0].getPath().getName());
FileStatus[] bStat = fs.listStatus(new Path(outDir, "B"));
assertEquals(1, bStat.length);
assertEquals("dir", bStat[0].getPath().getName());
FileStatus[] bDirStat = fs.listStatus(bStat[0].getPath());
assertEquals("part-r-00000" + extension, bDirStat[0].getPath().getName());
}
@Test
public void testOutputFilePerKey_NothingToOutput() throws Exception {
Pipeline p = new MRPipeline(this.getClass(), tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], p[1]);
}
}, Writables.tableOf(Writables.strings(), Writables.strings()))
.filter(FilterFns.<Pair<String, String>>REJECT_ALL())
.groupByKey()
.write(new TextPathPerKeyTarget(outDir));
p.done();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
assertFalse(fs.exists(outDir));
}
@Test
public void testOutputFilePerKey_Directories() throws Exception {
Pipeline p = new MRPipeline(this.getClass(), tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, String>>() {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0] + "/child", p[1]);
}
}, Writables.tableOf(Writables.strings(), Writables.strings()))
.groupByKey()
.write(new TextPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
Path aParent = new Path(outDir, "A");
FileStatus[] aParentStat = fs.listStatus(aParent);
assertEquals(1, aParentStat.length);
assertEquals("child", aParentStat[0].getPath().getName());
FileStatus[] aChildStat = fs.listStatus(new Path(aParent, "child"));
assertEquals(1, aChildStat.length);
assertEquals("part-r-00000", aChildStat[0].getPath().getName());
Path bParent = new Path(outDir, "B");
FileStatus[] bParentStat = fs.listStatus(bParent);
assertEquals(1, bParentStat.length);
assertEquals("child", bParentStat[0].getPath().getName());
FileStatus[] bChildStat = fs.listStatus(new Path(bParent, "child"));
assertEquals(1, bChildStat.length);
assertEquals("part-r-00000", bChildStat[0].getPath().getName());
}
}
| 2,586 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/text
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/text/xml/XmlSourceIT.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.Serializable;
import java.util.ArrayList;
import org.apache.crunch.MapFn;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.impl.mr.run.RuntimeParameters;
import org.apache.crunch.io.To;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.types.writable.Writables;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
@SuppressWarnings("serial")
public class XmlSourceIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = new TemporaryPath(RuntimeParameters.TMP_DIR, "hadoop.tmp.dir");
private static final ArrayList<String> RESULT_ELEMENTS = new ArrayList<String>();
private static final class TestMapFn extends MapFn<String, String> {
@Override
public String map(String input) {
RESULT_ELEMENTS.add(input);
return input;
}
}
@Before
public void beforeEachTest() {
RESULT_ELEMENTS.clear();
}
@Test
public void testPlainXmlUtf8() throws Exception {
String xmlInFile = tmpDir.copyResourceFileName("xmlSourceSample1.xml");
String outFile = tmpDir.getFileName("out");
XmlSource xmlSource = new XmlSource(xmlInFile, "<PLANT", "</PLANT>");
MRPipeline p = new MRPipeline(XmlSourceIT.class, tmpDir.getDefaultConfiguration());
p.read(xmlSource).by(new TestMapFn(), Writables.strings()).write(To.textFile(outFile));
p.done();
assertEquals("[36] elements expected but found: " + RESULT_ELEMENTS.size(), 36, RESULT_ELEMENTS.size());
}
@Test
public void testEncoding() throws Exception {
final ArrayList<String> expectedElements = Lists.newArrayList("<ПЛАНТ>One</ПЛАНТ> ",
"<ПЛАНТ>Две</ПЛАНТ> ", "<ПЛАНТ>Три</ПЛАНТ> ");
String xmlInFile = tmpDir.copyResourceFileName("xmlSourceSample2.xml");
String outFile = tmpDir.getFileName("out");
XmlSource xmlSource = new XmlSource(xmlInFile, "<ПЛАНТ", "</ПЛАНТ>", "UTF-16BE");
MRPipeline p = new MRPipeline(XmlSourceIT.class, tmpDir.getDefaultConfiguration());
p.read(xmlSource).by(new TestMapFn(), Writables.strings()).write(To.textFile(outFile));
p.done();
assertEquals(3, RESULT_ELEMENTS.size());
assertTrue("Expected elements: " + expectedElements + " not found!", RESULT_ELEMENTS.containsAll(expectedElements));
}
}
| 2,587 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/text
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/text/csv/CSVFileSourceIT.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.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.crunch.PCollection;
import org.apache.crunch.PTable;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.io.compress.DeflateCodec;
import org.junit.Rule;
import org.junit.Test;
public class CSVFileSourceIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testVanillaCSV() throws Exception {
final String[] expectedFileContents = { "1,2,3,4", "5,6,7,8", "9,10,11", "12,13,14" };
final String vanillaCSVFile = tmpDir.copyResourceFileName("vanilla.csv");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(vanillaCSVFile)));
final Collection<String> csvLinesList = csvLines.asCollection().getValue();
for (int i = 0; i < expectedFileContents.length; i++) {
assertTrue(csvLinesList.contains(expectedFileContents[i]));
}
}
@Test
public void testVanillaCSV_Compressed() throws Exception {
final String[] expectedFileContents = { "1,2,3,4", "5,6,7,8", "9,10,11", "12,13,14" };
CompressionCodecFactory codecFactory = new CompressionCodecFactory(tmpDir.getDefaultConfiguration());
CompressionCodec deflateCodec = codecFactory.getCodecByName(DeflateCodec.class.getName());
File compressedFile = tmpDir.getFile("vanilla." + deflateCodec.getDefaultExtension());
InputStream in = CSVFileSourceIT.class.getClassLoader().getResourceAsStream("vanilla.csv");
OutputStream out = deflateCodec.createOutputStream(new FileOutputStream(compressedFile));
try {
IOUtils.copy(in, out);
}finally {
in.close();
out.close();
}
final String vanillaCSVFile = tmpDir.copyResourceFileName("vanilla.csv");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(compressedFile.getPath())));
final Collection<String> csvLinesList = csvLines.asCollection().getValue();
for (int i = 0; i < expectedFileContents.length; i++) {
assertTrue(csvLinesList.contains(expectedFileContents[i]));
}
}
@Test
public void testVanillaCSVWithAdditionalActions() throws Exception {
final String[] expectedFileContents = { "1,2,3,4", "5,6,7,8", "9,10,11", "12,13,14" };
final String vanillaCSVFile = tmpDir.copyResourceFileName("vanilla.csv");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(vanillaCSVFile)));
final PTable<String, Long> countTable = csvLines.count();
final PCollection<String> csvLines2 = countTable.keys();
final Collection<String> csvLinesList = csvLines2.asCollection().getValue();
for (int i = 0; i < expectedFileContents.length; i++) {
assertTrue(csvLinesList.contains(expectedFileContents[i]));
}
}
@Test
public void testCSVWithNewlines() throws Exception {
final 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\"" };
final String csvWithNewlines = tmpDir.copyResourceFileName("withNewlines.csv");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(csvWithNewlines)));
final Collection<String> csvLinesList = csvLines.asCollection().getValue();
for (int i = 0; i < expectedFileContents.length; i++) {
assertTrue(csvLinesList.contains(expectedFileContents[i]));
}
}
/**
* This test is to make sure that custom char values set in the FileSource are
* successfully picked up and used later by the InputFormat.
*/
@Test
public void testCSVWithCustomQuoteAndNewlines() throws IOException {
final 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*",
"*Mac, Champion*,*5678 Tatooine Rd. Apt 5, Mobile, AL 36608*,*30*,*M*,*Some other date*,*short description*" };
final String csvWithNewlines = tmpDir.copyResourceFileName("customQuoteCharWithNewlines.csv");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(csvWithNewlines),
CSVLineReader.DEFAULT_BUFFER_SIZE, CSVLineReader.DEFAULT_INPUT_FILE_ENCODING, '*', '*',
CSVLineReader.DEFAULT_ESCAPE_CHARACTER, CSVLineReader.DEFAULT_MAXIMUM_RECORD_SIZE));
final Collection<String> csvLinesList = csvLines.asCollection().getValue();
for (int i = 0; i < expectedFileContents.length; i++) {
assertTrue(csvLinesList.contains(expectedFileContents[i]));
}
}
/**
* This is effectively a mirror the above 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");
final Pipeline pipeline = new MRPipeline(CSVFileSourceIT.class, tmpDir.getDefaultConfiguration());
final PCollection<String> csvLines = pipeline.read(new CSVFileSource(new Path(chineseLines),
CSVLineReader.DEFAULT_BUFFER_SIZE, CSVLineReader.DEFAULT_INPUT_FILE_ENCODING, '“', '”', '、',
CSVLineReader.DEFAULT_MAXIMUM_RECORD_SIZE));
final Collection<String> csvLinesList = csvLines.asCollection().getValue();
for (int i = 0; i < expectedChineseLines.length; i++) {
assertTrue(csvLinesList.contains(expectedChineseLines[i]));
}
}
}
| 2,588 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/parquet/AvroParquetPathPerKeyIT.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 com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org.apache.crunch.MapFn;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.fn.FilterFns;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.test.Person;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class AvroParquetPathPerKeyIT extends CrunchTestSupport implements Serializable {
@Test
public void testOutputFilePerKey() throws Exception {
Pipeline p = new MRPipeline(AvroParquetPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, Person>>() {
@Override
public Pair<String, Person> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], newPerson());
}
}, Avros.tableOf(Avros.strings(), Avros.records(Person.class)))
.groupByKey()
.write(new AvroParquetPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
FileStatus[] aStat = fs.listStatus(new Path(outDir, "A"));
assertEquals(1, aStat.length);
assertEquals("part-r-00000.parquet", aStat[0].getPath().getName());
FileStatus[] bStat = fs.listStatus(new Path(outDir, "B"));
assertEquals(1, bStat.length);
assertEquals("part-r-00000.parquet", bStat[0].getPath().getName());
}
@Test
public void testOutputFilePerKey_NothingToOutput() throws Exception {
Pipeline p = new MRPipeline(AvroParquetPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, Person>>() {
@Override
public Pair<String, Person> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0], newPerson());
}
}, Avros.tableOf(Avros.strings(), Avros.records(Person.class)))
.filter(FilterFns.<Pair<String, Person>>REJECT_ALL())
.groupByKey()
.write(new AvroParquetPathPerKeyTarget(outDir));
p.done();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
assertFalse(fs.exists(outDir));
}
@Test
public void testOutputFilePerKey_Directories() throws Exception {
Pipeline p = new MRPipeline(AvroParquetPathPerKeyIT.class, tempDir.getDefaultConfiguration());
Path outDir = tempDir.getPath("out");
p.read(From.textFile(tempDir.copyResourceFileName("docs.txt")))
.parallelDo(new MapFn<String, Pair<String, Person>>() {
@Override
public Pair<String, Person> map(String input) {
String[] p = input.split("\t");
return Pair.of(p[0] + "/child", newPerson());
}
}, Avros.tableOf(Avros.strings(), Avros.records(Person.class)))
.groupByKey()
.write(new AvroParquetPathPerKeyTarget(outDir));
p.done();
Set<String> names = Sets.newHashSet();
FileSystem fs = outDir.getFileSystem(tempDir.getDefaultConfiguration());
for (FileStatus fstat : fs.listStatus(outDir)) {
names.add(fstat.getPath().getName());
}
assertEquals(ImmutableSet.of("A", "B", "_SUCCESS"), names);
Path aParent = new Path(outDir, "A");
FileStatus[] aParentStat = fs.listStatus(aParent);
assertEquals(1, aParentStat.length);
assertEquals("child", aParentStat[0].getPath().getName());
FileStatus[] aChildStat = fs.listStatus(new Path(aParent, "child"));
assertEquals(1, aChildStat.length);
assertEquals("part-r-00000.parquet", aChildStat[0].getPath().getName());
Path bParent = new Path(outDir, "B");
FileStatus[] bParentStat = fs.listStatus(bParent);
assertEquals(1, bParentStat.length);
assertEquals("child", bParentStat[0].getPath().getName());
FileStatus[] bChildStat = fs.listStatus(new Path(bParent, "child"));
assertEquals(1, bChildStat.length);
assertEquals("part-r-00000.parquet", bChildStat[0].getPath().getName());
}
private Person newPerson() {
Person person = new Person();
person.name = "John Doe";
person.age = 42;
List<CharSequence> siblingNames = Lists.newArrayList();
siblingNames.add("Jimmy");
siblingNames.add("Jane");
person.siblingnames = siblingNames;
return person;
}
}
| 2,589 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/parquet/AvroParquetFileSourceTargetIT.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.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import com.google.common.collect.Iterables;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.util.Utf8;
import org.apache.crunch.FilterFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.io.avro.AvroFileSource;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.parquet.avro.AvroParquetWriter;
import com.google.common.collect.Lists;
import org.apache.parquet.column.ColumnReader;
import org.apache.parquet.filter.RecordFilter;
import org.apache.parquet.filter.UnboundRecordFilter;
@SuppressWarnings("serial")
public class AvroParquetFileSourceTargetIT implements Serializable {
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = tmpDir.getFile("test.avro.parquet");
}
private void populateGenericFile(List<GenericRecord> genericRecords, Schema schema) throws IOException {
AvroParquetWriter<GenericRecord> writer = new AvroParquetWriter<GenericRecord>(
new Path(avroFile.getPath()), schema);
for (GenericRecord record : genericRecords) {
writer.write(record);
}
writer.close();
}
@Test
public void testSpecific() throws IOException {
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(new AvroParquetFileSource<Person>(new Path(avroFile.getAbsolutePath()),
Avros.records(Person.class)));
List<Person> personList = Lists.newArrayList(genericCollection.materialize());
Person expectedPerson = new Person();
expectedPerson.name = "John Doe";
expectedPerson.age = 42;
List<CharSequence> siblingNames = Lists.newArrayList();
siblingNames.add("Jimmy");
siblingNames.add("Jane");
expectedPerson.siblingnames = siblingNames;
assertEquals(Lists.newArrayList(expectedPerson), Lists.newArrayList(personList));
}
@Test
public void testGeneric() 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);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Record> genericCollection = pipeline.read(new AvroParquetFileSource<Record>(new Path
(avroFile.getAbsolutePath()),
Avros.generics(genericPersonSchema)));
List<Record> recordList = Lists.newArrayList(genericCollection.materialize());
assertEquals(Lists.newArrayList(savedRecord), Lists.newArrayList(recordList));
}
@Test
public void testProjectionSpecific() throws IOException {
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(
AvroParquetFileSource.builder(Person.class)
.includeField("age")
.build(new Path(avroFile.getAbsolutePath())));
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<Person> ageOnly = pipeline2.read(
new AvroFileSource<Person>(new Path(outputFile.getAbsolutePath()), Avros.specifics(Person.class)));
Person person = Iterables.getOnlyElement(ageOnly.materialize());
assertNull(person.getName());
assertEquals(person.getAge().intValue(), 42);
assertNull(person.getSiblingnames());
}
@Test
public void testProjectionGeneric() throws IOException {
GenericRecord savedRecord = new 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$);
AvroParquetFileSource<GenericRecord> src = AvroParquetFileSource.builder(Person.SCHEMA$)
.includeField("age")
.build(new Path(avroFile.getAbsolutePath()));
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<GenericRecord> genericCollection = pipeline.read(src);
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<Record> ageOnly = pipeline2.read(
new AvroFileSource<Record>(new Path(outputFile.getAbsolutePath()), Avros.generics(src.getProjectedSchema())));
Record person = Iterables.getOnlyElement(ageOnly.materialize());
assertEquals(person.get(0), 42);
try {
person.get(1);
fail("Trying to get field outside of projection should fail");
} catch (IndexOutOfBoundsException e) {
// Expected
}
}
@Test
public void testCustomReadSchema_FieldSubset() throws IOException {
Schema readSchema = SchemaBuilder.record("PersonSubset")
.namespace("org.apache.crunch.test")
.fields()
.optionalString("name")
.endRecord();
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<GenericRecord> genericCollection = pipeline.read(
AvroParquetFileSource.builder(readSchema)
.includeField("name")
.build(new Path(avroFile.getAbsolutePath())));
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<GenericData.Record> namedPersonRecords = pipeline2.read(
From.avroFile(new Path(outputFile.getAbsolutePath())));
GenericRecord personSubset = Iterables.getOnlyElement(namedPersonRecords.materialize());
assertEquals(readSchema, personSubset.getSchema());
assertEquals(new Utf8("John Doe"), personSubset.get("name"));
}
@Test
public void testCustomReadSchemaGeneric_FieldSuperset() throws IOException {
Schema readSchema = SchemaBuilder.record("PersonSuperset")
.namespace("org.apache.crunch.test")
.fields()
.optionalString("name")
.optionalInt("age")
.name("siblingnames").type(Person.SCHEMA$.getField("siblingnames").schema()).withDefault(null)
.name("employer").type().stringType().stringDefault("Acme Corp")
.endRecord();
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<GenericRecord> genericCollection = pipeline.read(
AvroParquetFileSource.builder(readSchema)
.build(new Path(avroFile.getAbsolutePath())));
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<GenericData.Record> namedPersonRecords = pipeline2.read(
From.avroFile(new Path(outputFile.getAbsolutePath())));
GenericRecord personSuperset = Iterables.getOnlyElement(namedPersonRecords.materialize());
assertEquals(readSchema, personSuperset.getSchema());
assertEquals(new Utf8("John Doe"), personSuperset.get("name"));
assertEquals(42, personSuperset.get("age"));
assertEquals(Lists.newArrayList(new Utf8("Jimmy"), new Utf8("Jane")), personSuperset.get("siblingnames"));
assertEquals(new Utf8("Acme Corp"), personSuperset.get("employer"));
}
@Test
public void testCustomReadSchemaWithProjection() throws IOException {
Schema readSchema = SchemaBuilder.record("PersonSubsetWithProjection")
.namespace("org.apache.crunch.test")
.fields()
.optionalString("name")
.optionalInt("age")
.endRecord();
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<GenericRecord> genericCollection = pipeline.read(
AvroParquetFileSource.builder(readSchema)
.includeField("name")
.build(new Path(avroFile.getAbsolutePath())));
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<GenericData.Record> namedPersonRecords = pipeline2.read(
From.avroFile(new Path(outputFile.getAbsolutePath())));
GenericRecord personSubset = Iterables.getOnlyElement(namedPersonRecords.materialize());
assertEquals(readSchema, personSubset.getSchema());
assertEquals(new Utf8("John Doe"), personSubset.get("name"));
assertNull(personSubset.get("age"));
}
@Test
public void testProjectionFiltered() throws IOException {
GenericRecord savedRecord = new 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$);
Pipeline pipeline = new MRPipeline(AvroParquetFileSourceTargetIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(
AvroParquetFileSource.builder(Person.class)
.includeField("age")
.filterClass(RejectAllFilter.class)
.build(new Path(avroFile.getAbsolutePath())));
File outputFile = tmpDir.getFile("output");
Target avroFile = To.avroFile(outputFile.getAbsolutePath());
genericCollection.filter(new FilterFn<Person>() {
@Override
public boolean accept(Person input) {
return input != null;
}
}).write(avroFile);
pipeline.done();
Pipeline pipeline2 = new MRPipeline(AvroParquetFileSourceTargetIT.class,
tmpDir.getDefaultConfiguration());
PCollection<Person> ageOnly = pipeline2.read(
new AvroFileSource<Person>(new Path(outputFile.getAbsolutePath()), Avros.specifics(Person.class)));
assertTrue(Lists.newArrayList(ageOnly.materialize()).isEmpty());
}
public static class RejectAllFilter implements UnboundRecordFilter {
@Override
public RecordFilter bind(Iterable<ColumnReader> readers) {
return new RecordFilter() {
@Override
public boolean isMatch() {
return false;
}
};
}
}
}
| 2,590 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/io/parquet/AvroParquetPipelineIT.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 com.google.common.collect.Lists;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
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.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.Employee;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.parquet.avro.AvroParquetReader;
import org.apache.parquet.avro.AvroParquetWriter;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class AvroParquetPipelineIT implements Serializable {
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = tmpDir.getFile("test.avro.parquet");
}
private void populateGenericFile(List<GenericRecord> genericRecords, Schema schema) throws IOException {
FileOutputStream outputStream = new FileOutputStream(this.avroFile);
GenericDatumWriter<GenericRecord> genericDatumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(genericDatumWriter);
dataFileWriter.create(schema, outputStream);
for (GenericRecord record : genericRecords) {
dataFileWriter.append(record);
}
dataFileWriter.close();
outputStream.close();
}
private void populateGenericParquetFile(List<GenericRecord> genericRecords, Schema schema) throws IOException {
AvroParquetWriter<GenericRecord> writer = new AvroParquetWriter<GenericRecord>(
new Path(avroFile.getPath()), schema);
for (GenericRecord record : genericRecords) {
writer.write(record);
}
writer.close();
}
@Test
public void toAvroParquetFileTarget() throws Exception {
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$);
Pipeline pipeline = new MRPipeline(AvroParquetPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
File outputFile = tmpDir.getFile("output");
Target parquetFileTarget = new AvroParquetFileTarget(outputFile.getAbsolutePath());
pipeline.write(genericCollection, parquetFileTarget);
pipeline.run();
Person person = genericCollection.materialize().iterator().next();
Path parquetFile = new Path(new File(outputFile, "part-m-00000.parquet").getPath());
AvroParquetReader<Person> reader = new AvroParquetReader<Person>(parquetFile);
try {
Person readPerson = reader.read();
assertThat(readPerson, is(person));
} finally {
reader.close();
}
}
@Test
public void toAvroParquetFileTargetFromParquet() throws Exception {
GenericRecord savedRecord = new GenericData.Record(Person.SCHEMA$);
savedRecord.put("name", "John Doe");
savedRecord.put("age", 42);
savedRecord.put("siblingnames", Lists.newArrayList("Jimmy", "Jane"));
populateGenericParquetFile(Lists.newArrayList(savedRecord), Person.SCHEMA$);
Pipeline pipeline = new MRPipeline(AvroParquetPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(
new AvroParquetFileSource<Person>(new Path(avroFile.getAbsolutePath()), Avros.records(Person.class)));
File outputFile = tmpDir.getFile("output");
Target parquetFileTarget = new AvroParquetFileTarget(outputFile.getAbsolutePath());
pipeline.write(genericCollection, parquetFileTarget);
pipeline.run();
Person person = genericCollection.materialize().iterator().next();
Path parquetFile = new Path(new File(outputFile, "part-m-00000.parquet").getPath());
AvroParquetReader<Person> reader = new AvroParquetReader<Person>(parquetFile);
try {
Person readPerson = reader.read();
assertThat(readPerson, is(person));
} finally {
reader.close();
}
}
@Test
public void toAvroParquetFileMultipleTarget() throws Exception {
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$);
Pipeline pipeline = new MRPipeline(AvroParquetPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
PCollection<Employee> employees = genericCollection.parallelDo(new DoFn<Person, Employee>() {
@Override
public void process(Person person, Emitter<Employee> emitter) {
emitter.emit(new Employee(person.getName(), 0, "Eng"));
}
}, Avros.records(Employee.class));
File output1File = tmpDir.getFile("output1");
File output2File = tmpDir.getFile("output2");
pipeline.write(genericCollection, new AvroParquetFileTarget(output1File.getAbsolutePath()));
pipeline.write(employees, new AvroParquetFileSourceTarget(new Path(output2File.getAbsolutePath()),
Avros.records(Employee.class)));
pipeline.run();
Person person = genericCollection.materialize().iterator().next();
Employee employee = employees.materialize().iterator().next();
Path parquet1File = new Path(new File(output1File, "part-m-00000.parquet").getPath());
Path parquet2File = new Path(new File(output2File, "part-m-00000.parquet").getPath());
AvroParquetReader<Person> personReader = new AvroParquetReader<Person>(parquet1File);
try {
Person readPerson = personReader.read();
assertThat(readPerson, is(person));
} finally {
personReader.close();
}
AvroParquetReader<Employee> employeeReader = new AvroParquetReader<Employee>(parquet2File);
try {
Employee readEmployee = employeeReader.read();
assertThat(readEmployee, is(employee));
} finally {
employeeReader.close();
}
}
@Test
public void toAvroParquetFileTargetReadSource() throws Exception {
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$);
Pipeline pipeline = new MRPipeline(AvroParquetPipelineIT.class, tmpDir.getDefaultConfiguration());
PCollection<Person> genericCollection = pipeline.read(At.avroFile(avroFile.getAbsolutePath(),
Avros.records(Person.class)));
File outputFile = tmpDir.getFile("output");
Target parquetFileTarget = new AvroParquetFileTarget(outputFile.getAbsolutePath());
pipeline.write(genericCollection, parquetFileTarget);
pipeline.run();
Person person = genericCollection.materialize().iterator().next();
PCollection<Person> retrievedPeople = pipeline.read(new AvroParquetFileSource<Person>(
new Path(outputFile.toURI()), Avros.records(Person.class)));
Person retrievedPerson = retrievedPeople.materialize().iterator().next();
assertThat(retrievedPerson, is(person));
Path parquetFile = new Path(new File(outputFile, "part-m-00000.parquet").getPath());
AvroParquetReader<Person> reader = new AvroParquetReader<Person>(parquetFile);
try {
Person readPerson = reader.read();
assertThat(readPerson, is(person));
} finally {
reader.close();
}
}
}
| 2,591 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/AggregateIT.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.writable.Writables.strings;
import static org.apache.crunch.types.writable.Writables.tableOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
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.impl.mem.MemPipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.test.Employee;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTableType;
import org.apache.crunch.types.PTypeFamily;
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.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class AggregateIT {
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritables() throws Exception {
Pipeline pipeline = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakes = pipeline.readTextFile(shakesInputPath);
runMinMax(shakes, WritableTypeFamily.getInstance());
pipeline.done();
}
@Test
public void testAvro() throws Exception {
Pipeline pipeline = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
String shakesInputPath = tmpDir.copyResourceFileName("shakes.txt");
PCollection<String> shakes = pipeline.readTextFile(shakesInputPath);
runMinMax(shakes, AvroTypeFamily.getInstance());
pipeline.done();
}
@Test
public void testInMemoryAvro() throws Exception {
PCollection<String> someText = MemPipeline.collectionOf("first line", "second line", "third line");
runMinMax(someText, AvroTypeFamily.getInstance());
}
public static void runMinMax(PCollection<String> shakes, PTypeFamily family) throws Exception {
PCollection<Integer> lengths = shakes.parallelDo(new MapFn<String, Integer>() {
@Override
public Integer map(String input) {
return input.length();
}
}, family.ints());
PCollection<Integer> negLengths = lengths.parallelDo(new MapFn<Integer, Integer>() {
@Override
public Integer map(Integer input) {
return -input;
}
}, family.ints());
Integer maxLengths = Aggregate.max(lengths).getValue();
Integer minLengths = Aggregate.min(negLengths).getValue();
assertTrue(maxLengths != null);
assertTrue(minLengths != null);
assertEquals(maxLengths.intValue(), -minLengths.intValue());
}
private static class SplitFn extends MapFn<String, Pair<String, String>> {
@Override
public Pair<String, String> map(String input) {
String[] p = input.split("\\s+");
return Pair.of(p[0], p[1]);
}
}
@Test
public void testCollectUrls() throws Exception {
Pipeline p = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
String urlsInputPath = tmpDir.copyResourceFileName("urls.txt");
PTable<String, Collection<String>> urls = Aggregate.collectValues(p.readTextFile(urlsInputPath).parallelDo(
new SplitFn(), tableOf(strings(), strings())));
for (Pair<String, Collection<String>> e : urls.materialize()) {
String key = e.first();
int expectedSize = 0;
if ("www.A.com".equals(key)) {
expectedSize = 4;
} else if ("www.B.com".equals(key) || "www.F.com".equals(key)) {
expectedSize = 2;
} else if ("www.C.com".equals(key) || "www.D.com".equals(key) || "www.E.com".equals(key)) {
expectedSize = 1;
}
assertEquals("Checking key = " + key, expectedSize, e.second().size());
p.done();
}
}
@Test
public void testTopN() throws Exception {
PTableType<String, Integer> ptype = Avros.tableOf(Avros.strings(), Avros.ints());
PTable<String, Integer> counts = MemPipeline.typedTableOf(ptype, "foo", 12, "bar", 17, "baz", 29);
PTable<String, Integer> top2 = Aggregate.top(counts, 2, true);
assertEquals(ImmutableList.of(Pair.of("baz", 29), Pair.of("bar", 17)), top2.materialize());
PTable<String, Integer> bottom2 = Aggregate.top(counts, 2, false);
assertEquals(ImmutableList.of(Pair.of("foo", 12), Pair.of("bar", 17)), bottom2.materialize());
}
@Test
public void testTopN_MRPipeline() throws IOException {
Pipeline pipeline = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
PTable<StringWrapper, String> entries = pipeline
.read(From.textFile(tmpDir.copyResourceFileName("set1.txt"), Avros.strings()))
.by(new StringWrapper.StringToStringWrapperMapFn(), Avros.reflects(StringWrapper.class));
PTable<StringWrapper, String> topEntries = Aggregate.top(entries, 3, true);
List<Pair<StringWrapper, String>> expectedTop3 = Lists.newArrayList(
Pair.of(StringWrapper.wrap("e"), "e"),
Pair.of(StringWrapper.wrap("c"), "c"),
Pair.of(StringWrapper.wrap("b"), "b"));
assertEquals(
expectedTop3,
Lists.newArrayList(topEntries.materialize()));
}
@Test
public void testCollectValues_Writables() throws IOException {
Pipeline pipeline = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
Map<Integer, Collection<Text>> collectionMap = pipeline.readTextFile(tmpDir.copyResourceFileName("set2.txt"))
.parallelDo(new MapStringToTextPair(), Writables.tableOf(Writables.ints(), Writables.writables(Text.class)))
.collectValues().materializeToMap();
assertEquals(1, collectionMap.size());
assertTrue(collectionMap.get(1).containsAll(Lists.newArrayList(new Text("c"), new Text("d"), new Text("a"))));
}
@Test
public void testCollectValues_Avro() throws IOException {
MapStringToEmployeePair mapFn = new MapStringToEmployeePair();
Pipeline pipeline = new MRPipeline(AggregateIT.class, tmpDir.getDefaultConfiguration());
Map<Integer, Collection<Employee>> collectionMap = pipeline.readTextFile(tmpDir.copyResourceFileName("set2.txt"))
.parallelDo(mapFn, Avros.tableOf(Avros.ints(), Avros.records(Employee.class))).collectValues()
.materializeToMap();
assertEquals(1, collectionMap.size());
Employee empC = mapFn.map("c").second();
Employee empD = mapFn.map("d").second();
Employee empA = mapFn.map("a").second();
assertTrue(collectionMap.get(1).containsAll(Lists.newArrayList(empC, empD, empA)));
}
private static class MapStringToTextPair extends MapFn<String, Pair<Integer, Text>> {
@Override
public Pair<Integer, Text> map(String input) {
return Pair.of(1, new Text(input));
}
}
private static class MapStringToEmployeePair extends MapFn<String, Pair<Integer, Employee>> {
@Override
public Pair<Integer, Employee> map(String input) {
Employee emp = new Employee();
emp.name = input;
emp.salary = 0;
emp.department = "";
return Pair.of(1, emp);
}
}
public static class PojoText {
private String value;
public PojoText() {
this("");
}
public PojoText(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return String.format("PojoText<%s>", this.value);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PojoText other = (PojoText) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public int hashCode() {
return value == null ? 0 : value.hashCode();
}
}
}
| 2,592 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/MapredIT.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.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.PipelineResult.StageResult;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.io.To;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
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.Test;
public class MapredIT extends CrunchTestSupport 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(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 hasThou = false;
String notThou = "";
while (iter.hasNext()) {
String next = iter.next().toString();
if (next != null && next.contains("thou")) {
reporter.getCounter("thou", "count").increment(1);
hasThou = true;
} else {
notThou = next;
}
}
out.collect(new Text(notThou), hasThou ? new LongWritable(1L) : new LongWritable(0L));
}
}
@Test
public void testMapper() throws Exception {
Pipeline p = new MRPipeline(MapredIT.class, tempDir.getDefaultConfiguration());
Path shakesPath = tempDir.copyResourcePath("shakes.txt");
PCollection<String> in = p.read(From.textFile(shakesPath));
PTable<IntWritable, Text> two = in.parallelDo(new MapFn<String, Pair<IntWritable, Text>>() {
@Override
public Pair<IntWritable, Text> map(String input) {
return Pair.of(new IntWritable(input.length()), new Text(input));
}
}, Writables.tableOf(Writables.writables(IntWritable.class), Writables.writables(Text.class)));
PTable<Text, LongWritable> out = Mapred.map(two, TestMapper.class, Text.class, LongWritable.class);
out.write(To.sequenceFile(tempDir.getPath("temp")));
PipelineResult res = p.done();
assertEquals(1, res.getStageResults().size());
StageResult sr = res.getStageResults().get(0);
assertEquals(3285, sr.getCounters().findCounter("written", "out").getValue());
}
@Test
public void testReducer() throws Exception {
Pipeline p = new MRPipeline(MapredIT.class, tempDir.getDefaultConfiguration());
Path shakesPath = tempDir.copyResourcePath("shakes.txt");
PCollection<String> in = p.read(From.textFile(shakesPath));
PTable<IntWritable, Text> two = in.parallelDo(new MapFn<String, Pair<IntWritable, Text>>() {
@Override
public Pair<IntWritable, Text> map(String input) {
return Pair.of(new IntWritable(input.length()), new Text(input));
}
}, Writables.tableOf(Writables.writables(IntWritable.class), Writables.writables(Text.class)));
PTable<Text, LongWritable> out = Mapred.reduce(two.groupByKey(), TestReducer.class, Text.class, LongWritable.class);
out.write(To.sequenceFile(tempDir.getPath("temp")));
PipelineResult res = p.done();
assertEquals(1, res.getStageResults().size());
StageResult sr = res.getStageResults().get(0);
assertEquals(103, sr.getCounters().findCounter("thou", "count").getValue());
}
}
| 2,593 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/AvroTypeSortIT.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 static org.apache.crunch.types.avro.Avros.ints;
import static org.apache.crunch.types.avro.Avros.records;
import static org.apache.crunch.types.avro.Avros.strings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* Test sorting Avro types by selected inner field
*/
public class AvroTypeSortIT implements Serializable {
private static final long serialVersionUID = 1344118240353796561L;
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = File.createTempFile("avrotest", ".avro");
}
@After
public void tearDown() {
avroFile.delete();
}
@Test
public void testSortAvroTypesBySelectedFields() throws Exception {
MRPipeline pipeline = new MRPipeline(AvroTypeSortIT.class, tmpDir.getDefaultConfiguration());
Person ccc10 = createPerson("CCC", 10);
Person bbb20 = createPerson("BBB", 20);
Person aaa30 = createPerson("AAA", 30);
writeAvroFile(Lists.newArrayList(ccc10, bbb20, aaa30), avroFile);
PCollection<Person> unsorted = pipeline.read(At.avroFile(avroFile.getAbsolutePath(), records(Person.class)));
// Sort by Name
MapFn<Person, String> nameExtractor = new MapFn<Person, String>() {
@Override
public String map(Person input) {
return input.name.toString();
}
};
PCollection<Person> sortedByName = unsorted.by(nameExtractor, strings()).groupByKey().ungroup().values();
List<Person> sortedByNameList = Lists.newArrayList(sortedByName.materialize());
assertEquals(3, sortedByNameList.size());
assertEquals(aaa30, sortedByNameList.get(0));
assertEquals(bbb20, sortedByNameList.get(1));
assertEquals(ccc10, sortedByNameList.get(2));
// Sort by Age
MapFn<Person, Integer> ageExtractor = new MapFn<Person, Integer>() {
@Override
public Integer map(Person input) {
return input.age;
}
};
PCollection<Person> sortedByAge = unsorted.by(ageExtractor, ints()).groupByKey().ungroup().values();
List<Person> sortedByAgeList = Lists.newArrayList(sortedByAge.materialize());
assertEquals(3, sortedByAgeList.size());
assertEquals(ccc10, sortedByAgeList.get(0));
assertEquals(bbb20, sortedByAgeList.get(1));
assertEquals(aaa30, sortedByAgeList.get(2));
pipeline.done();
}
private static void writeAvroFile(List<Person> people, File avroFile) throws IOException {
FileOutputStream outputStream = new FileOutputStream(avroFile);
SpecificDatumWriter<Person> writer = new SpecificDatumWriter<Person>(Person.class);
DataFileWriter<Person> dataFileWriter = new DataFileWriter<Person>(writer);
dataFileWriter.create(Person.SCHEMA$, outputStream);
for (Person person : people) {
dataFileWriter.append(person);
}
dataFileWriter.close();
outputStream.close();
}
private static Person createPerson(String name, int age) {
Person person = new Person();
person.age = age;
person.name = name;
person.siblingnames = Lists.newArrayList();
return person;
}
}
| 2,594 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/SortByValueIT.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.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.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.lib.Sort.ColumnOrder;
import org.apache.crunch.lib.Sort.Order;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
/**
*
*/
public class SortByValueIT {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
private static class SplitFn extends MapFn<String, Pair<String, Long>> {
private String sep;
public SplitFn(String sep) {
this.sep = sep;
}
@Override
public Pair<String, Long> map(String input) {
String[] pieces = input.split(sep);
return Pair.of(pieces[0], Long.valueOf(pieces[1]));
}
}
@Test
public void testSortByValueWritables() throws Exception {
run(new MRPipeline(SortByValueIT.class), WritableTypeFamily.getInstance());
}
@Test
public void testSortByValueAvro() throws Exception {
run(new MRPipeline(SortByValueIT.class), AvroTypeFamily.getInstance());
}
public void run(Pipeline pipeline, PTypeFamily ptf) throws Exception {
String sbv = tmpDir.copyResourceFileName("sort_by_value.txt");
PTable<String, Long> letterCounts = pipeline.read(From.textFile(sbv)).parallelDo(new SplitFn("\t"),
ptf.tableOf(ptf.strings(), ptf.longs()));
PCollection<Pair<String, Long>> sorted = Sort.sortPairs(
letterCounts,
new ColumnOrder(2, Order.DESCENDING),
new ColumnOrder(1, Order.ASCENDING));
assertEquals(
ImmutableList.of(Pair.of("C", 3L), Pair.of("A", 2L), Pair.of("D", 2L), Pair.of("B", 1L), Pair.of("E", 1L)),
ImmutableList.copyOf(sorted.materialize()));
}
}
| 2,595 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/SpecificAvroGroupByIT.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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.Person;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.avro.Avros;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* Test {@link org.apache.crunch.types.avro.SafeAvroSerialization} with Specific Avro types
*/
public class SpecificAvroGroupByIT implements Serializable {
private static final long serialVersionUID = 1344118240353796561L;
private transient File avroFile;
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Before
public void setUp() throws IOException {
avroFile = File.createTempFile("avrotest", ".avro");
}
@After
public void tearDown() {
avroFile.delete();
}
@Test
public void testGrouByWithSpecificAvroType() throws Exception {
MRPipeline pipeline = new MRPipeline(SpecificAvroGroupByIT.class, tmpDir.getDefaultConfiguration());
testSpecificAvro(pipeline);
}
public void testSpecificAvro(MRPipeline pipeline) throws Exception {
createPersonAvroFile(avroFile);
PCollection<Person> unsorted = pipeline.read(At.avroFile(avroFile.getAbsolutePath(), Avros.records(Person.class)));
PTable<String, Person> sorted = unsorted.parallelDo(new MapFn<Person, Pair<String, Person>>() {
@Override
public Pair<String, Person> map(Person input) {
String key = input.name.toString();
return Pair.of(key, input);
}
}, Avros.tableOf(Avros.strings(), Avros.records(Person.class))).groupByKey().ungroup();
List<Pair<String, Person>> outputPersonList = Lists.newArrayList(sorted.materialize());
assertEquals(1, outputPersonList.size());
assertEquals(String.class, outputPersonList.get(0).first().getClass());
assertEquals(Person.class, outputPersonList.get(0).second().getClass());
pipeline.done();
}
private static void createPersonAvroFile(File avroFile) throws IOException {
Person person = new Person();
person.age = 40;
person.name = "Bob";
List<CharSequence> siblingNames = Lists.newArrayList();
siblingNames.add("Bob1");
siblingNames.add("Bob2");
person.siblingnames = siblingNames;
FileOutputStream outputStream = new FileOutputStream(avroFile);
SpecificDatumWriter<Person> writer = new SpecificDatumWriter<Person>(Person.class);
DataFileWriter<Person> dataFileWriter = new DataFileWriter<Person>(writer);
dataFileWriter.create(Person.SCHEMA$, outputStream);
dataFileWriter.append(person);
dataFileWriter.close();
outputStream.close();
}
}
| 2,596 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/SecondarySortIT.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.Serializable;
import org.apache.crunch.MapFn;
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.io.From;
import org.apache.crunch.test.CrunchTestSupport;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Test;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
public class SecondarySortIT extends CrunchTestSupport implements Serializable {
@Test
public void testSecondarySortAvros() throws Exception {
runSecondarySort(AvroTypeFamily.getInstance());
}
@Test
public void testSecondarySortWritables() throws Exception {
runSecondarySort(WritableTypeFamily.getInstance());
}
public void runSecondarySort(PTypeFamily ptf) throws Exception {
Pipeline p = new MRPipeline(SecondarySortIT.class, tempDir.getDefaultConfiguration());
String inputFile = tempDir.copyResourceFileName("secondary_sort_input.txt");
PTable<String, Pair<Integer, Integer>> in = p.read(From.textFile(inputFile))
.parallelDo(new MapFn<String, Pair<String, Pair<Integer, Integer>>>() {
@Override
public Pair<String, Pair<Integer, Integer>> map(String input) {
String[] pieces = input.split(",");
return Pair.of(pieces[0],
Pair.of(Integer.valueOf(pieces[1].trim()), Integer.valueOf(pieces[2].trim())));
}
}, ptf.tableOf(ptf.strings(), ptf.pairs(ptf.ints(), ptf.ints())));
Iterable<String> lines = SecondarySort.sortAndApply(in, new MapFn<Pair<String, Iterable<Pair<Integer, Integer>>>, String>() {
@Override
public String map(Pair<String, Iterable<Pair<Integer, Integer>>> input) {
Joiner j = Joiner.on(',');
return j.join(input.first(), j.join(input.second()));
}
}, ptf.strings()).materialize();
assertEquals(ImmutableList.of("one,[-5,10],[1,1],[2,-3]", "three,[0,-1]", "two,[1,7],[2,6],[4,5]"),
ImmutableList.copyOf(lines));
p.done();
}
}
| 2,597 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/SetIT.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 static org.junit.Assert.assertFalse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Tuple3;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.At;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Lists;
@RunWith(value = Parameterized.class)
public class SetIT {
private PTypeFamily typeFamily;
private Pipeline pipeline;
private PCollection<String> set1;
private PCollection<String> set2;
public SetIT(PTypeFamily typeFamily) {
this.typeFamily = typeFamily;
}
@Rule
public TemporaryPath tmpDir = TemporaryPaths.create();
@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { WritableTypeFamily.getInstance() }, { AvroTypeFamily.getInstance() } };
return Arrays.asList(data);
}
@Before
public void setUp() throws IOException {
String set1InputPath = tmpDir.copyResourceFileName("set1.txt");
String set2InputPath = tmpDir.copyResourceFileName("set2.txt");
pipeline = new MRPipeline(SetIT.class, tmpDir.getDefaultConfiguration());
set1 = pipeline.read(At.textFile(set1InputPath, typeFamily.strings()));
set2 = pipeline.read(At.textFile(set2InputPath, typeFamily.strings()));
}
@After
public void tearDown() {
pipeline.done();
}
@Test
public void testDifference() throws Exception {
PCollection<String> difference = Set.difference(set1, set2);
assertEquals(Lists.newArrayList("b", "e"), Lists.newArrayList(difference.materialize()));
}
@Test
public void testIntersection() throws Exception {
PCollection<String> intersection = Set.intersection(set1, set2);
assertEquals(Lists.newArrayList("a", "c"), Lists.newArrayList(intersection.materialize()));
}
@Test
public void testComm() throws Exception {
PCollection<Tuple3<String, String, String>> comm = Set.comm(set1, set2);
Iterator<Tuple3<String, String, String>> i = comm.materialize().iterator();
checkEquals(null, null, "a", i.next());
checkEquals("b", null, null, i.next());
checkEquals(null, null, "c", i.next());
checkEquals(null, "d", null, i.next());
checkEquals("e", null, null, i.next());
assertFalse(i.hasNext());
}
private void checkEquals(String s1, String s2, String s3, Tuple3<String, String, String> tuple) {
assertEquals("first string", s1, tuple.first());
assertEquals("second string", s2, tuple.second());
assertEquals("third string", s3, tuple.third());
}
}
| 2,598 |
0 |
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch
|
Create_ds/crunch/crunch-core/src/it/java/org/apache/crunch/lib/SortIT.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.lib.Sort.ColumnOrder.by;
import static org.apache.crunch.lib.Sort.Order.ASCENDING;
import static org.apache.crunch.lib.Sort.Order.DESCENDING;
import static org.apache.crunch.test.StringWrapper.wrap;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
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.Tuple3;
import org.apache.crunch.Tuple4;
import org.apache.crunch.TupleN;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.Sort.ColumnOrder;
import org.apache.crunch.lib.Sort.Order;
import org.apache.crunch.test.StringWrapper;
import org.apache.crunch.test.TemporaryPath;
import org.apache.crunch.test.TemporaryPaths;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.PTypeFamily;
import org.apache.crunch.types.avro.AvroTypeFamily;
import org.apache.crunch.types.avro.Avros;
import org.apache.crunch.types.writable.WritableTypeFamily;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.collect.Lists;
public class SortIT implements Serializable {
@Rule
public transient TemporaryPath tmpDir = TemporaryPaths.create();
@Test
public void testWritableSortAsc() throws Exception {
runSingle(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), Order.ASCENDING,
"A\tand this text as well");
}
@Test
public void testWritableSortDesc() throws Exception {
runSingle(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), Order.DESCENDING,
"B\tthis doc has some text");
}
@Test
public void testWritableSortAscDesc() throws Exception {
runPair(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING), "A",
"this doc has this text");
}
@Test
public void testWritableSortSecondDescFirstAsc() throws Exception {
runPair(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), by(2, DESCENDING), by(1, ASCENDING), "A",
"this doc has this text");
}
@Test
public void testWritableSortTripleAscDescAsc() throws Exception {
runTriple(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING),
by(3, ASCENDING), "A", "this", "doc");
}
@Test
public void testWritableSortQuadAscDescAscDesc() throws Exception {
runQuad(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING),
by(3, ASCENDING), by(4, DESCENDING), "A", "this", "doc", "has");
}
@Test
public void testWritableSortTupleNAscDesc() throws Exception {
runTupleN(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(),
new ColumnOrder[] { by(1, ASCENDING), by(2, DESCENDING) }, new String[] { "A", "this doc has this text" });
}
@Test
public void testWritableSortTable() throws Exception {
runTable(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), WritableTypeFamily.getInstance(), "A");
}
@Test
public void testAvroSortAsc() throws Exception {
runSingle(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), Order.ASCENDING, "A\tand this text as well");
}
@Test
public void testAvroSortDesc() throws Exception {
runSingle(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), Order.DESCENDING, "B\tthis doc has some text");
}
@Test
public void testAvroSortPairAscDesc() throws Exception {
runPair(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING), "A",
"this doc has this text");
}
@Test
public void testAvroSortPairSecondDescFirstAsc() throws Exception {
runPair(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), by(2, DESCENDING), by(1, ASCENDING), "A",
"this doc has this text");
}
@Test
public void testAvroSortTripleAscDescAsc() throws Exception {
runTriple(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING),
by(3, ASCENDING), "A", "this", "doc");
}
@Test
public void testAvroSortQuadAscDescAscDesc() throws Exception {
runQuad(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), by(1, ASCENDING), by(2, DESCENDING),
by(3, ASCENDING), by(4, DESCENDING), "A", "this", "doc", "has");
}
@Test
public void testAvroSortTupleNAscDesc() throws Exception {
runTupleN(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(),
new ColumnOrder[] { by(1, ASCENDING), by(2, DESCENDING) }, new String[] { "A", "this doc has this text" });
}
@Test
public void testAvroReflectSortPair() throws IOException {
Pipeline pipeline = new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration());
pipeline.enableDebug();
String rsrc = tmpDir.copyResourceFileName("set2.txt");
PCollection<Pair<String, StringWrapper>> in = pipeline.readTextFile(rsrc)
.parallelDo(new MapFn<String, Pair<String, StringWrapper>>() {
@Override
public Pair<String, StringWrapper> map(String input) {
return Pair.of(input, wrap(input));
}
}, Avros.pairs(Avros.strings(), Avros.reflects(StringWrapper.class)));
PCollection<Pair<String, StringWrapper>> sorted = Sort.sort(in, Order.ASCENDING);
List<Pair<String, StringWrapper>> expected = Lists.newArrayList();
expected.add(Pair.of("a", wrap("a")));
expected.add(Pair.of("c", wrap("c")));
expected.add(Pair.of("d", wrap("d")));
assertEquals(expected, Lists.newArrayList(sorted.materialize()));
}
@Test
public void testAvroReflectSortTable() throws IOException {
Pipeline pipeline = new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration());
PTable<String, StringWrapper> unsorted = pipeline.readTextFile(tmpDir.copyResourceFileName("set2.txt")).parallelDo(
new MapFn<String, Pair<String, StringWrapper>>() {
@Override
public Pair<String, StringWrapper> map(String input) {
return Pair.of(input, wrap(input));
}
}, Avros.tableOf(Avros.strings(), Avros.reflects(StringWrapper.class)));
PTable<String, StringWrapper> sorted = Sort.sort(unsorted);
List<Pair<String, StringWrapper>> expected = Lists.newArrayList();
expected.add(Pair.of("a", wrap("a")));
expected.add(Pair.of("c", wrap("c")));
expected.add(Pair.of("d", wrap("d")));
assertEquals(expected, Lists.newArrayList(sorted.materialize()));
}
@Test
public void testAvroSortTable() throws Exception {
runTable(new MRPipeline(SortIT.class, tmpDir.getDefaultConfiguration()), AvroTypeFamily.getInstance(), "A");
}
private void runSingle(Pipeline pipeline, PTypeFamily typeFamily, Order order, String firstLine) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
// following turns the input from Writables to required type family
PCollection<String> input2 = input.parallelDo(new DoFn<String, String>() {
@Override
public void process(String input, Emitter<String> emitter) {
emitter.emit(input);
}
}, typeFamily.strings());
PCollection<String> sorted = Sort.sort(input2, order);
Iterable<String> lines = sorted.materialize();
assertEquals(firstLine, lines.iterator().next());
pipeline.done(); // TODO: finally
}
private void runPair(Pipeline pipeline, PTypeFamily typeFamily, ColumnOrder first, ColumnOrder second,
String firstField, String secondField) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
PTable<String, String> kv = input.parallelDo(new DoFn<String, Pair<String, String>>() {
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
String[] split = input.split("[\t]+");
emitter.emit(Pair.of(split[0], split[1]));
}
}, typeFamily.tableOf(typeFamily.strings(), typeFamily.strings()));
PCollection<Pair<String, String>> sorted = Sort.sortPairs(kv, first, second);
List<Pair<String, String>> lines = Lists.newArrayList(sorted.materialize());
Pair<String, String> l = lines.iterator().next();
assertEquals(firstField, l.first());
assertEquals(secondField, l.second());
pipeline.done();
}
private void runTriple(Pipeline pipeline, PTypeFamily typeFamily, ColumnOrder first, ColumnOrder second,
ColumnOrder third, String firstField, String secondField, String thirdField) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
PCollection<Tuple3<String, String, String>> kv = input.parallelDo(
new DoFn<String, Tuple3<String, String, String>>() {
@Override
public void process(String input, Emitter<Tuple3<String, String, String>> emitter) {
String[] split = input.split("[\t ]+");
int len = split.length;
emitter.emit(Tuple3.of(split[0], split[1 % len], split[2 % len]));
}
}, typeFamily.triples(typeFamily.strings(), typeFamily.strings(), typeFamily.strings()));
PCollection<Tuple3<String, String, String>> sorted = Sort.sortTriples(kv, first, second, third);
List<Tuple3<String, String, String>> lines = Lists.newArrayList(sorted.materialize());
Tuple3<String, String, String> l = lines.iterator().next();
assertEquals(firstField, l.first());
assertEquals(secondField, l.second());
assertEquals(thirdField, l.third());
pipeline.done();
}
private void runQuad(Pipeline pipeline, PTypeFamily typeFamily, ColumnOrder first, ColumnOrder second,
ColumnOrder third, ColumnOrder fourth, String firstField, String secondField, String thirdField,
String fourthField) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
PCollection<Tuple4<String, String, String, String>> kv = input.parallelDo(
new DoFn<String, Tuple4<String, String, String, String>>() {
@Override
public void process(String input, Emitter<Tuple4<String, String, String, String>> emitter) {
String[] split = input.split("[\t ]+");
int len = split.length;
emitter.emit(Tuple4.of(split[0], split[1 % len], split[2 % len], split[3 % len]));
}
}, typeFamily.quads(typeFamily.strings(), typeFamily.strings(), typeFamily.strings(), typeFamily.strings()));
PCollection<Tuple4<String, String, String, String>> sorted = Sort.sortQuads(kv, first, second, third, fourth);
Iterable<Tuple4<String, String, String, String>> lines = sorted.materialize();
Tuple4<String, String, String, String> l = lines.iterator().next();
assertEquals(firstField, l.first());
assertEquals(secondField, l.second());
assertEquals(thirdField, l.third());
assertEquals(fourthField, l.fourth());
pipeline.done();
}
private void runTupleN(Pipeline pipeline, PTypeFamily typeFamily, ColumnOrder[] orders, String[] fields)
throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
PType[] types = new PType[orders.length];
Arrays.fill(types, typeFamily.strings());
PCollection<TupleN> kv = input.parallelDo(new DoFn<String, TupleN>() {
@Override
public void process(String input, Emitter<TupleN> emitter) {
String[] split = input.split("[\t]+");
emitter.emit(new TupleN(split));
}
}, typeFamily.tuples(types));
PCollection<TupleN> sorted = Sort.sortTuples(kv, orders);
Iterable<TupleN> lines = sorted.materialize();
TupleN l = lines.iterator().next();
int i = 0;
for (String field : fields) {
assertEquals(field, l.get(i++));
}
pipeline.done();
}
private void runTable(Pipeline pipeline, PTypeFamily typeFamily, String firstKey) throws IOException {
String inputPath = tmpDir.copyResourceFileName("docs.txt");
PCollection<String> input = pipeline.readTextFile(inputPath);
PTable<String, String> table = input.parallelDo(new DoFn<String, Pair<String, String>>() {
@Override
public void process(String input, Emitter<Pair<String, String>> emitter) {
String[] split = input.split("[\t]+");
emitter.emit(Pair.of(split[0], split[1]));
}
}, typeFamily.tableOf(typeFamily.strings(), typeFamily.strings()));
PTable<String, String> sorted = Sort.sort(table);
Iterable<Pair<String, String>> lines = sorted.materialize();
Pair<String, String> l = lines.iterator().next();
assertEquals(firstKey, l.first());
pipeline.done();
}
}
| 2,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.