id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
161,200
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalancePlan.java
RebalancePlan.plan
private void plan() { // Mapping of stealer node to list of primary partitions being moved final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create(); // Output initial and final cluster if(outputDir != null) RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir); // Determine which partitions must be stolen for(Node stealerNode: finalCluster.getNodes()) { List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster, finalCluster, stealerNode.getId()); if(stolenPrimaryPartitions.size() > 0) { numPrimaryPartitionMoves += stolenPrimaryPartitions.size(); stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(), stolenPrimaryPartitions); } } // Determine plan batch-by-batch int batches = 0; Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster); List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs; List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs; Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster, this.finalCluster); while(!stealerToStolenPrimaryPartitions.isEmpty()) { int partitions = 0; List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList(); for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) { partitionsMoved.add(stealerToPartition); batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster, stealerToPartition.getKey(), Lists.newArrayList(stealerToPartition.getValue())); partitions++; if(partitions == batchSize) break; } // Remove the partitions moved for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) { Entry<Integer, Integer> entry = partitionMoved.next(); stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue()); } if(outputDir != null) RebalanceUtils.dumpClusters(batchCurrentCluster, batchFinalCluster, outputDir, "batch-" + Integer.toString(batches) + "."); // Generate a plan to compute the tasks final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs); batchPlans.add(RebalanceBatchPlan); numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves(); numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves(); nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap()); zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap()); batches++; batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster); // batchCurrentStoreDefs can only be different from // batchFinalStoreDefs for the initial batch. batchCurrentStoreDefs = batchFinalStoreDefs; } logger.info(this); }
java
private void plan() { // Mapping of stealer node to list of primary partitions being moved final TreeMultimap<Integer, Integer> stealerToStolenPrimaryPartitions = TreeMultimap.create(); // Output initial and final cluster if(outputDir != null) RebalanceUtils.dumpClusters(currentCluster, finalCluster, outputDir); // Determine which partitions must be stolen for(Node stealerNode: finalCluster.getNodes()) { List<Integer> stolenPrimaryPartitions = RebalanceUtils.getStolenPrimaryPartitions(currentCluster, finalCluster, stealerNode.getId()); if(stolenPrimaryPartitions.size() > 0) { numPrimaryPartitionMoves += stolenPrimaryPartitions.size(); stealerToStolenPrimaryPartitions.putAll(stealerNode.getId(), stolenPrimaryPartitions); } } // Determine plan batch-by-batch int batches = 0; Cluster batchCurrentCluster = Cluster.cloneCluster(currentCluster); List<StoreDefinition> batchCurrentStoreDefs = this.currentStoreDefs; List<StoreDefinition> batchFinalStoreDefs = this.finalStoreDefs; Cluster batchFinalCluster = RebalanceUtils.getInterimCluster(this.currentCluster, this.finalCluster); while(!stealerToStolenPrimaryPartitions.isEmpty()) { int partitions = 0; List<Entry<Integer, Integer>> partitionsMoved = Lists.newArrayList(); for(Entry<Integer, Integer> stealerToPartition: stealerToStolenPrimaryPartitions.entries()) { partitionsMoved.add(stealerToPartition); batchFinalCluster = UpdateClusterUtils.createUpdatedCluster(batchFinalCluster, stealerToPartition.getKey(), Lists.newArrayList(stealerToPartition.getValue())); partitions++; if(partitions == batchSize) break; } // Remove the partitions moved for(Iterator<Entry<Integer, Integer>> partitionMoved = partitionsMoved.iterator(); partitionMoved.hasNext();) { Entry<Integer, Integer> entry = partitionMoved.next(); stealerToStolenPrimaryPartitions.remove(entry.getKey(), entry.getValue()); } if(outputDir != null) RebalanceUtils.dumpClusters(batchCurrentCluster, batchFinalCluster, outputDir, "batch-" + Integer.toString(batches) + "."); // Generate a plan to compute the tasks final RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(batchCurrentCluster, batchCurrentStoreDefs, batchFinalCluster, batchFinalStoreDefs); batchPlans.add(RebalanceBatchPlan); numXZonePartitionStoreMoves += RebalanceBatchPlan.getCrossZonePartitionStoreMoves(); numPartitionStoreMoves += RebalanceBatchPlan.getPartitionStoreMoves(); nodeMoveMap.add(RebalanceBatchPlan.getNodeMoveMap()); zoneMoveMap.add(RebalanceBatchPlan.getZoneMoveMap()); batches++; batchCurrentCluster = Cluster.cloneCluster(batchFinalCluster); // batchCurrentStoreDefs can only be different from // batchFinalStoreDefs for the initial batch. batchCurrentStoreDefs = batchFinalStoreDefs; } logger.info(this); }
[ "private", "void", "plan", "(", ")", "{", "// Mapping of stealer node to list of primary partitions being moved", "final", "TreeMultimap", "<", "Integer", ",", "Integer", ">", "stealerToStolenPrimaryPartitions", "=", "TreeMultimap", ".", "create", "(", ")", ";", "// Output initial and final cluster", "if", "(", "outputDir", "!=", "null", ")", "RebalanceUtils", ".", "dumpClusters", "(", "currentCluster", ",", "finalCluster", ",", "outputDir", ")", ";", "// Determine which partitions must be stolen", "for", "(", "Node", "stealerNode", ":", "finalCluster", ".", "getNodes", "(", ")", ")", "{", "List", "<", "Integer", ">", "stolenPrimaryPartitions", "=", "RebalanceUtils", ".", "getStolenPrimaryPartitions", "(", "currentCluster", ",", "finalCluster", ",", "stealerNode", ".", "getId", "(", ")", ")", ";", "if", "(", "stolenPrimaryPartitions", ".", "size", "(", ")", ">", "0", ")", "{", "numPrimaryPartitionMoves", "+=", "stolenPrimaryPartitions", ".", "size", "(", ")", ";", "stealerToStolenPrimaryPartitions", ".", "putAll", "(", "stealerNode", ".", "getId", "(", ")", ",", "stolenPrimaryPartitions", ")", ";", "}", "}", "// Determine plan batch-by-batch", "int", "batches", "=", "0", ";", "Cluster", "batchCurrentCluster", "=", "Cluster", ".", "cloneCluster", "(", "currentCluster", ")", ";", "List", "<", "StoreDefinition", ">", "batchCurrentStoreDefs", "=", "this", ".", "currentStoreDefs", ";", "List", "<", "StoreDefinition", ">", "batchFinalStoreDefs", "=", "this", ".", "finalStoreDefs", ";", "Cluster", "batchFinalCluster", "=", "RebalanceUtils", ".", "getInterimCluster", "(", "this", ".", "currentCluster", ",", "this", ".", "finalCluster", ")", ";", "while", "(", "!", "stealerToStolenPrimaryPartitions", ".", "isEmpty", "(", ")", ")", "{", "int", "partitions", "=", "0", ";", "List", "<", "Entry", "<", "Integer", ",", "Integer", ">", ">", "partitionsMoved", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Entry", "<", "Integer", ",", "Integer", ">", "stealerToPartition", ":", "stealerToStolenPrimaryPartitions", ".", "entries", "(", ")", ")", "{", "partitionsMoved", ".", "add", "(", "stealerToPartition", ")", ";", "batchFinalCluster", "=", "UpdateClusterUtils", ".", "createUpdatedCluster", "(", "batchFinalCluster", ",", "stealerToPartition", ".", "getKey", "(", ")", ",", "Lists", ".", "newArrayList", "(", "stealerToPartition", ".", "getValue", "(", ")", ")", ")", ";", "partitions", "++", ";", "if", "(", "partitions", "==", "batchSize", ")", "break", ";", "}", "// Remove the partitions moved", "for", "(", "Iterator", "<", "Entry", "<", "Integer", ",", "Integer", ">", ">", "partitionMoved", "=", "partitionsMoved", ".", "iterator", "(", ")", ";", "partitionMoved", ".", "hasNext", "(", ")", ";", ")", "{", "Entry", "<", "Integer", ",", "Integer", ">", "entry", "=", "partitionMoved", ".", "next", "(", ")", ";", "stealerToStolenPrimaryPartitions", ".", "remove", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "if", "(", "outputDir", "!=", "null", ")", "RebalanceUtils", ".", "dumpClusters", "(", "batchCurrentCluster", ",", "batchFinalCluster", ",", "outputDir", ",", "\"batch-\"", "+", "Integer", ".", "toString", "(", "batches", ")", "+", "\".\"", ")", ";", "// Generate a plan to compute the tasks", "final", "RebalanceBatchPlan", "RebalanceBatchPlan", "=", "new", "RebalanceBatchPlan", "(", "batchCurrentCluster", ",", "batchCurrentStoreDefs", ",", "batchFinalCluster", ",", "batchFinalStoreDefs", ")", ";", "batchPlans", ".", "add", "(", "RebalanceBatchPlan", ")", ";", "numXZonePartitionStoreMoves", "+=", "RebalanceBatchPlan", ".", "getCrossZonePartitionStoreMoves", "(", ")", ";", "numPartitionStoreMoves", "+=", "RebalanceBatchPlan", ".", "getPartitionStoreMoves", "(", ")", ";", "nodeMoveMap", ".", "add", "(", "RebalanceBatchPlan", ".", "getNodeMoveMap", "(", ")", ")", ";", "zoneMoveMap", ".", "add", "(", "RebalanceBatchPlan", ".", "getZoneMoveMap", "(", ")", ")", ";", "batches", "++", ";", "batchCurrentCluster", "=", "Cluster", ".", "cloneCluster", "(", "batchFinalCluster", ")", ";", "// batchCurrentStoreDefs can only be different from", "// batchFinalStoreDefs for the initial batch.", "batchCurrentStoreDefs", "=", "batchFinalStoreDefs", ";", "}", "logger", ".", "info", "(", "this", ")", ";", "}" ]
Create a plan. The plan consists of batches. Each batch involves the movement of no more than batchSize primary partitions. The movement of a single primary partition may require migration of other n-ary replicas, and potentially deletions. Migrating a primary or n-ary partition requires migrating one partition-store for every store hosted at that partition.
[ "Create", "a", "plan", ".", "The", "plan", "consists", "of", "batches", ".", "Each", "batch", "involves", "the", "movement", "of", "no", "more", "than", "batchSize", "primary", "partitions", ".", "The", "movement", "of", "a", "single", "primary", "partition", "may", "require", "migration", "of", "other", "n", "-", "ary", "replicas", "and", "potentially", "deletions", ".", "Migrating", "a", "primary", "or", "n", "-", "ary", "partition", "requires", "migrating", "one", "partition", "-", "store", "for", "every", "store", "hosted", "at", "that", "partition", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalancePlan.java#L152-L226
161,201
voldemort/voldemort
src/java/voldemort/client/rebalance/RebalancePlan.java
RebalancePlan.storageOverhead
private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) { double maxOverhead = Double.MIN_VALUE; PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs); StringBuilder sb = new StringBuilder(); sb.append("Per-node store-overhead:").append(Utils.NEWLINE); DecimalFormat doubleDf = new DecimalFormat("####.##"); for(int nodeId: finalCluster.getNodeIds()) { Node node = finalCluster.getNodeById(nodeId); String nodeTag = "Node " + String.format("%4d", nodeId) + " (" + node.getHost() + ")"; int initialLoad = 0; if(currentCluster.getNodeIds().contains(nodeId)) { initialLoad = pb.getNaryPartitionCount(nodeId); } int toLoad = 0; if(finalNodeToOverhead.containsKey(nodeId)) { toLoad = finalNodeToOverhead.get(nodeId); } double overhead = (initialLoad + toLoad) / (double) initialLoad; if(initialLoad > 0 && maxOverhead < overhead) { maxOverhead = overhead; } String loadTag = String.format("%6d", initialLoad) + " + " + String.format("%6d", toLoad) + " -> " + String.format("%6d", initialLoad + toLoad) + " (" + doubleDf.format(overhead) + " X)"; sb.append(nodeTag + " : " + loadTag).append(Utils.NEWLINE); } sb.append(Utils.NEWLINE) .append("**** Max per-node storage overhead: " + doubleDf.format(maxOverhead) + " X.") .append(Utils.NEWLINE); return (sb.toString()); }
java
private String storageOverhead(Map<Integer, Integer> finalNodeToOverhead) { double maxOverhead = Double.MIN_VALUE; PartitionBalance pb = new PartitionBalance(currentCluster, currentStoreDefs); StringBuilder sb = new StringBuilder(); sb.append("Per-node store-overhead:").append(Utils.NEWLINE); DecimalFormat doubleDf = new DecimalFormat("####.##"); for(int nodeId: finalCluster.getNodeIds()) { Node node = finalCluster.getNodeById(nodeId); String nodeTag = "Node " + String.format("%4d", nodeId) + " (" + node.getHost() + ")"; int initialLoad = 0; if(currentCluster.getNodeIds().contains(nodeId)) { initialLoad = pb.getNaryPartitionCount(nodeId); } int toLoad = 0; if(finalNodeToOverhead.containsKey(nodeId)) { toLoad = finalNodeToOverhead.get(nodeId); } double overhead = (initialLoad + toLoad) / (double) initialLoad; if(initialLoad > 0 && maxOverhead < overhead) { maxOverhead = overhead; } String loadTag = String.format("%6d", initialLoad) + " + " + String.format("%6d", toLoad) + " -> " + String.format("%6d", initialLoad + toLoad) + " (" + doubleDf.format(overhead) + " X)"; sb.append(nodeTag + " : " + loadTag).append(Utils.NEWLINE); } sb.append(Utils.NEWLINE) .append("**** Max per-node storage overhead: " + doubleDf.format(maxOverhead) + " X.") .append(Utils.NEWLINE); return (sb.toString()); }
[ "private", "String", "storageOverhead", "(", "Map", "<", "Integer", ",", "Integer", ">", "finalNodeToOverhead", ")", "{", "double", "maxOverhead", "=", "Double", ".", "MIN_VALUE", ";", "PartitionBalance", "pb", "=", "new", "PartitionBalance", "(", "currentCluster", ",", "currentStoreDefs", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"Per-node store-overhead:\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "DecimalFormat", "doubleDf", "=", "new", "DecimalFormat", "(", "\"####.##\"", ")", ";", "for", "(", "int", "nodeId", ":", "finalCluster", ".", "getNodeIds", "(", ")", ")", "{", "Node", "node", "=", "finalCluster", ".", "getNodeById", "(", "nodeId", ")", ";", "String", "nodeTag", "=", "\"Node \"", "+", "String", ".", "format", "(", "\"%4d\"", ",", "nodeId", ")", "+", "\" (\"", "+", "node", ".", "getHost", "(", ")", "+", "\")\"", ";", "int", "initialLoad", "=", "0", ";", "if", "(", "currentCluster", ".", "getNodeIds", "(", ")", ".", "contains", "(", "nodeId", ")", ")", "{", "initialLoad", "=", "pb", ".", "getNaryPartitionCount", "(", "nodeId", ")", ";", "}", "int", "toLoad", "=", "0", ";", "if", "(", "finalNodeToOverhead", ".", "containsKey", "(", "nodeId", ")", ")", "{", "toLoad", "=", "finalNodeToOverhead", ".", "get", "(", "nodeId", ")", ";", "}", "double", "overhead", "=", "(", "initialLoad", "+", "toLoad", ")", "/", "(", "double", ")", "initialLoad", ";", "if", "(", "initialLoad", ">", "0", "&&", "maxOverhead", "<", "overhead", ")", "{", "maxOverhead", "=", "overhead", ";", "}", "String", "loadTag", "=", "String", ".", "format", "(", "\"%6d\"", ",", "initialLoad", ")", "+", "\" + \"", "+", "String", ".", "format", "(", "\"%6d\"", ",", "toLoad", ")", "+", "\" -> \"", "+", "String", ".", "format", "(", "\"%6d\"", ",", "initialLoad", "+", "toLoad", ")", "+", "\" (\"", "+", "doubleDf", ".", "format", "(", "overhead", ")", "+", "\" X)\"", ";", "sb", ".", "append", "(", "nodeTag", "+", "\" : \"", "+", "loadTag", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "}", "sb", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ".", "append", "(", "\"**** Max per-node storage overhead: \"", "+", "doubleDf", ".", "format", "(", "maxOverhead", ")", "+", "\" X.\"", ")", ".", "append", "(", "Utils", ".", "NEWLINE", ")", ";", "return", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Determines storage overhead and returns pretty printed summary. @param finalNodeToOverhead Map of node IDs from final cluster to number of partition-stores to be moved to the node. @return pretty printed string summary of storage overhead.
[ "Determines", "storage", "overhead", "and", "returns", "pretty", "printed", "summary", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/rebalance/RebalancePlan.java#L235-L267
161,202
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.askConfirm
public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException { if(confirm) { System.out.println("Confirmed " + opDesc + " in command-line."); return true; } else { System.out.println("Are you sure you want to " + opDesc + "? (yes/no)"); BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); String text = buffer.readLine().toLowerCase(Locale.ENGLISH); boolean go = text.equals("yes") || text.equals("y"); if (!go) { System.out.println("Did not confirm; " + opDesc + " aborted."); } return go; } }
java
public static Boolean askConfirm(Boolean confirm, String opDesc) throws IOException { if(confirm) { System.out.println("Confirmed " + opDesc + " in command-line."); return true; } else { System.out.println("Are you sure you want to " + opDesc + "? (yes/no)"); BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); String text = buffer.readLine().toLowerCase(Locale.ENGLISH); boolean go = text.equals("yes") || text.equals("y"); if (!go) { System.out.println("Did not confirm; " + opDesc + " aborted."); } return go; } }
[ "public", "static", "Boolean", "askConfirm", "(", "Boolean", "confirm", ",", "String", "opDesc", ")", "throws", "IOException", "{", "if", "(", "confirm", ")", "{", "System", ".", "out", ".", "println", "(", "\"Confirmed \"", "+", "opDesc", "+", "\" in command-line.\"", ")", ";", "return", "true", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"Are you sure you want to \"", "+", "opDesc", "+", "\"? (yes/no)\"", ")", ";", "BufferedReader", "buffer", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "System", ".", "in", ")", ")", ";", "String", "text", "=", "buffer", ".", "readLine", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ";", "boolean", "go", "=", "text", ".", "equals", "(", "\"yes\"", ")", "||", "text", ".", "equals", "(", "\"y\"", ")", ";", "if", "(", "!", "go", ")", "{", "System", ".", "out", ".", "println", "(", "\"Did not confirm; \"", "+", "opDesc", "+", "\" aborted.\"", ")", ";", "}", "return", "go", ";", "}", "}" ]
Utility function that pauses and asks for confirmation on dangerous operations. @param confirm User has already confirmed in command-line input @param opDesc Description of the dangerous operation @throws IOException @return True if user confirms the operation in either command-line input or here.
[ "Utility", "function", "that", "pauses", "and", "asks", "for", "confirmation", "on", "dangerous", "operations", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L99-L113
161,203
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getValueList
public static List<String> getValueList(List<String> valuePairs, String delim) { List<String> valueList = Lists.newArrayList(); for(String valuePair: valuePairs) { String[] value = valuePair.split(delim, 2); if(value.length != 2) throw new VoldemortException("Invalid argument pair: " + valuePair); valueList.add(value[0]); valueList.add(value[1]); } return valueList; }
java
public static List<String> getValueList(List<String> valuePairs, String delim) { List<String> valueList = Lists.newArrayList(); for(String valuePair: valuePairs) { String[] value = valuePair.split(delim, 2); if(value.length != 2) throw new VoldemortException("Invalid argument pair: " + valuePair); valueList.add(value[0]); valueList.add(value[1]); } return valueList; }
[ "public", "static", "List", "<", "String", ">", "getValueList", "(", "List", "<", "String", ">", "valuePairs", ",", "String", "delim", ")", "{", "List", "<", "String", ">", "valueList", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "String", "valuePair", ":", "valuePairs", ")", "{", "String", "[", "]", "value", "=", "valuePair", ".", "split", "(", "delim", ",", "2", ")", ";", "if", "(", "value", ".", "length", "!=", "2", ")", "throw", "new", "VoldemortException", "(", "\"Invalid argument pair: \"", "+", "valuePair", ")", ";", "valueList", ".", "add", "(", "value", "[", "0", "]", ")", ";", "valueList", ".", "add", "(", "value", "[", "1", "]", ")", ";", "}", "return", "valueList", ";", "}" ]
Utility function that gives list of values from list of value-pair strings. @param valuePairs List of value-pair strings @param delim Delimiter that separates the value pair @returns The list of values; empty if no value-pair is present, The even elements are the first ones of the value pair, and the odd elements are the second ones. For example, if the list of value-pair is ["cluster.xml=file1", "stores.xml=file2"], and the pair delimiter is '=', we will then have the list of values in return: ["cluster.xml", "file1", "stores.xml", "file2"].
[ "Utility", "function", "that", "gives", "list", "of", "values", "from", "list", "of", "value", "-", "pair", "strings", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L128-L138
161,204
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.convertListToMap
public static <V> Map<V, V> convertListToMap(List<V> list) { Map<V, V> map = new HashMap<V, V>(); if(list.size() % 2 != 0) throw new VoldemortException("Failed to convert list to map."); for(int i = 0; i < list.size(); i += 2) { map.put(list.get(i), list.get(i + 1)); } return map; }
java
public static <V> Map<V, V> convertListToMap(List<V> list) { Map<V, V> map = new HashMap<V, V>(); if(list.size() % 2 != 0) throw new VoldemortException("Failed to convert list to map."); for(int i = 0; i < list.size(); i += 2) { map.put(list.get(i), list.get(i + 1)); } return map; }
[ "public", "static", "<", "V", ">", "Map", "<", "V", ",", "V", ">", "convertListToMap", "(", "List", "<", "V", ">", "list", ")", "{", "Map", "<", "V", ",", "V", ">", "map", "=", "new", "HashMap", "<", "V", ",", "V", ">", "(", ")", ";", "if", "(", "list", ".", "size", "(", ")", "%", "2", "!=", "0", ")", "throw", "new", "VoldemortException", "(", "\"Failed to convert list to map.\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "size", "(", ")", ";", "i", "+=", "2", ")", "{", "map", ".", "put", "(", "list", ".", "get", "(", "i", ")", ",", "list", ".", "get", "(", "i", "+", "1", ")", ")", ";", "}", "return", "map", ";", "}" ]
Utility function that converts a list to a map. @param list The list in which even elements are keys and odd elements are values. @rturn The map container that maps even elements to odd elements, e.g. 0->1, 2->3, etc.
[ "Utility", "function", "that", "converts", "a", "list", "to", "a", "map", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L148-L156
161,205
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getAdminClient
public static AdminClient getAdminClient(String url) { ClientConfig config = new ClientConfig().setBootstrapUrls(url) .setConnectionTimeout(5, TimeUnit.SECONDS); AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5); return new AdminClient(adminConfig, config); }
java
public static AdminClient getAdminClient(String url) { ClientConfig config = new ClientConfig().setBootstrapUrls(url) .setConnectionTimeout(5, TimeUnit.SECONDS); AdminClientConfig adminConfig = new AdminClientConfig().setAdminSocketTimeoutSec(5); return new AdminClient(adminConfig, config); }
[ "public", "static", "AdminClient", "getAdminClient", "(", "String", "url", ")", "{", "ClientConfig", "config", "=", "new", "ClientConfig", "(", ")", ".", "setBootstrapUrls", "(", "url", ")", ".", "setConnectionTimeout", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "AdminClientConfig", "adminConfig", "=", "new", "AdminClientConfig", "(", ")", ".", "setAdminSocketTimeoutSec", "(", "5", ")", ";", "return", "new", "AdminClient", "(", "adminConfig", ",", "config", ")", ";", "}" ]
Utility function that constructs AdminClient. @param url URL pointing to the bootstrap node @return Newly constructed AdminClient
[ "Utility", "function", "that", "constructs", "AdminClient", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L164-L170
161,206
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getAllNodeIds
public static List<Integer> getAllNodeIds(AdminClient adminClient) { List<Integer> nodeIds = Lists.newArrayList(); for(Integer nodeId: adminClient.getAdminClientCluster().getNodeIds()) { nodeIds.add(nodeId); } return nodeIds; }
java
public static List<Integer> getAllNodeIds(AdminClient adminClient) { List<Integer> nodeIds = Lists.newArrayList(); for(Integer nodeId: adminClient.getAdminClientCluster().getNodeIds()) { nodeIds.add(nodeId); } return nodeIds; }
[ "public", "static", "List", "<", "Integer", ">", "getAllNodeIds", "(", "AdminClient", "adminClient", ")", "{", "List", "<", "Integer", ">", "nodeIds", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Integer", "nodeId", ":", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodeIds", "(", ")", ")", "{", "nodeIds", ".", "add", "(", "nodeId", ")", ";", "}", "return", "nodeIds", ";", "}" ]
Utility function that fetches node ids. @param adminClient An instance of AdminClient points to given cluster @return Node ids in cluster
[ "Utility", "function", "that", "fetches", "node", "ids", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L178-L184
161,207
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getAllUserStoreNamesOnNode
public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) { List<String> storeNames = Lists.newArrayList(); List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); for(StoreDefinition storeDefinition: storeDefinitionList) { storeNames.add(storeDefinition.getName()); } return storeNames; }
java
public static List<String> getAllUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId) { List<String> storeNames = Lists.newArrayList(); List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); for(StoreDefinition storeDefinition: storeDefinitionList) { storeNames.add(storeDefinition.getName()); } return storeNames; }
[ "public", "static", "List", "<", "String", ">", "getAllUserStoreNamesOnNode", "(", "AdminClient", "adminClient", ",", "Integer", "nodeId", ")", "{", "List", "<", "String", ">", "storeNames", "=", "Lists", ".", "newArrayList", "(", ")", ";", "List", "<", "StoreDefinition", ">", "storeDefinitionList", "=", "adminClient", ".", "metadataMgmtOps", ".", "getRemoteStoreDefList", "(", "nodeId", ")", ".", "getValue", "(", ")", ";", "for", "(", "StoreDefinition", "storeDefinition", ":", "storeDefinitionList", ")", "{", "storeNames", ".", "add", "(", "storeDefinition", ".", "getName", "(", ")", ")", ";", "}", "return", "storeNames", ";", "}" ]
Utility function that fetches all stores on a node. @param adminClient An instance of AdminClient points to given cluster @param nodeId Node id to fetch stores from @return List of all store names
[ "Utility", "function", "that", "fetches", "all", "stores", "on", "a", "node", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L193-L202
161,208
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.validateUserStoreNamesOnNode
public static void validateUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId, List<String> storeNames) { List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>(); for(StoreDefinition storeDef: storeDefList) { existingStoreNames.put(storeDef.getName(), true); } for(String storeName: storeNames) { if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) { Utils.croak("Store " + storeName + " does not exist!"); } } }
java
public static void validateUserStoreNamesOnNode(AdminClient adminClient, Integer nodeId, List<String> storeNames) { List<StoreDefinition> storeDefList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); Map<String, Boolean> existingStoreNames = new HashMap<String, Boolean>(); for(StoreDefinition storeDef: storeDefList) { existingStoreNames.put(storeDef.getName(), true); } for(String storeName: storeNames) { if(!Boolean.TRUE.equals(existingStoreNames.get(storeName))) { Utils.croak("Store " + storeName + " does not exist!"); } } }
[ "public", "static", "void", "validateUserStoreNamesOnNode", "(", "AdminClient", "adminClient", ",", "Integer", "nodeId", ",", "List", "<", "String", ">", "storeNames", ")", "{", "List", "<", "StoreDefinition", ">", "storeDefList", "=", "adminClient", ".", "metadataMgmtOps", ".", "getRemoteStoreDefList", "(", "nodeId", ")", ".", "getValue", "(", ")", ";", "Map", "<", "String", ",", "Boolean", ">", "existingStoreNames", "=", "new", "HashMap", "<", "String", ",", "Boolean", ">", "(", ")", ";", "for", "(", "StoreDefinition", "storeDef", ":", "storeDefList", ")", "{", "existingStoreNames", ".", "put", "(", "storeDef", ".", "getName", "(", ")", ",", "true", ")", ";", "}", "for", "(", "String", "storeName", ":", "storeNames", ")", "{", "if", "(", "!", "Boolean", ".", "TRUE", ".", "equals", "(", "existingStoreNames", ".", "get", "(", "storeName", ")", ")", ")", "{", "Utils", ".", "croak", "(", "\"Store \"", "+", "storeName", "+", "\" does not exist!\"", ")", ";", "}", "}", "}" ]
Utility function that checks if store names are valid on a node. @param adminClient An instance of AdminClient points to given cluster @param nodeId Node id to fetch stores from @param storeNames Store names to check
[ "Utility", "function", "that", "checks", "if", "store", "names", "are", "valid", "on", "a", "node", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L228-L242
161,209
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getAllPartitions
public static List<Integer> getAllPartitions(AdminClient adminClient) { List<Integer> partIds = Lists.newArrayList(); partIds = Lists.newArrayList(); for(Node node: adminClient.getAdminClientCluster().getNodes()) { partIds.addAll(node.getPartitionIds()); } return partIds; }
java
public static List<Integer> getAllPartitions(AdminClient adminClient) { List<Integer> partIds = Lists.newArrayList(); partIds = Lists.newArrayList(); for(Node node: adminClient.getAdminClientCluster().getNodes()) { partIds.addAll(node.getPartitionIds()); } return partIds; }
[ "public", "static", "List", "<", "Integer", ">", "getAllPartitions", "(", "AdminClient", "adminClient", ")", "{", "List", "<", "Integer", ">", "partIds", "=", "Lists", ".", "newArrayList", "(", ")", ";", "partIds", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Node", "node", ":", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodes", "(", ")", ")", "{", "partIds", ".", "addAll", "(", "node", ".", "getPartitionIds", "(", ")", ")", ";", "}", "return", "partIds", ";", "}" ]
Utility function that fetches partitions. @param adminClient An instance of AdminClient points to given cluster @return all partitions on cluster
[ "Utility", "function", "that", "fetches", "partitions", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L250-L257
161,210
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getQuotaTypes
public static List<QuotaType> getQuotaTypes(List<String> strQuotaTypes) { if(strQuotaTypes.size() < 1) { throw new VoldemortException("Quota type not specified."); } List<QuotaType> quotaTypes; if(strQuotaTypes.size() == 1 && strQuotaTypes.get(0).equals(AdminToolUtils.QUOTATYPE_ALL)) { quotaTypes = Arrays.asList(QuotaType.values()); } else { quotaTypes = new ArrayList<QuotaType>(); for(String strQuotaType: strQuotaTypes) { QuotaType type = QuotaType.valueOf(strQuotaType); quotaTypes.add(type); } } return quotaTypes; }
java
public static List<QuotaType> getQuotaTypes(List<String> strQuotaTypes) { if(strQuotaTypes.size() < 1) { throw new VoldemortException("Quota type not specified."); } List<QuotaType> quotaTypes; if(strQuotaTypes.size() == 1 && strQuotaTypes.get(0).equals(AdminToolUtils.QUOTATYPE_ALL)) { quotaTypes = Arrays.asList(QuotaType.values()); } else { quotaTypes = new ArrayList<QuotaType>(); for(String strQuotaType: strQuotaTypes) { QuotaType type = QuotaType.valueOf(strQuotaType); quotaTypes.add(type); } } return quotaTypes; }
[ "public", "static", "List", "<", "QuotaType", ">", "getQuotaTypes", "(", "List", "<", "String", ">", "strQuotaTypes", ")", "{", "if", "(", "strQuotaTypes", ".", "size", "(", ")", "<", "1", ")", "{", "throw", "new", "VoldemortException", "(", "\"Quota type not specified.\"", ")", ";", "}", "List", "<", "QuotaType", ">", "quotaTypes", ";", "if", "(", "strQuotaTypes", ".", "size", "(", ")", "==", "1", "&&", "strQuotaTypes", ".", "get", "(", "0", ")", ".", "equals", "(", "AdminToolUtils", ".", "QUOTATYPE_ALL", ")", ")", "{", "quotaTypes", "=", "Arrays", ".", "asList", "(", "QuotaType", ".", "values", "(", ")", ")", ";", "}", "else", "{", "quotaTypes", "=", "new", "ArrayList", "<", "QuotaType", ">", "(", ")", ";", "for", "(", "String", "strQuotaType", ":", "strQuotaTypes", ")", "{", "QuotaType", "type", "=", "QuotaType", ".", "valueOf", "(", "strQuotaType", ")", ";", "quotaTypes", ".", "add", "(", "type", ")", ";", "}", "}", "return", "quotaTypes", ";", "}" ]
Utility function that fetches quota types.
[ "Utility", "function", "that", "fetches", "quota", "types", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L262-L277
161,211
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.createDir
public static File createDir(String dir) { // create outdir File directory = null; if(dir != null) { directory = new File(dir); if(!(directory.exists() || directory.mkdir())) { Utils.croak("Can't find or create directory " + dir); } } return directory; }
java
public static File createDir(String dir) { // create outdir File directory = null; if(dir != null) { directory = new File(dir); if(!(directory.exists() || directory.mkdir())) { Utils.croak("Can't find or create directory " + dir); } } return directory; }
[ "public", "static", "File", "createDir", "(", "String", "dir", ")", "{", "// create outdir", "File", "directory", "=", "null", ";", "if", "(", "dir", "!=", "null", ")", "{", "directory", "=", "new", "File", "(", "dir", ")", ";", "if", "(", "!", "(", "directory", ".", "exists", "(", ")", "||", "directory", ".", "mkdir", "(", ")", ")", ")", "{", "Utils", ".", "croak", "(", "\"Can't find or create directory \"", "+", "dir", ")", ";", "}", "}", "return", "directory", ";", "}" ]
Utility function that creates directory. @param dir Directory path @return File object of directory.
[ "Utility", "function", "that", "creates", "directory", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L285-L295
161,212
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getSystemStoreDefMap
public static Map<String, StoreDefinition> getSystemStoreDefMap() { Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap(); List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs(); for(StoreDefinition def: storesDefs) { sysStoreDefMap.put(def.getName(), def); } return sysStoreDefMap; }
java
public static Map<String, StoreDefinition> getSystemStoreDefMap() { Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap(); List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs(); for(StoreDefinition def: storesDefs) { sysStoreDefMap.put(def.getName(), def); } return sysStoreDefMap; }
[ "public", "static", "Map", "<", "String", ",", "StoreDefinition", ">", "getSystemStoreDefMap", "(", ")", "{", "Map", "<", "String", ",", "StoreDefinition", ">", "sysStoreDefMap", "=", "Maps", ".", "newHashMap", "(", ")", ";", "List", "<", "StoreDefinition", ">", "storesDefs", "=", "SystemStoreConstants", ".", "getAllSystemStoreDefs", "(", ")", ";", "for", "(", "StoreDefinition", "def", ":", "storesDefs", ")", "{", "sysStoreDefMap", ".", "put", "(", "def", ".", "getName", "(", ")", ",", "def", ")", ";", "}", "return", "sysStoreDefMap", ";", "}" ]
Utility function that fetches system store definitions @return The map container that maps store names to store definitions
[ "Utility", "function", "that", "fetches", "system", "store", "definitions" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L302-L309
161,213
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.getUserStoreDefMapOnNode
public static Map<String, StoreDefinition> getUserStoreDefMapOnNode(AdminClient adminClient, Integer nodeId) { List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); Map<String, StoreDefinition> storeDefinitionMap = Maps.newHashMap(); for(StoreDefinition storeDefinition: storeDefinitionList) { storeDefinitionMap.put(storeDefinition.getName(), storeDefinition); } return storeDefinitionMap; }
java
public static Map<String, StoreDefinition> getUserStoreDefMapOnNode(AdminClient adminClient, Integer nodeId) { List<StoreDefinition> storeDefinitionList = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId) .getValue(); Map<String, StoreDefinition> storeDefinitionMap = Maps.newHashMap(); for(StoreDefinition storeDefinition: storeDefinitionList) { storeDefinitionMap.put(storeDefinition.getName(), storeDefinition); } return storeDefinitionMap; }
[ "public", "static", "Map", "<", "String", ",", "StoreDefinition", ">", "getUserStoreDefMapOnNode", "(", "AdminClient", "adminClient", ",", "Integer", "nodeId", ")", "{", "List", "<", "StoreDefinition", ">", "storeDefinitionList", "=", "adminClient", ".", "metadataMgmtOps", ".", "getRemoteStoreDefList", "(", "nodeId", ")", ".", "getValue", "(", ")", ";", "Map", "<", "String", ",", "StoreDefinition", ">", "storeDefinitionMap", "=", "Maps", ".", "newHashMap", "(", ")", ";", "for", "(", "StoreDefinition", "storeDefinition", ":", "storeDefinitionList", ")", "{", "storeDefinitionMap", ".", "put", "(", "storeDefinition", ".", "getName", "(", ")", ",", "storeDefinition", ")", ";", "}", "return", "storeDefinitionMap", ";", "}" ]
Utility function that fetches user defined store definitions @param adminClient An instance of AdminClient points to given cluster @param nodeId Node id to fetch store definitions from @return The map container that maps store names to store definitions
[ "Utility", "function", "that", "fetches", "user", "defined", "store", "definitions" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L318-L327
161,214
voldemort/voldemort
src/java/voldemort/client/protocol/pb/ProtoUtils.java
ProtoUtils.decodeRebalanceTaskInfoMap
public static RebalanceTaskInfo decodeRebalanceTaskInfoMap(VAdminProto.RebalanceTaskInfoMap rebalanceTaskInfoMap) { RebalanceTaskInfo rebalanceTaskInfo = new RebalanceTaskInfo( rebalanceTaskInfoMap.getStealerId(), rebalanceTaskInfoMap.getDonorId(), decodeStoreToPartitionIds(rebalanceTaskInfoMap.getPerStorePartitionIdsList()), new ClusterMapper().readCluster(new StringReader(rebalanceTaskInfoMap.getInitialCluster()))); return rebalanceTaskInfo; }
java
public static RebalanceTaskInfo decodeRebalanceTaskInfoMap(VAdminProto.RebalanceTaskInfoMap rebalanceTaskInfoMap) { RebalanceTaskInfo rebalanceTaskInfo = new RebalanceTaskInfo( rebalanceTaskInfoMap.getStealerId(), rebalanceTaskInfoMap.getDonorId(), decodeStoreToPartitionIds(rebalanceTaskInfoMap.getPerStorePartitionIdsList()), new ClusterMapper().readCluster(new StringReader(rebalanceTaskInfoMap.getInitialCluster()))); return rebalanceTaskInfo; }
[ "public", "static", "RebalanceTaskInfo", "decodeRebalanceTaskInfoMap", "(", "VAdminProto", ".", "RebalanceTaskInfoMap", "rebalanceTaskInfoMap", ")", "{", "RebalanceTaskInfo", "rebalanceTaskInfo", "=", "new", "RebalanceTaskInfo", "(", "rebalanceTaskInfoMap", ".", "getStealerId", "(", ")", ",", "rebalanceTaskInfoMap", ".", "getDonorId", "(", ")", ",", "decodeStoreToPartitionIds", "(", "rebalanceTaskInfoMap", ".", "getPerStorePartitionIdsList", "(", ")", ")", ",", "new", "ClusterMapper", "(", ")", ".", "readCluster", "(", "new", "StringReader", "(", "rebalanceTaskInfoMap", ".", "getInitialCluster", "(", ")", ")", ")", ")", ";", "return", "rebalanceTaskInfo", ";", "}" ]
Given a protobuf rebalance-partition info, converts it into our rebalance-partition info @param rebalanceTaskInfoMap Proto-buff version of RebalanceTaskInfoMap @return RebalanceTaskInfo object.
[ "Given", "a", "protobuf", "rebalance", "-", "partition", "info", "converts", "it", "into", "our", "rebalance", "-", "partition", "info" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/pb/ProtoUtils.java#L70-L77
161,215
voldemort/voldemort
src/java/voldemort/client/protocol/pb/ProtoUtils.java
ProtoUtils.encodeRebalanceTaskInfoMap
public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) { return RebalanceTaskInfoMap.newBuilder() .setStealerId(stealInfo.getStealerId()) .setDonorId(stealInfo.getDonorId()) .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds())) .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster())) .build(); }
java
public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) { return RebalanceTaskInfoMap.newBuilder() .setStealerId(stealInfo.getStealerId()) .setDonorId(stealInfo.getDonorId()) .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds())) .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster())) .build(); }
[ "public", "static", "RebalanceTaskInfoMap", "encodeRebalanceTaskInfoMap", "(", "RebalanceTaskInfo", "stealInfo", ")", "{", "return", "RebalanceTaskInfoMap", ".", "newBuilder", "(", ")", ".", "setStealerId", "(", "stealInfo", ".", "getStealerId", "(", ")", ")", ".", "setDonorId", "(", "stealInfo", ".", "getDonorId", "(", ")", ")", ".", "addAllPerStorePartitionIds", "(", "ProtoUtils", ".", "encodeStoreToPartitionsTuple", "(", "stealInfo", ".", "getStoreToPartitionIds", "(", ")", ")", ")", ".", "setInitialCluster", "(", "new", "ClusterMapper", "(", ")", ".", "writeCluster", "(", "stealInfo", ".", "getInitialCluster", "(", ")", ")", ")", ".", "build", "(", ")", ";", "}" ]
Given a rebalance-task info, convert it into the protobuf equivalent @param stealInfo Rebalance task info @return Protobuf equivalent of the same
[ "Given", "a", "rebalance", "-", "task", "info", "convert", "it", "into", "the", "protobuf", "equivalent" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/client/protocol/pb/ProtoUtils.java#L101-L108
161,216
voldemort/voldemort
contrib/collections/src/java/voldemort/collections/VStack.java
VStack.getVersionedById
public Versioned<E> getVersionedById(int id) { Versioned<VListNode<E>> listNode = getListNode(id); if(listNode == null) throw new IndexOutOfBoundsException(); return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion()); }
java
public Versioned<E> getVersionedById(int id) { Versioned<VListNode<E>> listNode = getListNode(id); if(listNode == null) throw new IndexOutOfBoundsException(); return new Versioned<E>(listNode.getValue().getValue(), listNode.getVersion()); }
[ "public", "Versioned", "<", "E", ">", "getVersionedById", "(", "int", "id", ")", "{", "Versioned", "<", "VListNode", "<", "E", ">>", "listNode", "=", "getListNode", "(", "id", ")", ";", "if", "(", "listNode", "==", "null", ")", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "return", "new", "Versioned", "<", "E", ">", "(", "listNode", ".", "getValue", "(", ")", ".", "getValue", "(", ")", ",", "listNode", ".", "getVersion", "(", ")", ")", ";", "}" ]
Get the ver @param id @return
[ "Get", "the", "ver" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/collections/src/java/voldemort/collections/VStack.java#L272-L277
161,217
voldemort/voldemort
contrib/collections/src/java/voldemort/collections/VStack.java
VStack.setById
public E setById(final int id, final E element) { VListKey<K> key = new VListKey<K>(_key, id); UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element); if(!_storeClient.applyUpdate(updateElementAction)) throw new ObsoleteVersionException("update failed"); return updateElementAction.getResult(); }
java
public E setById(final int id, final E element) { VListKey<K> key = new VListKey<K>(_key, id); UpdateElementById<K, E> updateElementAction = new UpdateElementById<K, E>(key, element); if(!_storeClient.applyUpdate(updateElementAction)) throw new ObsoleteVersionException("update failed"); return updateElementAction.getResult(); }
[ "public", "E", "setById", "(", "final", "int", "id", ",", "final", "E", "element", ")", "{", "VListKey", "<", "K", ">", "key", "=", "new", "VListKey", "<", "K", ">", "(", "_key", ",", "id", ")", ";", "UpdateElementById", "<", "K", ",", "E", ">", "updateElementAction", "=", "new", "UpdateElementById", "<", "K", ",", "E", ">", "(", "key", ",", "element", ")", ";", "if", "(", "!", "_storeClient", ".", "applyUpdate", "(", "updateElementAction", ")", ")", "throw", "new", "ObsoleteVersionException", "(", "\"update failed\"", ")", ";", "return", "updateElementAction", ".", "getResult", "(", ")", ";", "}" ]
Put the given value to the appropriate id in the stack, using the version of the current list node identified by that id. @param id @param element element to set @return element that was replaced by the new element @throws ObsoleteVersionException when an update fails
[ "Put", "the", "given", "value", "to", "the", "appropriate", "id", "in", "the", "stack", "using", "the", "version", "of", "the", "current", "list", "node", "identified", "by", "that", "id", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/collections/src/java/voldemort/collections/VStack.java#L300-L308
161,218
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.allClustersEqual
private void allClustersEqual(final List<String> clusterUrls) { Validate.notEmpty(clusterUrls, "clusterUrls cannot be null"); // If only one clusterUrl return immediately if (clusterUrls.size() == 1) return; AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0)); Cluster clusterLhs = adminClientLhs.getAdminClientCluster(); for (int index = 1; index < clusterUrls.size(); index++) { AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index)); Cluster clusterRhs = adminClientRhs.getAdminClientCluster(); if (!areTwoClustersEqual(clusterLhs, clusterRhs)) throw new VoldemortException("Cluster " + clusterLhs.getName() + " is not the same as " + clusterRhs.getName()); } }
java
private void allClustersEqual(final List<String> clusterUrls) { Validate.notEmpty(clusterUrls, "clusterUrls cannot be null"); // If only one clusterUrl return immediately if (clusterUrls.size() == 1) return; AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0)); Cluster clusterLhs = adminClientLhs.getAdminClientCluster(); for (int index = 1; index < clusterUrls.size(); index++) { AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index)); Cluster clusterRhs = adminClientRhs.getAdminClientCluster(); if (!areTwoClustersEqual(clusterLhs, clusterRhs)) throw new VoldemortException("Cluster " + clusterLhs.getName() + " is not the same as " + clusterRhs.getName()); } }
[ "private", "void", "allClustersEqual", "(", "final", "List", "<", "String", ">", "clusterUrls", ")", "{", "Validate", ".", "notEmpty", "(", "clusterUrls", ",", "\"clusterUrls cannot be null\"", ")", ";", "// If only one clusterUrl return immediately", "if", "(", "clusterUrls", ".", "size", "(", ")", "==", "1", ")", "return", ";", "AdminClient", "adminClientLhs", "=", "adminClientPerCluster", ".", "get", "(", "clusterUrls", ".", "get", "(", "0", ")", ")", ";", "Cluster", "clusterLhs", "=", "adminClientLhs", ".", "getAdminClientCluster", "(", ")", ";", "for", "(", "int", "index", "=", "1", ";", "index", "<", "clusterUrls", ".", "size", "(", ")", ";", "index", "++", ")", "{", "AdminClient", "adminClientRhs", "=", "adminClientPerCluster", ".", "get", "(", "clusterUrls", ".", "get", "(", "index", ")", ")", ";", "Cluster", "clusterRhs", "=", "adminClientRhs", ".", "getAdminClientCluster", "(", ")", ";", "if", "(", "!", "areTwoClustersEqual", "(", "clusterLhs", ",", "clusterRhs", ")", ")", "throw", "new", "VoldemortException", "(", "\"Cluster \"", "+", "clusterLhs", ".", "getName", "(", ")", "+", "\" is not the same as \"", "+", "clusterRhs", ".", "getName", "(", ")", ")", ";", "}", "}" ]
Check if all cluster objects in the list are congruent. @param clusterUrls of cluster objects @return
[ "Check", "if", "all", "cluster", "objects", "in", "the", "list", "are", "congruent", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L416-L430
161,219
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.getInputPathJsonSchema
private synchronized JsonSchema getInputPathJsonSchema() throws IOException { if (inputPathJsonSchema == null) { // No need to query Hadoop more than once as this shouldn't change mid-run, // thus, we can lazily initialize and cache the result. inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath()); } return inputPathJsonSchema; }
java
private synchronized JsonSchema getInputPathJsonSchema() throws IOException { if (inputPathJsonSchema == null) { // No need to query Hadoop more than once as this shouldn't change mid-run, // thus, we can lazily initialize and cache the result. inputPathJsonSchema = HadoopUtils.getSchemaFromPath(getInputPath()); } return inputPathJsonSchema; }
[ "private", "synchronized", "JsonSchema", "getInputPathJsonSchema", "(", ")", "throws", "IOException", "{", "if", "(", "inputPathJsonSchema", "==", "null", ")", "{", "// No need to query Hadoop more than once as this shouldn't change mid-run,", "// thus, we can lazily initialize and cache the result.", "inputPathJsonSchema", "=", "HadoopUtils", ".", "getSchemaFromPath", "(", "getInputPath", "(", ")", ")", ";", "}", "return", "inputPathJsonSchema", ";", "}" ]
Get the Json Schema of the input path, assuming the path contains just one schema version in all files under that path.
[ "Get", "the", "Json", "Schema", "of", "the", "input", "path", "assuming", "the", "path", "contains", "just", "one", "schema", "version", "in", "all", "files", "under", "that", "path", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L892-L899
161,220
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.getInputPathAvroSchema
private synchronized Schema getInputPathAvroSchema() throws IOException { if (inputPathAvroSchema == null) { // No need to query Hadoop more than once as this shouldn't change mid-run, // thus, we can lazily initialize and cache the result. inputPathAvroSchema = AvroUtils.getAvroSchemaFromPath(getInputPath()); } return inputPathAvroSchema; }
java
private synchronized Schema getInputPathAvroSchema() throws IOException { if (inputPathAvroSchema == null) { // No need to query Hadoop more than once as this shouldn't change mid-run, // thus, we can lazily initialize and cache the result. inputPathAvroSchema = AvroUtils.getAvroSchemaFromPath(getInputPath()); } return inputPathAvroSchema; }
[ "private", "synchronized", "Schema", "getInputPathAvroSchema", "(", ")", "throws", "IOException", "{", "if", "(", "inputPathAvroSchema", "==", "null", ")", "{", "// No need to query Hadoop more than once as this shouldn't change mid-run,", "// thus, we can lazily initialize and cache the result.", "inputPathAvroSchema", "=", "AvroUtils", ".", "getAvroSchemaFromPath", "(", "getInputPath", "(", ")", ")", ";", "}", "return", "inputPathAvroSchema", ";", "}" ]
Get the Avro Schema of the input path, assuming the path contains just one schema version in all files under that path.
[ "Get", "the", "Avro", "Schema", "of", "the", "input", "path", "assuming", "the", "path", "contains", "just", "one", "schema", "version", "in", "all", "files", "under", "that", "path", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L905-L912
161,221
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.getRecordSchema
public String getRecordSchema() throws IOException { Schema schema = getInputPathAvroSchema(); String recSchema = schema.toString(); return recSchema; }
java
public String getRecordSchema() throws IOException { Schema schema = getInputPathAvroSchema(); String recSchema = schema.toString(); return recSchema; }
[ "public", "String", "getRecordSchema", "(", ")", "throws", "IOException", "{", "Schema", "schema", "=", "getInputPathAvroSchema", "(", ")", ";", "String", "recSchema", "=", "schema", ".", "toString", "(", ")", ";", "return", "recSchema", ";", "}" ]
Get the schema for the Avro Record from the object container file
[ "Get", "the", "schema", "for", "the", "Avro", "Record", "from", "the", "object", "container", "file" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L915-L919
161,222
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.getKeySchema
public String getKeySchema() throws IOException { Schema schema = getInputPathAvroSchema(); String keySchema = schema.getField(keyFieldName).schema().toString(); return keySchema; }
java
public String getKeySchema() throws IOException { Schema schema = getInputPathAvroSchema(); String keySchema = schema.getField(keyFieldName).schema().toString(); return keySchema; }
[ "public", "String", "getKeySchema", "(", ")", "throws", "IOException", "{", "Schema", "schema", "=", "getInputPathAvroSchema", "(", ")", ";", "String", "keySchema", "=", "schema", ".", "getField", "(", "keyFieldName", ")", ".", "schema", "(", ")", ".", "toString", "(", ")", ";", "return", "keySchema", ";", "}" ]
Extract schema of the key field
[ "Extract", "schema", "of", "the", "key", "field" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L922-L926
161,223
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.getValueSchema
public String getValueSchema() throws IOException { Schema schema = getInputPathAvroSchema(); String valueSchema = schema.getField(valueFieldName).schema().toString(); return valueSchema; }
java
public String getValueSchema() throws IOException { Schema schema = getInputPathAvroSchema(); String valueSchema = schema.getField(valueFieldName).schema().toString(); return valueSchema; }
[ "public", "String", "getValueSchema", "(", ")", "throws", "IOException", "{", "Schema", "schema", "=", "getInputPathAvroSchema", "(", ")", ";", "String", "valueSchema", "=", "schema", ".", "getField", "(", "valueFieldName", ")", ".", "schema", "(", ")", ".", "toString", "(", ")", ";", "return", "valueSchema", ";", "}" ]
Extract schema of the value field
[ "Extract", "schema", "of", "the", "value", "field" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L929-L933
161,224
voldemort/voldemort
contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java
VoldemortBuildAndPushJob.verifyOrAddStore
private void verifyOrAddStore(String clusterURL, String keySchema, String valueSchema) { String newStoreDefXml = VoldemortUtils.getStoreDefXml( storeName, props.getInt(BUILD_REPLICATION_FACTOR, 2), props.getInt(BUILD_REQUIRED_READS, 1), props.getInt(BUILD_REQUIRED_WRITES, 1), props.getNullableInt(BUILD_PREFERRED_READS), props.getNullableInt(BUILD_PREFERRED_WRITES), props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema), props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema), description, owners); log.info("Verifying store against cluster URL: " + clusterURL + "\n" + newStoreDefXml.toString()); StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml); try { adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, "BnP config/data", enableStoreCreation, this.storeVerificationExecutorService); } catch (UnreachableStoreException e) { log.info("verifyOrAddStore() failed on some nodes for clusterURL: " + clusterURL + " (this is harmless).", e); // When we can't reach some node, we just skip it and won't create the store on it. // Next time BnP is run while the node is up, it will get the store created. } // Other exceptions need to bubble up! storeDef = newStoreDef; }
java
private void verifyOrAddStore(String clusterURL, String keySchema, String valueSchema) { String newStoreDefXml = VoldemortUtils.getStoreDefXml( storeName, props.getInt(BUILD_REPLICATION_FACTOR, 2), props.getInt(BUILD_REQUIRED_READS, 1), props.getInt(BUILD_REQUIRED_WRITES, 1), props.getNullableInt(BUILD_PREFERRED_READS), props.getNullableInt(BUILD_PREFERRED_WRITES), props.getString(PUSH_FORCE_SCHEMA_KEY, keySchema), props.getString(PUSH_FORCE_SCHEMA_VALUE, valueSchema), description, owners); log.info("Verifying store against cluster URL: " + clusterURL + "\n" + newStoreDefXml.toString()); StoreDefinition newStoreDef = VoldemortUtils.getStoreDef(newStoreDefXml); try { adminClientPerCluster.get(clusterURL).storeMgmtOps.verifyOrAddStore(newStoreDef, "BnP config/data", enableStoreCreation, this.storeVerificationExecutorService); } catch (UnreachableStoreException e) { log.info("verifyOrAddStore() failed on some nodes for clusterURL: " + clusterURL + " (this is harmless).", e); // When we can't reach some node, we just skip it and won't create the store on it. // Next time BnP is run while the node is up, it will get the store created. } // Other exceptions need to bubble up! storeDef = newStoreDef; }
[ "private", "void", "verifyOrAddStore", "(", "String", "clusterURL", ",", "String", "keySchema", ",", "String", "valueSchema", ")", "{", "String", "newStoreDefXml", "=", "VoldemortUtils", ".", "getStoreDefXml", "(", "storeName", ",", "props", ".", "getInt", "(", "BUILD_REPLICATION_FACTOR", ",", "2", ")", ",", "props", ".", "getInt", "(", "BUILD_REQUIRED_READS", ",", "1", ")", ",", "props", ".", "getInt", "(", "BUILD_REQUIRED_WRITES", ",", "1", ")", ",", "props", ".", "getNullableInt", "(", "BUILD_PREFERRED_READS", ")", ",", "props", ".", "getNullableInt", "(", "BUILD_PREFERRED_WRITES", ")", ",", "props", ".", "getString", "(", "PUSH_FORCE_SCHEMA_KEY", ",", "keySchema", ")", ",", "props", ".", "getString", "(", "PUSH_FORCE_SCHEMA_VALUE", ",", "valueSchema", ")", ",", "description", ",", "owners", ")", ";", "log", ".", "info", "(", "\"Verifying store against cluster URL: \"", "+", "clusterURL", "+", "\"\\n\"", "+", "newStoreDefXml", ".", "toString", "(", ")", ")", ";", "StoreDefinition", "newStoreDef", "=", "VoldemortUtils", ".", "getStoreDef", "(", "newStoreDefXml", ")", ";", "try", "{", "adminClientPerCluster", ".", "get", "(", "clusterURL", ")", ".", "storeMgmtOps", ".", "verifyOrAddStore", "(", "newStoreDef", ",", "\"BnP config/data\"", ",", "enableStoreCreation", ",", "this", ".", "storeVerificationExecutorService", ")", ";", "}", "catch", "(", "UnreachableStoreException", "e", ")", "{", "log", ".", "info", "(", "\"verifyOrAddStore() failed on some nodes for clusterURL: \"", "+", "clusterURL", "+", "\" (this is harmless).\"", ",", "e", ")", ";", "// When we can't reach some node, we just skip it and won't create the store on it.", "// Next time BnP is run while the node is up, it will get the store created.", "}", "// Other exceptions need to bubble up!", "storeDef", "=", "newStoreDef", ";", "}" ]
For each node, checks if the store exists and then verifies that the remote schema matches the new one. If the remote store doesn't exist, it creates it.
[ "For", "each", "node", "checks", "if", "the", "store", "exists", "and", "then", "verifies", "that", "the", "remote", "schema", "matches", "the", "new", "one", ".", "If", "the", "remote", "store", "doesn", "t", "exist", "it", "creates", "it", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/contrib/hadoop-store-builder/src/java/voldemort/store/readonly/mr/azkaban/VoldemortBuildAndPushJob.java#L1014-L1042
161,225
voldemort/voldemort
src/java/voldemort/store/readonly/StoreVersionManager.java
StoreVersionManager.syncInternalStateFromFileSystem
public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) { // Make sure versions missing from the file-system are cleaned up from the internal state for (Long version: versionToEnabledMap.keySet()) { File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version); if (existingVersionDirs.length == 0) { removeVersion(version, alsoSyncRemoteState); } } // Make sure we have all versions on the file-system in the internal state File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir); if (versionDirs != null) { for (File versionDir: versionDirs) { long versionNumber = ReadOnlyUtils.getVersionId(versionDir); boolean versionEnabled = isVersionEnabled(versionDir); versionToEnabledMap.put(versionNumber, versionEnabled); } } // Identify the current version (based on a symlink in the file-system) File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir); if (currentVersionDir != null) { currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir); } else { currentVersion = -1; // Should we throw instead? } logger.info("Successfully synced internal state from local file-system: " + this.toString()); }
java
public void syncInternalStateFromFileSystem(boolean alsoSyncRemoteState) { // Make sure versions missing from the file-system are cleaned up from the internal state for (Long version: versionToEnabledMap.keySet()) { File[] existingVersionDirs = ReadOnlyUtils.getVersionDirs(rootDir, version, version); if (existingVersionDirs.length == 0) { removeVersion(version, alsoSyncRemoteState); } } // Make sure we have all versions on the file-system in the internal state File[] versionDirs = ReadOnlyUtils.getVersionDirs(rootDir); if (versionDirs != null) { for (File versionDir: versionDirs) { long versionNumber = ReadOnlyUtils.getVersionId(versionDir); boolean versionEnabled = isVersionEnabled(versionDir); versionToEnabledMap.put(versionNumber, versionEnabled); } } // Identify the current version (based on a symlink in the file-system) File currentVersionDir = ReadOnlyUtils.getCurrentVersion(rootDir); if (currentVersionDir != null) { currentVersion = ReadOnlyUtils.getVersionId(currentVersionDir); } else { currentVersion = -1; // Should we throw instead? } logger.info("Successfully synced internal state from local file-system: " + this.toString()); }
[ "public", "void", "syncInternalStateFromFileSystem", "(", "boolean", "alsoSyncRemoteState", ")", "{", "// Make sure versions missing from the file-system are cleaned up from the internal state", "for", "(", "Long", "version", ":", "versionToEnabledMap", ".", "keySet", "(", ")", ")", "{", "File", "[", "]", "existingVersionDirs", "=", "ReadOnlyUtils", ".", "getVersionDirs", "(", "rootDir", ",", "version", ",", "version", ")", ";", "if", "(", "existingVersionDirs", ".", "length", "==", "0", ")", "{", "removeVersion", "(", "version", ",", "alsoSyncRemoteState", ")", ";", "}", "}", "// Make sure we have all versions on the file-system in the internal state", "File", "[", "]", "versionDirs", "=", "ReadOnlyUtils", ".", "getVersionDirs", "(", "rootDir", ")", ";", "if", "(", "versionDirs", "!=", "null", ")", "{", "for", "(", "File", "versionDir", ":", "versionDirs", ")", "{", "long", "versionNumber", "=", "ReadOnlyUtils", ".", "getVersionId", "(", "versionDir", ")", ";", "boolean", "versionEnabled", "=", "isVersionEnabled", "(", "versionDir", ")", ";", "versionToEnabledMap", ".", "put", "(", "versionNumber", ",", "versionEnabled", ")", ";", "}", "}", "// Identify the current version (based on a symlink in the file-system)", "File", "currentVersionDir", "=", "ReadOnlyUtils", ".", "getCurrentVersion", "(", "rootDir", ")", ";", "if", "(", "currentVersionDir", "!=", "null", ")", "{", "currentVersion", "=", "ReadOnlyUtils", ".", "getVersionId", "(", "currentVersionDir", ")", ";", "}", "else", "{", "currentVersion", "=", "-", "1", ";", "// Should we throw instead?", "}", "logger", ".", "info", "(", "\"Successfully synced internal state from local file-system: \"", "+", "this", ".", "toString", "(", ")", ")", ";", "}" ]
Compares the StoreVersionManager's internal state with the content on the file-system of the rootDir provided at construction time. TODO: If the StoreVersionManager supports non-RO stores in the future, we should move some of the ReadOnlyUtils functions below to another Utils class.
[ "Compares", "the", "StoreVersionManager", "s", "internal", "state", "with", "the", "content", "on", "the", "file", "-", "system", "of", "the", "rootDir", "provided", "at", "construction", "time", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/StoreVersionManager.java#L86-L114
161,226
voldemort/voldemort
src/java/voldemort/store/readonly/StoreVersionManager.java
StoreVersionManager.persistDisabledVersion
private void persistDisabledVersion(long version) throws PersistenceFailureException { File disabledMarker = getDisabledMarkerFile(version); try { disabledMarker.createNewFile(); } catch (IOException e) { throw new PersistenceFailureException("Failed to create the disabled marker at path: " + disabledMarker.getAbsolutePath() + "\nThe store/version " + "will remain disabled only until the next restart.", e); } }
java
private void persistDisabledVersion(long version) throws PersistenceFailureException { File disabledMarker = getDisabledMarkerFile(version); try { disabledMarker.createNewFile(); } catch (IOException e) { throw new PersistenceFailureException("Failed to create the disabled marker at path: " + disabledMarker.getAbsolutePath() + "\nThe store/version " + "will remain disabled only until the next restart.", e); } }
[ "private", "void", "persistDisabledVersion", "(", "long", "version", ")", "throws", "PersistenceFailureException", "{", "File", "disabledMarker", "=", "getDisabledMarkerFile", "(", "version", ")", ";", "try", "{", "disabledMarker", ".", "createNewFile", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "PersistenceFailureException", "(", "\"Failed to create the disabled marker at path: \"", "+", "disabledMarker", ".", "getAbsolutePath", "(", ")", "+", "\"\\nThe store/version \"", "+", "\"will remain disabled only until the next restart.\"", ",", "e", ")", ";", "}", "}" ]
Places a disabled marker file in the directory of the specified version. @param version to disable @throws PersistenceFailureException if the marker file could not be created (can happen if the storage system has become read-only or is otherwise inaccessible).
[ "Places", "a", "disabled", "marker", "file", "in", "the", "directory", "of", "the", "specified", "version", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/StoreVersionManager.java#L206-L215
161,227
voldemort/voldemort
src/java/voldemort/store/readonly/StoreVersionManager.java
StoreVersionManager.persistEnabledVersion
private void persistEnabledVersion(long version) throws PersistenceFailureException { File disabledMarker = getDisabledMarkerFile(version); if (disabledMarker.exists()) { if (!disabledMarker.delete()) { throw new PersistenceFailureException("Failed to create the disabled marker at path: " + disabledMarker.getAbsolutePath() + "\nThe store/version " + "will remain enabled only until the next restart."); } } }
java
private void persistEnabledVersion(long version) throws PersistenceFailureException { File disabledMarker = getDisabledMarkerFile(version); if (disabledMarker.exists()) { if (!disabledMarker.delete()) { throw new PersistenceFailureException("Failed to create the disabled marker at path: " + disabledMarker.getAbsolutePath() + "\nThe store/version " + "will remain enabled only until the next restart."); } } }
[ "private", "void", "persistEnabledVersion", "(", "long", "version", ")", "throws", "PersistenceFailureException", "{", "File", "disabledMarker", "=", "getDisabledMarkerFile", "(", "version", ")", ";", "if", "(", "disabledMarker", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "disabledMarker", ".", "delete", "(", ")", ")", "{", "throw", "new", "PersistenceFailureException", "(", "\"Failed to create the disabled marker at path: \"", "+", "disabledMarker", ".", "getAbsolutePath", "(", ")", "+", "\"\\nThe store/version \"", "+", "\"will remain enabled only until the next restart.\"", ")", ";", "}", "}", "}" ]
Deletes the disabled marker file in the directory of the specified version. @param version to enable @throws PersistenceFailureException if the marker file could not be deleted (can happen if the storage system has become read-only or is otherwise inaccessible).
[ "Deletes", "the", "disabled", "marker", "file", "in", "the", "directory", "of", "the", "specified", "version", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/StoreVersionManager.java#L225-L234
161,228
voldemort/voldemort
src/java/voldemort/store/readonly/StoreVersionManager.java
StoreVersionManager.getDisabledMarkerFile
private File getDisabledMarkerFile(long version) throws PersistenceFailureException { File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version); if (versionDirArray.length == 0) { throw new PersistenceFailureException("getDisabledMarkerFile did not find the requested version directory" + " on disk. Version: " + version + ", rootDir: " + rootDir); } File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME); return disabledMarkerFile; }
java
private File getDisabledMarkerFile(long version) throws PersistenceFailureException { File[] versionDirArray = ReadOnlyUtils.getVersionDirs(rootDir, version, version); if (versionDirArray.length == 0) { throw new PersistenceFailureException("getDisabledMarkerFile did not find the requested version directory" + " on disk. Version: " + version + ", rootDir: " + rootDir); } File disabledMarkerFile = new File(versionDirArray[0], DISABLED_MARKER_NAME); return disabledMarkerFile; }
[ "private", "File", "getDisabledMarkerFile", "(", "long", "version", ")", "throws", "PersistenceFailureException", "{", "File", "[", "]", "versionDirArray", "=", "ReadOnlyUtils", ".", "getVersionDirs", "(", "rootDir", ",", "version", ",", "version", ")", ";", "if", "(", "versionDirArray", ".", "length", "==", "0", ")", "{", "throw", "new", "PersistenceFailureException", "(", "\"getDisabledMarkerFile did not find the requested version directory\"", "+", "\" on disk. Version: \"", "+", "version", "+", "\", rootDir: \"", "+", "rootDir", ")", ";", "}", "File", "disabledMarkerFile", "=", "new", "File", "(", "versionDirArray", "[", "0", "]", ",", "DISABLED_MARKER_NAME", ")", ";", "return", "disabledMarkerFile", ";", "}" ]
Gets the '.disabled' file for a given version of this store. That file may or may not exist. @param version of the store for which to get the '.disabled' file. @return an instance of {@link File} pointing to the '.disabled' file. @throws PersistenceFailureException if the requested version cannot be found.
[ "Gets", "the", ".", "disabled", "file", "for", "a", "given", "version", "of", "this", "store", ".", "That", "file", "may", "or", "may", "not", "exist", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/readonly/StoreVersionManager.java#L244-L252
161,229
voldemort/voldemort
src/java/voldemort/store/stats/SimpleCounter.java
SimpleCounter.getAvgEventValue
public Double getAvgEventValue() { resetIfNeeded(); synchronized(this) { long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval; if(eventsLastInterval > 0) return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0) / eventsLastInterval; else return 0.0; } }
java
public Double getAvgEventValue() { resetIfNeeded(); synchronized(this) { long eventsLastInterval = numEventsLastInterval - numEventsLastLastInterval; if(eventsLastInterval > 0) return ((totalEventValueLastInterval - totalEventValueLastLastInterval) * 1.0) / eventsLastInterval; else return 0.0; } }
[ "public", "Double", "getAvgEventValue", "(", ")", "{", "resetIfNeeded", "(", ")", ";", "synchronized", "(", "this", ")", "{", "long", "eventsLastInterval", "=", "numEventsLastInterval", "-", "numEventsLastLastInterval", ";", "if", "(", "eventsLastInterval", ">", "0", ")", "return", "(", "(", "totalEventValueLastInterval", "-", "totalEventValueLastLastInterval", ")", "*", "1.0", ")", "/", "eventsLastInterval", ";", "else", "return", "0.0", ";", "}", "}" ]
Returns the average event value in the current interval
[ "Returns", "the", "average", "event", "value", "in", "the", "current", "interval" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/SimpleCounter.java#L125-L135
161,230
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaCheck.executeCommand
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_CHECK); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK); url = (String) options.valueOf(AdminParserUtils.OPT_URL); // execute command if(metaKeys.size() == 0 || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) { metaKeys = Lists.newArrayList(); metaKeys.add(MetadataStore.CLUSTER_KEY); metaKeys.add(MetadataStore.STORES_KEY); metaKeys.add(MetadataStore.SERVER_STATE_KEY); } AdminClient adminClient = AdminToolUtils.getAdminClient(url); doMetaCheck(adminClient, metaKeys); }
java
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_CHECK); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK); url = (String) options.valueOf(AdminParserUtils.OPT_URL); // execute command if(metaKeys.size() == 0 || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) { metaKeys = Lists.newArrayList(); metaKeys.add(MetadataStore.CLUSTER_KEY); metaKeys.add(MetadataStore.STORES_KEY); metaKeys.add(MetadataStore.SERVER_STATE_KEY); } AdminClient adminClient = AdminToolUtils.getAdminClient(url); doMetaCheck(adminClient, metaKeys); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "// declare parameters", "List", "<", "String", ">", "metaKeys", "=", "null", ";", "String", "url", "=", "null", ";", "// parse command-line input", "args", "=", "AdminToolUtils", ".", "copyArrayAddFirst", "(", "args", ",", "\"--\"", "+", "OPT_HEAD_META_CHECK", ")", ";", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "// check required options and/or conflicting options", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "OPT_HEAD_META_CHECK", ")", ";", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "// load parameters", "metaKeys", "=", "(", "List", "<", "String", ">", ")", "options", ".", "valuesOf", "(", "OPT_HEAD_META_CHECK", ")", ";", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "// execute command", "if", "(", "metaKeys", ".", "size", "(", ")", "==", "0", "||", "(", "metaKeys", ".", "size", "(", ")", "==", "1", "&&", "metaKeys", ".", "get", "(", "0", ")", ".", "equals", "(", "METAKEY_ALL", ")", ")", ")", "{", "metaKeys", "=", "Lists", ".", "newArrayList", "(", ")", ";", "metaKeys", ".", "add", "(", "MetadataStore", ".", "CLUSTER_KEY", ")", ";", "metaKeys", ".", "add", "(", "MetadataStore", ".", "STORES_KEY", ")", ";", "metaKeys", ".", "add", "(", "MetadataStore", ".", "SERVER_STATE_KEY", ")", ";", "}", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "doMetaCheck", "(", "adminClient", ",", "metaKeys", ")", ";", "}" ]
Parses command-line and checks if metadata is consistent across all nodes. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "checks", "if", "metadata", "is", "consistent", "across", "all", "nodes", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L212-L250
161,231
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaClearRebalance.executeCommand
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters String url = null; List<Integer> nodeIds = null; Boolean allNodes = true; Boolean confirm = false; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); // load parameters url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } if(options.has(AdminParserUtils.OPT_CONFIRM)) { confirm = true; } // print summary System.out.println("Remove metadata related to rebalancing"); System.out.println("Location:"); System.out.println(" bootstrap url = " + url); if(allNodes) { System.out.println(" node = all nodes"); } else { System.out.println(" node = " + Joiner.on(", ").join(nodeIds)); } // execute command if(!AdminToolUtils.askConfirm(confirm, "remove metadata related to rebalancing")) { return; } AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds); doMetaClearRebalance(adminClient, nodeIds); }
java
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters String url = null; List<Integer> nodeIds = null; Boolean allNodes = true; Boolean confirm = false; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); // load parameters url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } if(options.has(AdminParserUtils.OPT_CONFIRM)) { confirm = true; } // print summary System.out.println("Remove metadata related to rebalancing"); System.out.println("Location:"); System.out.println(" bootstrap url = " + url); if(allNodes) { System.out.println(" node = all nodes"); } else { System.out.println(" node = " + Joiner.on(", ").join(nodeIds)); } // execute command if(!AdminToolUtils.askConfirm(confirm, "remove metadata related to rebalancing")) { return; } AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } AdminToolUtils.assertServerNotInRebalancingState(adminClient, nodeIds); doMetaClearRebalance(adminClient, nodeIds); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "// declare parameters", "String", "url", "=", "null", ";", "List", "<", "Integer", ">", "nodeIds", "=", "null", ";", "Boolean", "allNodes", "=", "true", ";", "Boolean", "confirm", "=", "false", ";", "// parse command-line input", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "// check required options and/or conflicting options", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "AdminParserUtils", ".", "checkOptional", "(", "options", ",", "AdminParserUtils", ".", "OPT_NODE", ",", "AdminParserUtils", ".", "OPT_ALL_NODES", ")", ";", "// load parameters", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ")", "{", "nodeIds", "=", "(", "List", "<", "Integer", ">", ")", "options", ".", "valuesOf", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ";", "allNodes", "=", "false", ";", "}", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_CONFIRM", ")", ")", "{", "confirm", "=", "true", ";", "}", "// print summary", "System", ".", "out", ".", "println", "(", "\"Remove metadata related to rebalancing\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"Location:\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" bootstrap url = \"", "+", "url", ")", ";", "if", "(", "allNodes", ")", "{", "System", ".", "out", ".", "println", "(", "\" node = all nodes\"", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\" node = \"", "+", "Joiner", ".", "on", "(", "\", \"", ")", ".", "join", "(", "nodeIds", ")", ")", ";", "}", "// execute command", "if", "(", "!", "AdminToolUtils", ".", "askConfirm", "(", "confirm", ",", "\"remove metadata related to rebalancing\"", ")", ")", "{", "return", ";", "}", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "if", "(", "allNodes", ")", "{", "nodeIds", "=", "AdminToolUtils", ".", "getAllNodeIds", "(", "adminClient", ")", ";", "}", "AdminToolUtils", ".", "assertServerNotInRebalancingState", "(", "adminClient", ",", "nodeIds", ")", ";", "doMetaClearRebalance", "(", "adminClient", ",", "nodeIds", ")", ";", "}" ]
Parses command-line and removes metadata related to rebalancing. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "removes", "metadata", "related", "to", "rebalancing", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L592-L649
161,232
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaClearRebalance.doMetaClearRebalance
public static void doMetaClearRebalance(AdminClient adminClient, List<Integer> nodeIds) { AdminToolUtils.assertServerNotInOfflineState(adminClient, nodeIds); System.out.println("Setting " + MetadataStore.SERVER_STATE_KEY + " to " + MetadataStore.VoldemortState.NORMAL_SERVER); doMetaSet(adminClient, nodeIds, MetadataStore.SERVER_STATE_KEY, MetadataStore.VoldemortState.NORMAL_SERVER.toString()); RebalancerState state = RebalancerState.create("[]"); System.out.println("Cleaning up " + MetadataStore.REBALANCING_STEAL_INFO + " to " + state.toJsonString()); doMetaSet(adminClient, nodeIds, MetadataStore.REBALANCING_STEAL_INFO, state.toJsonString()); System.out.println("Cleaning up " + MetadataStore.REBALANCING_SOURCE_CLUSTER_XML + " to empty string"); doMetaSet(adminClient, nodeIds, MetadataStore.REBALANCING_SOURCE_CLUSTER_XML, ""); }
java
public static void doMetaClearRebalance(AdminClient adminClient, List<Integer> nodeIds) { AdminToolUtils.assertServerNotInOfflineState(adminClient, nodeIds); System.out.println("Setting " + MetadataStore.SERVER_STATE_KEY + " to " + MetadataStore.VoldemortState.NORMAL_SERVER); doMetaSet(adminClient, nodeIds, MetadataStore.SERVER_STATE_KEY, MetadataStore.VoldemortState.NORMAL_SERVER.toString()); RebalancerState state = RebalancerState.create("[]"); System.out.println("Cleaning up " + MetadataStore.REBALANCING_STEAL_INFO + " to " + state.toJsonString()); doMetaSet(adminClient, nodeIds, MetadataStore.REBALANCING_STEAL_INFO, state.toJsonString()); System.out.println("Cleaning up " + MetadataStore.REBALANCING_SOURCE_CLUSTER_XML + " to empty string"); doMetaSet(adminClient, nodeIds, MetadataStore.REBALANCING_SOURCE_CLUSTER_XML, ""); }
[ "public", "static", "void", "doMetaClearRebalance", "(", "AdminClient", "adminClient", ",", "List", "<", "Integer", ">", "nodeIds", ")", "{", "AdminToolUtils", ".", "assertServerNotInOfflineState", "(", "adminClient", ",", "nodeIds", ")", ";", "System", ".", "out", ".", "println", "(", "\"Setting \"", "+", "MetadataStore", ".", "SERVER_STATE_KEY", "+", "\" to \"", "+", "MetadataStore", ".", "VoldemortState", ".", "NORMAL_SERVER", ")", ";", "doMetaSet", "(", "adminClient", ",", "nodeIds", ",", "MetadataStore", ".", "SERVER_STATE_KEY", ",", "MetadataStore", ".", "VoldemortState", ".", "NORMAL_SERVER", ".", "toString", "(", ")", ")", ";", "RebalancerState", "state", "=", "RebalancerState", ".", "create", "(", "\"[]\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"Cleaning up \"", "+", "MetadataStore", ".", "REBALANCING_STEAL_INFO", "+", "\" to \"", "+", "state", ".", "toJsonString", "(", ")", ")", ";", "doMetaSet", "(", "adminClient", ",", "nodeIds", ",", "MetadataStore", ".", "REBALANCING_STEAL_INFO", ",", "state", ".", "toJsonString", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"Cleaning up \"", "+", "MetadataStore", ".", "REBALANCING_SOURCE_CLUSTER_XML", "+", "\" to empty string\"", ")", ";", "doMetaSet", "(", "adminClient", ",", "nodeIds", ",", "MetadataStore", ".", "REBALANCING_SOURCE_CLUSTER_XML", ",", "\"\"", ")", ";", "}" ]
Removes metadata related to rebalancing. @param adminClient An instance of AdminClient points to given cluster @param nodeIds Node ids to clear metadata after rebalancing
[ "Removes", "metadata", "related", "to", "rebalancing", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L658-L676
161,233
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaGet.executeCommand
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; String dir = null; List<Integer> nodeIds = null; Boolean allNodes = true; Boolean verbose = false; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_DIR)) { dir = (String) options.valueOf(AdminParserUtils.OPT_DIR); } if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } if(options.has(OPT_VERBOSE)) { verbose = true; } // execute command File directory = AdminToolUtils.createDir(dir); AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) { metaKeys = Lists.newArrayList(); for(Object key: MetadataStore.METADATA_KEYS) { metaKeys.add((String) key); } } doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose); }
java
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; String dir = null; List<Integer> nodeIds = null; Boolean allNodes = true; Boolean verbose = false; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_DIR)) { dir = (String) options.valueOf(AdminParserUtils.OPT_DIR); } if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } if(options.has(OPT_VERBOSE)) { verbose = true; } // execute command File directory = AdminToolUtils.createDir(dir); AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) { metaKeys = Lists.newArrayList(); for(Object key: MetadataStore.METADATA_KEYS) { metaKeys.add((String) key); } } doMetaGet(adminClient, nodeIds, metaKeys, directory, verbose); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "// declare parameters", "List", "<", "String", ">", "metaKeys", "=", "null", ";", "String", "url", "=", "null", ";", "String", "dir", "=", "null", ";", "List", "<", "Integer", ">", "nodeIds", "=", "null", ";", "Boolean", "allNodes", "=", "true", ";", "Boolean", "verbose", "=", "false", ";", "// parse command-line input", "args", "=", "AdminToolUtils", ".", "copyArrayAddFirst", "(", "args", ",", "\"--\"", "+", "OPT_HEAD_META_GET", ")", ";", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "// check required options and/or conflicting options", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "OPT_HEAD_META_GET", ")", ";", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "AdminParserUtils", ".", "checkOptional", "(", "options", ",", "AdminParserUtils", ".", "OPT_NODE", ",", "AdminParserUtils", ".", "OPT_ALL_NODES", ")", ";", "// load parameters", "metaKeys", "=", "(", "List", "<", "String", ">", ")", "options", ".", "valuesOf", "(", "OPT_HEAD_META_GET", ")", ";", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_DIR", ")", ")", "{", "dir", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_DIR", ")", ";", "}", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ")", "{", "nodeIds", "=", "(", "List", "<", "Integer", ">", ")", "options", ".", "valuesOf", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ";", "allNodes", "=", "false", ";", "}", "if", "(", "options", ".", "has", "(", "OPT_VERBOSE", ")", ")", "{", "verbose", "=", "true", ";", "}", "// execute command", "File", "directory", "=", "AdminToolUtils", ".", "createDir", "(", "dir", ")", ";", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "if", "(", "allNodes", ")", "{", "nodeIds", "=", "AdminToolUtils", ".", "getAllNodeIds", "(", "adminClient", ")", ";", "}", "if", "(", "metaKeys", ".", "size", "(", ")", "==", "1", "&&", "metaKeys", ".", "get", "(", "0", ")", ".", "equals", "(", "METAKEY_ALL", ")", ")", "{", "metaKeys", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Object", "key", ":", "MetadataStore", ".", "METADATA_KEYS", ")", "{", "metaKeys", ".", "add", "(", "(", "String", ")", "key", ")", ";", "}", "}", "doMetaGet", "(", "adminClient", ",", "nodeIds", ",", "metaKeys", ",", "directory", ",", "verbose", ")", ";", "}" ]
Parses command-line and gets metadata. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "gets", "metadata", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L747-L805
161,234
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaGetRO.executeCommand
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; List<Integer> nodeIds = null; Boolean allNodes = true; List<String> storeNames = null; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE); // execute command AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) { metaKeys = Lists.newArrayList(); metaKeys.add(KEY_MAX_VERSION); metaKeys.add(KEY_CURRENT_VERSION); metaKeys.add(KEY_STORAGE_FORMAT); } doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys); }
java
@SuppressWarnings("unchecked") public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters List<String> metaKeys = null; String url = null; List<Integer> nodeIds = null; Boolean allNodes = true; List<String> storeNames = null; // parse command-line input args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_GET_RO); OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, OPT_HEAD_META_GET_RO); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); AdminParserUtils.checkOptional(options, AdminParserUtils.OPT_NODE, AdminParserUtils.OPT_ALL_NODES); AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_STORE); // load parameters metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_GET_RO); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_NODE)) { nodeIds = (List<Integer>) options.valuesOf(AdminParserUtils.OPT_NODE); allNodes = false; } storeNames = (List<String>) options.valuesOf(AdminParserUtils.OPT_STORE); // execute command AdminClient adminClient = AdminToolUtils.getAdminClient(url); if(allNodes) { nodeIds = AdminToolUtils.getAllNodeIds(adminClient); } if(metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL)) { metaKeys = Lists.newArrayList(); metaKeys.add(KEY_MAX_VERSION); metaKeys.add(KEY_CURRENT_VERSION); metaKeys.add(KEY_STORAGE_FORMAT); } doMetaGetRO(adminClient, nodeIds, storeNames, metaKeys); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "// declare parameters", "List", "<", "String", ">", "metaKeys", "=", "null", ";", "String", "url", "=", "null", ";", "List", "<", "Integer", ">", "nodeIds", "=", "null", ";", "Boolean", "allNodes", "=", "true", ";", "List", "<", "String", ">", "storeNames", "=", "null", ";", "// parse command-line input", "args", "=", "AdminToolUtils", ".", "copyArrayAddFirst", "(", "args", ",", "\"--\"", "+", "OPT_HEAD_META_GET_RO", ")", ";", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "// check required options and/or conflicting options", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "OPT_HEAD_META_GET_RO", ")", ";", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "AdminParserUtils", ".", "checkOptional", "(", "options", ",", "AdminParserUtils", ".", "OPT_NODE", ",", "AdminParserUtils", ".", "OPT_ALL_NODES", ")", ";", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_STORE", ")", ";", "// load parameters", "metaKeys", "=", "(", "List", "<", "String", ">", ")", "options", ".", "valuesOf", "(", "OPT_HEAD_META_GET_RO", ")", ";", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ")", "{", "nodeIds", "=", "(", "List", "<", "Integer", ">", ")", "options", ".", "valuesOf", "(", "AdminParserUtils", ".", "OPT_NODE", ")", ";", "allNodes", "=", "false", ";", "}", "storeNames", "=", "(", "List", "<", "String", ">", ")", "options", ".", "valuesOf", "(", "AdminParserUtils", ".", "OPT_STORE", ")", ";", "// execute command", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "if", "(", "allNodes", ")", "{", "nodeIds", "=", "AdminToolUtils", ".", "getAllNodeIds", "(", "adminClient", ")", ";", "}", "if", "(", "metaKeys", ".", "size", "(", ")", "==", "1", "&&", "metaKeys", ".", "get", "(", "0", ")", ".", "equals", "(", "METAKEY_ALL", ")", ")", "{", "metaKeys", "=", "Lists", ".", "newArrayList", "(", ")", ";", "metaKeys", ".", "add", "(", "KEY_MAX_VERSION", ")", ";", "metaKeys", ".", "add", "(", "KEY_CURRENT_VERSION", ")", ";", "metaKeys", ".", "add", "(", "KEY_STORAGE_FORMAT", ")", ";", "}", "doMetaGetRO", "(", "adminClient", ",", "nodeIds", ",", "storeNames", ",", "metaKeys", ")", ";", "}" ]
Parses command-line and gets read-only metadata. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "gets", "read", "-", "only", "metadata", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L952-L1004
161,235
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaGetRO.doMetaGetRO
public static void doMetaGetRO(AdminClient adminClient, Collection<Integer> nodeIds, List<String> storeNames, List<String> metaKeys) throws IOException { for(String key: metaKeys) { System.out.println("Metadata: " + key); if(!key.equals(KEY_MAX_VERSION) && !key.equals(KEY_CURRENT_VERSION) && !key.equals(KEY_STORAGE_FORMAT)) { System.out.println(" Invalid read-only metadata key: " + key); } else { for(Integer nodeId: nodeIds) { String hostName = adminClient.getAdminClientCluster() .getNodeById(nodeId) .getHost(); System.out.println(" Node: " + hostName + ":" + nodeId); if(key.equals(KEY_MAX_VERSION)) { Map<String, Long> mapStoreToROVersion = adminClient.readonlyOps.getROMaxVersion(nodeId, storeNames); for(String storeName: mapStoreToROVersion.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROVersion.get(storeName)); } } else if(key.equals(KEY_CURRENT_VERSION)) { Map<String, Long> mapStoreToROVersion = adminClient.readonlyOps.getROCurrentVersion(nodeId, storeNames); for(String storeName: mapStoreToROVersion.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROVersion.get(storeName)); } } else if(key.equals(KEY_STORAGE_FORMAT)) { Map<String, String> mapStoreToROFormat = adminClient.readonlyOps.getROStorageFormat(nodeId, storeNames); for(String storeName: mapStoreToROFormat.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROFormat.get(storeName)); } } } } System.out.println(); } }
java
public static void doMetaGetRO(AdminClient adminClient, Collection<Integer> nodeIds, List<String> storeNames, List<String> metaKeys) throws IOException { for(String key: metaKeys) { System.out.println("Metadata: " + key); if(!key.equals(KEY_MAX_VERSION) && !key.equals(KEY_CURRENT_VERSION) && !key.equals(KEY_STORAGE_FORMAT)) { System.out.println(" Invalid read-only metadata key: " + key); } else { for(Integer nodeId: nodeIds) { String hostName = adminClient.getAdminClientCluster() .getNodeById(nodeId) .getHost(); System.out.println(" Node: " + hostName + ":" + nodeId); if(key.equals(KEY_MAX_VERSION)) { Map<String, Long> mapStoreToROVersion = adminClient.readonlyOps.getROMaxVersion(nodeId, storeNames); for(String storeName: mapStoreToROVersion.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROVersion.get(storeName)); } } else if(key.equals(KEY_CURRENT_VERSION)) { Map<String, Long> mapStoreToROVersion = adminClient.readonlyOps.getROCurrentVersion(nodeId, storeNames); for(String storeName: mapStoreToROVersion.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROVersion.get(storeName)); } } else if(key.equals(KEY_STORAGE_FORMAT)) { Map<String, String> mapStoreToROFormat = adminClient.readonlyOps.getROStorageFormat(nodeId, storeNames); for(String storeName: mapStoreToROFormat.keySet()) { System.out.println(" " + storeName + ":" + mapStoreToROFormat.get(storeName)); } } } } System.out.println(); } }
[ "public", "static", "void", "doMetaGetRO", "(", "AdminClient", "adminClient", ",", "Collection", "<", "Integer", ">", "nodeIds", ",", "List", "<", "String", ">", "storeNames", ",", "List", "<", "String", ">", "metaKeys", ")", "throws", "IOException", "{", "for", "(", "String", "key", ":", "metaKeys", ")", "{", "System", ".", "out", ".", "println", "(", "\"Metadata: \"", "+", "key", ")", ";", "if", "(", "!", "key", ".", "equals", "(", "KEY_MAX_VERSION", ")", "&&", "!", "key", ".", "equals", "(", "KEY_CURRENT_VERSION", ")", "&&", "!", "key", ".", "equals", "(", "KEY_STORAGE_FORMAT", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\" Invalid read-only metadata key: \"", "+", "key", ")", ";", "}", "else", "{", "for", "(", "Integer", "nodeId", ":", "nodeIds", ")", "{", "String", "hostName", "=", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodeById", "(", "nodeId", ")", ".", "getHost", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\" Node: \"", "+", "hostName", "+", "\":\"", "+", "nodeId", ")", ";", "if", "(", "key", ".", "equals", "(", "KEY_MAX_VERSION", ")", ")", "{", "Map", "<", "String", ",", "Long", ">", "mapStoreToROVersion", "=", "adminClient", ".", "readonlyOps", ".", "getROMaxVersion", "(", "nodeId", ",", "storeNames", ")", ";", "for", "(", "String", "storeName", ":", "mapStoreToROVersion", ".", "keySet", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\" \"", "+", "storeName", "+", "\":\"", "+", "mapStoreToROVersion", ".", "get", "(", "storeName", ")", ")", ";", "}", "}", "else", "if", "(", "key", ".", "equals", "(", "KEY_CURRENT_VERSION", ")", ")", "{", "Map", "<", "String", ",", "Long", ">", "mapStoreToROVersion", "=", "adminClient", ".", "readonlyOps", ".", "getROCurrentVersion", "(", "nodeId", ",", "storeNames", ")", ";", "for", "(", "String", "storeName", ":", "mapStoreToROVersion", ".", "keySet", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\" \"", "+", "storeName", "+", "\":\"", "+", "mapStoreToROVersion", ".", "get", "(", "storeName", ")", ")", ";", "}", "}", "else", "if", "(", "key", ".", "equals", "(", "KEY_STORAGE_FORMAT", ")", ")", "{", "Map", "<", "String", ",", "String", ">", "mapStoreToROFormat", "=", "adminClient", ".", "readonlyOps", ".", "getROStorageFormat", "(", "nodeId", ",", "storeNames", ")", ";", "for", "(", "String", "storeName", ":", "mapStoreToROFormat", ".", "keySet", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\" \"", "+", "storeName", "+", "\":\"", "+", "mapStoreToROFormat", ".", "get", "(", "storeName", ")", ")", ";", "}", "}", "}", "}", "System", ".", "out", ".", "println", "(", ")", ";", "}", "}" ]
Gets read-only metadata. @param adminClient An instance of AdminClient points to given cluster @param nodeIds Node ids to fetch read-only metadata from @param storeNames Stores names to fetch read-only metadata from @param metaKeys List of read-only metadata to fetch @throws IOException
[ "Gets", "read", "-", "only", "metadata", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L1015-L1056
161,236
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaSet.doMetaUpdateVersionsOnStores
public static void doMetaUpdateVersionsOnStores(AdminClient adminClient, List<StoreDefinition> oldStoreDefs, List<StoreDefinition> newStoreDefs) { Set<String> storeNamesUnion = new HashSet<String>(); Map<String, StoreDefinition> oldStoreDefinitionMap = new HashMap<String, StoreDefinition>(); Map<String, StoreDefinition> newStoreDefinitionMap = new HashMap<String, StoreDefinition>(); List<String> storesChanged = new ArrayList<String>(); for(StoreDefinition storeDef: oldStoreDefs) { String storeName = storeDef.getName(); storeNamesUnion.add(storeName); oldStoreDefinitionMap.put(storeName, storeDef); } for(StoreDefinition storeDef: newStoreDefs) { String storeName = storeDef.getName(); storeNamesUnion.add(storeName); newStoreDefinitionMap.put(storeName, storeDef); } for(String storeName: storeNamesUnion) { StoreDefinition oldStoreDef = oldStoreDefinitionMap.get(storeName); StoreDefinition newStoreDef = newStoreDefinitionMap.get(storeName); if(oldStoreDef == null && newStoreDef != null || oldStoreDef != null && newStoreDef == null || oldStoreDef != null && newStoreDef != null && !oldStoreDef.equals(newStoreDef)) { storesChanged.add(storeName); } } System.out.println("Updating metadata version for the following stores: " + storesChanged); try { adminClient.metadataMgmtOps.updateMetadataversion(adminClient.getAdminClientCluster() .getNodeIds(), storesChanged); } catch(Exception e) { System.err.println("Error while updating metadata version for the specified store."); } }
java
public static void doMetaUpdateVersionsOnStores(AdminClient adminClient, List<StoreDefinition> oldStoreDefs, List<StoreDefinition> newStoreDefs) { Set<String> storeNamesUnion = new HashSet<String>(); Map<String, StoreDefinition> oldStoreDefinitionMap = new HashMap<String, StoreDefinition>(); Map<String, StoreDefinition> newStoreDefinitionMap = new HashMap<String, StoreDefinition>(); List<String> storesChanged = new ArrayList<String>(); for(StoreDefinition storeDef: oldStoreDefs) { String storeName = storeDef.getName(); storeNamesUnion.add(storeName); oldStoreDefinitionMap.put(storeName, storeDef); } for(StoreDefinition storeDef: newStoreDefs) { String storeName = storeDef.getName(); storeNamesUnion.add(storeName); newStoreDefinitionMap.put(storeName, storeDef); } for(String storeName: storeNamesUnion) { StoreDefinition oldStoreDef = oldStoreDefinitionMap.get(storeName); StoreDefinition newStoreDef = newStoreDefinitionMap.get(storeName); if(oldStoreDef == null && newStoreDef != null || oldStoreDef != null && newStoreDef == null || oldStoreDef != null && newStoreDef != null && !oldStoreDef.equals(newStoreDef)) { storesChanged.add(storeName); } } System.out.println("Updating metadata version for the following stores: " + storesChanged); try { adminClient.metadataMgmtOps.updateMetadataversion(adminClient.getAdminClientCluster() .getNodeIds(), storesChanged); } catch(Exception e) { System.err.println("Error while updating metadata version for the specified store."); } }
[ "public", "static", "void", "doMetaUpdateVersionsOnStores", "(", "AdminClient", "adminClient", ",", "List", "<", "StoreDefinition", ">", "oldStoreDefs", ",", "List", "<", "StoreDefinition", ">", "newStoreDefs", ")", "{", "Set", "<", "String", ">", "storeNamesUnion", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "Map", "<", "String", ",", "StoreDefinition", ">", "oldStoreDefinitionMap", "=", "new", "HashMap", "<", "String", ",", "StoreDefinition", ">", "(", ")", ";", "Map", "<", "String", ",", "StoreDefinition", ">", "newStoreDefinitionMap", "=", "new", "HashMap", "<", "String", ",", "StoreDefinition", ">", "(", ")", ";", "List", "<", "String", ">", "storesChanged", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "StoreDefinition", "storeDef", ":", "oldStoreDefs", ")", "{", "String", "storeName", "=", "storeDef", ".", "getName", "(", ")", ";", "storeNamesUnion", ".", "add", "(", "storeName", ")", ";", "oldStoreDefinitionMap", ".", "put", "(", "storeName", ",", "storeDef", ")", ";", "}", "for", "(", "StoreDefinition", "storeDef", ":", "newStoreDefs", ")", "{", "String", "storeName", "=", "storeDef", ".", "getName", "(", ")", ";", "storeNamesUnion", ".", "add", "(", "storeName", ")", ";", "newStoreDefinitionMap", ".", "put", "(", "storeName", ",", "storeDef", ")", ";", "}", "for", "(", "String", "storeName", ":", "storeNamesUnion", ")", "{", "StoreDefinition", "oldStoreDef", "=", "oldStoreDefinitionMap", ".", "get", "(", "storeName", ")", ";", "StoreDefinition", "newStoreDef", "=", "newStoreDefinitionMap", ".", "get", "(", "storeName", ")", ";", "if", "(", "oldStoreDef", "==", "null", "&&", "newStoreDef", "!=", "null", "||", "oldStoreDef", "!=", "null", "&&", "newStoreDef", "==", "null", "||", "oldStoreDef", "!=", "null", "&&", "newStoreDef", "!=", "null", "&&", "!", "oldStoreDef", ".", "equals", "(", "newStoreDef", ")", ")", "{", "storesChanged", ".", "add", "(", "storeName", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "\"Updating metadata version for the following stores: \"", "+", "storesChanged", ")", ";", "try", "{", "adminClient", ".", "metadataMgmtOps", ".", "updateMetadataversion", "(", "adminClient", ".", "getAdminClientCluster", "(", ")", ".", "getNodeIds", "(", ")", ",", "storesChanged", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Error while updating metadata version for the specified store.\"", ")", ";", "}", "}" ]
Updates metadata versions on stores. @param adminClient An instance of AdminClient points to given cluster @param oldStoreDefs List of old store definitions @param newStoreDefs List of new store definitions
[ "Updates", "metadata", "versions", "on", "stores", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L1485-L1520
161,237
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaSyncVersion.executeCommand
public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); String url = null; Boolean confirm = false; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_CONFIRM)) { confirm = true; } // print summary System.out.println("Synchronize metadata versions across all nodes"); System.out.println("Location:"); System.out.println(" bootstrap url = " + url); System.out.println(" node = all nodes"); AdminClient adminClient = AdminToolUtils.getAdminClient(url); AdminToolUtils.assertServerNotInRebalancingState(adminClient); Versioned<Properties> versionedProps = mergeAllVersions(adminClient); printVersions(versionedProps); // execute command if(!AdminToolUtils.askConfirm(confirm, "do you want to synchronize metadata versions to all node")) return; adminClient.metadataMgmtOps.setMetadataVersion(versionedProps); }
java
public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); String url = null; Boolean confirm = false; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); url = (String) options.valueOf(AdminParserUtils.OPT_URL); if(options.has(AdminParserUtils.OPT_CONFIRM)) { confirm = true; } // print summary System.out.println("Synchronize metadata versions across all nodes"); System.out.println("Location:"); System.out.println(" bootstrap url = " + url); System.out.println(" node = all nodes"); AdminClient adminClient = AdminToolUtils.getAdminClient(url); AdminToolUtils.assertServerNotInRebalancingState(adminClient); Versioned<Properties> versionedProps = mergeAllVersions(adminClient); printVersions(versionedProps); // execute command if(!AdminToolUtils.askConfirm(confirm, "do you want to synchronize metadata versions to all node")) return; adminClient.metadataMgmtOps.setMetadataVersion(versionedProps); }
[ "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "String", "url", "=", "null", ";", "Boolean", "confirm", "=", "false", ";", "// parse command-line input", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_CONFIRM", ")", ")", "{", "confirm", "=", "true", ";", "}", "// print summary", "System", ".", "out", ".", "println", "(", "\"Synchronize metadata versions across all nodes\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"Location:\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" bootstrap url = \"", "+", "url", ")", ";", "System", ".", "out", ".", "println", "(", "\" node = all nodes\"", ")", ";", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "AdminToolUtils", ".", "assertServerNotInRebalancingState", "(", "adminClient", ")", ";", "Versioned", "<", "Properties", ">", "versionedProps", "=", "mergeAllVersions", "(", "adminClient", ")", ";", "printVersions", "(", "versionedProps", ")", ";", "// execute command", "if", "(", "!", "AdminToolUtils", ".", "askConfirm", "(", "confirm", ",", "\"do you want to synchronize metadata versions to all node\"", ")", ")", "return", ";", "adminClient", ".", "metadataMgmtOps", ".", "setMetadataVersion", "(", "versionedProps", ")", ";", "}" ]
Parses command-line and synchronizes metadata versions across all nodes. @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "synchronizes", "metadata", "versions", "across", "all", "nodes", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L1571-L1611
161,238
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandMeta.java
SubCommandMetaCheckVersion.executeCommand
public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters String url = null; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); // load parameters url = (String) options.valueOf(AdminParserUtils.OPT_URL); // execute command AdminClient adminClient = AdminToolUtils.getAdminClient(url); doMetaCheckVersion(adminClient); }
java
public static void executeCommand(String[] args) throws IOException { OptionParser parser = getParser(); // declare parameters String url = null; // parse command-line input OptionSet options = parser.parse(args); if(options.has(AdminParserUtils.OPT_HELP)) { printHelp(System.out); return; } // check required options and/or conflicting options AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL); // load parameters url = (String) options.valueOf(AdminParserUtils.OPT_URL); // execute command AdminClient adminClient = AdminToolUtils.getAdminClient(url); doMetaCheckVersion(adminClient); }
[ "public", "static", "void", "executeCommand", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "OptionParser", "parser", "=", "getParser", "(", ")", ";", "// declare parameters", "String", "url", "=", "null", ";", "// parse command-line input", "OptionSet", "options", "=", "parser", ".", "parse", "(", "args", ")", ";", "if", "(", "options", ".", "has", "(", "AdminParserUtils", ".", "OPT_HELP", ")", ")", "{", "printHelp", "(", "System", ".", "out", ")", ";", "return", ";", "}", "// check required options and/or conflicting options", "AdminParserUtils", ".", "checkRequired", "(", "options", ",", "AdminParserUtils", ".", "OPT_URL", ")", ";", "// load parameters", "url", "=", "(", "String", ")", "options", ".", "valueOf", "(", "AdminParserUtils", ".", "OPT_URL", ")", ";", "// execute command", "AdminClient", "adminClient", "=", "AdminToolUtils", ".", "getAdminClient", "(", "url", ")", ";", "doMetaCheckVersion", "(", "adminClient", ")", ";", "}" ]
Parses command-line and verifies metadata versions on all the cluster nodes @param args Command-line input @param printHelp Tells whether to print help only or execute command actually @throws IOException
[ "Parses", "command", "-", "line", "and", "verifies", "metadata", "versions", "on", "all", "the", "cluster", "nodes" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandMeta.java#L1687-L1711
161,239
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java
FullScanFetchStreamRequestHandler.getKeyPartitionId
private Integer getKeyPartitionId(byte[] key) { Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key); Utils.notNull(keyPartitionId); return keyPartitionId; }
java
private Integer getKeyPartitionId(byte[] key) { Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key); Utils.notNull(keyPartitionId); return keyPartitionId; }
[ "private", "Integer", "getKeyPartitionId", "(", "byte", "[", "]", "key", ")", "{", "Integer", "keyPartitionId", "=", "storeInstance", ".", "getNodesPartitionIdForKey", "(", "nodeId", ",", "key", ")", ";", "Utils", ".", "notNull", "(", "keyPartitionId", ")", ";", "return", "keyPartitionId", ";", "}" ]
Given the key, figures out which partition on the local node hosts the key. @param key @return
[ "Given", "the", "key", "figures", "out", "which", "partition", "on", "the", "local", "node", "hosts", "the", "key", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java#L80-L85
161,240
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java
FullScanFetchStreamRequestHandler.isItemAccepted
protected boolean isItemAccepted(byte[] key) { boolean entryAccepted = false; if (!fetchOrphaned) { if (isKeyNeeded(key)) { entryAccepted = true; } } else { if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) { entryAccepted = true; } } return entryAccepted; }
java
protected boolean isItemAccepted(byte[] key) { boolean entryAccepted = false; if (!fetchOrphaned) { if (isKeyNeeded(key)) { entryAccepted = true; } } else { if (!StoreRoutingPlan.checkKeyBelongsToNode(key, nodeId, initialCluster, storeDef)) { entryAccepted = true; } } return entryAccepted; }
[ "protected", "boolean", "isItemAccepted", "(", "byte", "[", "]", "key", ")", "{", "boolean", "entryAccepted", "=", "false", ";", "if", "(", "!", "fetchOrphaned", ")", "{", "if", "(", "isKeyNeeded", "(", "key", ")", ")", "{", "entryAccepted", "=", "true", ";", "}", "}", "else", "{", "if", "(", "!", "StoreRoutingPlan", ".", "checkKeyBelongsToNode", "(", "key", ",", "nodeId", ",", "initialCluster", ",", "storeDef", ")", ")", "{", "entryAccepted", "=", "true", ";", "}", "}", "return", "entryAccepted", ";", "}" ]
Determines if entry is accepted. For normal usage, this means confirming that the key is needed. For orphan usage, this simply means confirming the key belongs to the node. @param key @return true iff entry is accepted.
[ "Determines", "if", "entry", "is", "accepted", ".", "For", "normal", "usage", "this", "means", "confirming", "that", "the", "key", "is", "needed", ".", "For", "orphan", "usage", "this", "simply", "means", "confirming", "the", "key", "belongs", "to", "the", "node", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java#L126-L138
161,241
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java
FullScanFetchStreamRequestHandler.accountForFetchedKey
protected void accountForFetchedKey(byte[] key) { fetched++; if (streamStats != null) { streamStats.reportStreamingFetch(operation); } if (recordsPerPartition <= 0) { return; } Integer keyPartitionId = getKeyPartitionId(key); Long partitionFetch = partitionFetches.get(keyPartitionId); Utils.notNull(partitionFetch); partitionFetch++; partitionFetches.put(keyPartitionId, partitionFetch); if (partitionFetch == recordsPerPartition) { if (partitionsToFetch.contains(keyPartitionId)) { partitionsToFetch.remove(keyPartitionId); } else { logger.warn("Partitions to fetch did not contain expected partition ID: " + keyPartitionId); } } else if (partitionFetch > recordsPerPartition) { logger.warn("Partition fetch count larger than expected for partition ID " + keyPartitionId + " : " + partitionFetch); } }
java
protected void accountForFetchedKey(byte[] key) { fetched++; if (streamStats != null) { streamStats.reportStreamingFetch(operation); } if (recordsPerPartition <= 0) { return; } Integer keyPartitionId = getKeyPartitionId(key); Long partitionFetch = partitionFetches.get(keyPartitionId); Utils.notNull(partitionFetch); partitionFetch++; partitionFetches.put(keyPartitionId, partitionFetch); if (partitionFetch == recordsPerPartition) { if (partitionsToFetch.contains(keyPartitionId)) { partitionsToFetch.remove(keyPartitionId); } else { logger.warn("Partitions to fetch did not contain expected partition ID: " + keyPartitionId); } } else if (partitionFetch > recordsPerPartition) { logger.warn("Partition fetch count larger than expected for partition ID " + keyPartitionId + " : " + partitionFetch); } }
[ "protected", "void", "accountForFetchedKey", "(", "byte", "[", "]", "key", ")", "{", "fetched", "++", ";", "if", "(", "streamStats", "!=", "null", ")", "{", "streamStats", ".", "reportStreamingFetch", "(", "operation", ")", ";", "}", "if", "(", "recordsPerPartition", "<=", "0", ")", "{", "return", ";", "}", "Integer", "keyPartitionId", "=", "getKeyPartitionId", "(", "key", ")", ";", "Long", "partitionFetch", "=", "partitionFetches", ".", "get", "(", "keyPartitionId", ")", ";", "Utils", ".", "notNull", "(", "partitionFetch", ")", ";", "partitionFetch", "++", ";", "partitionFetches", ".", "put", "(", "keyPartitionId", ",", "partitionFetch", ")", ";", "if", "(", "partitionFetch", "==", "recordsPerPartition", ")", "{", "if", "(", "partitionsToFetch", ".", "contains", "(", "keyPartitionId", ")", ")", "{", "partitionsToFetch", ".", "remove", "(", "keyPartitionId", ")", ";", "}", "else", "{", "logger", ".", "warn", "(", "\"Partitions to fetch did not contain expected partition ID: \"", "+", "keyPartitionId", ")", ";", "}", "}", "else", "if", "(", "partitionFetch", ">", "recordsPerPartition", ")", "{", "logger", ".", "warn", "(", "\"Partition fetch count larger than expected for partition ID \"", "+", "keyPartitionId", "+", "\" : \"", "+", "partitionFetch", ")", ";", "}", "}" ]
Account for key being fetched. @param key
[ "Account", "for", "key", "being", "fetched", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java#L145-L172
161,242
voldemort/voldemort
src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java
FullScanFetchStreamRequestHandler.determineRequestHandlerState
protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) { if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) { return StreamRequestHandlerState.WRITING; } else { logger.info("Finished fetch " + itemTag + " for store '" + storageEngine.getName() + "' with partitions " + partitionIds); progressInfoMessage("Fetch " + itemTag + " (end of scan)"); return StreamRequestHandlerState.COMPLETE; } }
java
protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) { if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) { return StreamRequestHandlerState.WRITING; } else { logger.info("Finished fetch " + itemTag + " for store '" + storageEngine.getName() + "' with partitions " + partitionIds); progressInfoMessage("Fetch " + itemTag + " (end of scan)"); return StreamRequestHandlerState.COMPLETE; } }
[ "protected", "StreamRequestHandlerState", "determineRequestHandlerState", "(", "String", "itemTag", ")", "{", "if", "(", "keyIterator", ".", "hasNext", "(", ")", "&&", "!", "fetchedEnoughForAllPartitions", "(", ")", ")", "{", "return", "StreamRequestHandlerState", ".", "WRITING", ";", "}", "else", "{", "logger", ".", "info", "(", "\"Finished fetch \"", "+", "itemTag", "+", "\" for store '\"", "+", "storageEngine", ".", "getName", "(", ")", "+", "\"' with partitions \"", "+", "partitionIds", ")", ";", "progressInfoMessage", "(", "\"Fetch \"", "+", "itemTag", "+", "\" (end of scan)\"", ")", ";", "return", "StreamRequestHandlerState", ".", "COMPLETE", ";", "}", "}" ]
Determines if still WRITING or COMPLETE. @param itemTag mad libs style string to insert into progress message. @return state of stream request handler
[ "Determines", "if", "still", "WRITING", "or", "COMPLETE", "." ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/protocol/admin/FullScanFetchStreamRequestHandler.java#L197-L208
161,243
voldemort/voldemort
src/java/voldemort/store/AbstractStorageEngine.java
AbstractStorageEngine.resolveAndConstructVersionsToPersist
protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage, List<Versioned<V>> multiPutValues) { List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size()); // Go over all the values and determine whether the version is // acceptable for(Versioned<V> value: multiPutValues) { Iterator<Versioned<V>> iter = valuesInStorage.iterator(); boolean obsolete = false; // Compare the current version with a set of accepted versions while(iter.hasNext()) { Versioned<V> curr = iter.next(); Occurred occurred = value.getVersion().compare(curr.getVersion()); if(occurred == Occurred.BEFORE) { obsolete = true; break; } else if(occurred == Occurred.AFTER) { iter.remove(); } } if(obsolete) { // add to return value if obsolete obsoleteVals.add(value); } else { // else update the set of accepted versions valuesInStorage.add(value); } } return obsoleteVals; }
java
protected List<Versioned<V>> resolveAndConstructVersionsToPersist(List<Versioned<V>> valuesInStorage, List<Versioned<V>> multiPutValues) { List<Versioned<V>> obsoleteVals = new ArrayList<Versioned<V>>(multiPutValues.size()); // Go over all the values and determine whether the version is // acceptable for(Versioned<V> value: multiPutValues) { Iterator<Versioned<V>> iter = valuesInStorage.iterator(); boolean obsolete = false; // Compare the current version with a set of accepted versions while(iter.hasNext()) { Versioned<V> curr = iter.next(); Occurred occurred = value.getVersion().compare(curr.getVersion()); if(occurred == Occurred.BEFORE) { obsolete = true; break; } else if(occurred == Occurred.AFTER) { iter.remove(); } } if(obsolete) { // add to return value if obsolete obsoleteVals.add(value); } else { // else update the set of accepted versions valuesInStorage.add(value); } } return obsoleteVals; }
[ "protected", "List", "<", "Versioned", "<", "V", ">", ">", "resolveAndConstructVersionsToPersist", "(", "List", "<", "Versioned", "<", "V", ">", ">", "valuesInStorage", ",", "List", "<", "Versioned", "<", "V", ">", ">", "multiPutValues", ")", "{", "List", "<", "Versioned", "<", "V", ">>", "obsoleteVals", "=", "new", "ArrayList", "<", "Versioned", "<", "V", ">", ">", "(", "multiPutValues", ".", "size", "(", ")", ")", ";", "// Go over all the values and determine whether the version is", "// acceptable", "for", "(", "Versioned", "<", "V", ">", "value", ":", "multiPutValues", ")", "{", "Iterator", "<", "Versioned", "<", "V", ">>", "iter", "=", "valuesInStorage", ".", "iterator", "(", ")", ";", "boolean", "obsolete", "=", "false", ";", "// Compare the current version with a set of accepted versions", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Versioned", "<", "V", ">", "curr", "=", "iter", ".", "next", "(", ")", ";", "Occurred", "occurred", "=", "value", ".", "getVersion", "(", ")", ".", "compare", "(", "curr", ".", "getVersion", "(", ")", ")", ";", "if", "(", "occurred", "==", "Occurred", ".", "BEFORE", ")", "{", "obsolete", "=", "true", ";", "break", ";", "}", "else", "if", "(", "occurred", "==", "Occurred", ".", "AFTER", ")", "{", "iter", ".", "remove", "(", ")", ";", "}", "}", "if", "(", "obsolete", ")", "{", "// add to return value if obsolete", "obsoleteVals", ".", "add", "(", "value", ")", ";", "}", "else", "{", "// else update the set of accepted versions", "valuesInStorage", ".", "add", "(", "value", ")", ";", "}", "}", "return", "obsoleteVals", ";", "}" ]
Computes the final list of versions to be stored, on top of what is currently being stored. Final list is valuesInStorage modified in place @param valuesInStorage list of versions currently in storage @param multiPutValues list of new versions being written to storage @return list of versions from multiPutVals that were rejected as obsolete
[ "Computes", "the", "final", "list", "of", "versions", "to", "be", "stored", "on", "top", "of", "what", "is", "currently", "being", "stored", ".", "Final", "list", "is", "valuesInStorage", "modified", "in", "place" ]
a7dbdea58032021361680faacf2782cf981c5332
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/AbstractStorageEngine.java#L93-L122
161,244
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
ScopeImpl.installInternalProvider
private <T> InternalProviderImpl installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider, boolean isBound, boolean isTestProvider) { if (bindingName == null) { if (isBound) { return installUnNamedProvider(mapClassesToUnNamedBoundProviders, clazz, internalProvider, isTestProvider); } else { return installUnNamedProvider(mapClassesToUnNamedUnBoundProviders, clazz, internalProvider, isTestProvider); } } else { return installNamedProvider(mapClassesToNamedBoundProviders, clazz, bindingName, internalProvider, isTestProvider); } }
java
private <T> InternalProviderImpl installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider, boolean isBound, boolean isTestProvider) { if (bindingName == null) { if (isBound) { return installUnNamedProvider(mapClassesToUnNamedBoundProviders, clazz, internalProvider, isTestProvider); } else { return installUnNamedProvider(mapClassesToUnNamedUnBoundProviders, clazz, internalProvider, isTestProvider); } } else { return installNamedProvider(mapClassesToNamedBoundProviders, clazz, bindingName, internalProvider, isTestProvider); } }
[ "private", "<", "T", ">", "InternalProviderImpl", "installInternalProvider", "(", "Class", "<", "T", ">", "clazz", ",", "String", "bindingName", ",", "InternalProviderImpl", "<", "?", "extends", "T", ">", "internalProvider", ",", "boolean", "isBound", ",", "boolean", "isTestProvider", ")", "{", "if", "(", "bindingName", "==", "null", ")", "{", "if", "(", "isBound", ")", "{", "return", "installUnNamedProvider", "(", "mapClassesToUnNamedBoundProviders", ",", "clazz", ",", "internalProvider", ",", "isTestProvider", ")", ";", "}", "else", "{", "return", "installUnNamedProvider", "(", "mapClassesToUnNamedUnBoundProviders", ",", "clazz", ",", "internalProvider", ",", "isTestProvider", ")", ";", "}", "}", "else", "{", "return", "installNamedProvider", "(", "mapClassesToNamedBoundProviders", ",", "clazz", ",", "bindingName", ",", "internalProvider", ",", "isTestProvider", ")", ";", "}", "}" ]
Installs a provider either in the scope or the pool of unbound providers. @param clazz the class for which to install the provider. @param bindingName the name, possibly {@code null}, for which to install the scoped provider. @param internalProvider the internal provider to install. @param isBound whether or not the provider is bound to the scope or belongs to the pool of unbound providers. @param isTestProvider whether or not is a test provider, installed through a Test Module that should override existing providers for the same class-bindingname. @param <T> the type of {@code clazz}. Note to maintainers : we don't use this method directly, both {@link #installBoundProvider(Class, String, InternalProviderImpl, boolean)} and {@link #installUnBoundProvider(Class, String, InternalProviderImpl)} are a facade of this method and make the calls more clear.
[ "Installs", "a", "provider", "either", "in", "the", "scope", "or", "the", "pool", "of", "unbound", "providers", "." ]
54476ca9a5fa48809c15a46e43e38db9ed7e1a75
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/ScopeImpl.java#L479-L490
161,245
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
ScopeImpl.reset
@Override protected void reset() { super.reset(); mapClassesToNamedBoundProviders.clear(); mapClassesToUnNamedBoundProviders.clear(); hasTestModules = false; installBindingForScope(); }
java
@Override protected void reset() { super.reset(); mapClassesToNamedBoundProviders.clear(); mapClassesToUnNamedBoundProviders.clear(); hasTestModules = false; installBindingForScope(); }
[ "@", "Override", "protected", "void", "reset", "(", ")", "{", "super", ".", "reset", "(", ")", ";", "mapClassesToNamedBoundProviders", ".", "clear", "(", ")", ";", "mapClassesToUnNamedBoundProviders", ".", "clear", "(", ")", ";", "hasTestModules", "=", "false", ";", "installBindingForScope", "(", ")", ";", "}" ]
Resets the state of the scope. Useful for automation testing when we want to reset the scope used to install test modules.
[ "Resets", "the", "state", "of", "the", "scope", ".", "Useful", "for", "automation", "testing", "when", "we", "want", "to", "reset", "the", "scope", "used", "to", "install", "test", "modules", "." ]
54476ca9a5fa48809c15a46e43e38db9ed7e1a75
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/ScopeImpl.java#L541-L548
161,246
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/InternalProviderImpl.java
InternalProviderImpl.get
public synchronized T get(Scope scope) { if (instance != null) { return instance; } if (providerInstance != null) { if (isProvidingSingletonInScope) { instance = providerInstance.get(); //gc providerInstance = null; return instance; } return providerInstance.get(); } if (factoryClass != null && factory == null) { factory = FactoryLocator.getFactory(factoryClass); //gc factoryClass = null; } if (factory != null) { if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) { return factory.createInstance(scope); } instance = factory.createInstance(scope); //gc factory = null; return instance; } if (providerFactoryClass != null && providerFactory == null) { providerFactory = FactoryLocator.getFactory(providerFactoryClass); //gc providerFactoryClass = null; } if (providerFactory != null) { if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) { instance = providerFactory.createInstance(scope).get(); //gc providerFactory = null; return instance; } if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) { providerInstance = providerFactory.createInstance(scope); //gc providerFactory = null; return providerInstance.get(); } return providerFactory.createInstance(scope).get(); } throw new IllegalStateException("A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen."); }
java
public synchronized T get(Scope scope) { if (instance != null) { return instance; } if (providerInstance != null) { if (isProvidingSingletonInScope) { instance = providerInstance.get(); //gc providerInstance = null; return instance; } return providerInstance.get(); } if (factoryClass != null && factory == null) { factory = FactoryLocator.getFactory(factoryClass); //gc factoryClass = null; } if (factory != null) { if (!factory.hasScopeAnnotation() && !isCreatingSingletonInScope) { return factory.createInstance(scope); } instance = factory.createInstance(scope); //gc factory = null; return instance; } if (providerFactoryClass != null && providerFactory == null) { providerFactory = FactoryLocator.getFactory(providerFactoryClass); //gc providerFactoryClass = null; } if (providerFactory != null) { if (providerFactory.hasProvidesSingletonInScopeAnnotation() || isProvidingSingletonInScope) { instance = providerFactory.createInstance(scope).get(); //gc providerFactory = null; return instance; } if (providerFactory.hasScopeAnnotation() || isCreatingSingletonInScope) { providerInstance = providerFactory.createInstance(scope); //gc providerFactory = null; return providerInstance.get(); } return providerFactory.createInstance(scope).get(); } throw new IllegalStateException("A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen."); }
[ "public", "synchronized", "T", "get", "(", "Scope", "scope", ")", "{", "if", "(", "instance", "!=", "null", ")", "{", "return", "instance", ";", "}", "if", "(", "providerInstance", "!=", "null", ")", "{", "if", "(", "isProvidingSingletonInScope", ")", "{", "instance", "=", "providerInstance", ".", "get", "(", ")", ";", "//gc", "providerInstance", "=", "null", ";", "return", "instance", ";", "}", "return", "providerInstance", ".", "get", "(", ")", ";", "}", "if", "(", "factoryClass", "!=", "null", "&&", "factory", "==", "null", ")", "{", "factory", "=", "FactoryLocator", ".", "getFactory", "(", "factoryClass", ")", ";", "//gc", "factoryClass", "=", "null", ";", "}", "if", "(", "factory", "!=", "null", ")", "{", "if", "(", "!", "factory", ".", "hasScopeAnnotation", "(", ")", "&&", "!", "isCreatingSingletonInScope", ")", "{", "return", "factory", ".", "createInstance", "(", "scope", ")", ";", "}", "instance", "=", "factory", ".", "createInstance", "(", "scope", ")", ";", "//gc", "factory", "=", "null", ";", "return", "instance", ";", "}", "if", "(", "providerFactoryClass", "!=", "null", "&&", "providerFactory", "==", "null", ")", "{", "providerFactory", "=", "FactoryLocator", ".", "getFactory", "(", "providerFactoryClass", ")", ";", "//gc", "providerFactoryClass", "=", "null", ";", "}", "if", "(", "providerFactory", "!=", "null", ")", "{", "if", "(", "providerFactory", ".", "hasProvidesSingletonInScopeAnnotation", "(", ")", "||", "isProvidingSingletonInScope", ")", "{", "instance", "=", "providerFactory", ".", "createInstance", "(", "scope", ")", ".", "get", "(", ")", ";", "//gc", "providerFactory", "=", "null", ";", "return", "instance", ";", "}", "if", "(", "providerFactory", ".", "hasScopeAnnotation", "(", ")", "||", "isCreatingSingletonInScope", ")", "{", "providerInstance", "=", "providerFactory", ".", "createInstance", "(", "scope", ")", ";", "//gc", "providerFactory", "=", "null", ";", "return", "providerInstance", ".", "get", "(", ")", ";", "}", "return", "providerFactory", ".", "createInstance", "(", "scope", ")", ".", "get", "(", ")", ";", "}", "throw", "new", "IllegalStateException", "(", "\"A provider can only be used with an instance, a provider, a factory or a provider factory. Should not happen.\"", ")", ";", "}" ]
of the unbound provider (
[ "of", "the", "unbound", "provider", "(" ]
54476ca9a5fa48809c15a46e43e38db9ed7e1a75
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/InternalProviderImpl.java#L70-L126
161,247
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/Toothpick.java
Toothpick.closeScope
public static void closeScope(Object name) { //we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree ScopeNode scope = (ScopeNode) MAP_KEY_TO_SCOPE.remove(name); if (scope != null) { ScopeNode parentScope = scope.getParentScope(); if (parentScope != null) { parentScope.removeChild(scope); } else { ConfigurationHolder.configuration.onScopeForestReset(); } removeScopeAndChildrenFromMap(scope); } }
java
public static void closeScope(Object name) { //we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree ScopeNode scope = (ScopeNode) MAP_KEY_TO_SCOPE.remove(name); if (scope != null) { ScopeNode parentScope = scope.getParentScope(); if (parentScope != null) { parentScope.removeChild(scope); } else { ConfigurationHolder.configuration.onScopeForestReset(); } removeScopeAndChildrenFromMap(scope); } }
[ "public", "static", "void", "closeScope", "(", "Object", "name", ")", "{", "//we remove the scope first, so that other threads don't see it, and see the next snapshot of the tree", "ScopeNode", "scope", "=", "(", "ScopeNode", ")", "MAP_KEY_TO_SCOPE", ".", "remove", "(", "name", ")", ";", "if", "(", "scope", "!=", "null", ")", "{", "ScopeNode", "parentScope", "=", "scope", ".", "getParentScope", "(", ")", ";", "if", "(", "parentScope", "!=", "null", ")", "{", "parentScope", ".", "removeChild", "(", "scope", ")", ";", "}", "else", "{", "ConfigurationHolder", ".", "configuration", ".", "onScopeForestReset", "(", ")", ";", "}", "removeScopeAndChildrenFromMap", "(", "scope", ")", ";", "}", "}" ]
Detach a scope from its parent, this will trigger the garbage collection of this scope and it's sub-scopes if they are not referenced outside of Toothpick. @param name the name of the scope to close.
[ "Detach", "a", "scope", "from", "its", "parent", "this", "will", "trigger", "the", "garbage", "collection", "of", "this", "scope", "and", "it", "s", "sub", "-", "scopes", "if", "they", "are", "not", "referenced", "outside", "of", "Toothpick", "." ]
54476ca9a5fa48809c15a46e43e38db9ed7e1a75
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/Toothpick.java#L120-L132
161,248
stephanenicolas/toothpick
toothpick-runtime/src/main/java/toothpick/Toothpick.java
Toothpick.reset
public static void reset() { for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) { closeScope(name); } ConfigurationHolder.configuration.onScopeForestReset(); ScopeImpl.resetUnBoundProviders(); }
java
public static void reset() { for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) { closeScope(name); } ConfigurationHolder.configuration.onScopeForestReset(); ScopeImpl.resetUnBoundProviders(); }
[ "public", "static", "void", "reset", "(", ")", "{", "for", "(", "Object", "name", ":", "Collections", ".", "list", "(", "MAP_KEY_TO_SCOPE", ".", "keys", "(", ")", ")", ")", "{", "closeScope", "(", "name", ")", ";", "}", "ConfigurationHolder", ".", "configuration", ".", "onScopeForestReset", "(", ")", ";", "ScopeImpl", ".", "resetUnBoundProviders", "(", ")", ";", "}" ]
Clears all scopes. Useful for testing and not getting any leak...
[ "Clears", "all", "scopes", ".", "Useful", "for", "testing", "and", "not", "getting", "any", "leak", "..." ]
54476ca9a5fa48809c15a46e43e38db9ed7e1a75
https://github.com/stephanenicolas/toothpick/blob/54476ca9a5fa48809c15a46e43e38db9ed7e1a75/toothpick-runtime/src/main/java/toothpick/Toothpick.java#L137-L143
161,249
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwRevisionProcessorBroker.java
MwRevisionProcessorBroker.notifyMwRevisionProcessors
void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) { if (mwRevision == null || mwRevision.getPageId() <= 0) { return; } for (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) { if (rs.onlyCurrentRevisions == isCurrent && (rs.model == null || mwRevision.getModel().equals( rs.model))) { rs.mwRevisionProcessor.processRevision(mwRevision); } } }
java
void notifyMwRevisionProcessors(MwRevision mwRevision, boolean isCurrent) { if (mwRevision == null || mwRevision.getPageId() <= 0) { return; } for (MwRevisionProcessorBroker.RevisionSubscription rs : this.revisionSubscriptions) { if (rs.onlyCurrentRevisions == isCurrent && (rs.model == null || mwRevision.getModel().equals( rs.model))) { rs.mwRevisionProcessor.processRevision(mwRevision); } } }
[ "void", "notifyMwRevisionProcessors", "(", "MwRevision", "mwRevision", ",", "boolean", "isCurrent", ")", "{", "if", "(", "mwRevision", "==", "null", "||", "mwRevision", ".", "getPageId", "(", ")", "<=", "0", ")", "{", "return", ";", "}", "for", "(", "MwRevisionProcessorBroker", ".", "RevisionSubscription", "rs", ":", "this", ".", "revisionSubscriptions", ")", "{", "if", "(", "rs", ".", "onlyCurrentRevisions", "==", "isCurrent", "&&", "(", "rs", ".", "model", "==", "null", "||", "mwRevision", ".", "getModel", "(", ")", ".", "equals", "(", "rs", ".", "model", ")", ")", ")", "{", "rs", ".", "mwRevisionProcessor", ".", "processRevision", "(", "mwRevision", ")", ";", "}", "}", "}" ]
Notifies all interested subscribers of the given revision. @param mwRevision the given revision @param isCurrent true if this is guaranteed to be the most current revision
[ "Notifies", "all", "interested", "subscribers", "of", "the", "given", "revision", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwRevisionProcessorBroker.java#L175-L186
161,250
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/ItemIdValueImpl.java
ItemIdValueImpl.fromIri
static ItemIdValueImpl fromIri(String iri) { int separator = iri.lastIndexOf('/') + 1; try { return new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid Wikibase entity IRI: " + iri, e); } }
java
static ItemIdValueImpl fromIri(String iri) { int separator = iri.lastIndexOf('/') + 1; try { return new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid Wikibase entity IRI: " + iri, e); } }
[ "static", "ItemIdValueImpl", "fromIri", "(", "String", "iri", ")", "{", "int", "separator", "=", "iri", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ";", "try", "{", "return", "new", "ItemIdValueImpl", "(", "iri", ".", "substring", "(", "separator", ")", ",", "iri", ".", "substring", "(", "0", ",", "separator", ")", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid Wikibase entity IRI: \"", "+", "iri", ",", "e", ")", ";", "}", "}" ]
Parses an item IRI @param iri the item IRI like http://www.wikidata.org/entity/Q42 @throws IllegalArgumentException if the IRI is invalid or does not ends with an item id
[ "Parses", "an", "item", "IRI" ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/ItemIdValueImpl.java#L67-L74
161,251
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwRevisionImpl.java
MwRevisionImpl.resetCurrentRevisionData
void resetCurrentRevisionData() { this.revisionId = NO_REVISION_ID; // impossible as an id in MediaWiki this.parentRevisionId = NO_REVISION_ID; this.text = null; this.comment = null; this.format = null; this.timeStamp = null; this.model = null; }
java
void resetCurrentRevisionData() { this.revisionId = NO_REVISION_ID; // impossible as an id in MediaWiki this.parentRevisionId = NO_REVISION_ID; this.text = null; this.comment = null; this.format = null; this.timeStamp = null; this.model = null; }
[ "void", "resetCurrentRevisionData", "(", ")", "{", "this", ".", "revisionId", "=", "NO_REVISION_ID", ";", "// impossible as an id in MediaWiki", "this", ".", "parentRevisionId", "=", "NO_REVISION_ID", ";", "this", ".", "text", "=", "null", ";", "this", ".", "comment", "=", "null", ";", "this", ".", "format", "=", "null", ";", "this", ".", "timeStamp", "=", "null", ";", "this", ".", "model", "=", "null", ";", "}" ]
Resets all member fields that hold information about the revision that is currently being processed.
[ "Resets", "all", "member", "fields", "that", "hold", "information", "about", "the", "revision", "that", "is", "currently", "being", "processed", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwRevisionImpl.java#L168-L176
161,252
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/TermedStatementDocumentImpl.java
TermedStatementDocumentImpl.toTerm
private static MonolingualTextValue toTerm(MonolingualTextValue term) { return term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText()); }
java
private static MonolingualTextValue toTerm(MonolingualTextValue term) { return term instanceof TermImpl ? term : new TermImpl(term.getLanguageCode(), term.getText()); }
[ "private", "static", "MonolingualTextValue", "toTerm", "(", "MonolingualTextValue", "term", ")", "{", "return", "term", "instanceof", "TermImpl", "?", "term", ":", "new", "TermImpl", "(", "term", ".", "getLanguageCode", "(", ")", ",", "term", ".", "getText", "(", ")", ")", ";", "}" ]
We need to make sure the terms are of the right type, otherwise they will not be serialized correctly.
[ "We", "need", "to", "make", "sure", "the", "terms", "are", "of", "the", "right", "type", "otherwise", "they", "will", "not", "be", "serialized", "correctly", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/TermedStatementDocumentImpl.java#L219-L221
161,253
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.writePropertyData
private void writePropertyData() { try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("properties.csv"))) { out.println("Id" + ",Label" + ",Description" + ",URL" + ",Datatype" + ",Uses in statements" + ",Items with such statements" + ",Uses in statements with qualifiers" + ",Uses in qualifiers" + ",Uses in references" + ",Uses total" + ",Related properties"); List<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>( this.propertyRecords.entrySet()); Collections.sort(list, new UsageRecordComparator()); for (Entry<PropertyIdValue, PropertyRecord> entry : list) { printPropertyRecord(out, entry.getValue(), entry.getKey()); } } catch (IOException e) { e.printStackTrace(); } }
java
private void writePropertyData() { try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("properties.csv"))) { out.println("Id" + ",Label" + ",Description" + ",URL" + ",Datatype" + ",Uses in statements" + ",Items with such statements" + ",Uses in statements with qualifiers" + ",Uses in qualifiers" + ",Uses in references" + ",Uses total" + ",Related properties"); List<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>( this.propertyRecords.entrySet()); Collections.sort(list, new UsageRecordComparator()); for (Entry<PropertyIdValue, PropertyRecord> entry : list) { printPropertyRecord(out, entry.getValue(), entry.getKey()); } } catch (IOException e) { e.printStackTrace(); } }
[ "private", "void", "writePropertyData", "(", ")", "{", "try", "(", "PrintStream", "out", "=", "new", "PrintStream", "(", "ExampleHelpers", ".", "openExampleFileOuputStream", "(", "\"properties.csv\"", ")", ")", ")", "{", "out", ".", "println", "(", "\"Id\"", "+", "\",Label\"", "+", "\",Description\"", "+", "\",URL\"", "+", "\",Datatype\"", "+", "\",Uses in statements\"", "+", "\",Items with such statements\"", "+", "\",Uses in statements with qualifiers\"", "+", "\",Uses in qualifiers\"", "+", "\",Uses in references\"", "+", "\",Uses total\"", "+", "\",Related properties\"", ")", ";", "List", "<", "Entry", "<", "PropertyIdValue", ",", "PropertyRecord", ">", ">", "list", "=", "new", "ArrayList", "<", "Entry", "<", "PropertyIdValue", ",", "PropertyRecord", ">", ">", "(", "this", ".", "propertyRecords", ".", "entrySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "list", ",", "new", "UsageRecordComparator", "(", ")", ")", ";", "for", "(", "Entry", "<", "PropertyIdValue", ",", "PropertyRecord", ">", "entry", ":", "list", ")", "{", "printPropertyRecord", "(", "out", ",", "entry", ".", "getValue", "(", ")", ",", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Writes the data collected about properties to a file.
[ "Writes", "the", "data", "collected", "about", "properties", "to", "a", "file", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L482-L502
161,254
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.writeClassData
private void writeClassData() { try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("classes.csv"))) { out.println("Id" + ",Label" + ",Description" + ",URL" + ",Image" + ",Number of direct instances" + ",Number of direct subclasses" + ",Direct superclasses" + ",All superclasses" + ",Related properties"); List<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>( this.classRecords.entrySet()); Collections.sort(list, new ClassUsageRecordComparator()); for (Entry<EntityIdValue, ClassRecord> entry : list) { if (entry.getValue().itemCount > 0 || entry.getValue().subclassCount > 0) { printClassRecord(out, entry.getValue(), entry.getKey()); } } } catch (IOException e) { e.printStackTrace(); } }
java
private void writeClassData() { try (PrintStream out = new PrintStream( ExampleHelpers.openExampleFileOuputStream("classes.csv"))) { out.println("Id" + ",Label" + ",Description" + ",URL" + ",Image" + ",Number of direct instances" + ",Number of direct subclasses" + ",Direct superclasses" + ",All superclasses" + ",Related properties"); List<Entry<EntityIdValue, ClassRecord>> list = new ArrayList<>( this.classRecords.entrySet()); Collections.sort(list, new ClassUsageRecordComparator()); for (Entry<EntityIdValue, ClassRecord> entry : list) { if (entry.getValue().itemCount > 0 || entry.getValue().subclassCount > 0) { printClassRecord(out, entry.getValue(), entry.getKey()); } } } catch (IOException e) { e.printStackTrace(); } }
[ "private", "void", "writeClassData", "(", ")", "{", "try", "(", "PrintStream", "out", "=", "new", "PrintStream", "(", "ExampleHelpers", ".", "openExampleFileOuputStream", "(", "\"classes.csv\"", ")", ")", ")", "{", "out", ".", "println", "(", "\"Id\"", "+", "\",Label\"", "+", "\",Description\"", "+", "\",URL\"", "+", "\",Image\"", "+", "\",Number of direct instances\"", "+", "\",Number of direct subclasses\"", "+", "\",Direct superclasses\"", "+", "\",All superclasses\"", "+", "\",Related properties\"", ")", ";", "List", "<", "Entry", "<", "EntityIdValue", ",", "ClassRecord", ">", ">", "list", "=", "new", "ArrayList", "<>", "(", "this", ".", "classRecords", ".", "entrySet", "(", ")", ")", ";", "Collections", ".", "sort", "(", "list", ",", "new", "ClassUsageRecordComparator", "(", ")", ")", ";", "for", "(", "Entry", "<", "EntityIdValue", ",", "ClassRecord", ">", "entry", ":", "list", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", ".", "itemCount", ">", "0", "||", "entry", ".", "getValue", "(", ")", ".", "subclassCount", ">", "0", ")", "{", "printClassRecord", "(", "out", ",", "entry", ".", "getValue", "(", ")", ",", "entry", ".", "getKey", "(", ")", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Writes the data collected about classes to a file.
[ "Writes", "the", "data", "collected", "about", "classes", "to", "a", "file", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L507-L529
161,255
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.printClassRecord
private void printClassRecord(PrintStream out, ClassRecord classRecord, EntityIdValue entityIdValue) { printTerms(out, classRecord.itemDocument, entityIdValue, "\"" + getClassLabel(entityIdValue) + "\""); printImage(out, classRecord.itemDocument); out.print("," + classRecord.itemCount + "," + classRecord.subclassCount); printClassList(out, classRecord.superClasses); HashSet<EntityIdValue> superClasses = new HashSet<>(); for (EntityIdValue superClass : classRecord.superClasses) { addSuperClasses(superClass, superClasses); } printClassList(out, superClasses); printRelatedProperties(out, classRecord); out.println(""); }
java
private void printClassRecord(PrintStream out, ClassRecord classRecord, EntityIdValue entityIdValue) { printTerms(out, classRecord.itemDocument, entityIdValue, "\"" + getClassLabel(entityIdValue) + "\""); printImage(out, classRecord.itemDocument); out.print("," + classRecord.itemCount + "," + classRecord.subclassCount); printClassList(out, classRecord.superClasses); HashSet<EntityIdValue> superClasses = new HashSet<>(); for (EntityIdValue superClass : classRecord.superClasses) { addSuperClasses(superClass, superClasses); } printClassList(out, superClasses); printRelatedProperties(out, classRecord); out.println(""); }
[ "private", "void", "printClassRecord", "(", "PrintStream", "out", ",", "ClassRecord", "classRecord", ",", "EntityIdValue", "entityIdValue", ")", "{", "printTerms", "(", "out", ",", "classRecord", ".", "itemDocument", ",", "entityIdValue", ",", "\"\\\"\"", "+", "getClassLabel", "(", "entityIdValue", ")", "+", "\"\\\"\"", ")", ";", "printImage", "(", "out", ",", "classRecord", ".", "itemDocument", ")", ";", "out", ".", "print", "(", "\",\"", "+", "classRecord", ".", "itemCount", "+", "\",\"", "+", "classRecord", ".", "subclassCount", ")", ";", "printClassList", "(", "out", ",", "classRecord", ".", "superClasses", ")", ";", "HashSet", "<", "EntityIdValue", ">", "superClasses", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "EntityIdValue", "superClass", ":", "classRecord", ".", "superClasses", ")", "{", "addSuperClasses", "(", "superClass", ",", "superClasses", ")", ";", "}", "printClassList", "(", "out", ",", "superClasses", ")", ";", "printRelatedProperties", "(", "out", ",", "classRecord", ")", ";", "out", ".", "println", "(", "\"\"", ")", ";", "}" ]
Prints the data for a single class to the given stream. This will be a single line in CSV. @param out the output to write to @param classRecord the class record to write @param entityIdValue the item id that this class record belongs to
[ "Prints", "the", "data", "for", "a", "single", "class", "to", "the", "given", "stream", ".", "This", "will", "be", "a", "single", "line", "in", "CSV", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L542-L562
161,256
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.printImage
private void printImage(PrintStream out, ItemDocument itemDocument) { String imageFile = null; if (itemDocument != null) { for (StatementGroup sg : itemDocument.getStatementGroups()) { boolean isImage = "P18".equals(sg.getProperty().getId()); if (!isImage) { continue; } for (Statement s : sg) { if (s.getMainSnak() instanceof ValueSnak) { Value value = s.getMainSnak().getValue(); if (value instanceof StringValue) { imageFile = ((StringValue) value).getString(); break; } } } if (imageFile != null) { break; } } } if (imageFile == null) { out.print(",\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\""); } else { try { String imageFileEncoded; imageFileEncoded = URLEncoder.encode( imageFile.replace(" ", "_"), "utf-8"); // Keep special title symbols unescaped: imageFileEncoded = imageFileEncoded.replace("%3A", ":") .replace("%2F", "/"); out.print("," + csvStringEscape("http://commons.wikimedia.org/w/thumb.php?f=" + imageFileEncoded) + "&w=50"); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Your JRE does not support UTF-8 encoding. Srsly?!", e); } } }
java
private void printImage(PrintStream out, ItemDocument itemDocument) { String imageFile = null; if (itemDocument != null) { for (StatementGroup sg : itemDocument.getStatementGroups()) { boolean isImage = "P18".equals(sg.getProperty().getId()); if (!isImage) { continue; } for (Statement s : sg) { if (s.getMainSnak() instanceof ValueSnak) { Value value = s.getMainSnak().getValue(); if (value instanceof StringValue) { imageFile = ((StringValue) value).getString(); break; } } } if (imageFile != null) { break; } } } if (imageFile == null) { out.print(",\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\""); } else { try { String imageFileEncoded; imageFileEncoded = URLEncoder.encode( imageFile.replace(" ", "_"), "utf-8"); // Keep special title symbols unescaped: imageFileEncoded = imageFileEncoded.replace("%3A", ":") .replace("%2F", "/"); out.print("," + csvStringEscape("http://commons.wikimedia.org/w/thumb.php?f=" + imageFileEncoded) + "&w=50"); } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Your JRE does not support UTF-8 encoding. Srsly?!", e); } } }
[ "private", "void", "printImage", "(", "PrintStream", "out", ",", "ItemDocument", "itemDocument", ")", "{", "String", "imageFile", "=", "null", ";", "if", "(", "itemDocument", "!=", "null", ")", "{", "for", "(", "StatementGroup", "sg", ":", "itemDocument", ".", "getStatementGroups", "(", ")", ")", "{", "boolean", "isImage", "=", "\"P18\"", ".", "equals", "(", "sg", ".", "getProperty", "(", ")", ".", "getId", "(", ")", ")", ";", "if", "(", "!", "isImage", ")", "{", "continue", ";", "}", "for", "(", "Statement", "s", ":", "sg", ")", "{", "if", "(", "s", ".", "getMainSnak", "(", ")", "instanceof", "ValueSnak", ")", "{", "Value", "value", "=", "s", ".", "getMainSnak", "(", ")", ".", "getValue", "(", ")", ";", "if", "(", "value", "instanceof", "StringValue", ")", "{", "imageFile", "=", "(", "(", "StringValue", ")", "value", ")", ".", "getString", "(", ")", ";", "break", ";", "}", "}", "}", "if", "(", "imageFile", "!=", "null", ")", "{", "break", ";", "}", "}", "}", "if", "(", "imageFile", "==", "null", ")", "{", "out", ".", "print", "(", "\",\\\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\\\"\"", ")", ";", "}", "else", "{", "try", "{", "String", "imageFileEncoded", ";", "imageFileEncoded", "=", "URLEncoder", ".", "encode", "(", "imageFile", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", ",", "\"utf-8\"", ")", ";", "// Keep special title symbols unescaped:", "imageFileEncoded", "=", "imageFileEncoded", ".", "replace", "(", "\"%3A\"", ",", "\":\"", ")", ".", "replace", "(", "\"%2F\"", ",", "\"/\"", ")", ";", "out", ".", "print", "(", "\",\"", "+", "csvStringEscape", "(", "\"http://commons.wikimedia.org/w/thumb.php?f=\"", "+", "imageFileEncoded", ")", "+", "\"&w=50\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Your JRE does not support UTF-8 encoding. Srsly?!\"", ",", "e", ")", ";", "}", "}", "}" ]
Prints the URL of a thumbnail for the given item document to the output, or a default image if no image is given for the item. @param out the output to write to @param itemDocument the document that may provide the image information
[ "Prints", "the", "URL", "of", "a", "thumbnail", "for", "the", "given", "item", "document", "to", "the", "output", "or", "a", "default", "image", "if", "no", "image", "is", "given", "for", "the", "item", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L659-L701
161,257
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.printPropertyRecord
private void printPropertyRecord(PrintStream out, PropertyRecord propertyRecord, PropertyIdValue propertyIdValue) { printTerms(out, propertyRecord.propertyDocument, propertyIdValue, null); String datatype = "Unknown"; if (propertyRecord.propertyDocument != null) { datatype = getDatatypeLabel(propertyRecord.propertyDocument .getDatatype()); } out.print("," + datatype + "," + propertyRecord.statementCount + "," + propertyRecord.itemCount + "," + propertyRecord.statementWithQualifierCount + "," + propertyRecord.qualifierCount + "," + propertyRecord.referenceCount + "," + (propertyRecord.statementCount + propertyRecord.qualifierCount + propertyRecord.referenceCount)); printRelatedProperties(out, propertyRecord); out.println(""); }
java
private void printPropertyRecord(PrintStream out, PropertyRecord propertyRecord, PropertyIdValue propertyIdValue) { printTerms(out, propertyRecord.propertyDocument, propertyIdValue, null); String datatype = "Unknown"; if (propertyRecord.propertyDocument != null) { datatype = getDatatypeLabel(propertyRecord.propertyDocument .getDatatype()); } out.print("," + datatype + "," + propertyRecord.statementCount + "," + propertyRecord.itemCount + "," + propertyRecord.statementWithQualifierCount + "," + propertyRecord.qualifierCount + "," + propertyRecord.referenceCount + "," + (propertyRecord.statementCount + propertyRecord.qualifierCount + propertyRecord.referenceCount)); printRelatedProperties(out, propertyRecord); out.println(""); }
[ "private", "void", "printPropertyRecord", "(", "PrintStream", "out", ",", "PropertyRecord", "propertyRecord", ",", "PropertyIdValue", "propertyIdValue", ")", "{", "printTerms", "(", "out", ",", "propertyRecord", ".", "propertyDocument", ",", "propertyIdValue", ",", "null", ")", ";", "String", "datatype", "=", "\"Unknown\"", ";", "if", "(", "propertyRecord", ".", "propertyDocument", "!=", "null", ")", "{", "datatype", "=", "getDatatypeLabel", "(", "propertyRecord", ".", "propertyDocument", ".", "getDatatype", "(", ")", ")", ";", "}", "out", ".", "print", "(", "\",\"", "+", "datatype", "+", "\",\"", "+", "propertyRecord", ".", "statementCount", "+", "\",\"", "+", "propertyRecord", ".", "itemCount", "+", "\",\"", "+", "propertyRecord", ".", "statementWithQualifierCount", "+", "\",\"", "+", "propertyRecord", ".", "qualifierCount", "+", "\",\"", "+", "propertyRecord", ".", "referenceCount", "+", "\",\"", "+", "(", "propertyRecord", ".", "statementCount", "+", "propertyRecord", ".", "qualifierCount", "+", "propertyRecord", ".", "referenceCount", ")", ")", ";", "printRelatedProperties", "(", "out", ",", "propertyRecord", ")", ";", "out", ".", "println", "(", "\"\"", ")", ";", "}" ]
Prints the data of one property to the given output. This will be a single line in CSV. @param out the output to write to @param propertyRecord the data to write @param propertyIdValue the property that the data refers to
[ "Prints", "the", "data", "of", "one", "property", "to", "the", "given", "output", ".", "This", "will", "be", "a", "single", "line", "in", "CSV", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L714-L744
161,258
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.getDatatypeLabel
private String getDatatypeLabel(DatatypeIdValue datatype) { if (datatype.getIri() == null) { // TODO should be redundant once the // JSON parsing works return "Unknown"; } switch (datatype.getIri()) { case DatatypeIdValue.DT_COMMONS_MEDIA: return "Commons media"; case DatatypeIdValue.DT_GLOBE_COORDINATES: return "Globe coordinates"; case DatatypeIdValue.DT_ITEM: return "Item"; case DatatypeIdValue.DT_QUANTITY: return "Quantity"; case DatatypeIdValue.DT_STRING: return "String"; case DatatypeIdValue.DT_TIME: return "Time"; case DatatypeIdValue.DT_URL: return "URL"; case DatatypeIdValue.DT_PROPERTY: return "Property"; case DatatypeIdValue.DT_EXTERNAL_ID: return "External identifier"; case DatatypeIdValue.DT_MATH: return "Math"; case DatatypeIdValue.DT_MONOLINGUAL_TEXT: return "Monolingual Text"; default: throw new RuntimeException("Unknown datatype " + datatype.getIri()); } }
java
private String getDatatypeLabel(DatatypeIdValue datatype) { if (datatype.getIri() == null) { // TODO should be redundant once the // JSON parsing works return "Unknown"; } switch (datatype.getIri()) { case DatatypeIdValue.DT_COMMONS_MEDIA: return "Commons media"; case DatatypeIdValue.DT_GLOBE_COORDINATES: return "Globe coordinates"; case DatatypeIdValue.DT_ITEM: return "Item"; case DatatypeIdValue.DT_QUANTITY: return "Quantity"; case DatatypeIdValue.DT_STRING: return "String"; case DatatypeIdValue.DT_TIME: return "Time"; case DatatypeIdValue.DT_URL: return "URL"; case DatatypeIdValue.DT_PROPERTY: return "Property"; case DatatypeIdValue.DT_EXTERNAL_ID: return "External identifier"; case DatatypeIdValue.DT_MATH: return "Math"; case DatatypeIdValue.DT_MONOLINGUAL_TEXT: return "Monolingual Text"; default: throw new RuntimeException("Unknown datatype " + datatype.getIri()); } }
[ "private", "String", "getDatatypeLabel", "(", "DatatypeIdValue", "datatype", ")", "{", "if", "(", "datatype", ".", "getIri", "(", ")", "==", "null", ")", "{", "// TODO should be redundant once the", "// JSON parsing works", "return", "\"Unknown\"", ";", "}", "switch", "(", "datatype", ".", "getIri", "(", ")", ")", "{", "case", "DatatypeIdValue", ".", "DT_COMMONS_MEDIA", ":", "return", "\"Commons media\"", ";", "case", "DatatypeIdValue", ".", "DT_GLOBE_COORDINATES", ":", "return", "\"Globe coordinates\"", ";", "case", "DatatypeIdValue", ".", "DT_ITEM", ":", "return", "\"Item\"", ";", "case", "DatatypeIdValue", ".", "DT_QUANTITY", ":", "return", "\"Quantity\"", ";", "case", "DatatypeIdValue", ".", "DT_STRING", ":", "return", "\"String\"", ";", "case", "DatatypeIdValue", ".", "DT_TIME", ":", "return", "\"Time\"", ";", "case", "DatatypeIdValue", ".", "DT_URL", ":", "return", "\"URL\"", ";", "case", "DatatypeIdValue", ".", "DT_PROPERTY", ":", "return", "\"Property\"", ";", "case", "DatatypeIdValue", ".", "DT_EXTERNAL_ID", ":", "return", "\"External identifier\"", ";", "case", "DatatypeIdValue", ".", "DT_MATH", ":", "return", "\"Math\"", ";", "case", "DatatypeIdValue", ".", "DT_MONOLINGUAL_TEXT", ":", "return", "\"Monolingual Text\"", ";", "default", ":", "throw", "new", "RuntimeException", "(", "\"Unknown datatype \"", "+", "datatype", ".", "getIri", "(", ")", ")", ";", "}", "}" ]
Returns an English label for a given datatype. @param datatype the datatype to label @return the label
[ "Returns", "an", "English", "label", "for", "a", "given", "datatype", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L753-L785
161,259
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.getPropertyLabel
private String getPropertyLabel(PropertyIdValue propertyIdValue) { PropertyRecord propertyRecord = this.propertyRecords .get(propertyIdValue); if (propertyRecord == null || propertyRecord.propertyDocument == null) { return propertyIdValue.getId(); } else { return getLabel(propertyIdValue, propertyRecord.propertyDocument); } }
java
private String getPropertyLabel(PropertyIdValue propertyIdValue) { PropertyRecord propertyRecord = this.propertyRecords .get(propertyIdValue); if (propertyRecord == null || propertyRecord.propertyDocument == null) { return propertyIdValue.getId(); } else { return getLabel(propertyIdValue, propertyRecord.propertyDocument); } }
[ "private", "String", "getPropertyLabel", "(", "PropertyIdValue", "propertyIdValue", ")", "{", "PropertyRecord", "propertyRecord", "=", "this", ".", "propertyRecords", ".", "get", "(", "propertyIdValue", ")", ";", "if", "(", "propertyRecord", "==", "null", "||", "propertyRecord", ".", "propertyDocument", "==", "null", ")", "{", "return", "propertyIdValue", ".", "getId", "(", ")", ";", "}", "else", "{", "return", "getLabel", "(", "propertyIdValue", ",", "propertyRecord", ".", "propertyDocument", ")", ";", "}", "}" ]
Returns a string that should be used as a label for the given property. @param propertyIdValue the property to label @return the label
[ "Returns", "a", "string", "that", "should", "be", "used", "as", "a", "label", "for", "the", "given", "property", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L853-L861
161,260
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java
ClassPropertyUsageAnalyzer.getClassLabel
private String getClassLabel(EntityIdValue entityIdValue) { ClassRecord classRecord = this.classRecords.get(entityIdValue); String label; if (classRecord == null || classRecord.itemDocument == null) { label = entityIdValue.getId(); } else { label = getLabel(entityIdValue, classRecord.itemDocument); } EntityIdValue labelOwner = this.labels.get(label); if (labelOwner == null) { this.labels.put(label, entityIdValue); return label; } else if (labelOwner.equals(entityIdValue)) { return label; } else { return label + " (" + entityIdValue.getId() + ")"; } }
java
private String getClassLabel(EntityIdValue entityIdValue) { ClassRecord classRecord = this.classRecords.get(entityIdValue); String label; if (classRecord == null || classRecord.itemDocument == null) { label = entityIdValue.getId(); } else { label = getLabel(entityIdValue, classRecord.itemDocument); } EntityIdValue labelOwner = this.labels.get(label); if (labelOwner == null) { this.labels.put(label, entityIdValue); return label; } else if (labelOwner.equals(entityIdValue)) { return label; } else { return label + " (" + entityIdValue.getId() + ")"; } }
[ "private", "String", "getClassLabel", "(", "EntityIdValue", "entityIdValue", ")", "{", "ClassRecord", "classRecord", "=", "this", ".", "classRecords", ".", "get", "(", "entityIdValue", ")", ";", "String", "label", ";", "if", "(", "classRecord", "==", "null", "||", "classRecord", ".", "itemDocument", "==", "null", ")", "{", "label", "=", "entityIdValue", ".", "getId", "(", ")", ";", "}", "else", "{", "label", "=", "getLabel", "(", "entityIdValue", ",", "classRecord", ".", "itemDocument", ")", ";", "}", "EntityIdValue", "labelOwner", "=", "this", ".", "labels", ".", "get", "(", "label", ")", ";", "if", "(", "labelOwner", "==", "null", ")", "{", "this", ".", "labels", ".", "put", "(", "label", ",", "entityIdValue", ")", ";", "return", "label", ";", "}", "else", "if", "(", "labelOwner", ".", "equals", "(", "entityIdValue", ")", ")", "{", "return", "label", ";", "}", "else", "{", "return", "label", "+", "\" (\"", "+", "entityIdValue", ".", "getId", "(", ")", "+", "\")\"", ";", "}", "}" ]
Returns a string that should be used as a label for the given item. The method also ensures that each label is used for only one class. Other classes with the same label will have their QID added for disambiguation. @param entityIdValue the item to label @return the label
[ "Returns", "a", "string", "that", "should", "be", "used", "as", "a", "label", "for", "the", "given", "item", ".", "The", "method", "also", "ensures", "that", "each", "label", "is", "used", "for", "only", "one", "class", ".", "Other", "classes", "with", "the", "same", "label", "will", "have", "their", "QID", "added", "for", "disambiguation", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/ClassPropertyUsageAnalyzer.java#L872-L890
161,261
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/values/TimeValueConverter.java
TimeValueConverter.writeValue
@Override public void writeValue(TimeValue value, Resource resource) throws RDFHandlerException { this.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE, RdfWriter.WB_TIME_VALUE); this.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME, TimeValueConverter.getTimeLiteral(value, this.rdfWriter)); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_PRECISION, value.getPrecision()); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_TIMEZONE, value.getTimezoneOffset()); this.rdfWriter.writeTripleUriObject(resource, RdfWriter.WB_TIME_CALENDAR_MODEL, value.getPreferredCalendarModel()); }
java
@Override public void writeValue(TimeValue value, Resource resource) throws RDFHandlerException { this.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE, RdfWriter.WB_TIME_VALUE); this.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME, TimeValueConverter.getTimeLiteral(value, this.rdfWriter)); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_PRECISION, value.getPrecision()); this.rdfWriter.writeTripleIntegerObject(resource, RdfWriter.WB_TIME_TIMEZONE, value.getTimezoneOffset()); this.rdfWriter.writeTripleUriObject(resource, RdfWriter.WB_TIME_CALENDAR_MODEL, value.getPreferredCalendarModel()); }
[ "@", "Override", "public", "void", "writeValue", "(", "TimeValue", "value", ",", "Resource", "resource", ")", "throws", "RDFHandlerException", "{", "this", ".", "rdfWriter", ".", "writeTripleValueObject", "(", "resource", ",", "RdfWriter", ".", "RDF_TYPE", ",", "RdfWriter", ".", "WB_TIME_VALUE", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleValueObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME", ",", "TimeValueConverter", ".", "getTimeLiteral", "(", "value", ",", "this", ".", "rdfWriter", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleIntegerObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_PRECISION", ",", "value", ".", "getPrecision", "(", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleIntegerObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_TIMEZONE", ",", "value", ".", "getTimezoneOffset", "(", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "resource", ",", "RdfWriter", ".", "WB_TIME_CALENDAR_MODEL", ",", "value", ".", "getPreferredCalendarModel", "(", ")", ")", ";", "}" ]
Write the auxiliary RDF data for encoding the given value. @param value the value to write @param resource the (subject) URI to use to represent this value in RDF @throws RDFHandlerException
[ "Write", "the", "auxiliary", "RDF", "data", "for", "encoding", "the", "given", "value", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/values/TimeValueConverter.java#L78-L95
161,262
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java
SetLabelsForNumbersBot.main
public static void main(String[] args) throws LoginFailedException, IOException, MediaWikiApiErrorException { ExampleHelpers.configureLogging(); printDocumentation(); SetLabelsForNumbersBot bot = new SetLabelsForNumbersBot(); ExampleHelpers.processEntitiesFromWikidataDump(bot); bot.finish(); System.out.println("*** Done."); }
java
public static void main(String[] args) throws LoginFailedException, IOException, MediaWikiApiErrorException { ExampleHelpers.configureLogging(); printDocumentation(); SetLabelsForNumbersBot bot = new SetLabelsForNumbersBot(); ExampleHelpers.processEntitiesFromWikidataDump(bot); bot.finish(); System.out.println("*** Done."); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "LoginFailedException", ",", "IOException", ",", "MediaWikiApiErrorException", "{", "ExampleHelpers", ".", "configureLogging", "(", ")", ";", "printDocumentation", "(", ")", ";", "SetLabelsForNumbersBot", "bot", "=", "new", "SetLabelsForNumbersBot", "(", ")", ";", "ExampleHelpers", ".", "processEntitiesFromWikidataDump", "(", "bot", ")", ";", "bot", ".", "finish", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"*** Done.\"", ")", ";", "}" ]
Main method to run the bot. @param args @throws LoginFailedException @throws IOException @throws MediaWikiApiErrorException
[ "Main", "method", "to", "run", "the", "bot", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java#L134-L144
161,263
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java
SetLabelsForNumbersBot.addLabelForNumbers
protected void addLabelForNumbers(ItemIdValue itemIdValue) { String qid = itemIdValue.getId(); try { // Fetch the online version of the item to make sure we edit the // current version: ItemDocument currentItemDocument = (ItemDocument) dataFetcher .getEntityDocument(qid); if (currentItemDocument == null) { System.out.println("*** " + qid + " could not be fetched. Maybe it has been deleted."); return; } // Check if we still have exactly one numeric value: QuantityValue number = currentItemDocument .findStatementQuantityValue("P1181"); if (number == null) { System.out.println("*** No unique numeric value for " + qid); return; } // Check if the item is in a known numeric class: if (!currentItemDocument.hasStatementValue("P31", numberClasses)) { System.out .println("*** " + qid + " is not in a known class of integer numbers. Skipping."); return; } // Check if the value is integer and build label string: String numberString; try { BigInteger intValue = number.getNumericValue() .toBigIntegerExact(); numberString = intValue.toString(); } catch (ArithmeticException e) { System.out.println("*** Numeric value for " + qid + " is not an integer: " + number.getNumericValue()); return; } // Construct data to write: ItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder .forItemId(itemIdValue).withRevisionId( currentItemDocument.getRevisionId()); ArrayList<String> languages = new ArrayList<>( arabicNumeralLanguages.length); for (int i = 0; i < arabicNumeralLanguages.length; i++) { if (!currentItemDocument.getLabels().containsKey( arabicNumeralLanguages[i])) { itemDocumentBuilder.withLabel(numberString, arabicNumeralLanguages[i]); languages.add(arabicNumeralLanguages[i]); } } if (languages.size() == 0) { System.out.println("*** Labels already complete for " + qid); return; } logEntityModification(currentItemDocument.getEntityId(), numberString, languages); dataEditor.editItemDocument(itemDocumentBuilder.build(), false, "Set labels to numeric value (Task MB1)"); } catch (MediaWikiApiErrorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
java
protected void addLabelForNumbers(ItemIdValue itemIdValue) { String qid = itemIdValue.getId(); try { // Fetch the online version of the item to make sure we edit the // current version: ItemDocument currentItemDocument = (ItemDocument) dataFetcher .getEntityDocument(qid); if (currentItemDocument == null) { System.out.println("*** " + qid + " could not be fetched. Maybe it has been deleted."); return; } // Check if we still have exactly one numeric value: QuantityValue number = currentItemDocument .findStatementQuantityValue("P1181"); if (number == null) { System.out.println("*** No unique numeric value for " + qid); return; } // Check if the item is in a known numeric class: if (!currentItemDocument.hasStatementValue("P31", numberClasses)) { System.out .println("*** " + qid + " is not in a known class of integer numbers. Skipping."); return; } // Check if the value is integer and build label string: String numberString; try { BigInteger intValue = number.getNumericValue() .toBigIntegerExact(); numberString = intValue.toString(); } catch (ArithmeticException e) { System.out.println("*** Numeric value for " + qid + " is not an integer: " + number.getNumericValue()); return; } // Construct data to write: ItemDocumentBuilder itemDocumentBuilder = ItemDocumentBuilder .forItemId(itemIdValue).withRevisionId( currentItemDocument.getRevisionId()); ArrayList<String> languages = new ArrayList<>( arabicNumeralLanguages.length); for (int i = 0; i < arabicNumeralLanguages.length; i++) { if (!currentItemDocument.getLabels().containsKey( arabicNumeralLanguages[i])) { itemDocumentBuilder.withLabel(numberString, arabicNumeralLanguages[i]); languages.add(arabicNumeralLanguages[i]); } } if (languages.size() == 0) { System.out.println("*** Labels already complete for " + qid); return; } logEntityModification(currentItemDocument.getEntityId(), numberString, languages); dataEditor.editItemDocument(itemDocumentBuilder.build(), false, "Set labels to numeric value (Task MB1)"); } catch (MediaWikiApiErrorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
[ "protected", "void", "addLabelForNumbers", "(", "ItemIdValue", "itemIdValue", ")", "{", "String", "qid", "=", "itemIdValue", ".", "getId", "(", ")", ";", "try", "{", "// Fetch the online version of the item to make sure we edit the", "// current version:", "ItemDocument", "currentItemDocument", "=", "(", "ItemDocument", ")", "dataFetcher", ".", "getEntityDocument", "(", "qid", ")", ";", "if", "(", "currentItemDocument", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** \"", "+", "qid", "+", "\" could not be fetched. Maybe it has been deleted.\"", ")", ";", "return", ";", "}", "// Check if we still have exactly one numeric value:", "QuantityValue", "number", "=", "currentItemDocument", ".", "findStatementQuantityValue", "(", "\"P1181\"", ")", ";", "if", "(", "number", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** No unique numeric value for \"", "+", "qid", ")", ";", "return", ";", "}", "// Check if the item is in a known numeric class:", "if", "(", "!", "currentItemDocument", ".", "hasStatementValue", "(", "\"P31\"", ",", "numberClasses", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** \"", "+", "qid", "+", "\" is not in a known class of integer numbers. Skipping.\"", ")", ";", "return", ";", "}", "// Check if the value is integer and build label string:", "String", "numberString", ";", "try", "{", "BigInteger", "intValue", "=", "number", ".", "getNumericValue", "(", ")", ".", "toBigIntegerExact", "(", ")", ";", "numberString", "=", "intValue", ".", "toString", "(", ")", ";", "}", "catch", "(", "ArithmeticException", "e", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** Numeric value for \"", "+", "qid", "+", "\" is not an integer: \"", "+", "number", ".", "getNumericValue", "(", ")", ")", ";", "return", ";", "}", "// Construct data to write:", "ItemDocumentBuilder", "itemDocumentBuilder", "=", "ItemDocumentBuilder", ".", "forItemId", "(", "itemIdValue", ")", ".", "withRevisionId", "(", "currentItemDocument", ".", "getRevisionId", "(", ")", ")", ";", "ArrayList", "<", "String", ">", "languages", "=", "new", "ArrayList", "<>", "(", "arabicNumeralLanguages", ".", "length", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arabicNumeralLanguages", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "currentItemDocument", ".", "getLabels", "(", ")", ".", "containsKey", "(", "arabicNumeralLanguages", "[", "i", "]", ")", ")", "{", "itemDocumentBuilder", ".", "withLabel", "(", "numberString", ",", "arabicNumeralLanguages", "[", "i", "]", ")", ";", "languages", ".", "add", "(", "arabicNumeralLanguages", "[", "i", "]", ")", ";", "}", "}", "if", "(", "languages", ".", "size", "(", ")", "==", "0", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** Labels already complete for \"", "+", "qid", ")", ";", "return", ";", "}", "logEntityModification", "(", "currentItemDocument", ".", "getEntityId", "(", ")", ",", "numberString", ",", "languages", ")", ";", "dataEditor", ".", "editItemDocument", "(", "itemDocumentBuilder", ".", "build", "(", ")", ",", "false", ",", "\"Set labels to numeric value (Task MB1)\"", ")", ";", "}", "catch", "(", "MediaWikiApiErrorException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Fetches the current online data for the given item, and adds numerical labels if necessary. @param itemIdValue the id of the document to inspect
[ "Fetches", "the", "current", "online", "data", "for", "the", "given", "item", "and", "adds", "numerical", "labels", "if", "necessary", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java#L220-L294
161,264
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java
SetLabelsForNumbersBot.lacksSomeLanguage
protected boolean lacksSomeLanguage(ItemDocument itemDocument) { for (int i = 0; i < arabicNumeralLanguages.length; i++) { if (!itemDocument.getLabels() .containsKey(arabicNumeralLanguages[i])) { return true; } } return false; }
java
protected boolean lacksSomeLanguage(ItemDocument itemDocument) { for (int i = 0; i < arabicNumeralLanguages.length; i++) { if (!itemDocument.getLabels() .containsKey(arabicNumeralLanguages[i])) { return true; } } return false; }
[ "protected", "boolean", "lacksSomeLanguage", "(", "ItemDocument", "itemDocument", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arabicNumeralLanguages", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "itemDocument", ".", "getLabels", "(", ")", ".", "containsKey", "(", "arabicNumeralLanguages", "[", "i", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if the given item document lacks a label for at least one of the languages covered. @param itemDocument @return true if some label is missing
[ "Returns", "true", "if", "the", "given", "item", "document", "lacks", "a", "label", "for", "at", "least", "one", "of", "the", "languages", "covered", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/bots/SetLabelsForNumbersBot.java#L303-L311
161,265
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/LifeExpectancyProcessor.java
LifeExpectancyProcessor.writeFinalResults
public void writeFinalResults() { printStatus(); try (PrintStream out = new PrintStream( ExampleHelpers .openExampleFileOuputStream("life-expectancies.csv"))) { for (int i = 0; i < lifeSpans.length; i++) { if (peopleCount[i] != 0) { out.println(i + "," + (double) lifeSpans[i] / peopleCount[i] + "," + peopleCount[i]); } } } catch (IOException e) { e.printStackTrace(); } }
java
public void writeFinalResults() { printStatus(); try (PrintStream out = new PrintStream( ExampleHelpers .openExampleFileOuputStream("life-expectancies.csv"))) { for (int i = 0; i < lifeSpans.length; i++) { if (peopleCount[i] != 0) { out.println(i + "," + (double) lifeSpans[i] / peopleCount[i] + "," + peopleCount[i]); } } } catch (IOException e) { e.printStackTrace(); } }
[ "public", "void", "writeFinalResults", "(", ")", "{", "printStatus", "(", ")", ";", "try", "(", "PrintStream", "out", "=", "new", "PrintStream", "(", "ExampleHelpers", ".", "openExampleFileOuputStream", "(", "\"life-expectancies.csv\"", ")", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lifeSpans", ".", "length", ";", "i", "++", ")", "{", "if", "(", "peopleCount", "[", "i", "]", "!=", "0", ")", "{", "out", ".", "println", "(", "i", "+", "\",\"", "+", "(", "double", ")", "lifeSpans", "[", "i", "]", "/", "peopleCount", "[", "i", "]", "+", "\",\"", "+", "peopleCount", "[", "i", "]", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Writes the results of the processing to a file.
[ "Writes", "the", "results", "of", "the", "processing", "to", "a", "file", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/LifeExpectancyProcessor.java#L94-L110
161,266
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.createDirectory
private static void createDirectory(Path path) throws IOException { try { Files.createDirectory(path); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(path)) { throw e; } } }
java
private static void createDirectory(Path path) throws IOException { try { Files.createDirectory(path); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(path)) { throw e; } } }
[ "private", "static", "void", "createDirectory", "(", "Path", "path", ")", "throws", "IOException", "{", "try", "{", "Files", ".", "createDirectory", "(", "path", ")", ";", "}", "catch", "(", "FileAlreadyExistsException", "e", ")", "{", "if", "(", "!", "Files", ".", "isDirectory", "(", "path", ")", ")", "{", "throw", "e", ";", "}", "}", "}" ]
Create a directory at the given path if it does not exist yet. @param path the path to the directory @throws IOException if it was not possible to create a directory at the given path
[ "Create", "a", "directory", "at", "the", "given", "path", "if", "it", "does", "not", "exist", "yet", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L392-L400
161,267
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.openResultFileOuputStream
public static FileOutputStream openResultFileOuputStream( Path resultDirectory, String filename) throws IOException { Path filePath = resultDirectory.resolve(filename); return new FileOutputStream(filePath.toFile()); }
java
public static FileOutputStream openResultFileOuputStream( Path resultDirectory, String filename) throws IOException { Path filePath = resultDirectory.resolve(filename); return new FileOutputStream(filePath.toFile()); }
[ "public", "static", "FileOutputStream", "openResultFileOuputStream", "(", "Path", "resultDirectory", ",", "String", "filename", ")", "throws", "IOException", "{", "Path", "filePath", "=", "resultDirectory", ".", "resolve", "(", "filename", ")", ";", "return", "new", "FileOutputStream", "(", "filePath", ".", "toFile", "(", ")", ")", ";", "}" ]
Opens a new FileOutputStream for a file of the given name in the given result directory. Any file of this name that exists already will be replaced. The caller is responsible for eventually closing the stream. @param resultDirectory the path to the result directory @param filename the name of the file to write to @return FileOutputStream for the file @throws IOException if the file or example output directory could not be created
[ "Opens", "a", "new", "FileOutputStream", "for", "a", "file", "of", "the", "given", "name", "in", "the", "given", "result", "directory", ".", "Any", "file", "of", "this", "name", "that", "exists", "already", "will", "be", "replaced", ".", "The", "caller", "is", "responsible", "for", "eventually", "closing", "the", "stream", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L415-L419
161,268
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.addSuperClasses
private void addSuperClasses(Integer directSuperClass, ClassRecord subClassRecord) { if (subClassRecord.superClasses.contains(directSuperClass)) { return; } subClassRecord.superClasses.add(directSuperClass); ClassRecord superClassRecord = getClassRecord(directSuperClass); if (superClassRecord == null) { return; } for (Integer superClass : superClassRecord.directSuperClasses) { addSuperClasses(superClass, subClassRecord); } }
java
private void addSuperClasses(Integer directSuperClass, ClassRecord subClassRecord) { if (subClassRecord.superClasses.contains(directSuperClass)) { return; } subClassRecord.superClasses.add(directSuperClass); ClassRecord superClassRecord = getClassRecord(directSuperClass); if (superClassRecord == null) { return; } for (Integer superClass : superClassRecord.directSuperClasses) { addSuperClasses(superClass, subClassRecord); } }
[ "private", "void", "addSuperClasses", "(", "Integer", "directSuperClass", ",", "ClassRecord", "subClassRecord", ")", "{", "if", "(", "subClassRecord", ".", "superClasses", ".", "contains", "(", "directSuperClass", ")", ")", "{", "return", ";", "}", "subClassRecord", ".", "superClasses", ".", "add", "(", "directSuperClass", ")", ";", "ClassRecord", "superClassRecord", "=", "getClassRecord", "(", "directSuperClass", ")", ";", "if", "(", "superClassRecord", "==", "null", ")", "{", "return", ";", "}", "for", "(", "Integer", "superClass", ":", "superClassRecord", ".", "directSuperClasses", ")", "{", "addSuperClasses", "(", "superClass", ",", "subClassRecord", ")", ";", "}", "}" ]
Recursively add indirect subclasses to a class record. @param directSuperClass the superclass to add (together with its own superclasses) @param subClassRecord the subclass to add to
[ "Recursively", "add", "indirect", "subclasses", "to", "a", "class", "record", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L681-L695
161,269
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.getNumId
private Integer getNumId(String idString, boolean isUri) { String numString; if (isUri) { if (!idString.startsWith("http://www.wikidata.org/entity/")) { return 0; } numString = idString.substring("http://www.wikidata.org/entity/Q" .length()); } else { numString = idString.substring(1); } return Integer.parseInt(numString); }
java
private Integer getNumId(String idString, boolean isUri) { String numString; if (isUri) { if (!idString.startsWith("http://www.wikidata.org/entity/")) { return 0; } numString = idString.substring("http://www.wikidata.org/entity/Q" .length()); } else { numString = idString.substring(1); } return Integer.parseInt(numString); }
[ "private", "Integer", "getNumId", "(", "String", "idString", ",", "boolean", "isUri", ")", "{", "String", "numString", ";", "if", "(", "isUri", ")", "{", "if", "(", "!", "idString", ".", "startsWith", "(", "\"http://www.wikidata.org/entity/\"", ")", ")", "{", "return", "0", ";", "}", "numString", "=", "idString", ".", "substring", "(", "\"http://www.wikidata.org/entity/Q\"", ".", "length", "(", ")", ")", ";", "}", "else", "{", "numString", "=", "idString", ".", "substring", "(", "1", ")", ";", "}", "return", "Integer", ".", "parseInt", "(", "numString", ")", ";", "}" ]
Extracts a numeric id from a string, which can be either a Wikidata entity URI or a short entity or property id. @param idString @param isUri @return numeric id, or 0 if there was an error
[ "Extracts", "a", "numeric", "id", "from", "a", "string", "which", "can", "be", "either", "a", "Wikidata", "entity", "URI", "or", "a", "short", "entity", "or", "property", "id", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L705-L717
161,270
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.countCooccurringProperties
private void countCooccurringProperties( StatementDocument statementDocument, UsageRecord usageRecord, PropertyIdValue thisPropertyIdValue) { for (StatementGroup sg : statementDocument.getStatementGroups()) { if (!sg.getProperty().equals(thisPropertyIdValue)) { Integer propertyId = getNumId(sg.getProperty().getId(), false); if (!usageRecord.propertyCoCounts.containsKey(propertyId)) { usageRecord.propertyCoCounts.put(propertyId, 1); } else { usageRecord.propertyCoCounts.put(propertyId, usageRecord.propertyCoCounts.get(propertyId) + 1); } } } }
java
private void countCooccurringProperties( StatementDocument statementDocument, UsageRecord usageRecord, PropertyIdValue thisPropertyIdValue) { for (StatementGroup sg : statementDocument.getStatementGroups()) { if (!sg.getProperty().equals(thisPropertyIdValue)) { Integer propertyId = getNumId(sg.getProperty().getId(), false); if (!usageRecord.propertyCoCounts.containsKey(propertyId)) { usageRecord.propertyCoCounts.put(propertyId, 1); } else { usageRecord.propertyCoCounts.put(propertyId, usageRecord.propertyCoCounts.get(propertyId) + 1); } } } }
[ "private", "void", "countCooccurringProperties", "(", "StatementDocument", "statementDocument", ",", "UsageRecord", "usageRecord", ",", "PropertyIdValue", "thisPropertyIdValue", ")", "{", "for", "(", "StatementGroup", "sg", ":", "statementDocument", ".", "getStatementGroups", "(", ")", ")", "{", "if", "(", "!", "sg", ".", "getProperty", "(", ")", ".", "equals", "(", "thisPropertyIdValue", ")", ")", "{", "Integer", "propertyId", "=", "getNumId", "(", "sg", ".", "getProperty", "(", ")", ".", "getId", "(", ")", ",", "false", ")", ";", "if", "(", "!", "usageRecord", ".", "propertyCoCounts", ".", "containsKey", "(", "propertyId", ")", ")", "{", "usageRecord", ".", "propertyCoCounts", ".", "put", "(", "propertyId", ",", "1", ")", ";", "}", "else", "{", "usageRecord", ".", "propertyCoCounts", ".", "put", "(", "propertyId", ",", "usageRecord", ".", "propertyCoCounts", ".", "get", "(", "propertyId", ")", "+", "1", ")", ";", "}", "}", "}", "}" ]
Counts each property for which there is a statement in the given item document, ignoring the property thisPropertyIdValue to avoid properties counting themselves. @param statementDocument @param usageRecord @param thisPropertyIdValue
[ "Counts", "each", "property", "for", "which", "there", "is", "a", "statement", "in", "the", "given", "item", "document", "ignoring", "the", "property", "thisPropertyIdValue", "to", "avoid", "properties", "counting", "themselves", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L763-L777
161,271
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.runSparqlQuery
private InputStream runSparqlQuery(String query) throws IOException { try { String queryString = "query=" + URLEncoder.encode(query, "UTF-8") + "&format=json"; URL url = new URL("https://query.wikidata.org/sparql?" + queryString); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod("GET"); return connection.getInputStream(); } catch (UnsupportedEncodingException | MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }
java
private InputStream runSparqlQuery(String query) throws IOException { try { String queryString = "query=" + URLEncoder.encode(query, "UTF-8") + "&format=json"; URL url = new URL("https://query.wikidata.org/sparql?" + queryString); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod("GET"); return connection.getInputStream(); } catch (UnsupportedEncodingException | MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } }
[ "private", "InputStream", "runSparqlQuery", "(", "String", "query", ")", "throws", "IOException", "{", "try", "{", "String", "queryString", "=", "\"query=\"", "+", "URLEncoder", ".", "encode", "(", "query", ",", "\"UTF-8\"", ")", "+", "\"&format=json\"", ";", "URL", "url", "=", "new", "URL", "(", "\"https://query.wikidata.org/sparql?\"", "+", "queryString", ")", ";", "HttpURLConnection", "connection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "connection", ".", "setRequestMethod", "(", "\"GET\"", ")", ";", "return", "connection", ".", "getInputStream", "(", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "|", "MalformedURLException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Executes a given SPARQL query and returns a stream with the result in JSON format. @param query @return @throws IOException
[ "Executes", "a", "given", "SPARQL", "query", "and", "returns", "a", "stream", "with", "the", "result", "in", "JSON", "format", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L787-L801
161,272
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.writePropertyData
private void writePropertyData() { try (PrintStream out = new PrintStream(openResultFileOuputStream( resultDirectory, "properties.json"))) { out.println("{"); int count = 0; for (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords .entrySet()) { if (count > 0) { out.println(","); } out.print("\"" + propertyEntry.getKey() + "\":"); mapper.writeValue(out, propertyEntry.getValue()); count++; } out.println("\n}"); System.out.println(" Serialized information for " + count + " properties."); } catch (IOException e) { e.printStackTrace(); } }
java
private void writePropertyData() { try (PrintStream out = new PrintStream(openResultFileOuputStream( resultDirectory, "properties.json"))) { out.println("{"); int count = 0; for (Entry<Integer, PropertyRecord> propertyEntry : this.propertyRecords .entrySet()) { if (count > 0) { out.println(","); } out.print("\"" + propertyEntry.getKey() + "\":"); mapper.writeValue(out, propertyEntry.getValue()); count++; } out.println("\n}"); System.out.println(" Serialized information for " + count + " properties."); } catch (IOException e) { e.printStackTrace(); } }
[ "private", "void", "writePropertyData", "(", ")", "{", "try", "(", "PrintStream", "out", "=", "new", "PrintStream", "(", "openResultFileOuputStream", "(", "resultDirectory", ",", "\"properties.json\"", ")", ")", ")", "{", "out", ".", "println", "(", "\"{\"", ")", ";", "int", "count", "=", "0", ";", "for", "(", "Entry", "<", "Integer", ",", "PropertyRecord", ">", "propertyEntry", ":", "this", ".", "propertyRecords", ".", "entrySet", "(", ")", ")", "{", "if", "(", "count", ">", "0", ")", "{", "out", ".", "println", "(", "\",\"", ")", ";", "}", "out", ".", "print", "(", "\"\\\"\"", "+", "propertyEntry", ".", "getKey", "(", ")", "+", "\"\\\":\"", ")", ";", "mapper", ".", "writeValue", "(", "out", ",", "propertyEntry", ".", "getValue", "(", ")", ")", ";", "count", "++", ";", "}", "out", ".", "println", "(", "\"\\n}\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" Serialized information for \"", "+", "count", "+", "\" properties.\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Writes all data that was collected about properties to a json file.
[ "Writes", "all", "data", "that", "was", "collected", "about", "properties", "to", "a", "json", "file", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L816-L838
161,273
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java
SchemaUsageAnalyzer.writeClassData
private void writeClassData() { try (PrintStream out = new PrintStream(openResultFileOuputStream( resultDirectory, "classes.json"))) { out.println("{"); // Add direct subclass information: for (Entry<Integer, ClassRecord> classEntry : this.classRecords .entrySet()) { if (classEntry.getValue().subclassCount == 0 && classEntry.getValue().itemCount == 0) { continue; } for (Integer superClass : classEntry.getValue().directSuperClasses) { this.classRecords.get(superClass).nonemptyDirectSubclasses .add(classEntry.getKey().toString()); } } int count = 0; int countNoLabel = 0; for (Entry<Integer, ClassRecord> classEntry : this.classRecords .entrySet()) { if (classEntry.getValue().subclassCount == 0 && classEntry.getValue().itemCount == 0) { continue; } if (classEntry.getValue().label == null) { countNoLabel++; } if (count > 0) { out.println(","); } out.print("\"" + classEntry.getKey() + "\":"); mapper.writeValue(out, classEntry.getValue()); count++; } out.println("\n}"); System.out.println(" Serialized information for " + count + " class items."); System.out.println(" -- class items with missing label: " + countNoLabel); } catch (IOException e) { e.printStackTrace(); } }
java
private void writeClassData() { try (PrintStream out = new PrintStream(openResultFileOuputStream( resultDirectory, "classes.json"))) { out.println("{"); // Add direct subclass information: for (Entry<Integer, ClassRecord> classEntry : this.classRecords .entrySet()) { if (classEntry.getValue().subclassCount == 0 && classEntry.getValue().itemCount == 0) { continue; } for (Integer superClass : classEntry.getValue().directSuperClasses) { this.classRecords.get(superClass).nonemptyDirectSubclasses .add(classEntry.getKey().toString()); } } int count = 0; int countNoLabel = 0; for (Entry<Integer, ClassRecord> classEntry : this.classRecords .entrySet()) { if (classEntry.getValue().subclassCount == 0 && classEntry.getValue().itemCount == 0) { continue; } if (classEntry.getValue().label == null) { countNoLabel++; } if (count > 0) { out.println(","); } out.print("\"" + classEntry.getKey() + "\":"); mapper.writeValue(out, classEntry.getValue()); count++; } out.println("\n}"); System.out.println(" Serialized information for " + count + " class items."); System.out.println(" -- class items with missing label: " + countNoLabel); } catch (IOException e) { e.printStackTrace(); } }
[ "private", "void", "writeClassData", "(", ")", "{", "try", "(", "PrintStream", "out", "=", "new", "PrintStream", "(", "openResultFileOuputStream", "(", "resultDirectory", ",", "\"classes.json\"", ")", ")", ")", "{", "out", ".", "println", "(", "\"{\"", ")", ";", "// Add direct subclass information:", "for", "(", "Entry", "<", "Integer", ",", "ClassRecord", ">", "classEntry", ":", "this", ".", "classRecords", ".", "entrySet", "(", ")", ")", "{", "if", "(", "classEntry", ".", "getValue", "(", ")", ".", "subclassCount", "==", "0", "&&", "classEntry", ".", "getValue", "(", ")", ".", "itemCount", "==", "0", ")", "{", "continue", ";", "}", "for", "(", "Integer", "superClass", ":", "classEntry", ".", "getValue", "(", ")", ".", "directSuperClasses", ")", "{", "this", ".", "classRecords", ".", "get", "(", "superClass", ")", ".", "nonemptyDirectSubclasses", ".", "add", "(", "classEntry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "int", "count", "=", "0", ";", "int", "countNoLabel", "=", "0", ";", "for", "(", "Entry", "<", "Integer", ",", "ClassRecord", ">", "classEntry", ":", "this", ".", "classRecords", ".", "entrySet", "(", ")", ")", "{", "if", "(", "classEntry", ".", "getValue", "(", ")", ".", "subclassCount", "==", "0", "&&", "classEntry", ".", "getValue", "(", ")", ".", "itemCount", "==", "0", ")", "{", "continue", ";", "}", "if", "(", "classEntry", ".", "getValue", "(", ")", ".", "label", "==", "null", ")", "{", "countNoLabel", "++", ";", "}", "if", "(", "count", ">", "0", ")", "{", "out", ".", "println", "(", "\",\"", ")", ";", "}", "out", ".", "print", "(", "\"\\\"\"", "+", "classEntry", ".", "getKey", "(", ")", "+", "\"\\\":\"", ")", ";", "mapper", ".", "writeValue", "(", "out", ",", "classEntry", ".", "getValue", "(", ")", ")", ";", "count", "++", ";", "}", "out", ".", "println", "(", "\"\\n}\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" Serialized information for \"", "+", "count", "+", "\" class items.\"", ")", ";", "System", ".", "out", ".", "println", "(", "\" -- class items with missing label: \"", "+", "countNoLabel", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Writes all data that was collected about classes to a json file.
[ "Writes", "all", "data", "that", "was", "collected", "about", "classes", "to", "a", "json", "file", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/SchemaUsageAnalyzer.java#L861-L908
161,274
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/DataFormatter.java
DataFormatter.formatTimeISO8601
public static String formatTimeISO8601(TimeValue value) { StringBuilder builder = new StringBuilder(); DecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR); DecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER); if (value.getYear() > 0) { builder.append("+"); } builder.append(yearForm.format(value.getYear())); builder.append("-"); builder.append(timeForm.format(value.getMonth())); builder.append("-"); builder.append(timeForm.format(value.getDay())); builder.append("T"); builder.append(timeForm.format(value.getHour())); builder.append(":"); builder.append(timeForm.format(value.getMinute())); builder.append(":"); builder.append(timeForm.format(value.getSecond())); builder.append("Z"); return builder.toString(); }
java
public static String formatTimeISO8601(TimeValue value) { StringBuilder builder = new StringBuilder(); DecimalFormat yearForm = new DecimalFormat(FORMAT_YEAR); DecimalFormat timeForm = new DecimalFormat(FORMAT_OTHER); if (value.getYear() > 0) { builder.append("+"); } builder.append(yearForm.format(value.getYear())); builder.append("-"); builder.append(timeForm.format(value.getMonth())); builder.append("-"); builder.append(timeForm.format(value.getDay())); builder.append("T"); builder.append(timeForm.format(value.getHour())); builder.append(":"); builder.append(timeForm.format(value.getMinute())); builder.append(":"); builder.append(timeForm.format(value.getSecond())); builder.append("Z"); return builder.toString(); }
[ "public", "static", "String", "formatTimeISO8601", "(", "TimeValue", "value", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "DecimalFormat", "yearForm", "=", "new", "DecimalFormat", "(", "FORMAT_YEAR", ")", ";", "DecimalFormat", "timeForm", "=", "new", "DecimalFormat", "(", "FORMAT_OTHER", ")", ";", "if", "(", "value", ".", "getYear", "(", ")", ">", "0", ")", "{", "builder", ".", "append", "(", "\"+\"", ")", ";", "}", "builder", ".", "append", "(", "yearForm", ".", "format", "(", "value", ".", "getYear", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"-\"", ")", ";", "builder", ".", "append", "(", "timeForm", ".", "format", "(", "value", ".", "getMonth", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"-\"", ")", ";", "builder", ".", "append", "(", "timeForm", ".", "format", "(", "value", ".", "getDay", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"T\"", ")", ";", "builder", ".", "append", "(", "timeForm", ".", "format", "(", "value", ".", "getHour", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\":\"", ")", ";", "builder", ".", "append", "(", "timeForm", ".", "format", "(", "value", ".", "getMinute", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\":\"", ")", ";", "builder", ".", "append", "(", "timeForm", ".", "format", "(", "value", ".", "getSecond", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"Z\"", ")", ";", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Returns a representation of the date from the value attributes as ISO 8601 encoding. @param value @return ISO 8601 value (String)
[ "Returns", "a", "representation", "of", "the", "date", "from", "the", "value", "attributes", "as", "ISO", "8601", "encoding", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/DataFormatter.java#L47-L67
161,275
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/DataFormatter.java
DataFormatter.formatBigDecimal
public static String formatBigDecimal(BigDecimal number) { if (number.signum() != -1) { return "+" + number.toString(); } else { return number.toString(); } }
java
public static String formatBigDecimal(BigDecimal number) { if (number.signum() != -1) { return "+" + number.toString(); } else { return number.toString(); } }
[ "public", "static", "String", "formatBigDecimal", "(", "BigDecimal", "number", ")", "{", "if", "(", "number", ".", "signum", "(", ")", "!=", "-", "1", ")", "{", "return", "\"+\"", "+", "number", ".", "toString", "(", ")", ";", "}", "else", "{", "return", "number", ".", "toString", "(", ")", ";", "}", "}" ]
Returns a signed string representation of the given number. @param number @return String for BigDecimal value
[ "Returns", "a", "signed", "string", "representation", "of", "the", "given", "number", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/DataFormatter.java#L75-L81
161,276
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwLocalDumpFile.java
MwLocalDumpFile.guessDumpContentType
private static DumpContentType guessDumpContentType(String fileName) { String lcDumpName = fileName.toLowerCase(); if (lcDumpName.contains(".json.gz")) { return DumpContentType.JSON; } else if (lcDumpName.contains(".json.bz2")) { return DumpContentType.JSON; } else if (lcDumpName.contains(".sql.gz")) { return DumpContentType.SITES; } else if (lcDumpName.contains(".xml.bz2")) { if (lcDumpName.contains("daily")) { return DumpContentType.DAILY; } else if (lcDumpName.contains("current")) { return DumpContentType.CURRENT; } else { return DumpContentType.FULL; } } else { logger.warn("Could not guess type of the dump file \"" + fileName + "\". Defaulting to json.gz."); return DumpContentType.JSON; } }
java
private static DumpContentType guessDumpContentType(String fileName) { String lcDumpName = fileName.toLowerCase(); if (lcDumpName.contains(".json.gz")) { return DumpContentType.JSON; } else if (lcDumpName.contains(".json.bz2")) { return DumpContentType.JSON; } else if (lcDumpName.contains(".sql.gz")) { return DumpContentType.SITES; } else if (lcDumpName.contains(".xml.bz2")) { if (lcDumpName.contains("daily")) { return DumpContentType.DAILY; } else if (lcDumpName.contains("current")) { return DumpContentType.CURRENT; } else { return DumpContentType.FULL; } } else { logger.warn("Could not guess type of the dump file \"" + fileName + "\". Defaulting to json.gz."); return DumpContentType.JSON; } }
[ "private", "static", "DumpContentType", "guessDumpContentType", "(", "String", "fileName", ")", "{", "String", "lcDumpName", "=", "fileName", ".", "toLowerCase", "(", ")", ";", "if", "(", "lcDumpName", ".", "contains", "(", "\".json.gz\"", ")", ")", "{", "return", "DumpContentType", ".", "JSON", ";", "}", "else", "if", "(", "lcDumpName", ".", "contains", "(", "\".json.bz2\"", ")", ")", "{", "return", "DumpContentType", ".", "JSON", ";", "}", "else", "if", "(", "lcDumpName", ".", "contains", "(", "\".sql.gz\"", ")", ")", "{", "return", "DumpContentType", ".", "SITES", ";", "}", "else", "if", "(", "lcDumpName", ".", "contains", "(", "\".xml.bz2\"", ")", ")", "{", "if", "(", "lcDumpName", ".", "contains", "(", "\"daily\"", ")", ")", "{", "return", "DumpContentType", ".", "DAILY", ";", "}", "else", "if", "(", "lcDumpName", ".", "contains", "(", "\"current\"", ")", ")", "{", "return", "DumpContentType", ".", "CURRENT", ";", "}", "else", "{", "return", "DumpContentType", ".", "FULL", ";", "}", "}", "else", "{", "logger", ".", "warn", "(", "\"Could not guess type of the dump file \\\"\"", "+", "fileName", "+", "\"\\\". Defaulting to json.gz.\"", ")", ";", "return", "DumpContentType", ".", "JSON", ";", "}", "}" ]
Guess the type of the given dump from its filename. @param fileName @return dump type, defaulting to JSON if no type was found
[ "Guess", "the", "type", "of", "the", "given", "dump", "from", "its", "filename", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwLocalDumpFile.java#L229-L250
161,277
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwLocalDumpFile.java
MwLocalDumpFile.guessDumpDate
private static String guessDumpDate(String fileName) { Pattern p = Pattern.compile("([0-9]{8})"); Matcher m = p.matcher(fileName); if (m.find()) { return m.group(1); } else { logger.info("Could not guess date of the dump file \"" + fileName + "\". Defaulting to YYYYMMDD."); return "YYYYMMDD"; } }
java
private static String guessDumpDate(String fileName) { Pattern p = Pattern.compile("([0-9]{8})"); Matcher m = p.matcher(fileName); if (m.find()) { return m.group(1); } else { logger.info("Could not guess date of the dump file \"" + fileName + "\". Defaulting to YYYYMMDD."); return "YYYYMMDD"; } }
[ "private", "static", "String", "guessDumpDate", "(", "String", "fileName", ")", "{", "Pattern", "p", "=", "Pattern", ".", "compile", "(", "\"([0-9]{8})\"", ")", ";", "Matcher", "m", "=", "p", ".", "matcher", "(", "fileName", ")", ";", "if", "(", "m", ".", "find", "(", ")", ")", "{", "return", "m", ".", "group", "(", "1", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\"Could not guess date of the dump file \\\"\"", "+", "fileName", "+", "\"\\\". Defaulting to YYYYMMDD.\"", ")", ";", "return", "\"YYYYMMDD\"", ";", "}", "}" ]
Guess the date of the dump from the given dump file name. @param fileName @return 8-digit date stamp or YYYYMMDD if none was found
[ "Guess", "the", "date", "of", "the", "dump", "from", "the", "given", "dump", "file", "name", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwLocalDumpFile.java#L258-L269
161,278
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RankBuffer.java
RankBuffer.add
public void add(StatementRank rank, Resource subject) { if (this.bestRank == rank) { subjects.add(subject); } else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) { //We found a preferred statement subjects.clear(); bestRank = StatementRank.PREFERRED; subjects.add(subject); } }
java
public void add(StatementRank rank, Resource subject) { if (this.bestRank == rank) { subjects.add(subject); } else if(bestRank == StatementRank.NORMAL && rank == StatementRank.PREFERRED) { //We found a preferred statement subjects.clear(); bestRank = StatementRank.PREFERRED; subjects.add(subject); } }
[ "public", "void", "add", "(", "StatementRank", "rank", ",", "Resource", "subject", ")", "{", "if", "(", "this", ".", "bestRank", "==", "rank", ")", "{", "subjects", ".", "add", "(", "subject", ")", ";", "}", "else", "if", "(", "bestRank", "==", "StatementRank", ".", "NORMAL", "&&", "rank", "==", "StatementRank", ".", "PREFERRED", ")", "{", "//We found a preferred statement", "subjects", ".", "clear", "(", ")", ";", "bestRank", "=", "StatementRank", ".", "PREFERRED", ";", "subjects", ".", "add", "(", "subject", ")", ";", "}", "}" ]
Adds a Statement. @param rank rank of the statement @param subject rdf resource that refers to the statement
[ "Adds", "a", "Statement", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RankBuffer.java#L67-L76
161,279
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java
SnakRdfConverter.writeAuxiliaryTriples
public void writeAuxiliaryTriples() throws RDFHandlerException { for (PropertyRestriction pr : this.someValuesQueue) { writeSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject); } this.someValuesQueue.clear(); this.valueRdfConverter.writeAuxiliaryTriples(); }
java
public void writeAuxiliaryTriples() throws RDFHandlerException { for (PropertyRestriction pr : this.someValuesQueue) { writeSomeValueRestriction(pr.propertyUri, pr.rangeUri, pr.subject); } this.someValuesQueue.clear(); this.valueRdfConverter.writeAuxiliaryTriples(); }
[ "public", "void", "writeAuxiliaryTriples", "(", ")", "throws", "RDFHandlerException", "{", "for", "(", "PropertyRestriction", "pr", ":", "this", ".", "someValuesQueue", ")", "{", "writeSomeValueRestriction", "(", "pr", ".", "propertyUri", ",", "pr", ".", "rangeUri", ",", "pr", ".", "subject", ")", ";", "}", "this", ".", "someValuesQueue", ".", "clear", "(", ")", ";", "this", ".", "valueRdfConverter", ".", "writeAuxiliaryTriples", "(", ")", ";", "}" ]
Writes all auxiliary triples that have been buffered recently. This includes OWL property restrictions but it also includes any auxiliary triples required by complex values that were used in snaks. @throws RDFHandlerException if there was a problem writing the RDF triples
[ "Writes", "all", "auxiliary", "triples", "that", "have", "been", "buffered", "recently", ".", "This", "includes", "OWL", "property", "restrictions", "but", "it", "also", "includes", "any", "auxiliary", "triples", "required", "by", "complex", "values", "that", "were", "used", "in", "snaks", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java#L231-L238
161,280
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java
SnakRdfConverter.writeSomeValueRestriction
void writeSomeValueRestriction(String propertyUri, String rangeUri, Resource bnode) throws RDFHandlerException { this.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE, RdfWriter.OWL_RESTRICTION); this.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY, propertyUri); this.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_SOME_VALUES_FROM, rangeUri); }
java
void writeSomeValueRestriction(String propertyUri, String rangeUri, Resource bnode) throws RDFHandlerException { this.rdfWriter.writeTripleValueObject(bnode, RdfWriter.RDF_TYPE, RdfWriter.OWL_RESTRICTION); this.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_ON_PROPERTY, propertyUri); this.rdfWriter.writeTripleUriObject(bnode, RdfWriter.OWL_SOME_VALUES_FROM, rangeUri); }
[ "void", "writeSomeValueRestriction", "(", "String", "propertyUri", ",", "String", "rangeUri", ",", "Resource", "bnode", ")", "throws", "RDFHandlerException", "{", "this", ".", "rdfWriter", ".", "writeTripleValueObject", "(", "bnode", ",", "RdfWriter", ".", "RDF_TYPE", ",", "RdfWriter", ".", "OWL_RESTRICTION", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "bnode", ",", "RdfWriter", ".", "OWL_ON_PROPERTY", ",", "propertyUri", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "bnode", ",", "RdfWriter", ".", "OWL_SOME_VALUES_FROM", ",", "rangeUri", ")", ";", "}" ]
Writes a buffered some-value restriction. @param propertyUri URI of the property to which the restriction applies @param rangeUri URI of the class or datatype to which the restriction applies @param bnode blank node representing the restriction @throws RDFHandlerException if there was a problem writing the RDF triples
[ "Writes", "a", "buffered", "some", "-", "value", "restriction", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java#L252-L260
161,281
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java
SnakRdfConverter.getRangeUri
String getRangeUri(PropertyIdValue propertyIdValue) { String datatype = this.propertyRegister .getPropertyType(propertyIdValue); if (datatype == null) return null; switch (datatype) { case DatatypeIdValue.DT_MONOLINGUAL_TEXT: this.rdfConversionBuffer.addDatatypeProperty(propertyIdValue); return Vocabulary.RDF_LANG_STRING; case DatatypeIdValue.DT_STRING: case DatatypeIdValue.DT_EXTERNAL_ID: case DatatypeIdValue.DT_MATH: this.rdfConversionBuffer.addDatatypeProperty(propertyIdValue); return Vocabulary.XSD_STRING; case DatatypeIdValue.DT_COMMONS_MEDIA: case DatatypeIdValue.DT_GLOBE_COORDINATES: case DatatypeIdValue.DT_ITEM: case DatatypeIdValue.DT_PROPERTY: case DatatypeIdValue.DT_LEXEME: case DatatypeIdValue.DT_FORM: case DatatypeIdValue.DT_SENSE: case DatatypeIdValue.DT_TIME: case DatatypeIdValue.DT_URL: case DatatypeIdValue.DT_GEO_SHAPE: case DatatypeIdValue.DT_TABULAR_DATA: case DatatypeIdValue.DT_QUANTITY: this.rdfConversionBuffer.addObjectProperty(propertyIdValue); return Vocabulary.OWL_THING; default: return null; } }
java
String getRangeUri(PropertyIdValue propertyIdValue) { String datatype = this.propertyRegister .getPropertyType(propertyIdValue); if (datatype == null) return null; switch (datatype) { case DatatypeIdValue.DT_MONOLINGUAL_TEXT: this.rdfConversionBuffer.addDatatypeProperty(propertyIdValue); return Vocabulary.RDF_LANG_STRING; case DatatypeIdValue.DT_STRING: case DatatypeIdValue.DT_EXTERNAL_ID: case DatatypeIdValue.DT_MATH: this.rdfConversionBuffer.addDatatypeProperty(propertyIdValue); return Vocabulary.XSD_STRING; case DatatypeIdValue.DT_COMMONS_MEDIA: case DatatypeIdValue.DT_GLOBE_COORDINATES: case DatatypeIdValue.DT_ITEM: case DatatypeIdValue.DT_PROPERTY: case DatatypeIdValue.DT_LEXEME: case DatatypeIdValue.DT_FORM: case DatatypeIdValue.DT_SENSE: case DatatypeIdValue.DT_TIME: case DatatypeIdValue.DT_URL: case DatatypeIdValue.DT_GEO_SHAPE: case DatatypeIdValue.DT_TABULAR_DATA: case DatatypeIdValue.DT_QUANTITY: this.rdfConversionBuffer.addObjectProperty(propertyIdValue); return Vocabulary.OWL_THING; default: return null; } }
[ "String", "getRangeUri", "(", "PropertyIdValue", "propertyIdValue", ")", "{", "String", "datatype", "=", "this", ".", "propertyRegister", ".", "getPropertyType", "(", "propertyIdValue", ")", ";", "if", "(", "datatype", "==", "null", ")", "return", "null", ";", "switch", "(", "datatype", ")", "{", "case", "DatatypeIdValue", ".", "DT_MONOLINGUAL_TEXT", ":", "this", ".", "rdfConversionBuffer", ".", "addDatatypeProperty", "(", "propertyIdValue", ")", ";", "return", "Vocabulary", ".", "RDF_LANG_STRING", ";", "case", "DatatypeIdValue", ".", "DT_STRING", ":", "case", "DatatypeIdValue", ".", "DT_EXTERNAL_ID", ":", "case", "DatatypeIdValue", ".", "DT_MATH", ":", "this", ".", "rdfConversionBuffer", ".", "addDatatypeProperty", "(", "propertyIdValue", ")", ";", "return", "Vocabulary", ".", "XSD_STRING", ";", "case", "DatatypeIdValue", ".", "DT_COMMONS_MEDIA", ":", "case", "DatatypeIdValue", ".", "DT_GLOBE_COORDINATES", ":", "case", "DatatypeIdValue", ".", "DT_ITEM", ":", "case", "DatatypeIdValue", ".", "DT_PROPERTY", ":", "case", "DatatypeIdValue", ".", "DT_LEXEME", ":", "case", "DatatypeIdValue", ".", "DT_FORM", ":", "case", "DatatypeIdValue", ".", "DT_SENSE", ":", "case", "DatatypeIdValue", ".", "DT_TIME", ":", "case", "DatatypeIdValue", ".", "DT_URL", ":", "case", "DatatypeIdValue", ".", "DT_GEO_SHAPE", ":", "case", "DatatypeIdValue", ".", "DT_TABULAR_DATA", ":", "case", "DatatypeIdValue", ".", "DT_QUANTITY", ":", "this", ".", "rdfConversionBuffer", ".", "addObjectProperty", "(", "propertyIdValue", ")", ";", "return", "Vocabulary", ".", "OWL_THING", ";", "default", ":", "return", "null", ";", "}", "}" ]
Returns the class of datatype URI that best characterizes the range of the given property based on its datatype. @param propertyIdValue the property for which to get a range @return the range URI or null if the datatype could not be identified.
[ "Returns", "the", "class", "of", "datatype", "URI", "that", "best", "characterizes", "the", "range", "of", "the", "given", "property", "based", "on", "its", "datatype", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java#L270-L303
161,282
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java
SnakRdfConverter.addSomeValuesRestriction
void addSomeValuesRestriction(Resource subject, String propertyUri, String rangeUri) { this.someValuesQueue.add(new PropertyRestriction(subject, propertyUri, rangeUri)); }
java
void addSomeValuesRestriction(Resource subject, String propertyUri, String rangeUri) { this.someValuesQueue.add(new PropertyRestriction(subject, propertyUri, rangeUri)); }
[ "void", "addSomeValuesRestriction", "(", "Resource", "subject", ",", "String", "propertyUri", ",", "String", "rangeUri", ")", "{", "this", ".", "someValuesQueue", ".", "add", "(", "new", "PropertyRestriction", "(", "subject", ",", "propertyUri", ",", "rangeUri", ")", ")", ";", "}" ]
Adds the given some-value restriction to the list of restrictions that should still be serialized. The given resource will be used as a subject. @param subject @param propertyUri @param rangeUri
[ "Adds", "the", "given", "some", "-", "value", "restriction", "to", "the", "list", "of", "restrictions", "that", "should", "still", "be", "serialized", ".", "The", "given", "resource", "will", "be", "used", "as", "a", "subject", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/SnakRdfConverter.java#L313-L317
161,283
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java
WikibaseDataFetcher.getEntityDocumentMap
Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities, WbGetEntitiesActionData properties) throws MediaWikiApiErrorException, IOException { if (numOfEntities == 0) { return Collections.emptyMap(); } configureProperties(properties); return this.wbGetEntitiesAction.wbGetEntities(properties); }
java
Map<String, EntityDocument> getEntityDocumentMap(int numOfEntities, WbGetEntitiesActionData properties) throws MediaWikiApiErrorException, IOException { if (numOfEntities == 0) { return Collections.emptyMap(); } configureProperties(properties); return this.wbGetEntitiesAction.wbGetEntities(properties); }
[ "Map", "<", "String", ",", "EntityDocument", ">", "getEntityDocumentMap", "(", "int", "numOfEntities", ",", "WbGetEntitiesActionData", "properties", ")", "throws", "MediaWikiApiErrorException", ",", "IOException", "{", "if", "(", "numOfEntities", "==", "0", ")", "{", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "configureProperties", "(", "properties", ")", ";", "return", "this", ".", "wbGetEntitiesAction", ".", "wbGetEntities", "(", "properties", ")", ";", "}" ]
Creates a map of identifiers or page titles to documents retrieved via the APIs. @param numOfEntities number of entities that should be retrieved @param properties WbGetEntitiesProperties object that includes all relevant parameters for the wbgetentities action @return map of document identifiers or titles to documents retrieved via the API URL @throws MediaWikiApiErrorException @throws IOException
[ "Creates", "a", "map", "of", "identifiers", "or", "page", "titles", "to", "documents", "retrieved", "via", "the", "APIs", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java#L297-L305
161,284
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java
WikibaseDataFetcher.setRequestProps
private void setRequestProps(WbGetEntitiesActionData properties) { StringBuilder builder = new StringBuilder(); builder.append("info|datatype"); if (!this.filter.excludeAllLanguages()) { builder.append("|labels|aliases|descriptions"); } if (!this.filter.excludeAllProperties()) { builder.append("|claims"); } if (!this.filter.excludeAllSiteLinks()) { builder.append("|sitelinks"); } properties.props = builder.toString(); }
java
private void setRequestProps(WbGetEntitiesActionData properties) { StringBuilder builder = new StringBuilder(); builder.append("info|datatype"); if (!this.filter.excludeAllLanguages()) { builder.append("|labels|aliases|descriptions"); } if (!this.filter.excludeAllProperties()) { builder.append("|claims"); } if (!this.filter.excludeAllSiteLinks()) { builder.append("|sitelinks"); } properties.props = builder.toString(); }
[ "private", "void", "setRequestProps", "(", "WbGetEntitiesActionData", "properties", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"info|datatype\"", ")", ";", "if", "(", "!", "this", ".", "filter", ".", "excludeAllLanguages", "(", ")", ")", "{", "builder", ".", "append", "(", "\"|labels|aliases|descriptions\"", ")", ";", "}", "if", "(", "!", "this", ".", "filter", ".", "excludeAllProperties", "(", ")", ")", "{", "builder", ".", "append", "(", "\"|claims\"", ")", ";", "}", "if", "(", "!", "this", ".", "filter", ".", "excludeAllSiteLinks", "(", ")", ")", "{", "builder", ".", "append", "(", "\"|sitelinks\"", ")", ";", "}", "properties", ".", "props", "=", "builder", ".", "toString", "(", ")", ";", "}" ]
Sets the value for the API's "props" parameter based on the current settings. @param properties current setting of parameters
[ "Sets", "the", "value", "for", "the", "API", "s", "props", "parameter", "based", "on", "the", "current", "settings", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java#L364-L378
161,285
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java
WikibaseDataFetcher.setRequestLanguages
private void setRequestLanguages(WbGetEntitiesActionData properties) { if (this.filter.excludeAllLanguages() || this.filter.getLanguageFilter() == null) { return; } properties.languages = ApiConnection.implodeObjects(this.filter .getLanguageFilter()); }
java
private void setRequestLanguages(WbGetEntitiesActionData properties) { if (this.filter.excludeAllLanguages() || this.filter.getLanguageFilter() == null) { return; } properties.languages = ApiConnection.implodeObjects(this.filter .getLanguageFilter()); }
[ "private", "void", "setRequestLanguages", "(", "WbGetEntitiesActionData", "properties", ")", "{", "if", "(", "this", ".", "filter", ".", "excludeAllLanguages", "(", ")", "||", "this", ".", "filter", ".", "getLanguageFilter", "(", ")", "==", "null", ")", "{", "return", ";", "}", "properties", ".", "languages", "=", "ApiConnection", ".", "implodeObjects", "(", "this", ".", "filter", ".", "getLanguageFilter", "(", ")", ")", ";", "}" ]
Sets the value for the API's "languages" parameter based on the current settings. @param properties current setting of parameters
[ "Sets", "the", "value", "for", "the", "API", "s", "languages", "parameter", "based", "on", "the", "current", "settings", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java#L387-L394
161,286
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java
WikibaseDataFetcher.setRequestSitefilter
private void setRequestSitefilter(WbGetEntitiesActionData properties) { if (this.filter.excludeAllSiteLinks() || this.filter.getSiteLinkFilter() == null) { return; } properties.sitefilter = ApiConnection.implodeObjects(this.filter .getSiteLinkFilter()); }
java
private void setRequestSitefilter(WbGetEntitiesActionData properties) { if (this.filter.excludeAllSiteLinks() || this.filter.getSiteLinkFilter() == null) { return; } properties.sitefilter = ApiConnection.implodeObjects(this.filter .getSiteLinkFilter()); }
[ "private", "void", "setRequestSitefilter", "(", "WbGetEntitiesActionData", "properties", ")", "{", "if", "(", "this", ".", "filter", ".", "excludeAllSiteLinks", "(", ")", "||", "this", ".", "filter", ".", "getSiteLinkFilter", "(", ")", "==", "null", ")", "{", "return", ";", "}", "properties", ".", "sitefilter", "=", "ApiConnection", ".", "implodeObjects", "(", "this", ".", "filter", ".", "getSiteLinkFilter", "(", ")", ")", ";", "}" ]
Sets the value for the API's "sitefilter" parameter based on the current settings. @param properties current setting of parameters
[ "Sets", "the", "value", "for", "the", "API", "s", "sitefilter", "parameter", "based", "on", "the", "current", "settings", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java#L403-L410
161,287
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwSitesDumpFileProcessor.java
MwSitesDumpFileProcessor.processSiteRow
void processSiteRow(String siteRow) { String[] row = getSiteRowFields(siteRow); String filePath = ""; String pagePath = ""; String dataArray = row[8].substring(row[8].indexOf('{'), row[8].length() - 2); // Explanation for the regular expression below: // "'{' or ';'" followed by either // "NOT: ';', '{', or '}'" repeated one or more times; or // "a single '}'" // The first case matches ";s:5:\"paths\"" // but also ";a:2:" in "{s:5:\"paths\";a:2:{s:9:\ ...". // The second case matches ";}" which terminates (sub)arrays. Matcher matcher = Pattern.compile("[{;](([^;}{][^;}{]*)|[}])").matcher( dataArray); String prevString = ""; String curString = ""; String path = ""; boolean valuePosition = false; while (matcher.find()) { String match = matcher.group().substring(1); if (match.length() == 0) { valuePosition = false; continue; } if (match.charAt(0) == 's') { valuePosition = !valuePosition && !"".equals(prevString); curString = match.substring(match.indexOf('"') + 1, match.length() - 2); } else if (match.charAt(0) == 'a') { valuePosition = false; path = path + "/" + prevString; } else if ("}".equals(match)) { valuePosition = false; path = path.substring(0, path.lastIndexOf('/')); } if (valuePosition && "file_path".equals(prevString) && "/paths".equals(path)) { filePath = curString; } else if (valuePosition && "page_path".equals(prevString) && "/paths".equals(path)) { pagePath = curString; } prevString = curString; curString = ""; } MwSitesDumpFileProcessor.logger.debug("Found site data \"" + row[1] + "\" (group \"" + row[3] + "\", language \"" + row[5] + "\", type \"" + row[2] + "\")"); this.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath, pagePath); }
java
void processSiteRow(String siteRow) { String[] row = getSiteRowFields(siteRow); String filePath = ""; String pagePath = ""; String dataArray = row[8].substring(row[8].indexOf('{'), row[8].length() - 2); // Explanation for the regular expression below: // "'{' or ';'" followed by either // "NOT: ';', '{', or '}'" repeated one or more times; or // "a single '}'" // The first case matches ";s:5:\"paths\"" // but also ";a:2:" in "{s:5:\"paths\";a:2:{s:9:\ ...". // The second case matches ";}" which terminates (sub)arrays. Matcher matcher = Pattern.compile("[{;](([^;}{][^;}{]*)|[}])").matcher( dataArray); String prevString = ""; String curString = ""; String path = ""; boolean valuePosition = false; while (matcher.find()) { String match = matcher.group().substring(1); if (match.length() == 0) { valuePosition = false; continue; } if (match.charAt(0) == 's') { valuePosition = !valuePosition && !"".equals(prevString); curString = match.substring(match.indexOf('"') + 1, match.length() - 2); } else if (match.charAt(0) == 'a') { valuePosition = false; path = path + "/" + prevString; } else if ("}".equals(match)) { valuePosition = false; path = path.substring(0, path.lastIndexOf('/')); } if (valuePosition && "file_path".equals(prevString) && "/paths".equals(path)) { filePath = curString; } else if (valuePosition && "page_path".equals(prevString) && "/paths".equals(path)) { pagePath = curString; } prevString = curString; curString = ""; } MwSitesDumpFileProcessor.logger.debug("Found site data \"" + row[1] + "\" (group \"" + row[3] + "\", language \"" + row[5] + "\", type \"" + row[2] + "\")"); this.sites.setSiteInformation(row[1], row[3], row[5], row[2], filePath, pagePath); }
[ "void", "processSiteRow", "(", "String", "siteRow", ")", "{", "String", "[", "]", "row", "=", "getSiteRowFields", "(", "siteRow", ")", ";", "String", "filePath", "=", "\"\"", ";", "String", "pagePath", "=", "\"\"", ";", "String", "dataArray", "=", "row", "[", "8", "]", ".", "substring", "(", "row", "[", "8", "]", ".", "indexOf", "(", "'", "'", ")", ",", "row", "[", "8", "]", ".", "length", "(", ")", "-", "2", ")", ";", "// Explanation for the regular expression below:", "// \"'{' or ';'\" followed by either", "// \"NOT: ';', '{', or '}'\" repeated one or more times; or", "// \"a single '}'\"", "// The first case matches \";s:5:\\\"paths\\\"\"", "// but also \";a:2:\" in \"{s:5:\\\"paths\\\";a:2:{s:9:\\ ...\".", "// The second case matches \";}\" which terminates (sub)arrays.", "Matcher", "matcher", "=", "Pattern", ".", "compile", "(", "\"[{;](([^;}{][^;}{]*)|[}])\"", ")", ".", "matcher", "(", "dataArray", ")", ";", "String", "prevString", "=", "\"\"", ";", "String", "curString", "=", "\"\"", ";", "String", "path", "=", "\"\"", ";", "boolean", "valuePosition", "=", "false", ";", "while", "(", "matcher", ".", "find", "(", ")", ")", "{", "String", "match", "=", "matcher", ".", "group", "(", ")", ".", "substring", "(", "1", ")", ";", "if", "(", "match", ".", "length", "(", ")", "==", "0", ")", "{", "valuePosition", "=", "false", ";", "continue", ";", "}", "if", "(", "match", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "valuePosition", "=", "!", "valuePosition", "&&", "!", "\"\"", ".", "equals", "(", "prevString", ")", ";", "curString", "=", "match", ".", "substring", "(", "match", ".", "indexOf", "(", "'", "'", ")", "+", "1", ",", "match", ".", "length", "(", ")", "-", "2", ")", ";", "}", "else", "if", "(", "match", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "valuePosition", "=", "false", ";", "path", "=", "path", "+", "\"/\"", "+", "prevString", ";", "}", "else", "if", "(", "\"}\"", ".", "equals", "(", "match", ")", ")", "{", "valuePosition", "=", "false", ";", "path", "=", "path", ".", "substring", "(", "0", ",", "path", ".", "lastIndexOf", "(", "'", "'", ")", ")", ";", "}", "if", "(", "valuePosition", "&&", "\"file_path\"", ".", "equals", "(", "prevString", ")", "&&", "\"/paths\"", ".", "equals", "(", "path", ")", ")", "{", "filePath", "=", "curString", ";", "}", "else", "if", "(", "valuePosition", "&&", "\"page_path\"", ".", "equals", "(", "prevString", ")", "&&", "\"/paths\"", ".", "equals", "(", "path", ")", ")", "{", "pagePath", "=", "curString", ";", "}", "prevString", "=", "curString", ";", "curString", "=", "\"\"", ";", "}", "MwSitesDumpFileProcessor", ".", "logger", ".", "debug", "(", "\"Found site data \\\"\"", "+", "row", "[", "1", "]", "+", "\"\\\" (group \\\"\"", "+", "row", "[", "3", "]", "+", "\"\\\", language \\\"\"", "+", "row", "[", "5", "]", "+", "\"\\\", type \\\"\"", "+", "row", "[", "2", "]", "+", "\"\\\")\"", ")", ";", "this", ".", "sites", ".", "setSiteInformation", "(", "row", "[", "1", "]", ",", "row", "[", "3", "]", ",", "row", "[", "5", "]", ",", "row", "[", "2", "]", ",", "filePath", ",", "pagePath", ")", ";", "}" ]
Processes a row of the sites table and stores the site information found therein. @param siteRow string serialisation of a sites table row as found in the SQL dump
[ "Processes", "a", "row", "of", "the", "sites", "table", "and", "stores", "the", "site", "information", "found", "therein", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/MwSitesDumpFileProcessor.java#L99-L157
161,288
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.start
public synchronized void start() { if ((todoFlags & RECORD_CPUTIME) != 0) { currentStartCpuTime = getThreadCpuTime(threadId); } else { currentStartCpuTime = -1; } if ((todoFlags & RECORD_WALLTIME) != 0) { currentStartWallTime = System.nanoTime(); } else { currentStartWallTime = -1; } isRunning = true; }
java
public synchronized void start() { if ((todoFlags & RECORD_CPUTIME) != 0) { currentStartCpuTime = getThreadCpuTime(threadId); } else { currentStartCpuTime = -1; } if ((todoFlags & RECORD_WALLTIME) != 0) { currentStartWallTime = System.nanoTime(); } else { currentStartWallTime = -1; } isRunning = true; }
[ "public", "synchronized", "void", "start", "(", ")", "{", "if", "(", "(", "todoFlags", "&", "RECORD_CPUTIME", ")", "!=", "0", ")", "{", "currentStartCpuTime", "=", "getThreadCpuTime", "(", "threadId", ")", ";", "}", "else", "{", "currentStartCpuTime", "=", "-", "1", ";", "}", "if", "(", "(", "todoFlags", "&", "RECORD_WALLTIME", ")", "!=", "0", ")", "{", "currentStartWallTime", "=", "System", ".", "nanoTime", "(", ")", ";", "}", "else", "{", "currentStartWallTime", "=", "-", "1", ";", "}", "isRunning", "=", "true", ";", "}" ]
Start the timer.
[ "Start", "the", "timer", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L200-L212
161,289
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.startNamedTimer
public static void startNamedTimer(String timerName, int todoFlags, long threadId) { getNamedTimer(timerName, todoFlags, threadId).start(); }
java
public static void startNamedTimer(String timerName, int todoFlags, long threadId) { getNamedTimer(timerName, todoFlags, threadId).start(); }
[ "public", "static", "void", "startNamedTimer", "(", "String", "timerName", ",", "int", "todoFlags", ",", "long", "threadId", ")", "{", "getNamedTimer", "(", "timerName", ",", "todoFlags", ",", "threadId", ")", ".", "start", "(", ")", ";", "}" ]
Start a timer of the given string name for the current thread. If no such timer exists yet, then it will be newly created. @param timerName the name of the timer @param todoFlags @param threadId of the thread to track, or 0 if only system clock should be tracked
[ "Start", "a", "timer", "of", "the", "given", "string", "name", "for", "the", "current", "thread", ".", "If", "no", "such", "timer", "exists", "yet", "then", "it", "will", "be", "newly", "created", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L375-L378
161,290
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.stopNamedTimer
public static long stopNamedTimer(String timerName, int todoFlags) { return stopNamedTimer(timerName, todoFlags, Thread.currentThread() .getId()); }
java
public static long stopNamedTimer(String timerName, int todoFlags) { return stopNamedTimer(timerName, todoFlags, Thread.currentThread() .getId()); }
[ "public", "static", "long", "stopNamedTimer", "(", "String", "timerName", ",", "int", "todoFlags", ")", "{", "return", "stopNamedTimer", "(", "timerName", ",", "todoFlags", ",", "Thread", ".", "currentThread", "(", ")", ".", "getId", "(", ")", ")", ";", "}" ]
Stop a timer of the given string name for the current thread. If no such timer exists, -1 will be returned. Otherwise the return value is the CPU time that was measured. @param timerName the name of the timer @param todoFlags @return CPU time if timer existed and was running, and -1 otherwise
[ "Stop", "a", "timer", "of", "the", "given", "string", "name", "for", "the", "current", "thread", ".", "If", "no", "such", "timer", "exists", "-", "1", "will", "be", "returned", ".", "Otherwise", "the", "return", "value", "is", "the", "CPU", "time", "that", "was", "measured", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L404-L407
161,291
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.resetNamedTimer
public static void resetNamedTimer(String timerName, int todoFlags, long threadId) { getNamedTimer(timerName, todoFlags, threadId).reset(); }
java
public static void resetNamedTimer(String timerName, int todoFlags, long threadId) { getNamedTimer(timerName, todoFlags, threadId).reset(); }
[ "public", "static", "void", "resetNamedTimer", "(", "String", "timerName", ",", "int", "todoFlags", ",", "long", "threadId", ")", "{", "getNamedTimer", "(", "timerName", ",", "todoFlags", ",", "threadId", ")", ".", "reset", "(", ")", ";", "}" ]
Reset a timer of the given string name for the given thread. If no such timer exists yet, then it will be newly created. @param timerName the name of the timer @param todoFlags @param threadId of the thread to track, or 0 if only system clock should be tracked
[ "Reset", "a", "timer", "of", "the", "given", "string", "name", "for", "the", "given", "thread", ".", "If", "no", "such", "timer", "exists", "yet", "then", "it", "will", "be", "newly", "created", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L466-L469
161,292
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.getNamedTimer
public static Timer getNamedTimer(String timerName, int todoFlags) { return getNamedTimer(timerName, todoFlags, Thread.currentThread() .getId()); }
java
public static Timer getNamedTimer(String timerName, int todoFlags) { return getNamedTimer(timerName, todoFlags, Thread.currentThread() .getId()); }
[ "public", "static", "Timer", "getNamedTimer", "(", "String", "timerName", ",", "int", "todoFlags", ")", "{", "return", "getNamedTimer", "(", "timerName", ",", "todoFlags", ",", "Thread", ".", "currentThread", "(", ")", ".", "getId", "(", ")", ")", ";", "}" ]
Get a timer of the given string name and todos for the current thread. If no such timer exists yet, then it will be newly created. @param timerName the name of the timer @param todoFlags @return timer
[ "Get", "a", "timer", "of", "the", "given", "string", "name", "and", "todos", "for", "the", "current", "thread", ".", "If", "no", "such", "timer", "exists", "yet", "then", "it", "will", "be", "newly", "created", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L494-L497
161,293
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.getNamedTimer
public static Timer getNamedTimer(String timerName, int todoFlags, long threadId) { Timer key = new Timer(timerName, todoFlags, threadId); registeredTimers.putIfAbsent(key, key); return registeredTimers.get(key); }
java
public static Timer getNamedTimer(String timerName, int todoFlags, long threadId) { Timer key = new Timer(timerName, todoFlags, threadId); registeredTimers.putIfAbsent(key, key); return registeredTimers.get(key); }
[ "public", "static", "Timer", "getNamedTimer", "(", "String", "timerName", ",", "int", "todoFlags", ",", "long", "threadId", ")", "{", "Timer", "key", "=", "new", "Timer", "(", "timerName", ",", "todoFlags", ",", "threadId", ")", ";", "registeredTimers", ".", "putIfAbsent", "(", "key", ",", "key", ")", ";", "return", "registeredTimers", ".", "get", "(", "key", ")", ";", "}" ]
Get a timer of the given string name for the given thread. If no such timer exists yet, then it will be newly created. @param timerName the name of the timer @param todoFlags @param threadId of the thread to track, or 0 if only system clock should be tracked @return timer
[ "Get", "a", "timer", "of", "the", "given", "string", "name", "for", "the", "given", "thread", ".", "If", "no", "such", "timer", "exists", "yet", "then", "it", "will", "be", "newly", "created", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L511-L516
161,294
Wikidata/Wikidata-Toolkit
wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java
Timer.getNamedTotalTimer
public static Timer getNamedTotalTimer(String timerName) { long totalCpuTime = 0; long totalSystemTime = 0; int measurements = 0; int timerCount = 0; int todoFlags = RECORD_NONE; Timer previousTimer = null; for (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) { if (entry.getValue().name.equals(timerName)) { previousTimer = entry.getValue(); timerCount += 1; totalCpuTime += previousTimer.totalCpuTime; totalSystemTime += previousTimer.totalWallTime; measurements += previousTimer.measurements; todoFlags |= previousTimer.todoFlags; } } if (timerCount == 1) { return previousTimer; } else { Timer result = new Timer(timerName, todoFlags, 0); result.totalCpuTime = totalCpuTime; result.totalWallTime = totalSystemTime; result.measurements = measurements; result.threadCount = timerCount; return result; } }
java
public static Timer getNamedTotalTimer(String timerName) { long totalCpuTime = 0; long totalSystemTime = 0; int measurements = 0; int timerCount = 0; int todoFlags = RECORD_NONE; Timer previousTimer = null; for (Map.Entry<Timer, Timer> entry : registeredTimers.entrySet()) { if (entry.getValue().name.equals(timerName)) { previousTimer = entry.getValue(); timerCount += 1; totalCpuTime += previousTimer.totalCpuTime; totalSystemTime += previousTimer.totalWallTime; measurements += previousTimer.measurements; todoFlags |= previousTimer.todoFlags; } } if (timerCount == 1) { return previousTimer; } else { Timer result = new Timer(timerName, todoFlags, 0); result.totalCpuTime = totalCpuTime; result.totalWallTime = totalSystemTime; result.measurements = measurements; result.threadCount = timerCount; return result; } }
[ "public", "static", "Timer", "getNamedTotalTimer", "(", "String", "timerName", ")", "{", "long", "totalCpuTime", "=", "0", ";", "long", "totalSystemTime", "=", "0", ";", "int", "measurements", "=", "0", ";", "int", "timerCount", "=", "0", ";", "int", "todoFlags", "=", "RECORD_NONE", ";", "Timer", "previousTimer", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "Timer", ",", "Timer", ">", "entry", ":", "registeredTimers", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", ".", "name", ".", "equals", "(", "timerName", ")", ")", "{", "previousTimer", "=", "entry", ".", "getValue", "(", ")", ";", "timerCount", "+=", "1", ";", "totalCpuTime", "+=", "previousTimer", ".", "totalCpuTime", ";", "totalSystemTime", "+=", "previousTimer", ".", "totalWallTime", ";", "measurements", "+=", "previousTimer", ".", "measurements", ";", "todoFlags", "|=", "previousTimer", ".", "todoFlags", ";", "}", "}", "if", "(", "timerCount", "==", "1", ")", "{", "return", "previousTimer", ";", "}", "else", "{", "Timer", "result", "=", "new", "Timer", "(", "timerName", ",", "todoFlags", ",", "0", ")", ";", "result", ".", "totalCpuTime", "=", "totalCpuTime", ";", "result", ".", "totalWallTime", "=", "totalSystemTime", ";", "result", ".", "measurements", "=", "measurements", ";", "result", ".", "threadCount", "=", "timerCount", ";", "return", "result", ";", "}", "}" ]
Collect the total times measured by all known named timers of the given name. This is useful to add up times that were collected across separate threads. @param timerName @return timer
[ "Collect", "the", "total", "times", "measured", "by", "all", "known", "named", "timers", "of", "the", "given", "name", ".", "This", "is", "useful", "to", "add", "up", "times", "that", "were", "collected", "across", "separate", "threads", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-util/src/main/java/org/wikidata/wdtk/util/Timer.java#L526-L555
161,295
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java
Client.performActions
public void performActions() { if (this.clientConfiguration.getActions().isEmpty()) { this.clientConfiguration.printHelp(); return; } this.dumpProcessingController.setOfflineMode(this.clientConfiguration .getOfflineMode()); if (this.clientConfiguration.getDumpDirectoryLocation() != null) { try { this.dumpProcessingController .setDownloadDirectory(this.clientConfiguration .getDumpDirectoryLocation()); } catch (IOException e) { logger.error("Could not set download directory to " + this.clientConfiguration.getDumpDirectoryLocation() + ": " + e.getMessage()); logger.error("Aborting"); return; } } dumpProcessingController.setLanguageFilter(this.clientConfiguration .getFilterLanguages()); dumpProcessingController.setSiteLinkFilter(this.clientConfiguration .getFilterSiteKeys()); dumpProcessingController.setPropertyFilter(this.clientConfiguration .getFilterProperties()); MwDumpFile dumpFile = this.clientConfiguration.getLocalDumpFile(); if (dumpFile == null) { dumpFile = dumpProcessingController .getMostRecentDump(DumpContentType.JSON); } else { if (!dumpFile.isAvailable()) { logger.error("Dump file not found or not readable: " + dumpFile.toString()); return; } } this.clientConfiguration.setProjectName(dumpFile.getProjectName()); this.clientConfiguration.setDateStamp(dumpFile.getDateStamp()); boolean hasReadyProcessor = false; for (DumpProcessingAction props : this.clientConfiguration.getActions()) { if (!props.isReady()) { continue; } if (props.needsSites()) { prepareSites(); if (this.sites == null) { // sites unavailable continue; } props.setSites(this.sites); } props.setDumpInformation(dumpFile.getProjectName(), dumpFile.getDateStamp()); this.dumpProcessingController.registerEntityDocumentProcessor( props, null, true); hasReadyProcessor = true; } if (!hasReadyProcessor) { return; // silent; non-ready action should report its problem // directly } if (!this.clientConfiguration.isQuiet()) { EntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor( 0); this.dumpProcessingController.registerEntityDocumentProcessor( entityTimerProcessor, null, true); } openActions(); this.dumpProcessingController.processDump(dumpFile); closeActions(); try { writeReport(); } catch (IOException e) { logger.error("Could not print report file: " + e.getMessage()); } }
java
public void performActions() { if (this.clientConfiguration.getActions().isEmpty()) { this.clientConfiguration.printHelp(); return; } this.dumpProcessingController.setOfflineMode(this.clientConfiguration .getOfflineMode()); if (this.clientConfiguration.getDumpDirectoryLocation() != null) { try { this.dumpProcessingController .setDownloadDirectory(this.clientConfiguration .getDumpDirectoryLocation()); } catch (IOException e) { logger.error("Could not set download directory to " + this.clientConfiguration.getDumpDirectoryLocation() + ": " + e.getMessage()); logger.error("Aborting"); return; } } dumpProcessingController.setLanguageFilter(this.clientConfiguration .getFilterLanguages()); dumpProcessingController.setSiteLinkFilter(this.clientConfiguration .getFilterSiteKeys()); dumpProcessingController.setPropertyFilter(this.clientConfiguration .getFilterProperties()); MwDumpFile dumpFile = this.clientConfiguration.getLocalDumpFile(); if (dumpFile == null) { dumpFile = dumpProcessingController .getMostRecentDump(DumpContentType.JSON); } else { if (!dumpFile.isAvailable()) { logger.error("Dump file not found or not readable: " + dumpFile.toString()); return; } } this.clientConfiguration.setProjectName(dumpFile.getProjectName()); this.clientConfiguration.setDateStamp(dumpFile.getDateStamp()); boolean hasReadyProcessor = false; for (DumpProcessingAction props : this.clientConfiguration.getActions()) { if (!props.isReady()) { continue; } if (props.needsSites()) { prepareSites(); if (this.sites == null) { // sites unavailable continue; } props.setSites(this.sites); } props.setDumpInformation(dumpFile.getProjectName(), dumpFile.getDateStamp()); this.dumpProcessingController.registerEntityDocumentProcessor( props, null, true); hasReadyProcessor = true; } if (!hasReadyProcessor) { return; // silent; non-ready action should report its problem // directly } if (!this.clientConfiguration.isQuiet()) { EntityTimerProcessor entityTimerProcessor = new EntityTimerProcessor( 0); this.dumpProcessingController.registerEntityDocumentProcessor( entityTimerProcessor, null, true); } openActions(); this.dumpProcessingController.processDump(dumpFile); closeActions(); try { writeReport(); } catch (IOException e) { logger.error("Could not print report file: " + e.getMessage()); } }
[ "public", "void", "performActions", "(", ")", "{", "if", "(", "this", ".", "clientConfiguration", ".", "getActions", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "this", ".", "clientConfiguration", ".", "printHelp", "(", ")", ";", "return", ";", "}", "this", ".", "dumpProcessingController", ".", "setOfflineMode", "(", "this", ".", "clientConfiguration", ".", "getOfflineMode", "(", ")", ")", ";", "if", "(", "this", ".", "clientConfiguration", ".", "getDumpDirectoryLocation", "(", ")", "!=", "null", ")", "{", "try", "{", "this", ".", "dumpProcessingController", ".", "setDownloadDirectory", "(", "this", ".", "clientConfiguration", ".", "getDumpDirectoryLocation", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Could not set download directory to \"", "+", "this", ".", "clientConfiguration", ".", "getDumpDirectoryLocation", "(", ")", "+", "\": \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "logger", ".", "error", "(", "\"Aborting\"", ")", ";", "return", ";", "}", "}", "dumpProcessingController", ".", "setLanguageFilter", "(", "this", ".", "clientConfiguration", ".", "getFilterLanguages", "(", ")", ")", ";", "dumpProcessingController", ".", "setSiteLinkFilter", "(", "this", ".", "clientConfiguration", ".", "getFilterSiteKeys", "(", ")", ")", ";", "dumpProcessingController", ".", "setPropertyFilter", "(", "this", ".", "clientConfiguration", ".", "getFilterProperties", "(", ")", ")", ";", "MwDumpFile", "dumpFile", "=", "this", ".", "clientConfiguration", ".", "getLocalDumpFile", "(", ")", ";", "if", "(", "dumpFile", "==", "null", ")", "{", "dumpFile", "=", "dumpProcessingController", ".", "getMostRecentDump", "(", "DumpContentType", ".", "JSON", ")", ";", "}", "else", "{", "if", "(", "!", "dumpFile", ".", "isAvailable", "(", ")", ")", "{", "logger", ".", "error", "(", "\"Dump file not found or not readable: \"", "+", "dumpFile", ".", "toString", "(", ")", ")", ";", "return", ";", "}", "}", "this", ".", "clientConfiguration", ".", "setProjectName", "(", "dumpFile", ".", "getProjectName", "(", ")", ")", ";", "this", ".", "clientConfiguration", ".", "setDateStamp", "(", "dumpFile", ".", "getDateStamp", "(", ")", ")", ";", "boolean", "hasReadyProcessor", "=", "false", ";", "for", "(", "DumpProcessingAction", "props", ":", "this", ".", "clientConfiguration", ".", "getActions", "(", ")", ")", "{", "if", "(", "!", "props", ".", "isReady", "(", ")", ")", "{", "continue", ";", "}", "if", "(", "props", ".", "needsSites", "(", ")", ")", "{", "prepareSites", "(", ")", ";", "if", "(", "this", ".", "sites", "==", "null", ")", "{", "// sites unavailable", "continue", ";", "}", "props", ".", "setSites", "(", "this", ".", "sites", ")", ";", "}", "props", ".", "setDumpInformation", "(", "dumpFile", ".", "getProjectName", "(", ")", ",", "dumpFile", ".", "getDateStamp", "(", ")", ")", ";", "this", ".", "dumpProcessingController", ".", "registerEntityDocumentProcessor", "(", "props", ",", "null", ",", "true", ")", ";", "hasReadyProcessor", "=", "true", ";", "}", "if", "(", "!", "hasReadyProcessor", ")", "{", "return", ";", "// silent; non-ready action should report its problem", "// directly", "}", "if", "(", "!", "this", ".", "clientConfiguration", ".", "isQuiet", "(", ")", ")", "{", "EntityTimerProcessor", "entityTimerProcessor", "=", "new", "EntityTimerProcessor", "(", "0", ")", ";", "this", ".", "dumpProcessingController", ".", "registerEntityDocumentProcessor", "(", "entityTimerProcessor", ",", "null", ",", "true", ")", ";", "}", "openActions", "(", ")", ";", "this", ".", "dumpProcessingController", ".", "processDump", "(", "dumpFile", ")", ";", "closeActions", "(", ")", ";", "try", "{", "writeReport", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Could not print report file: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Performs all actions that have been configured.
[ "Performs", "all", "actions", "that", "have", "been", "configured", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java#L91-L179
161,296
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java
Client.initializeLogging
private void initializeLogging() { // Since logging is static, make sure this is done only once even if // multiple clients are created (e.g., during tests) if (consoleAppender != null) { return; } consoleAppender = new ConsoleAppender(); consoleAppender.setLayout(new PatternLayout(LOG_PATTERN)); consoleAppender.setThreshold(Level.INFO); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMin(Level.TRACE); filter.setLevelMax(Level.INFO); consoleAppender.addFilter(filter); consoleAppender.activateOptions(); org.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender); errorAppender = new ConsoleAppender(); errorAppender.setLayout(new PatternLayout(LOG_PATTERN)); errorAppender.setThreshold(Level.WARN); errorAppender.setTarget(ConsoleAppender.SYSTEM_ERR); errorAppender.activateOptions(); org.apache.log4j.Logger.getRootLogger().addAppender(errorAppender); }
java
private void initializeLogging() { // Since logging is static, make sure this is done only once even if // multiple clients are created (e.g., during tests) if (consoleAppender != null) { return; } consoleAppender = new ConsoleAppender(); consoleAppender.setLayout(new PatternLayout(LOG_PATTERN)); consoleAppender.setThreshold(Level.INFO); LevelRangeFilter filter = new LevelRangeFilter(); filter.setLevelMin(Level.TRACE); filter.setLevelMax(Level.INFO); consoleAppender.addFilter(filter); consoleAppender.activateOptions(); org.apache.log4j.Logger.getRootLogger().addAppender(consoleAppender); errorAppender = new ConsoleAppender(); errorAppender.setLayout(new PatternLayout(LOG_PATTERN)); errorAppender.setThreshold(Level.WARN); errorAppender.setTarget(ConsoleAppender.SYSTEM_ERR); errorAppender.activateOptions(); org.apache.log4j.Logger.getRootLogger().addAppender(errorAppender); }
[ "private", "void", "initializeLogging", "(", ")", "{", "// Since logging is static, make sure this is done only once even if", "// multiple clients are created (e.g., during tests)", "if", "(", "consoleAppender", "!=", "null", ")", "{", "return", ";", "}", "consoleAppender", "=", "new", "ConsoleAppender", "(", ")", ";", "consoleAppender", ".", "setLayout", "(", "new", "PatternLayout", "(", "LOG_PATTERN", ")", ")", ";", "consoleAppender", ".", "setThreshold", "(", "Level", ".", "INFO", ")", ";", "LevelRangeFilter", "filter", "=", "new", "LevelRangeFilter", "(", ")", ";", "filter", ".", "setLevelMin", "(", "Level", ".", "TRACE", ")", ";", "filter", ".", "setLevelMax", "(", "Level", ".", "INFO", ")", ";", "consoleAppender", ".", "addFilter", "(", "filter", ")", ";", "consoleAppender", ".", "activateOptions", "(", ")", ";", "org", ".", "apache", ".", "log4j", ".", "Logger", ".", "getRootLogger", "(", ")", ".", "addAppender", "(", "consoleAppender", ")", ";", "errorAppender", "=", "new", "ConsoleAppender", "(", ")", ";", "errorAppender", ".", "setLayout", "(", "new", "PatternLayout", "(", "LOG_PATTERN", ")", ")", ";", "errorAppender", ".", "setThreshold", "(", "Level", ".", "WARN", ")", ";", "errorAppender", ".", "setTarget", "(", "ConsoleAppender", ".", "SYSTEM_ERR", ")", ";", "errorAppender", ".", "activateOptions", "(", ")", ";", "org", ".", "apache", ".", "log4j", ".", "Logger", ".", "getRootLogger", "(", ")", ".", "addAppender", "(", "errorAppender", ")", ";", "}" ]
Sets up Log4J to write log messages to the console. Low-priority messages are logged to stdout while high-priority messages go to stderr.
[ "Sets", "up", "Log4J", "to", "write", "log", "messages", "to", "the", "console", ".", "Low", "-", "priority", "messages", "are", "logged", "to", "stdout", "while", "high", "-", "priority", "messages", "go", "to", "stderr", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java#L196-L219
161,297
Wikidata/Wikidata-Toolkit
wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java
Client.main
public static void main(String[] args) throws ParseException, IOException { Client client = new Client( new DumpProcessingController("wikidatawiki"), args); client.performActions(); }
java
public static void main(String[] args) throws ParseException, IOException { Client client = new Client( new DumpProcessingController("wikidatawiki"), args); client.performActions(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "ParseException", ",", "IOException", "{", "Client", "client", "=", "new", "Client", "(", "new", "DumpProcessingController", "(", "\"wikidatawiki\"", ")", ",", "args", ")", ";", "client", ".", "performActions", "(", ")", ";", "}" ]
Launches the client with the specified parameters. @param args command line parameters @throws ParseException @throws IOException
[ "Launches", "the", "client", "with", "the", "specified", "parameters", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-client/src/main/java/org/wikidata/wdtk/client/Client.java#L292-L296
161,298
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java
RdfConverter.writeBasicDeclarations
public void writeBasicDeclarations() throws RDFHandlerException { for (Map.Entry<String, String> uriType : Vocabulary .getKnownVocabularyTypes().entrySet()) { this.rdfWriter.writeTripleUriObject(uriType.getKey(), RdfWriter.RDF_TYPE, uriType.getValue()); } }
java
public void writeBasicDeclarations() throws RDFHandlerException { for (Map.Entry<String, String> uriType : Vocabulary .getKnownVocabularyTypes().entrySet()) { this.rdfWriter.writeTripleUriObject(uriType.getKey(), RdfWriter.RDF_TYPE, uriType.getValue()); } }
[ "public", "void", "writeBasicDeclarations", "(", ")", "throws", "RDFHandlerException", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "uriType", ":", "Vocabulary", ".", "getKnownVocabularyTypes", "(", ")", ".", "entrySet", "(", ")", ")", "{", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "uriType", ".", "getKey", "(", ")", ",", "RdfWriter", ".", "RDF_TYPE", ",", "uriType", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Writes OWL declarations for all basic vocabulary elements used in the dump. @throws RDFHandlerException
[ "Writes", "OWL", "declarations", "for", "all", "basic", "vocabulary", "elements", "used", "in", "the", "dump", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java#L102-L108
161,299
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java
RdfConverter.writeInterPropertyLinks
void writeInterPropertyLinks(PropertyDocument document) throws RDFHandlerException { Resource subject = this.rdfWriter.getUri(document.getEntityId() .getIri()); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_DIRECT_CLAIM_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.DIRECT)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_CLAIM_PROP), Vocabulary.getPropertyUri( document.getEntityId(), PropertyContext.STATEMENT)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_STATEMENT_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.VALUE_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_STATEMENT_VALUE_PROP), Vocabulary.getPropertyUri(document.getEntityId(), PropertyContext.VALUE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_QUALIFIER_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.QUALIFIER_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_QUALIFIER_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.QUALIFIER)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_REFERENCE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.REFERENCE_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_REFERENCE_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.REFERENCE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_NO_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.NO_VALUE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_NO_QUALIFIER_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.NO_QUALIFIER_VALUE)); // TODO something more with NO_VALUE }
java
void writeInterPropertyLinks(PropertyDocument document) throws RDFHandlerException { Resource subject = this.rdfWriter.getUri(document.getEntityId() .getIri()); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_DIRECT_CLAIM_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.DIRECT)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_CLAIM_PROP), Vocabulary.getPropertyUri( document.getEntityId(), PropertyContext.STATEMENT)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_STATEMENT_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.VALUE_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_STATEMENT_VALUE_PROP), Vocabulary.getPropertyUri(document.getEntityId(), PropertyContext.VALUE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_QUALIFIER_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.QUALIFIER_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_QUALIFIER_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.QUALIFIER)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_REFERENCE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.REFERENCE_SIMPLE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_REFERENCE_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.REFERENCE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_NO_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.NO_VALUE)); this.rdfWriter.writeTripleUriObject(subject, this.rdfWriter .getUri(Vocabulary.WB_NO_QUALIFIER_VALUE_PROP), Vocabulary .getPropertyUri(document.getEntityId(), PropertyContext.NO_QUALIFIER_VALUE)); // TODO something more with NO_VALUE }
[ "void", "writeInterPropertyLinks", "(", "PropertyDocument", "document", ")", "throws", "RDFHandlerException", "{", "Resource", "subject", "=", "this", ".", "rdfWriter", ".", "getUri", "(", "document", ".", "getEntityId", "(", ")", ".", "getIri", "(", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_DIRECT_CLAIM_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "DIRECT", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_CLAIM_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "STATEMENT", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_STATEMENT_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "VALUE_SIMPLE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_STATEMENT_VALUE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "VALUE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_QUALIFIER_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "QUALIFIER_SIMPLE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_QUALIFIER_VALUE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "QUALIFIER", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_REFERENCE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "REFERENCE_SIMPLE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_REFERENCE_VALUE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "REFERENCE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_NO_VALUE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "NO_VALUE", ")", ")", ";", "this", ".", "rdfWriter", ".", "writeTripleUriObject", "(", "subject", ",", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "WB_NO_QUALIFIER_VALUE_PROP", ")", ",", "Vocabulary", ".", "getPropertyUri", "(", "document", ".", "getEntityId", "(", ")", ",", "PropertyContext", ".", "NO_QUALIFIER_VALUE", ")", ")", ";", "// TODO something more with NO_VALUE", "}" ]
Writes triples which conect properties with there corresponding rdf properties for statements, simple statements, qualifiers, reference attributes and values. @param document @throws RDFHandlerException
[ "Writes", "triples", "which", "conect", "properties", "with", "there", "corresponding", "rdf", "properties", "for", "statements", "simple", "statements", "qualifiers", "reference", "attributes", "and", "values", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/RdfConverter.java#L213-L265