-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathShortestPathsMapper.java
74 lines (63 loc) · 2.49 KB
/
ShortestPathsMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
public class ShortestPathsMapper
extends Mapper<Object, Text, Text, Text>{
private Logger logger = Logger.getLogger(this.getClass());
private static final String NULL_NODE = "null";
@Override
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
String source = conf.get("source"); // the source node
String line = value.toString();
String[] nodes = line.split("\\s+");
if (nodes.length < 2) {
return;
}
String from = nodes[0];
String partPath = source;
long distance = Long.MAX_VALUE;
String previous = NULL_NODE;
String zero = Long.toString(0);
String inf = Long.toString(Long.MAX_VALUE);
Text outKey = new Text(from);
Text outValue = new Text();
if (nodes.length == 2) {
// First time, input is the adjacency list
if (from.equals(source)) {
distance = 0;
outValue.set(String.join(" ", nodes[1], zero, from));
} else {
outValue.set(String.join(" ", nodes[1], inf, NULL_NODE));
}
} else {
// In all other iterations, input is the reducer's output
distance = Long.parseLong(nodes[2]);
partPath = nodes[3];
outValue.set(String.join(" ", nodes[1], nodes[2], nodes[3]));
}
logger.debug(outKey + " " + outValue);
context.write(outKey, outValue);
for (String neighbour : nodes[1].split(",")) {
String pathFromSource = source;
if (neighbour.equals(NULL_NODE)) {
return;
}
outKey.set(neighbour);
long newDistance = distance;
if (newDistance != Long.MAX_VALUE) {
newDistance += 1;
if (!partPath.equals(from)) {
pathFromSource = from + "," + partPath;
}
outValue.set(String.join(" ", Long.toString(newDistance),
pathFromSource));
logger.debug(outKey + " " + outValue);
context.write(outKey, outValue);
}
}
}
}