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
partition
stringclasses
1 value
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java
SpiderSession.copyObjectIDsToBatch
private void copyObjectIDsToBatch(BatchResult batchResult, DBObjectBatch dbObjBatch) { if (batchResult.getResultObjectCount() < dbObjBatch.getObjectCount()) { m_logger.warn("Batch result returned fewer objects ({}) than input batch ({})", batchResult.getResultObjectCount(), dbObjBatch.getObjectCount()); } Iterator<ObjectResult> resultIter = batchResult.getResultObjects().iterator(); Iterator<DBObject> objectIter = dbObjBatch.getObjects().iterator(); while (resultIter.hasNext()) { if (!objectIter.hasNext()) { m_logger.warn("Batch result has more objects ({}) than input batch ({})!", batchResult.getResultObjectCount(), dbObjBatch.getObjectCount()); break; } ObjectResult objResult = resultIter.next(); DBObject dbObj = objectIter.next(); if (Utils.isEmpty(dbObj.getObjectID())) { dbObj.setObjectID(objResult.getObjectID()); } else if (!dbObj.getObjectID().equals(objResult.getObjectID())) { m_logger.warn("Batch results out of order: expected ID '{}', got '{}'", dbObj.getObjectID(), objResult.getObjectID()); } } }
java
private void copyObjectIDsToBatch(BatchResult batchResult, DBObjectBatch dbObjBatch) { if (batchResult.getResultObjectCount() < dbObjBatch.getObjectCount()) { m_logger.warn("Batch result returned fewer objects ({}) than input batch ({})", batchResult.getResultObjectCount(), dbObjBatch.getObjectCount()); } Iterator<ObjectResult> resultIter = batchResult.getResultObjects().iterator(); Iterator<DBObject> objectIter = dbObjBatch.getObjects().iterator(); while (resultIter.hasNext()) { if (!objectIter.hasNext()) { m_logger.warn("Batch result has more objects ({}) than input batch ({})!", batchResult.getResultObjectCount(), dbObjBatch.getObjectCount()); break; } ObjectResult objResult = resultIter.next(); DBObject dbObj = objectIter.next(); if (Utils.isEmpty(dbObj.getObjectID())) { dbObj.setObjectID(objResult.getObjectID()); } else if (!dbObj.getObjectID().equals(objResult.getObjectID())) { m_logger.warn("Batch results out of order: expected ID '{}', got '{}'", dbObj.getObjectID(), objResult.getObjectID()); } } }
[ "private", "void", "copyObjectIDsToBatch", "(", "BatchResult", "batchResult", ",", "DBObjectBatch", "dbObjBatch", ")", "{", "if", "(", "batchResult", ".", "getResultObjectCount", "(", ")", "<", "dbObjBatch", ".", "getObjectCount", "(", ")", ")", "{", "m_logger", ...
within the given DBObjectBatch.
[ "within", "the", "given", "DBObjectBatch", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java#L552-L574
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java
SpiderSession.verifyApplication
private void verifyApplication() { String ss = m_appDef.getStorageService(); if (Utils.isEmpty(ss) || !ss.startsWith("Spider")) { throw new RuntimeException("Application '" + m_appDef.getAppName() + "' is not an Spider application"); } }
java
private void verifyApplication() { String ss = m_appDef.getStorageService(); if (Utils.isEmpty(ss) || !ss.startsWith("Spider")) { throw new RuntimeException("Application '" + m_appDef.getAppName() + "' is not an Spider application"); } }
[ "private", "void", "verifyApplication", "(", ")", "{", "String", "ss", "=", "m_appDef", ".", "getStorageService", "(", ")", ";", "if", "(", "Utils", ".", "isEmpty", "(", "ss", ")", "||", "!", "ss", ".", "startsWith", "(", "\"Spider\"", ")", ")", "{", ...
Throw if this session's AppDef is not for a Spider app.
[ "Throw", "if", "this", "session", "s", "AppDef", "is", "not", "for", "a", "Spider", "app", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java#L577-L583
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java
CassandraNode.getVersionNumber
double getVersionNumber() { if(cassandraVersion > 0) { return cassandraVersion; } String version = getReleaseVersion(); if (version == null) { throw new IllegalStateException("Can't get Cassandra release version."); } String[] toks = version.split("\\."); if (toks.length >= 3) { try { StringBuilder b = new StringBuilder(); int len = toks[0].length(); if(len == 1) { b.append("00"); } else if (len == 2) { b.append("0"); } b.append(toks[0]); len = toks[1].length(); if(len == 1) { b.append("00"); } else if (len == 2) { b.append("0"); } b.append(toks[1]); for(int i = 0; i < toks[2].length(); i++) { char c = toks[2].charAt(i); if(Character.isDigit(c)) { if(i == 0) { b.append('.'); } b.append(c); } else { break; } } cassandraVersion = Double.valueOf(b.toString()); return cassandraVersion; } catch (Exception e) { } } throw new IllegalStateException("Can't parse Cassandra release version string: \"" + version + "\""); }
java
double getVersionNumber() { if(cassandraVersion > 0) { return cassandraVersion; } String version = getReleaseVersion(); if (version == null) { throw new IllegalStateException("Can't get Cassandra release version."); } String[] toks = version.split("\\."); if (toks.length >= 3) { try { StringBuilder b = new StringBuilder(); int len = toks[0].length(); if(len == 1) { b.append("00"); } else if (len == 2) { b.append("0"); } b.append(toks[0]); len = toks[1].length(); if(len == 1) { b.append("00"); } else if (len == 2) { b.append("0"); } b.append(toks[1]); for(int i = 0; i < toks[2].length(); i++) { char c = toks[2].charAt(i); if(Character.isDigit(c)) { if(i == 0) { b.append('.'); } b.append(c); } else { break; } } cassandraVersion = Double.valueOf(b.toString()); return cassandraVersion; } catch (Exception e) { } } throw new IllegalStateException("Can't parse Cassandra release version string: \"" + version + "\""); }
[ "double", "getVersionNumber", "(", ")", "{", "if", "(", "cassandraVersion", ">", "0", ")", "{", "return", "cassandraVersion", ";", "}", "String", "version", "=", "getReleaseVersion", "(", ")", ";", "if", "(", "version", "==", "null", ")", "{", "throw", "...
12.23.345bla-bla => 012023.345
[ "12", ".", "23", ".", "345bla", "-", "bla", "=", ">", "012023", ".", "345" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java#L234-L288
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java
CassandraNode.getDataMap_1_1
private Map<File, File[]> getDataMap_1_1(String[] dataDirs) { Map<File, File[]> map = new HashMap<File, File[]>(); boolean doLog = false; if(!lockedMessages.contains("getDataMap")) { lockedMessages.add("getDataMap"); doLog = true; } for (int i = 0; i < dataDirs.length; i++) { File dir = new File(dataDirs[i]); if (!dir.canRead()) { if(doLog) { logger.warn("Can't read: " + dir); } continue; } File[] ksList = dir.listFiles(); for (int j = 0; j < ksList.length; j++) { if (ksList[j].isDirectory()) { File[] familyList = ksList[j].listFiles(); for(int n = 0; n < familyList.length; n++) { if(familyList[n].isDirectory()) { ArrayList<File> snapshots = new ArrayList<File>(); File snDir = new File(familyList[n], SNAPSHOTS_DIR_NAME); if (snDir.isDirectory()) { File[] snList = snDir.listFiles(); for (int k = 0; k < snList.length; k++) { if (snList[k].isDirectory()) { snapshots.add(snList[k]); } } } map.put(familyList[n], snapshots.toArray(new File[snapshots.size()])); } } } } } // if(doLog) { // logger.debug("familiesCount=" + map.size()); // // for(File f : map.keySet()) { // File[] snaps = map.get(f); // logger.debug("family: " + f.getAbsolutePath() + ", snapshotsCount=" + snaps.length); // // for(int i = 0; i < snaps.length; i++) { // logger.debug("snaps[" + i + "]: " + snaps[i]); // } // } // } return map; }
java
private Map<File, File[]> getDataMap_1_1(String[] dataDirs) { Map<File, File[]> map = new HashMap<File, File[]>(); boolean doLog = false; if(!lockedMessages.contains("getDataMap")) { lockedMessages.add("getDataMap"); doLog = true; } for (int i = 0; i < dataDirs.length; i++) { File dir = new File(dataDirs[i]); if (!dir.canRead()) { if(doLog) { logger.warn("Can't read: " + dir); } continue; } File[] ksList = dir.listFiles(); for (int j = 0; j < ksList.length; j++) { if (ksList[j].isDirectory()) { File[] familyList = ksList[j].listFiles(); for(int n = 0; n < familyList.length; n++) { if(familyList[n].isDirectory()) { ArrayList<File> snapshots = new ArrayList<File>(); File snDir = new File(familyList[n], SNAPSHOTS_DIR_NAME); if (snDir.isDirectory()) { File[] snList = snDir.listFiles(); for (int k = 0; k < snList.length; k++) { if (snList[k].isDirectory()) { snapshots.add(snList[k]); } } } map.put(familyList[n], snapshots.toArray(new File[snapshots.size()])); } } } } } // if(doLog) { // logger.debug("familiesCount=" + map.size()); // // for(File f : map.keySet()) { // File[] snaps = map.get(f); // logger.debug("family: " + f.getAbsolutePath() + ", snapshotsCount=" + snaps.length); // // for(int i = 0; i < snaps.length; i++) { // logger.debug("snaps[" + i + "]: " + snaps[i]); // } // } // } return map; }
[ "private", "Map", "<", "File", ",", "File", "[", "]", ">", "getDataMap_1_1", "(", "String", "[", "]", "dataDirs", ")", "{", "Map", "<", "File", ",", "File", "[", "]", ">", "map", "=", "new", "HashMap", "<", "File", ",", "File", "[", "]", ">", "...
family-dir -> snapshot-dir-list
[ "family", "-", "dir", "-", ">", "snapshot", "-", "dir", "-", "list" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java#L1052-L1115
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java
CassandraNode.getDataMap
private Map<File, File> getDataMap(int vcode, String[] dataDirs, String snapshotName) { Map<File, File> map = new HashMap<File, File>(); Map<File, File[]> src = vcode==0 ? getDataMap_1_0(dataDirs) : getDataMap_1_1(dataDirs); for (File ks : src.keySet()) { File[] sn = src.get(ks); if (sn != null) { for (int i = 0; i < sn.length; i++) { if (snapshotName.equals(sn[i].getName())) { map.put(ks, sn[i]); break; } } } } return map; }
java
private Map<File, File> getDataMap(int vcode, String[] dataDirs, String snapshotName) { Map<File, File> map = new HashMap<File, File>(); Map<File, File[]> src = vcode==0 ? getDataMap_1_0(dataDirs) : getDataMap_1_1(dataDirs); for (File ks : src.keySet()) { File[] sn = src.get(ks); if (sn != null) { for (int i = 0; i < sn.length; i++) { if (snapshotName.equals(sn[i].getName())) { map.put(ks, sn[i]); break; } } } } return map; }
[ "private", "Map", "<", "File", ",", "File", ">", "getDataMap", "(", "int", "vcode", ",", "String", "[", "]", "dataDirs", ",", "String", "snapshotName", ")", "{", "Map", "<", "File", ",", "File", ">", "map", "=", "new", "HashMap", "<", "File", ",", ...
keyspace-dir -> snapshot-dir
[ "keyspace", "-", "dir", "-", ">", "snapshot", "-", "dir" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/mbeans/CassandraNode.java#L1118-L1136
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java
HelloDory.run
private void run(String[] args) { if (args.length != 2) { usage(); } System.out.println("Opening Doradus server: " + args[0] + ":" + args[1]); try (DoradusClient client = new DoradusClient(args[0], Integer.parseInt(args[1]))) { deleteApplication(client); createApplication(client); addData(client); queryData(client); deleteData(client); } }
java
private void run(String[] args) { if (args.length != 2) { usage(); } System.out.println("Opening Doradus server: " + args[0] + ":" + args[1]); try (DoradusClient client = new DoradusClient(args[0], Integer.parseInt(args[1]))) { deleteApplication(client); createApplication(client); addData(client); queryData(client); deleteData(client); } }
[ "private", "void", "run", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "!=", "2", ")", "{", "usage", "(", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"Opening Doradus server: \"", "+", "args", "[", "0...
Create a Dory client connection and execute the example commands.
[ "Create", "a", "Dory", "client", "connection", "and", "execute", "the", "example", "commands", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java#L84-L97
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java
HelloDory.deleteApplication
private void deleteApplication(DoradusClient client) { Command command = Command.builder() .withName("DeleteAppWithKey") .withParam("application", "HelloSpider") .withParam("key", "Arachnid") .build(); client.runCommand(command); // Ignore response }
java
private void deleteApplication(DoradusClient client) { Command command = Command.builder() .withName("DeleteAppWithKey") .withParam("application", "HelloSpider") .withParam("key", "Arachnid") .build(); client.runCommand(command); // Ignore response }
[ "private", "void", "deleteApplication", "(", "DoradusClient", "client", ")", "{", "Command", "command", "=", "Command", ".", "builder", "(", ")", ".", "withName", "(", "\"DeleteAppWithKey\"", ")", ".", "withParam", "(", "\"application\"", ",", "\"HelloSpider\"", ...
Delete the existing HelloSpider application if present.
[ "Delete", "the", "existing", "HelloSpider", "application", "if", "present", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java#L102-L109
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java
HelloDory.createApplication
private void createApplication(DoradusClient client) { ApplicationDefinition appDef = ApplicationDefinition.builder() .withName("HelloSpider") .withKey("Arachnid") .withOption("StorageService", "SpiderService") .withTable(TableDefinition.builder() .withName("Movies") .withField(FieldDefinition.builder().withName("Name").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("ReleaseDate").withType(FieldType.TIMESTAMP).build()) .withField(FieldDefinition.builder().withName("Cancelled").withType(FieldType.BOOLEAN).build()) .withField(FieldDefinition.builder().withName("Director").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("Leads").withType(FieldType.LINK).withExtent("Actors").withInverse("ActedIn").build()) .withField(FieldDefinition.builder().withName("Budget").withType(FieldType.INTEGER).build()) .build() ) .withTable(TableDefinition.builder() .withName("Actors") .withField(FieldDefinition.builder().withName("FirstName").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("LastName").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("ActedIn").withType(FieldType.LINK).withExtent("Movies").withInverse("Leads").build()) .build() ).build(); Command command = Command.builder() .withName("DefineApp") .withParam("ApplicationDefinition", appDef) .build(); RESTResponse response = client.runCommand(command); if (response.isFailed()) { throw new RuntimeException("DefineApp failed: " + response); } }
java
private void createApplication(DoradusClient client) { ApplicationDefinition appDef = ApplicationDefinition.builder() .withName("HelloSpider") .withKey("Arachnid") .withOption("StorageService", "SpiderService") .withTable(TableDefinition.builder() .withName("Movies") .withField(FieldDefinition.builder().withName("Name").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("ReleaseDate").withType(FieldType.TIMESTAMP).build()) .withField(FieldDefinition.builder().withName("Cancelled").withType(FieldType.BOOLEAN).build()) .withField(FieldDefinition.builder().withName("Director").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("Leads").withType(FieldType.LINK).withExtent("Actors").withInverse("ActedIn").build()) .withField(FieldDefinition.builder().withName("Budget").withType(FieldType.INTEGER).build()) .build() ) .withTable(TableDefinition.builder() .withName("Actors") .withField(FieldDefinition.builder().withName("FirstName").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("LastName").withType(FieldType.TEXT).build()) .withField(FieldDefinition.builder().withName("ActedIn").withType(FieldType.LINK).withExtent("Movies").withInverse("Leads").build()) .build() ).build(); Command command = Command.builder() .withName("DefineApp") .withParam("ApplicationDefinition", appDef) .build(); RESTResponse response = client.runCommand(command); if (response.isFailed()) { throw new RuntimeException("DefineApp failed: " + response); } }
[ "private", "void", "createApplication", "(", "DoradusClient", "client", ")", "{", "ApplicationDefinition", "appDef", "=", "ApplicationDefinition", ".", "builder", "(", ")", ".", "withName", "(", "\"HelloSpider\"", ")", ".", "withKey", "(", "\"Arachnid\"", ")", "."...
Create the HelloSpider application definition.
[ "Create", "the", "HelloSpider", "application", "definition", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java#L112-L142
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java
HelloDory.deleteData
private void deleteData(DoradusClient client) { DBObject dbObject = DBObject.builder() .withValue("_ID", "TMaguire") .build(); DBObjectBatch dbObjectBatch = DBObjectBatch.builder().withObject(dbObject).build(); Command command = Command.builder().withName("Delete") .withParam("application", "HelloSpider") .withParam("table", "Actors") .withParam("batch", dbObjectBatch) .build(); RESTResponse response = client.runCommand(command); if (response.isFailed()) { throw new RuntimeException("Delete batch failed: " + response.getBody()); } }
java
private void deleteData(DoradusClient client) { DBObject dbObject = DBObject.builder() .withValue("_ID", "TMaguire") .build(); DBObjectBatch dbObjectBatch = DBObjectBatch.builder().withObject(dbObject).build(); Command command = Command.builder().withName("Delete") .withParam("application", "HelloSpider") .withParam("table", "Actors") .withParam("batch", dbObjectBatch) .build(); RESTResponse response = client.runCommand(command); if (response.isFailed()) { throw new RuntimeException("Delete batch failed: " + response.getBody()); } }
[ "private", "void", "deleteData", "(", "DoradusClient", "client", ")", "{", "DBObject", "dbObject", "=", "DBObject", ".", "builder", "(", ")", ".", "withValue", "(", "\"_ID\"", ",", "\"TMaguire\"", ")", ".", "build", "(", ")", ";", "DBObjectBatch", "dbObjectB...
Delete data by ID
[ "Delete", "data", "by", "ID" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/HelloDory.java#L267-L281
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/CSVDumper.java
CSVDumper.loadSchema
private void loadSchema() { m_logger.info("Loading schema for application: {}", m_config.app); m_client = new Client(m_config.host, m_config.port, m_config.getTLSParams()); m_client.setCredentials(m_config.getCredentials()); m_session = m_client.openApplication(m_config.app); // throws if unknown app m_appDef = m_session.getAppDef(); if (m_config.optimize) { computeLinkFanouts(); } }
java
private void loadSchema() { m_logger.info("Loading schema for application: {}", m_config.app); m_client = new Client(m_config.host, m_config.port, m_config.getTLSParams()); m_client.setCredentials(m_config.getCredentials()); m_session = m_client.openApplication(m_config.app); // throws if unknown app m_appDef = m_session.getAppDef(); if (m_config.optimize) { computeLinkFanouts(); } }
[ "private", "void", "loadSchema", "(", ")", "{", "m_logger", ".", "info", "(", "\"Loading schema for application: {}\"", ",", "m_config", ".", "app", ")", ";", "m_client", "=", "new", "Client", "(", "m_config", ".", "host", ",", "m_config", ".", "port", ",", ...
Connect to the Doradus server and download the requested application's schema.
[ "Connect", "to", "the", "Doradus", "server", "and", "download", "the", "requested", "application", "s", "schema", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/CSVDumper.java#L247-L256
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/utils/CSVDumper.java
CSVDumper.computeLinkFanouts
private void computeLinkFanouts(TableDefinition tableDef, Map<String, MutableFloat> tableLinkFanoutMap) { m_logger.info("Computing link field fanouts for table: {}", tableDef.getTableName()); StringBuilder buffer = new StringBuilder(); for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { if (fieldDef.isLinkField()) { if (buffer.length() > 0) { buffer.append(","); } buffer.append(fieldDef.getName()); } } if (buffer.length() == 0) { return; } Map<String, String> queryParams = new HashMap<>(); queryParams.put("q", "*"); queryParams.put("f", buffer.toString()); queryParams.put("s", Integer.toString(LINK_FANOUT_SAMPLE_SIZE)); if (m_session instanceof OLAPSession) { queryParams.put("shards", m_config.shard); } QueryResult qResult = m_session.objectQuery(tableDef.getTableName(), queryParams); Collection<DBObject> objectSet = qResult.getResultObjects(); if (objectSet.size() == 0) { return; } Map<String, AtomicInteger> linkValueCounts = new HashMap<String, AtomicInteger>(); int totalObjs = 0; for (DBObject dbObj : objectSet) { totalObjs++; for (String fieldName : dbObj.getFieldNames()) { if (tableDef.isLinkField(fieldName)) { Collection<String> linkValues = dbObj.getFieldValues(fieldName); AtomicInteger totalLinkValues = linkValueCounts.get(fieldName); if (totalLinkValues == null) { linkValueCounts.put(fieldName, new AtomicInteger(linkValues.size())); } else { totalLinkValues.addAndGet(linkValues.size()); } } } } for (String fieldName : linkValueCounts.keySet()) { AtomicInteger totalLinkValues = linkValueCounts.get(fieldName); float linkFanout = totalLinkValues.get() / (float)totalObjs; // may round to 0 m_logger.info("Average fanout for link {}: {}", fieldName, linkFanout); tableLinkFanoutMap.put(fieldName, new MutableFloat(linkFanout)); } }
java
private void computeLinkFanouts(TableDefinition tableDef, Map<String, MutableFloat> tableLinkFanoutMap) { m_logger.info("Computing link field fanouts for table: {}", tableDef.getTableName()); StringBuilder buffer = new StringBuilder(); for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { if (fieldDef.isLinkField()) { if (buffer.length() > 0) { buffer.append(","); } buffer.append(fieldDef.getName()); } } if (buffer.length() == 0) { return; } Map<String, String> queryParams = new HashMap<>(); queryParams.put("q", "*"); queryParams.put("f", buffer.toString()); queryParams.put("s", Integer.toString(LINK_FANOUT_SAMPLE_SIZE)); if (m_session instanceof OLAPSession) { queryParams.put("shards", m_config.shard); } QueryResult qResult = m_session.objectQuery(tableDef.getTableName(), queryParams); Collection<DBObject> objectSet = qResult.getResultObjects(); if (objectSet.size() == 0) { return; } Map<String, AtomicInteger> linkValueCounts = new HashMap<String, AtomicInteger>(); int totalObjs = 0; for (DBObject dbObj : objectSet) { totalObjs++; for (String fieldName : dbObj.getFieldNames()) { if (tableDef.isLinkField(fieldName)) { Collection<String> linkValues = dbObj.getFieldValues(fieldName); AtomicInteger totalLinkValues = linkValueCounts.get(fieldName); if (totalLinkValues == null) { linkValueCounts.put(fieldName, new AtomicInteger(linkValues.size())); } else { totalLinkValues.addAndGet(linkValues.size()); } } } } for (String fieldName : linkValueCounts.keySet()) { AtomicInteger totalLinkValues = linkValueCounts.get(fieldName); float linkFanout = totalLinkValues.get() / (float)totalObjs; // may round to 0 m_logger.info("Average fanout for link {}: {}", fieldName, linkFanout); tableLinkFanoutMap.put(fieldName, new MutableFloat(linkFanout)); } }
[ "private", "void", "computeLinkFanouts", "(", "TableDefinition", "tableDef", ",", "Map", "<", "String", ",", "MutableFloat", ">", "tableLinkFanoutMap", ")", "{", "m_logger", ".", "info", "(", "\"Computing link field fanouts for table: {}\"", ",", "tableDef", ".", "get...
Compute link fanouts for the given table
[ "Compute", "link", "fanouts", "for", "the", "given", "table" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/utils/CSVDumper.java#L358-L410
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java
TimerGroup.start
private void start(long time, String name){ name = getName(name); TimerGroupItem timer = m_timers.get(name); if (timer == null){ timer = new TimerGroupItem(name); m_timers.put(name, timer); } timer.start(time); m_total.start(time); }
java
private void start(long time, String name){ name = getName(name); TimerGroupItem timer = m_timers.get(name); if (timer == null){ timer = new TimerGroupItem(name); m_timers.put(name, timer); } timer.start(time); m_total.start(time); }
[ "private", "void", "start", "(", "long", "time", ",", "String", "name", ")", "{", "name", "=", "getName", "(", "name", ")", ";", "TimerGroupItem", "timer", "=", "m_timers", ".", "get", "(", "name", ")", ";", "if", "(", "timer", "==", "null", ")", "...
Start the named timer if the condition is true.
[ "Start", "the", "named", "timer", "if", "the", "condition", "is", "true", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java#L153-L162
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java
TimerGroup.stop
private long stop(long time, String name){ m_total.stop(time); TimerGroupItem timer = m_timers.get(getName(name)); long elapsedTime = 0; if (timer != null){ elapsedTime = timer.stop(time); } checkLog(time); return elapsedTime; }
java
private long stop(long time, String name){ m_total.stop(time); TimerGroupItem timer = m_timers.get(getName(name)); long elapsedTime = 0; if (timer != null){ elapsedTime = timer.stop(time); } checkLog(time); return elapsedTime; }
[ "private", "long", "stop", "(", "long", "time", ",", "String", "name", ")", "{", "m_total", ".", "stop", "(", "time", ")", ";", "TimerGroupItem", "timer", "=", "m_timers", ".", "get", "(", "getName", "(", "name", ")", ")", ";", "long", "elapsedTime", ...
Stop the named timer if the condition is true.
[ "Stop", "the", "named", "timer", "if", "the", "condition", "is", "true", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java#L174-L183
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java
TimerGroup.log
private void log(boolean finalLog, String format, Object... args) { if (m_condition){ if (format != null ){ m_logger.debug(String.format(format, args)); } ArrayList<String> timerNames = new ArrayList<String>(m_timers.keySet()); Collections.sort(timerNames); for (String name : timerNames){ TimerGroupItem timer = m_timers.get(name); if (finalLog || timer.changed()){ m_logger.debug(timer.toString(finalLog)); } } m_logger.debug(m_total.toString(finalLog)); ArrayList<String> counterNames = new ArrayList<String>(m_counters.keySet()); Collections.sort(counterNames); for (String name : counterNames){ Counter counter = m_counters.get(name); if (finalLog || counter.changed()){ String text = String.format("%s: (%s)", name, counter.toString(finalLog)); m_logger.debug(text); } } } }
java
private void log(boolean finalLog, String format, Object... args) { if (m_condition){ if (format != null ){ m_logger.debug(String.format(format, args)); } ArrayList<String> timerNames = new ArrayList<String>(m_timers.keySet()); Collections.sort(timerNames); for (String name : timerNames){ TimerGroupItem timer = m_timers.get(name); if (finalLog || timer.changed()){ m_logger.debug(timer.toString(finalLog)); } } m_logger.debug(m_total.toString(finalLog)); ArrayList<String> counterNames = new ArrayList<String>(m_counters.keySet()); Collections.sort(counterNames); for (String name : counterNames){ Counter counter = m_counters.get(name); if (finalLog || counter.changed()){ String text = String.format("%s: (%s)", name, counter.toString(finalLog)); m_logger.debug(text); } } } }
[ "private", "void", "log", "(", "boolean", "finalLog", ",", "String", "format", ",", "Object", "...", "args", ")", "{", "if", "(", "m_condition", ")", "{", "if", "(", "format", "!=", "null", ")", "{", "m_logger", ".", "debug", "(", "String", ".", "for...
Log elapsed time of all named timers if the condition is true.
[ "Log", "elapsed", "time", "of", "all", "named", "timers", "if", "the", "condition", "is", "true", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/utilities/TimerGroup.java#L199-L223
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java
DBObjectBatch.parse
public void parse(UNode rootNode) { assert rootNode != null; // Ensure root node is named "batch". Utils.require(rootNode.getName().equals("batch"), "'batch' expected: " + rootNode.getName()); // Parse child nodes. for (String memberName : rootNode.getMemberNames()) { UNode childNode = rootNode.getMember(memberName); if (childNode.getName().equals("docs")) { Utils.require(childNode.isCollection(), "'docs' must be a collection: " + childNode); for (UNode docNode : childNode.getMemberList()) { Utils.require(docNode.getName().equals("doc"), "'doc' node expected as child of 'docs': " + docNode); addObject(new DBObject()).parse(docNode); } } else { Utils.require(false, "Unrecognized child node of 'batch': " + memberName); } } }
java
public void parse(UNode rootNode) { assert rootNode != null; // Ensure root node is named "batch". Utils.require(rootNode.getName().equals("batch"), "'batch' expected: " + rootNode.getName()); // Parse child nodes. for (String memberName : rootNode.getMemberNames()) { UNode childNode = rootNode.getMember(memberName); if (childNode.getName().equals("docs")) { Utils.require(childNode.isCollection(), "'docs' must be a collection: " + childNode); for (UNode docNode : childNode.getMemberList()) { Utils.require(docNode.getName().equals("doc"), "'doc' node expected as child of 'docs': " + docNode); addObject(new DBObject()).parse(docNode); } } else { Utils.require(false, "Unrecognized child node of 'batch': " + memberName); } } }
[ "public", "void", "parse", "(", "UNode", "rootNode", ")", "{", "assert", "rootNode", "!=", "null", ";", "// Ensure root node is named \"batch\".\r", "Utils", ".", "require", "(", "rootNode", ".", "getName", "(", ")", ".", "equals", "(", "\"batch\"", ")", ",", ...
Parse a batch object update rooted at the given UNode. The root node must be a MAP named "batch". Child nodes must be a recognized option or a "docs" array containing "doc" objects. An exception is thrown if the batch is malformed. @param rootNode Root node of a UNode tree defined an object update batch.
[ "Parse", "a", "batch", "object", "update", "rooted", "at", "the", "given", "UNode", ".", "The", "root", "node", "must", "be", "a", "MAP", "named", "batch", ".", "Child", "nodes", "must", "be", "a", "recognized", "option", "or", "a", "docs", "array", "c...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java#L221-L242
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java
DBObjectBatch.toDoc
public UNode toDoc() { // Root object is a MAP called "batch". UNode batchNode = UNode.createMapNode("batch"); // Add a "docs" node as an array. UNode docsNode = batchNode.addArrayNode("docs"); for (DBObject dbObj : m_dbObjList) { docsNode.addChildNode(dbObj.toDoc()); } return batchNode; }
java
public UNode toDoc() { // Root object is a MAP called "batch". UNode batchNode = UNode.createMapNode("batch"); // Add a "docs" node as an array. UNode docsNode = batchNode.addArrayNode("docs"); for (DBObject dbObj : m_dbObjList) { docsNode.addChildNode(dbObj.toDoc()); } return batchNode; }
[ "public", "UNode", "toDoc", "(", ")", "{", "// Root object is a MAP called \"batch\".\r", "UNode", "batchNode", "=", "UNode", ".", "createMapNode", "(", "\"batch\"", ")", ";", "// Add a \"docs\" node as an array.\r", "UNode", "docsNode", "=", "batchNode", ".", "addArray...
Serialize this DBObjectBatch object into a UNode tree and return the root node. @return Root node of a UNode tree representing this batch update.
[ "Serialize", "this", "DBObjectBatch", "object", "into", "a", "UNode", "tree", "and", "return", "the", "root", "node", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java#L270-L280
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java
DBObjectBatch.addObject
public DBObject addObject(String objID, String tableName) { DBObject dbObj = new DBObject(objID, tableName); m_dbObjList.add(dbObj); return dbObj; }
java
public DBObject addObject(String objID, String tableName) { DBObject dbObj = new DBObject(objID, tableName); m_dbObjList.add(dbObj); return dbObj; }
[ "public", "DBObject", "addObject", "(", "String", "objID", ",", "String", "tableName", ")", "{", "DBObject", "dbObj", "=", "new", "DBObject", "(", "objID", ",", "tableName", ")", ";", "m_dbObjList", ".", "add", "(", "dbObj", ")", ";", "return", "dbObj", ...
Create a new DBObject with the given object ID and table name, add it to this DBObjectBatch, and return it. @param objID New DBObject's object ID, if any. @param tableName New DBObject's table name, if any. @return New DBObject.
[ "Create", "a", "new", "DBObject", "with", "the", "given", "object", "ID", "and", "table", "name", "add", "it", "to", "this", "DBObjectBatch", "and", "return", "it", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/DBObjectBatch.java#L303-L307
train
QSFT/Doradus
doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java
JettyWebServer.configureJettyServer
private Server configureJettyServer() { LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(m_maxTaskQueue); QueuedThreadPool threadPool = new QueuedThreadPool(m_maxconns, m_defaultMinThreads, m_defaultIdleTimeout, taskQueue); Server server = new Server(threadPool); server.setStopAtShutdown(true); return server; }
java
private Server configureJettyServer() { LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(m_maxTaskQueue); QueuedThreadPool threadPool = new QueuedThreadPool(m_maxconns, m_defaultMinThreads, m_defaultIdleTimeout, taskQueue); Server server = new Server(threadPool); server.setStopAtShutdown(true); return server; }
[ "private", "Server", "configureJettyServer", "(", ")", "{", "LinkedBlockingQueue", "<", "Runnable", ">", "taskQueue", "=", "new", "LinkedBlockingQueue", "<", "Runnable", ">", "(", "m_maxTaskQueue", ")", ";", "QueuedThreadPool", "threadPool", "=", "new", "QueuedThrea...
Create, configure, and return the Jetty Server object.
[ "Create", "configure", "and", "return", "the", "Jetty", "Server", "object", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java#L157-L164
train
QSFT/Doradus
doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java
JettyWebServer.configureConnector
private ServerConnector configureConnector() { ServerConnector connector = null; if (m_tls) { connector = createSSLConnector(); } else { // Unsecured connector connector = new ServerConnector(m_jettyServer); } if (m_restaddr != null) { connector.setHost(m_restaddr); } connector.setPort(m_restport); connector.setIdleTimeout(SOCKET_TIMEOUT_MILLIS); connector.addBean(new ConnListener()); // invokes registered callbacks, if any return connector; }
java
private ServerConnector configureConnector() { ServerConnector connector = null; if (m_tls) { connector = createSSLConnector(); } else { // Unsecured connector connector = new ServerConnector(m_jettyServer); } if (m_restaddr != null) { connector.setHost(m_restaddr); } connector.setPort(m_restport); connector.setIdleTimeout(SOCKET_TIMEOUT_MILLIS); connector.addBean(new ConnListener()); // invokes registered callbacks, if any return connector; }
[ "private", "ServerConnector", "configureConnector", "(", ")", "{", "ServerConnector", "connector", "=", "null", ";", "if", "(", "m_tls", ")", "{", "connector", "=", "createSSLConnector", "(", ")", ";", "}", "else", "{", "// Unsecured connector", "connector", "="...
Create, configure, and return the ServerConnector object.
[ "Create", "configure", "and", "return", "the", "ServerConnector", "object", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java#L167-L182
train
QSFT/Doradus
doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java
JettyWebServer.configureHandler
private ServletHandler configureHandler(String servletClassName) { ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(servletClassName, "/*"); return handler; }
java
private ServletHandler configureHandler(String servletClassName) { ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(servletClassName, "/*"); return handler; }
[ "private", "ServletHandler", "configureHandler", "(", "String", "servletClassName", ")", "{", "ServletHandler", "handler", "=", "new", "ServletHandler", "(", ")", ";", "handler", ".", "addServletWithMapping", "(", "servletClassName", ",", "\"/*\"", ")", ";", "return...
Create, configure, and return the ServletHandler object.
[ "Create", "configure", "and", "return", "the", "ServletHandler", "object", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-jetty/src/main/java/com/dell/doradus/server/JettyWebServer.java#L185-L189
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java
Task.run
@Override public final void run() { String taskID = m_taskRecord.getTaskID(); m_logger.debug("Starting task '{}' in tenant '{}'", taskID, m_tenant); try { TaskManagerService.instance().registerTaskStarted(this); m_lastProgressTimestamp = System.currentTimeMillis(); setTaskStart(); execute(); setTaskFinish(); } catch (Throwable e) { m_logger.error("Task '" + taskID + "' failed", e); String stackTrace = Utils.getStackTrace(e); setTaskFailed(stackTrace); } finally { TaskManagerService.instance().registerTaskEnded(this); } }
java
@Override public final void run() { String taskID = m_taskRecord.getTaskID(); m_logger.debug("Starting task '{}' in tenant '{}'", taskID, m_tenant); try { TaskManagerService.instance().registerTaskStarted(this); m_lastProgressTimestamp = System.currentTimeMillis(); setTaskStart(); execute(); setTaskFinish(); } catch (Throwable e) { m_logger.error("Task '" + taskID + "' failed", e); String stackTrace = Utils.getStackTrace(e); setTaskFailed(stackTrace); } finally { TaskManagerService.instance().registerTaskEnded(this); } }
[ "@", "Override", "public", "final", "void", "run", "(", ")", "{", "String", "taskID", "=", "m_taskRecord", ".", "getTaskID", "(", ")", ";", "m_logger", ".", "debug", "(", "\"Starting task '{}' in tenant '{}'\"", ",", "taskID", ",", "m_tenant", ")", ";", "try...
Called by the TaskManagerService to begin the execution of the task.
[ "Called", "by", "the", "TaskManagerService", "to", "begin", "the", "execution", "of", "the", "task", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java#L110-L127
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java
Task.setTaskStart
private void setTaskStart() { m_taskRecord.setProperty(TaskRecord.PROP_EXECUTOR, m_hostID); m_taskRecord.setProperty(TaskRecord.PROP_START_TIME, Long.toString(System.currentTimeMillis())); m_taskRecord.setProperty(TaskRecord.PROP_FINISH_TIME, null); m_taskRecord.setProperty(TaskRecord.PROP_PROGRESS, null); m_taskRecord.setProperty(TaskRecord.PROP_PROGRESS_TIME, null); m_taskRecord.setProperty(TaskRecord.PROP_FAIL_REASON, null); m_taskRecord.setStatus(TaskStatus.IN_PROGRESS); TaskManagerService.instance().updateTaskStatus(m_tenant, m_taskRecord, false); }
java
private void setTaskStart() { m_taskRecord.setProperty(TaskRecord.PROP_EXECUTOR, m_hostID); m_taskRecord.setProperty(TaskRecord.PROP_START_TIME, Long.toString(System.currentTimeMillis())); m_taskRecord.setProperty(TaskRecord.PROP_FINISH_TIME, null); m_taskRecord.setProperty(TaskRecord.PROP_PROGRESS, null); m_taskRecord.setProperty(TaskRecord.PROP_PROGRESS_TIME, null); m_taskRecord.setProperty(TaskRecord.PROP_FAIL_REASON, null); m_taskRecord.setStatus(TaskStatus.IN_PROGRESS); TaskManagerService.instance().updateTaskStatus(m_tenant, m_taskRecord, false); }
[ "private", "void", "setTaskStart", "(", ")", "{", "m_taskRecord", ".", "setProperty", "(", "TaskRecord", ".", "PROP_EXECUTOR", ",", "m_hostID", ")", ";", "m_taskRecord", ".", "setProperty", "(", "TaskRecord", ".", "PROP_START_TIME", ",", "Long", ".", "toString",...
Update the job status record that shows this job has started.
[ "Update", "the", "job", "status", "record", "that", "shows", "this", "job", "has", "started", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java#L170-L179
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java
Task.setTaskFailed
private void setTaskFailed(String reason) { m_taskRecord.setProperty(TaskRecord.PROP_EXECUTOR, m_hostID); m_taskRecord.setProperty(TaskRecord.PROP_FINISH_TIME, Long.toString(System.currentTimeMillis())); m_taskRecord.setProperty(TaskRecord.PROP_FAIL_REASON, reason); m_taskRecord.setStatus(TaskStatus.FAILED); TaskManagerService.instance().updateTaskStatus(m_tenant, m_taskRecord, true); }
java
private void setTaskFailed(String reason) { m_taskRecord.setProperty(TaskRecord.PROP_EXECUTOR, m_hostID); m_taskRecord.setProperty(TaskRecord.PROP_FINISH_TIME, Long.toString(System.currentTimeMillis())); m_taskRecord.setProperty(TaskRecord.PROP_FAIL_REASON, reason); m_taskRecord.setStatus(TaskStatus.FAILED); TaskManagerService.instance().updateTaskStatus(m_tenant, m_taskRecord, true); }
[ "private", "void", "setTaskFailed", "(", "String", "reason", ")", "{", "m_taskRecord", ".", "setProperty", "(", "TaskRecord", ".", "PROP_EXECUTOR", ",", "m_hostID", ")", ";", "m_taskRecord", ".", "setProperty", "(", "TaskRecord", ".", "PROP_FINISH_TIME", ",", "L...
Update the job status record that shows this job has failed.
[ "Update", "the", "job", "status", "record", "that", "shows", "this", "job", "has", "failed", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/Task.java#L198-L204
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.reconnect
private void reconnect() throws IOException { // First ensure we're closed. close(); // Attempt to re-open. try { createSocket(); } catch (Exception e) { e.printStackTrace(); throw new IOException("Cannot connect to server", e); } m_inStream = m_socket.getInputStream(); m_outStream = m_socket.getOutputStream(); }
java
private void reconnect() throws IOException { // First ensure we're closed. close(); // Attempt to re-open. try { createSocket(); } catch (Exception e) { e.printStackTrace(); throw new IOException("Cannot connect to server", e); } m_inStream = m_socket.getInputStream(); m_outStream = m_socket.getOutputStream(); }
[ "private", "void", "reconnect", "(", ")", "throws", "IOException", "{", "// First ensure we're closed.\r", "close", "(", ")", ";", "// Attempt to re-open.\r", "try", "{", "createSocket", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", ...
Attempt to reconnect to the Doradus server
[ "Attempt", "to", "reconnect", "to", "the", "Doradus", "server" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L352-L365
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.sendAndReceive
private RESTResponse sendAndReceive(HttpMethod method, String uri, Map<String, String> headers, byte[] body) throws IOException { // Add standard headers assert headers != null; headers.put(HttpDefs.HOST, m_host); headers.put(HttpDefs.ACCEPT, m_acceptFormat.toString()); headers.put(HttpDefs.CONTENT_LENGTH, Integer.toString(body == null ? 0 : body.length)); if (m_bCompress) { headers.put(HttpDefs.ACCEPT_ENCODING, "gzip"); } if (m_credentials != null) { String authString = "Basic " + Utils.base64FromString(m_credentials.getUserid() + ":" + m_credentials.getPassword()); headers.put("Authorization", authString); } // Form the message header. StringBuilder buffer = new StringBuilder(); buffer.append(method.toString()); buffer.append(" "); buffer.append(addTenantParam(uri)); buffer.append(" HTTP/1.1\r\n"); for (String name : headers.keySet()) { buffer.append(name); buffer.append(": "); buffer.append(headers.get(name)); buffer.append("\r\n"); } buffer.append("\r\n"); m_logger.debug("Sending request to uri '{}'; message length={}", uri, headers.get(HttpDefs.CONTENT_LENGTH)); return sendAndReceive(buffer.toString(), body); }
java
private RESTResponse sendAndReceive(HttpMethod method, String uri, Map<String, String> headers, byte[] body) throws IOException { // Add standard headers assert headers != null; headers.put(HttpDefs.HOST, m_host); headers.put(HttpDefs.ACCEPT, m_acceptFormat.toString()); headers.put(HttpDefs.CONTENT_LENGTH, Integer.toString(body == null ? 0 : body.length)); if (m_bCompress) { headers.put(HttpDefs.ACCEPT_ENCODING, "gzip"); } if (m_credentials != null) { String authString = "Basic " + Utils.base64FromString(m_credentials.getUserid() + ":" + m_credentials.getPassword()); headers.put("Authorization", authString); } // Form the message header. StringBuilder buffer = new StringBuilder(); buffer.append(method.toString()); buffer.append(" "); buffer.append(addTenantParam(uri)); buffer.append(" HTTP/1.1\r\n"); for (String name : headers.keySet()) { buffer.append(name); buffer.append(": "); buffer.append(headers.get(name)); buffer.append("\r\n"); } buffer.append("\r\n"); m_logger.debug("Sending request to uri '{}'; message length={}", uri, headers.get(HttpDefs.CONTENT_LENGTH)); return sendAndReceive(buffer.toString(), body); }
[ "private", "RESTResponse", "sendAndReceive", "(", "HttpMethod", "method", ",", "String", "uri", ",", "Map", "<", "String", ",", "String", ">", "headers", ",", "byte", "[", "]", "body", ")", "throws", "IOException", "{", "// Add standard headers\r", "assert", "...
Add standard headers to the given request and send it.
[ "Add", "standard", "headers", "to", "the", "given", "request", "and", "send", "it", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L368-L403
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.sendAndReceive
private RESTResponse sendAndReceive(String header, byte[] body) throws IOException { // Fail before trying if socket has been closed. if (isClosed()) { throw new IOException("Socket has been closed"); } Exception lastException = null; for (int attempt = 0; attempt < MAX_SOCKET_RETRIES; attempt++) { try { sendRequest(header, body); return readResponse(); } catch (IOException e) { // Attempt to reconnect; if this fails, the server's probably down and we // let reconnect's IOException pass through. lastException = e; m_logger.warn("Socket error occurred -- reconnecting", e); reconnect(); } } // Here, all reconnects succeeded but retries failed; something else is wrong with // the server or the request. throw new IOException("Socket error; all retries failed", lastException); }
java
private RESTResponse sendAndReceive(String header, byte[] body) throws IOException { // Fail before trying if socket has been closed. if (isClosed()) { throw new IOException("Socket has been closed"); } Exception lastException = null; for (int attempt = 0; attempt < MAX_SOCKET_RETRIES; attempt++) { try { sendRequest(header, body); return readResponse(); } catch (IOException e) { // Attempt to reconnect; if this fails, the server's probably down and we // let reconnect's IOException pass through. lastException = e; m_logger.warn("Socket error occurred -- reconnecting", e); reconnect(); } } // Here, all reconnects succeeded but retries failed; something else is wrong with // the server or the request. throw new IOException("Socket error; all retries failed", lastException); }
[ "private", "RESTResponse", "sendAndReceive", "(", "String", "header", ",", "byte", "[", "]", "body", ")", "throws", "IOException", "{", "// Fail before trying if socket has been closed.\r", "if", "(", "isClosed", "(", ")", ")", "{", "throw", "new", "IOException", ...
we reconnect and retry up to MAX_SOCKET_RETRIES before giving up.
[ "we", "reconnect", "and", "retry", "up", "to", "MAX_SOCKET_RETRIES", "before", "giving", "up", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L407-L429
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.sendRequest
private void sendRequest(String header, byte[] body) throws IOException { // Send entire message in one write, else suffer the fate of weird TCP/IP stacks. byte[] headerBytes = Utils.toBytes(header); byte[] requestBytes = headerBytes; if (body != null && body.length > 0) { requestBytes = new byte[headerBytes.length + body.length]; System.arraycopy(headerBytes, 0, requestBytes, 0, headerBytes.length); System.arraycopy(body, 0, requestBytes, headerBytes.length, body.length); } // Send the header and body (if any) and flush the result. m_outStream.write(requestBytes); m_outStream.flush(); }
java
private void sendRequest(String header, byte[] body) throws IOException { // Send entire message in one write, else suffer the fate of weird TCP/IP stacks. byte[] headerBytes = Utils.toBytes(header); byte[] requestBytes = headerBytes; if (body != null && body.length > 0) { requestBytes = new byte[headerBytes.length + body.length]; System.arraycopy(headerBytes, 0, requestBytes, 0, headerBytes.length); System.arraycopy(body, 0, requestBytes, headerBytes.length, body.length); } // Send the header and body (if any) and flush the result. m_outStream.write(requestBytes); m_outStream.flush(); }
[ "private", "void", "sendRequest", "(", "String", "header", ",", "byte", "[", "]", "body", ")", "throws", "IOException", "{", "// Send entire message in one write, else suffer the fate of weird TCP/IP stacks.\r", "byte", "[", "]", "headerBytes", "=", "Utils", ".", "toByt...
Send the request represented by the given header and optional body.
[ "Send", "the", "request", "represented", "by", "the", "given", "header", "and", "optional", "body", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L433-L446
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.readResponse
private RESTResponse readResponse() throws IOException { // Read response code from the header line. HttpCode resultCode = readStatusLine(); // Read and save headers, keeping track of content-length if we find it. Map<String, String> headers = new HashMap<String, String>(); int contentLength = 0; String headerLine = readHeader(); while (headerLine.length() > 2) { // Read header and split into parts based on ":" separator. Both parts are // trimmed, and the header is up-cased. int colonInx = headerLine.indexOf(':'); String headerName = // Use the whole line if there's no colon colonInx <= 0 ? headerLine.trim().toUpperCase() : headerLine.substring(0, colonInx).trim().toUpperCase(); String headerValue = // Use an empty string if there's no colon colonInx <= 0 ? "" : headerLine.substring(colonInx + 1).trim(); headers.put(headerName, headerValue); if (headerName.equals(HttpDefs.CONTENT_LENGTH)) { try { contentLength = Integer.parseInt(headerValue); } catch (NumberFormatException e) { // Turn into IOException throw new IOException("Invalid content-length value: " + headerLine); } } headerLine = readHeader(); } // Final header line should be CRLF if (!headerLine.equals("\r\n")) { throw new IOException("Header not properly terminated: " + headerLine); } // If we have a response entity, read that now. byte[] body = null; if (contentLength > 0) { body = readBody(contentLength); // Decompress output entity if needed. String contentEncoding = headers.get(HttpDefs.CONTENT_ENCODING); if (contentEncoding != null) { Utils.require(contentEncoding.equalsIgnoreCase("gzip"), "Unrecognized output Content-Encoding: " + contentEncoding); body = Utils.decompressGZIP(body); } } return new RESTResponse(resultCode, body, headers); }
java
private RESTResponse readResponse() throws IOException { // Read response code from the header line. HttpCode resultCode = readStatusLine(); // Read and save headers, keeping track of content-length if we find it. Map<String, String> headers = new HashMap<String, String>(); int contentLength = 0; String headerLine = readHeader(); while (headerLine.length() > 2) { // Read header and split into parts based on ":" separator. Both parts are // trimmed, and the header is up-cased. int colonInx = headerLine.indexOf(':'); String headerName = // Use the whole line if there's no colon colonInx <= 0 ? headerLine.trim().toUpperCase() : headerLine.substring(0, colonInx).trim().toUpperCase(); String headerValue = // Use an empty string if there's no colon colonInx <= 0 ? "" : headerLine.substring(colonInx + 1).trim(); headers.put(headerName, headerValue); if (headerName.equals(HttpDefs.CONTENT_LENGTH)) { try { contentLength = Integer.parseInt(headerValue); } catch (NumberFormatException e) { // Turn into IOException throw new IOException("Invalid content-length value: " + headerLine); } } headerLine = readHeader(); } // Final header line should be CRLF if (!headerLine.equals("\r\n")) { throw new IOException("Header not properly terminated: " + headerLine); } // If we have a response entity, read that now. byte[] body = null; if (contentLength > 0) { body = readBody(contentLength); // Decompress output entity if needed. String contentEncoding = headers.get(HttpDefs.CONTENT_ENCODING); if (contentEncoding != null) { Utils.require(contentEncoding.equalsIgnoreCase("gzip"), "Unrecognized output Content-Encoding: " + contentEncoding); body = Utils.decompressGZIP(body); } } return new RESTResponse(resultCode, body, headers); }
[ "private", "RESTResponse", "readResponse", "(", ")", "throws", "IOException", "{", "// Read response code from the header line.\r", "HttpCode", "resultCode", "=", "readStatusLine", "(", ")", ";", "// Read and save headers, keeping track of content-length if we find it.\r", "Map", ...
a RESTResponse object.
[ "a", "RESTResponse", "object", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L450-L498
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.readStatusLine
private HttpCode readStatusLine() throws IOException { // Read a line of text, which should be in the format HTTP/<version <code> <reason> String statusLine = readHeader(); String[] parts = statusLine.split(" +"); if (parts.length < 3) { throw new IOException("Badly formed response status line: " + statusLine); } try { // Attempt to convert the return code into an enum. int code = Integer.parseInt(parts[1]); HttpCode result = HttpCode.findByCode(code); if (result == null) { throw new IOException("Unrecognized result code: " + code); } return result; } catch (NumberFormatException e) { // Turn into a bad response line error. throw new IOException("Badly formed response status line: " + statusLine); } }
java
private HttpCode readStatusLine() throws IOException { // Read a line of text, which should be in the format HTTP/<version <code> <reason> String statusLine = readHeader(); String[] parts = statusLine.split(" +"); if (parts.length < 3) { throw new IOException("Badly formed response status line: " + statusLine); } try { // Attempt to convert the return code into an enum. int code = Integer.parseInt(parts[1]); HttpCode result = HttpCode.findByCode(code); if (result == null) { throw new IOException("Unrecognized result code: " + code); } return result; } catch (NumberFormatException e) { // Turn into a bad response line error. throw new IOException("Badly formed response status line: " + statusLine); } }
[ "private", "HttpCode", "readStatusLine", "(", ")", "throws", "IOException", "{", "// Read a line of text, which should be in the format HTTP/<version <code> <reason>\r", "String", "statusLine", "=", "readHeader", "(", ")", ";", "String", "[", "]", "parts", "=", "statusLine"...
Read a REST response status line and return the status code from it.
[ "Read", "a", "REST", "response", "status", "line", "and", "return", "the", "status", "code", "from", "it", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L501-L520
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.createSocket
private void createSocket() throws Exception { // Some socket options, notably setReceiveBufferSize, must be set before the // socket is connected. So, first create the socket, then set options, then connect. if (m_sslParams != null) { SSLSocketFactory factory = m_sslParams.createSSLContext().getSocketFactory(); m_socket = factory.createSocket(m_host, m_port); setSocketOptions(); ((SSLSocket)m_socket).startHandshake(); } else { m_socket = new Socket(); setSocketOptions(); SocketAddress sockAddr = new InetSocketAddress(m_host, m_port); m_socket.connect(sockAddr); } }
java
private void createSocket() throws Exception { // Some socket options, notably setReceiveBufferSize, must be set before the // socket is connected. So, first create the socket, then set options, then connect. if (m_sslParams != null) { SSLSocketFactory factory = m_sslParams.createSSLContext().getSocketFactory(); m_socket = factory.createSocket(m_host, m_port); setSocketOptions(); ((SSLSocket)m_socket).startHandshake(); } else { m_socket = new Socket(); setSocketOptions(); SocketAddress sockAddr = new InetSocketAddress(m_host, m_port); m_socket.connect(sockAddr); } }
[ "private", "void", "createSocket", "(", ")", "throws", "Exception", "{", "// Some socket options, notably setReceiveBufferSize, must be set before the\r", "// socket is connected. So, first create the socket, then set options, then connect.\r", "if", "(", "m_sslParams", "!=", "null", "...
Create a socket connection, setting m_socket, using configured parameters.
[ "Create", "a", "socket", "connection", "setting", "m_socket", "using", "configured", "parameters", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L558-L572
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java
RESTClient.setSocketOptions
private void setSocketOptions() throws SocketException { if (DISABLE_NAGLES) { // Disable Nagle's algorithm (significant on Windows). m_socket.setTcpNoDelay(true); m_logger.debug("Nagle's algorithm disabled."); } if (USE_CUSTOM_BUFFER_SIZE) { // Improve default send/receive buffer sizes from default (often 8K). if (m_socket.getSendBufferSize() < NET_BUFFER_SIZE) { m_logger.debug("SendBufferSize increased from {} to {}", m_socket.getSendBufferSize(), NET_BUFFER_SIZE); m_socket.setSendBufferSize(NET_BUFFER_SIZE); } if (m_socket.getReceiveBufferSize() < NET_BUFFER_SIZE) { m_logger.debug("ReceiveBufferSize increased from {} to {}", m_socket.getReceiveBufferSize(), NET_BUFFER_SIZE); m_socket.setReceiveBufferSize(NET_BUFFER_SIZE); } } }
java
private void setSocketOptions() throws SocketException { if (DISABLE_NAGLES) { // Disable Nagle's algorithm (significant on Windows). m_socket.setTcpNoDelay(true); m_logger.debug("Nagle's algorithm disabled."); } if (USE_CUSTOM_BUFFER_SIZE) { // Improve default send/receive buffer sizes from default (often 8K). if (m_socket.getSendBufferSize() < NET_BUFFER_SIZE) { m_logger.debug("SendBufferSize increased from {} to {}", m_socket.getSendBufferSize(), NET_BUFFER_SIZE); m_socket.setSendBufferSize(NET_BUFFER_SIZE); } if (m_socket.getReceiveBufferSize() < NET_BUFFER_SIZE) { m_logger.debug("ReceiveBufferSize increased from {} to {}", m_socket.getReceiveBufferSize(), NET_BUFFER_SIZE); m_socket.setReceiveBufferSize(NET_BUFFER_SIZE); } } }
[ "private", "void", "setSocketOptions", "(", ")", "throws", "SocketException", "{", "if", "(", "DISABLE_NAGLES", ")", "{", "// Disable Nagle's algorithm (significant on Windows).\r", "m_socket", ".", "setTcpNoDelay", "(", "true", ")", ";", "m_logger", ".", "debug", "("...
Customize socket options
[ "Customize", "socket", "options" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/RESTClient.java#L575-L594
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/logservice/ChunkField.java
ChunkField.set
public void set(int[] indexes, int[] offsets, int[] lengths) { m_size = indexes.length; m_valuesCount = offsets.length; m_offsets = offsets; m_lengths = lengths; m_prefixes = new int[offsets.length]; m_suffixes = new int[offsets.length]; m_indexes = indexes; }
java
public void set(int[] indexes, int[] offsets, int[] lengths) { m_size = indexes.length; m_valuesCount = offsets.length; m_offsets = offsets; m_lengths = lengths; m_prefixes = new int[offsets.length]; m_suffixes = new int[offsets.length]; m_indexes = indexes; }
[ "public", "void", "set", "(", "int", "[", "]", "indexes", ",", "int", "[", "]", "offsets", ",", "int", "[", "]", "lengths", ")", "{", "m_size", "=", "indexes", ".", "length", ";", "m_valuesCount", "=", "offsets", ".", "length", ";", "m_offsets", "=",...
for synthetic fields
[ "for", "synthetic", "fields" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/logservice/ChunkField.java#L135-L143
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java
CQLSchemaManager.keyspaceDefaultsToCQLString
@SuppressWarnings("unchecked") private String keyspaceDefaultsToCQLString() { // Default defaults: boolean durable_writes = true; Map<String, Object> replication = new HashMap<String, Object>(); replication.put("class", "SimpleStrategy"); replication.put("replication_factor", "1"); // Legacy support: ReplicationFactor if (m_dbservice.getParam("ReplicationFactor") != null) { replication.put("replication_factor", m_dbservice.getParamString("ReplicationFactor")); } // Override any options specified in ks_defaults Map<String, Object> ksDefs = m_dbservice.getParamMap("ks_defaults"); if (ksDefs != null) { if (ksDefs.containsKey("durable_writes")) { durable_writes = Boolean.parseBoolean(ksDefs.get("durable_writes").toString()); } if (ksDefs.containsKey("strategy_class")) { replication.put("class", ksDefs.get("strategy_class").toString()); } if (ksDefs.containsKey("strategy_options")) { Object value = ksDefs.get("strategy_options"); if (value instanceof Map) { Map<String, Object> replOpts = (Map<String, Object>)value; if (replOpts.containsKey("replication_factor")) { replication.put("replication_factor", replOpts.get("replication_factor").toString()); } } } } StringBuilder buffer = new StringBuilder(); buffer.append(" WITH DURABLE_WRITES="); buffer.append(durable_writes); buffer.append(" AND REPLICATION="); buffer.append(mapToCQLString(replication)); return buffer.toString(); }
java
@SuppressWarnings("unchecked") private String keyspaceDefaultsToCQLString() { // Default defaults: boolean durable_writes = true; Map<String, Object> replication = new HashMap<String, Object>(); replication.put("class", "SimpleStrategy"); replication.put("replication_factor", "1"); // Legacy support: ReplicationFactor if (m_dbservice.getParam("ReplicationFactor") != null) { replication.put("replication_factor", m_dbservice.getParamString("ReplicationFactor")); } // Override any options specified in ks_defaults Map<String, Object> ksDefs = m_dbservice.getParamMap("ks_defaults"); if (ksDefs != null) { if (ksDefs.containsKey("durable_writes")) { durable_writes = Boolean.parseBoolean(ksDefs.get("durable_writes").toString()); } if (ksDefs.containsKey("strategy_class")) { replication.put("class", ksDefs.get("strategy_class").toString()); } if (ksDefs.containsKey("strategy_options")) { Object value = ksDefs.get("strategy_options"); if (value instanceof Map) { Map<String, Object> replOpts = (Map<String, Object>)value; if (replOpts.containsKey("replication_factor")) { replication.put("replication_factor", replOpts.get("replication_factor").toString()); } } } } StringBuilder buffer = new StringBuilder(); buffer.append(" WITH DURABLE_WRITES="); buffer.append(durable_writes); buffer.append(" AND REPLICATION="); buffer.append(mapToCQLString(replication)); return buffer.toString(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "String", "keyspaceDefaultsToCQLString", "(", ")", "{", "// Default defaults:", "boolean", "durable_writes", "=", "true", ";", "Map", "<", "String", ",", "Object", ">", "replication", "=", "new", "Hash...
Allow RF to be overridden with ReplicationFactor in the given options.
[ "Allow", "RF", "to", "be", "overridden", "with", "ReplicationFactor", "in", "the", "given", "options", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java#L194-L233
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java
CQLSchemaManager.mapToCQLString
private static String mapToCQLString(Map<String, Object> valueMap) { StringBuffer buffer = new StringBuffer(); buffer.append("{"); boolean bFirst = true; for (String name : valueMap.keySet()) { if (bFirst) { bFirst = false; } else { buffer.append(","); } buffer.append("'"); buffer.append(name); buffer.append("':"); Object value = valueMap.get(name); if (value instanceof String) { buffer.append("'"); buffer.append(value.toString()); buffer.append("'"); } else { buffer.append(value.toString()); } } buffer.append("}"); return buffer.toString(); }
java
private static String mapToCQLString(Map<String, Object> valueMap) { StringBuffer buffer = new StringBuffer(); buffer.append("{"); boolean bFirst = true; for (String name : valueMap.keySet()) { if (bFirst) { bFirst = false; } else { buffer.append(","); } buffer.append("'"); buffer.append(name); buffer.append("':"); Object value = valueMap.get(name); if (value instanceof String) { buffer.append("'"); buffer.append(value.toString()); buffer.append("'"); } else { buffer.append(value.toString()); } } buffer.append("}"); return buffer.toString(); }
[ "private", "static", "String", "mapToCQLString", "(", "Map", "<", "String", ",", "Object", ">", "valueMap", ")", "{", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", ")", ";", "buffer", ".", "append", "(", "\"{\"", ")", ";", "boolean", "bFirst",...
Values must be quoted if they aren't literals.
[ "Values", "must", "be", "quoted", "if", "they", "aren", "t", "literals", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java#L237-L261
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java
CQLSchemaManager.executeCQL
private ResultSet executeCQL(String cql) { m_logger.debug("Executing CQL: {}", cql); try { return m_dbservice.getSession().execute(cql); } catch (Exception e) { m_logger.error("CQL query failed", e); m_logger.info(" Query={}", cql); throw e; } }
java
private ResultSet executeCQL(String cql) { m_logger.debug("Executing CQL: {}", cql); try { return m_dbservice.getSession().execute(cql); } catch (Exception e) { m_logger.error("CQL query failed", e); m_logger.info(" Query={}", cql); throw e; } }
[ "private", "ResultSet", "executeCQL", "(", "String", "cql", ")", "{", "m_logger", ".", "debug", "(", "\"Executing CQL: {}\"", ",", "cql", ")", ";", "try", "{", "return", "m_dbservice", ".", "getSession", "(", ")", ".", "execute", "(", "cql", ")", ";", "}...
Execute and optionally log the given CQL statement.
[ "Execute", "and", "optionally", "log", "the", "given", "CQL", "statement", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java#L264-L273
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java
SpiderDataAger.checkTable
private void checkTable() { // Documentation says that "0 xxx" means data-aging is disabled. if (m_retentionAge.getValue() == 0) { m_logger.info("Data aging disabled for table: {}", m_tableDef.getTableName()); return; } m_logger.info("Checking expired objects for: {}", m_tableDef.getTableName()); GregorianCalendar checkDate = new GregorianCalendar(Utils.UTC_TIMEZONE); GregorianCalendar expireDate = m_retentionAge.getExpiredDate(checkDate); int objsExpired = 0; String fixedQuery = buildFixedQuery(expireDate); String contToken = null; StringBuilder uriParam = new StringBuilder(); do { uriParam.setLength(0); uriParam.append(fixedQuery); if (!Utils.isEmpty(contToken)) { uriParam.append("&g="); uriParam.append(contToken); } ObjectQuery objQuery = new ObjectQuery(m_tableDef, uriParam.toString()); SearchResultList resultList = SpiderService.instance().objectQuery(m_tableDef, objQuery); List<String> objIDs = new ArrayList<>(); for (SearchResult result : resultList.results) { objIDs.add(result.id()); } if (deleteBatch(objIDs)) { contToken = resultList.continuation_token; } else { contToken = null; } objsExpired += objIDs.size(); reportProgress("Expired " + objsExpired + " objects"); } while (!Utils.isEmpty(contToken)); m_logger.info("Deleted {} objects for {}", objsExpired, m_tableDef.getTableName()); }
java
private void checkTable() { // Documentation says that "0 xxx" means data-aging is disabled. if (m_retentionAge.getValue() == 0) { m_logger.info("Data aging disabled for table: {}", m_tableDef.getTableName()); return; } m_logger.info("Checking expired objects for: {}", m_tableDef.getTableName()); GregorianCalendar checkDate = new GregorianCalendar(Utils.UTC_TIMEZONE); GregorianCalendar expireDate = m_retentionAge.getExpiredDate(checkDate); int objsExpired = 0; String fixedQuery = buildFixedQuery(expireDate); String contToken = null; StringBuilder uriParam = new StringBuilder(); do { uriParam.setLength(0); uriParam.append(fixedQuery); if (!Utils.isEmpty(contToken)) { uriParam.append("&g="); uriParam.append(contToken); } ObjectQuery objQuery = new ObjectQuery(m_tableDef, uriParam.toString()); SearchResultList resultList = SpiderService.instance().objectQuery(m_tableDef, objQuery); List<String> objIDs = new ArrayList<>(); for (SearchResult result : resultList.results) { objIDs.add(result.id()); } if (deleteBatch(objIDs)) { contToken = resultList.continuation_token; } else { contToken = null; } objsExpired += objIDs.size(); reportProgress("Expired " + objsExpired + " objects"); } while (!Utils.isEmpty(contToken)); m_logger.info("Deleted {} objects for {}", objsExpired, m_tableDef.getTableName()); }
[ "private", "void", "checkTable", "(", ")", "{", "// Documentation says that \"0 xxx\" means data-aging is disabled.", "if", "(", "m_retentionAge", ".", "getValue", "(", ")", "==", "0", ")", "{", "m_logger", ".", "info", "(", "\"Data aging disabled for table: {}\"", ",",...
Scan the given table for expired objects relative to the given date.
[ "Scan", "the", "given", "table", "for", "expired", "objects", "relative", "to", "the", "given", "date", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java#L75-L114
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java
SpiderDataAger.buildFixedQuery
private String buildFixedQuery(GregorianCalendar expireDate) { // Query: '{aging field} <= "{expire date}"', fetching the _ID and // aging field, up to a batch full at a time. StringBuilder fixedParams = new StringBuilder(); fixedParams.append("q="); fixedParams.append(m_agingFieldDef.getName()); fixedParams.append(" <= \""); fixedParams.append(Utils.formatDate(expireDate)); fixedParams.append("\""); // Fields: _ID. fixedParams.append("&f=_ID"); // Size: QUERY_PAGE_SIZE fixedParams.append("&s="); fixedParams.append(QUERY_PAGE_SIZE); return fixedParams.toString(); }
java
private String buildFixedQuery(GregorianCalendar expireDate) { // Query: '{aging field} <= "{expire date}"', fetching the _ID and // aging field, up to a batch full at a time. StringBuilder fixedParams = new StringBuilder(); fixedParams.append("q="); fixedParams.append(m_agingFieldDef.getName()); fixedParams.append(" <= \""); fixedParams.append(Utils.formatDate(expireDate)); fixedParams.append("\""); // Fields: _ID. fixedParams.append("&f=_ID"); // Size: QUERY_PAGE_SIZE fixedParams.append("&s="); fixedParams.append(QUERY_PAGE_SIZE); return fixedParams.toString(); }
[ "private", "String", "buildFixedQuery", "(", "GregorianCalendar", "expireDate", ")", "{", "// Query: '{aging field} <= \"{expire date}\"', fetching the _ID and", "// aging field, up to a batch full at a time.", "StringBuilder", "fixedParams", "=", "new", "StringBuilder", "(", ")", ...
Build the fixed part of the query that fetches a batch of object IDs.
[ "Build", "the", "fixed", "part", "of", "the", "query", "that", "fetches", "a", "batch", "of", "object", "IDs", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java#L117-L134
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java
SpiderDataAger.deleteBatch
private boolean deleteBatch(List<String> objIDs) { if (objIDs.size() == 0) { return false; } m_logger.debug("Deleting batch of {} objects from {}", objIDs.size(), m_tableDef.getTableName()); BatchObjectUpdater batchUpdater = new BatchObjectUpdater(m_tableDef); BatchResult batchResult = batchUpdater.deleteBatch(objIDs); if (batchResult.isFailed()) { m_logger.error("Batch query failed: {}", batchResult.getErrorMessage()); return false; } return true; }
java
private boolean deleteBatch(List<String> objIDs) { if (objIDs.size() == 0) { return false; } m_logger.debug("Deleting batch of {} objects from {}", objIDs.size(), m_tableDef.getTableName()); BatchObjectUpdater batchUpdater = new BatchObjectUpdater(m_tableDef); BatchResult batchResult = batchUpdater.deleteBatch(objIDs); if (batchResult.isFailed()) { m_logger.error("Batch query failed: {}", batchResult.getErrorMessage()); return false; } return true; }
[ "private", "boolean", "deleteBatch", "(", "List", "<", "String", ">", "objIDs", ")", "{", "if", "(", "objIDs", ".", "size", "(", ")", "==", "0", ")", "{", "return", "false", ";", "}", "m_logger", ".", "debug", "(", "\"Deleting batch of {} objects from {}\"...
update failed or we didn't execute an update.
[ "update", "failed", "or", "we", "didn", "t", "execute", "an", "update", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderDataAger.java#L138-L150
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.commit
public void commit(DBTransaction transaction) { try { applyUpdates(transaction); } catch (Exception e) { m_logger.error("Updates failed", e); throw e; } finally { transaction.clear(); } }
java
public void commit(DBTransaction transaction) { try { applyUpdates(transaction); } catch (Exception e) { m_logger.error("Updates failed", e); throw e; } finally { transaction.clear(); } }
[ "public", "void", "commit", "(", "DBTransaction", "transaction", ")", "{", "try", "{", "applyUpdates", "(", "transaction", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "m_logger", ".", "error", "(", "\"Updates failed\"", ",", "e", ")", ";", "...
Apply the updates accumulated in this transaction. The updates are cleared even if the update fails.
[ "Apply", "the", "updates", "accumulated", "in", "this", "transaction", ".", "The", "updates", "are", "cleared", "even", "if", "the", "update", "fails", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L53-L62
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.applyUpdates
private void applyUpdates(DBTransaction transaction) { if (transaction.getMutationsCount() == 0) { m_logger.debug("Skipping commit with no updates"); } else if (m_dbservice.getParamBoolean("async_updates")) { executeUpdatesAsynchronous(transaction); } else { executeUpdatesSynchronous(transaction); } }
java
private void applyUpdates(DBTransaction transaction) { if (transaction.getMutationsCount() == 0) { m_logger.debug("Skipping commit with no updates"); } else if (m_dbservice.getParamBoolean("async_updates")) { executeUpdatesAsynchronous(transaction); } else { executeUpdatesSynchronous(transaction); } }
[ "private", "void", "applyUpdates", "(", "DBTransaction", "transaction", ")", "{", "if", "(", "transaction", ".", "getMutationsCount", "(", ")", "==", "0", ")", "{", "m_logger", ".", "debug", "(", "\"Skipping commit with no updates\"", ")", ";", "}", "else", "i...
Execute a batch statement that applies all updates in this transaction.
[ "Execute", "a", "batch", "statement", "that", "applies", "all", "updates", "in", "this", "transaction", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L65-L73
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.executeUpdatesAsynchronous
private void executeUpdatesAsynchronous(DBTransaction transaction) { Collection<BoundStatement> mutations = getMutations(transaction); List<ResultSetFuture> futureList = new ArrayList<>(mutations.size()); for(BoundStatement mutation: mutations) { ResultSetFuture future = m_dbservice.getSession().executeAsync(mutation); futureList.add(future); } m_logger.debug("Waiting for {} asynchronous futures", futureList.size()); for (ResultSetFuture future : futureList) { future.getUninterruptibly(); } }
java
private void executeUpdatesAsynchronous(DBTransaction transaction) { Collection<BoundStatement> mutations = getMutations(transaction); List<ResultSetFuture> futureList = new ArrayList<>(mutations.size()); for(BoundStatement mutation: mutations) { ResultSetFuture future = m_dbservice.getSession().executeAsync(mutation); futureList.add(future); } m_logger.debug("Waiting for {} asynchronous futures", futureList.size()); for (ResultSetFuture future : futureList) { future.getUninterruptibly(); } }
[ "private", "void", "executeUpdatesAsynchronous", "(", "DBTransaction", "transaction", ")", "{", "Collection", "<", "BoundStatement", ">", "mutations", "=", "getMutations", "(", "transaction", ")", ";", "List", "<", "ResultSetFuture", ">", "futureList", "=", "new", ...
Execute all updates asynchronously and wait for results.
[ "Execute", "all", "updates", "asynchronously", "and", "wait", "for", "results", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L76-L87
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.executeUpdatesSynchronous
private void executeUpdatesSynchronous(DBTransaction transaction) { BatchStatement batchState = new BatchStatement(Type.UNLOGGED); batchState.addAll(getMutations(transaction)); executeBatch(batchState); }
java
private void executeUpdatesSynchronous(DBTransaction transaction) { BatchStatement batchState = new BatchStatement(Type.UNLOGGED); batchState.addAll(getMutations(transaction)); executeBatch(batchState); }
[ "private", "void", "executeUpdatesSynchronous", "(", "DBTransaction", "transaction", ")", "{", "BatchStatement", "batchState", "=", "new", "BatchStatement", "(", "Type", ".", "UNLOGGED", ")", ";", "batchState", ".", "addAll", "(", "getMutations", "(", "transaction",...
Execute all updates and deletes using synchronous statements.
[ "Execute", "all", "updates", "and", "deletes", "using", "synchronous", "statements", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L90-L94
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.addColumnUpdate
private BoundStatement addColumnUpdate(String tableName, String key, DColumn column, boolean isBinaryValue) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.INSERT_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, column.getName()); if (isBinaryValue) { boundState.setBytes(2, ByteBuffer.wrap(column.getRawValue())); } else { boundState.setString(2, column.getValue()); } return boundState; }
java
private BoundStatement addColumnUpdate(String tableName, String key, DColumn column, boolean isBinaryValue) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.INSERT_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, column.getName()); if (isBinaryValue) { boundState.setBytes(2, ByteBuffer.wrap(column.getRawValue())); } else { boundState.setString(2, column.getValue()); } return boundState; }
[ "private", "BoundStatement", "addColumnUpdate", "(", "String", "tableName", ",", "String", "key", ",", "DColumn", "column", ",", "boolean", "isBinaryValue", ")", "{", "PreparedStatement", "prepState", "=", "m_dbservice", ".", "getPreparedUpdate", "(", "Update", ".",...
Create and return a BoundStatement for the given column update.
[ "Create", "and", "return", "a", "BoundStatement", "for", "the", "given", "column", "update", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L115-L126
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.addColumnDelete
private BoundStatement addColumnDelete(String tableName, String key, String colName) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_COLUMN, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, colName); return boundState; }
java
private BoundStatement addColumnDelete(String tableName, String key, String colName) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_COLUMN, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); boundState.setString(1, colName); return boundState; }
[ "private", "BoundStatement", "addColumnDelete", "(", "String", "tableName", ",", "String", "key", ",", "String", "colName", ")", "{", "PreparedStatement", "prepState", "=", "m_dbservice", ".", "getPreparedUpdate", "(", "Update", ".", "DELETE_COLUMN", ",", "tableName...
Create and return a BoundStatement that deletes the given column.
[ "Create", "and", "return", "a", "BoundStatement", "that", "deletes", "the", "given", "column", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L130-L136
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.addRowDelete
private BoundStatement addRowDelete(String tableName, String key) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); return boundState; }
java
private BoundStatement addRowDelete(String tableName, String key) { PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_ROW, tableName); BoundStatement boundState = prepState.bind(); boundState.setString(0, key); return boundState; }
[ "private", "BoundStatement", "addRowDelete", "(", "String", "tableName", ",", "String", "key", ")", "{", "PreparedStatement", "prepState", "=", "m_dbservice", ".", "getPreparedUpdate", "(", "Update", ".", "DELETE_ROW", ",", "tableName", ")", ";", "BoundStatement", ...
Create and return a BoundStatement that deletes the given row.
[ "Create", "and", "return", "a", "BoundStatement", "that", "deletes", "the", "given", "row", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L139-L144
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java
CQLTransaction.executeBatch
private void executeBatch(BatchStatement batchState) { if (batchState.size() > 0) { m_logger.debug("Executing synchronous batch with {} statements", batchState.size()); m_dbservice.getSession().execute(batchState); } }
java
private void executeBatch(BatchStatement batchState) { if (batchState.size() > 0) { m_logger.debug("Executing synchronous batch with {} statements", batchState.size()); m_dbservice.getSession().execute(batchState); } }
[ "private", "void", "executeBatch", "(", "BatchStatement", "batchState", ")", "{", "if", "(", "batchState", ".", "size", "(", ")", ">", "0", ")", "{", "m_logger", ".", "debug", "(", "\"Executing synchronous batch with {} statements\"", ",", "batchState", ".", "si...
Execute and given update statement.
[ "Execute", "and", "given", "update", "statement", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L148-L153
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/mbeans/ServerMonitor.java
ServerMonitor.onRequestRejected
public synchronized void onRequestRejected(String reason) { allRequestsTracker.onRequestRejected(reason); recentRequestsTracker.onRequestRejected(reason); meter.mark(); }
java
public synchronized void onRequestRejected(String reason) { allRequestsTracker.onRequestRejected(reason); recentRequestsTracker.onRequestRejected(reason); meter.mark(); }
[ "public", "synchronized", "void", "onRequestRejected", "(", "String", "reason", ")", "{", "allRequestsTracker", ".", "onRequestRejected", "(", "reason", ")", ";", "recentRequestsTracker", ".", "onRequestRejected", "(", "reason", ")", ";", "meter", ".", "mark", "("...
Registers an invalid request rejected by the server.
[ "Registers", "an", "invalid", "request", "rejected", "by", "the", "server", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/mbeans/ServerMonitor.java#L231-L235
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java
OLAPSession.deleteShard
public boolean deleteShard(String shard) { Utils.require(!Utils.isEmpty(shard), "shard"); try { // Send a DELETE request to "/{application}/_shards/{shard}" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(Utils.urlEncode(shard)); RESTResponse response = m_restClient.sendRequest(HttpMethod.DELETE, uri.toString()); m_logger.debug("deleteShard() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
java
public boolean deleteShard(String shard) { Utils.require(!Utils.isEmpty(shard), "shard"); try { // Send a DELETE request to "/{application}/_shards/{shard}" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(Utils.urlEncode(shard)); RESTResponse response = m_restClient.sendRequest(HttpMethod.DELETE, uri.toString()); m_logger.debug("deleteShard() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "boolean", "deleteShard", "(", "String", "shard", ")", "{", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "shard", ")", ",", "\"shard\"", ")", ";", "try", "{", "// Send a DELETE request to \"/{application}/_shards/{shard}\"\r", "String...
Delete the OLAP shard with the given name belonging to this session's application. True is returned if the delete was successful. An exception is thrown if an error occurred. @param shard Shard name. @return True if the shard was successfully deleted.
[ "Delete", "the", "OLAP", "shard", "with", "the", "given", "name", "belonging", "to", "this", "session", "s", "application", ".", "True", "is", "returned", "if", "the", "delete", "was", "successful", ".", "An", "exception", "is", "thrown", "if", "an", "erro...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java#L133-L149
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java
OLAPSession.getShardNames
public Collection<String> getShardNames() { List<String> shardNames = new ArrayList<>(); try { // Send a GET request to "/{application}/_shards" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards"); RESTResponse response = m_restClient.sendRequest(HttpMethod.GET, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); // Response should be UNode tree in the form /Results/{application}/shards // where "shards" is an array of shard names. UNode rootNode = getUNodeResult(response); UNode appNode = rootNode.getMember(m_appDef.getAppName()); UNode shardsNode = appNode.getMember("shards"); for (UNode shardNode : shardsNode.getMemberList()) { shardNames.add(shardNode.getValue()); } return shardNames; } catch (Exception e) { throw new RuntimeException(e); } }
java
public Collection<String> getShardNames() { List<String> shardNames = new ArrayList<>(); try { // Send a GET request to "/{application}/_shards" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards"); RESTResponse response = m_restClient.sendRequest(HttpMethod.GET, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); // Response should be UNode tree in the form /Results/{application}/shards // where "shards" is an array of shard names. UNode rootNode = getUNodeResult(response); UNode appNode = rootNode.getMember(m_appDef.getAppName()); UNode shardsNode = appNode.getMember("shards"); for (UNode shardNode : shardsNode.getMemberList()) { shardNames.add(shardNode.getValue()); } return shardNames; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "Collection", "<", "String", ">", "getShardNames", "(", ")", "{", "List", "<", "String", ">", "shardNames", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "// Send a GET request to \"/{application}/_shards\"\r", "StringBuilder", "uri", "=", ...
Get a list of all shard names owned by this application. If there are no shards with data yet, an empty collection is returned. @return Collection of shard names, possibly empty.
[ "Get", "a", "list", "of", "all", "shard", "names", "owned", "by", "this", "application", ".", "If", "there", "are", "no", "shards", "with", "data", "yet", "an", "empty", "collection", "is", "returned", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java#L157-L181
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java
OLAPSession.getShardStats
public UNode getShardStats(String shardName) { try { // Send a GET request to "/{application}/_shards/{shard}" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(shardName); RESTResponse response = m_restClient.sendRequest(HttpMethod.GET, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); return getUNodeResult(response); } catch (Exception e) { throw new RuntimeException(e); } }
java
public UNode getShardStats(String shardName) { try { // Send a GET request to "/{application}/_shards/{shard}" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(shardName); RESTResponse response = m_restClient.sendRequest(HttpMethod.GET, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); return getUNodeResult(response); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "UNode", "getShardStats", "(", "String", "shardName", ")", "{", "try", "{", "// Send a GET request to \"/{application}/_shards/{shard}\"\r", "StringBuilder", "uri", "=", "new", "StringBuilder", "(", "Utils", ".", "isEmpty", "(", "m_restClient", ".", "getApiPre...
Get statistics for the given shard name. Since the response to this command is subject to change, the command result is parsed into a UNode, and the root object is returned. An exception is thrown if the given shard name does not exist or does not have any data. @param shardName Name of a shard to query. @return Root {@link UNode} of the parsed result.
[ "Get", "statistics", "for", "the", "given", "shard", "name", ".", "Since", "the", "response", "to", "this", "command", "is", "subject", "to", "change", "the", "command", "result", "is", "parsed", "into", "a", "UNode", "and", "the", "root", "object", "is", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java#L192-L207
train
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java
OLAPSession.mergeShard
public boolean mergeShard(String shard, Date expireDate) { Utils.require(!Utils.isEmpty(shard), "shard"); try { // Send a POST request to "/{application}/_shards/{shard}[?expire-date=<date>]" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(Utils.urlEncode(shard)); if (expireDate != null) { uri.append("?expire-date="); uri.append(Utils.urlEncode(Utils.formatDateUTC(expireDate))); } RESTResponse response = m_restClient.sendRequest(HttpMethod.POST, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
java
public boolean mergeShard(String shard, Date expireDate) { Utils.require(!Utils.isEmpty(shard), "shard"); try { // Send a POST request to "/{application}/_shards/{shard}[?expire-date=<date>]" StringBuilder uri = new StringBuilder(Utils.isEmpty(m_restClient.getApiPrefix()) ? "" : "/" + m_restClient.getApiPrefix()); uri.append("/"); uri.append(Utils.urlEncode(m_appDef.getAppName())); uri.append("/_shards/"); uri.append(Utils.urlEncode(shard)); if (expireDate != null) { uri.append("?expire-date="); uri.append(Utils.urlEncode(Utils.formatDateUTC(expireDate))); } RESTResponse response = m_restClient.sendRequest(HttpMethod.POST, uri.toString()); m_logger.debug("mergeShard() response: {}", response.toString()); throwIfErrorResponse(response); return true; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "boolean", "mergeShard", "(", "String", "shard", ",", "Date", "expireDate", ")", "{", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "shard", ")", ",", "\"shard\"", ")", ";", "try", "{", "// Send a POST request to \"/{application}/_...
Request a merge of the OLAP shard with the given name belonging to this session's application. Optionally set the shard's expire-date to the given value. True is returned if the merge was successful. An exception is thrown if an error occurred. @param shard Shard name. @param expireDate Optional value for shard's new expire-date. Leave null if the shard should have no expiration date. @return True if the merge was successful.
[ "Request", "a", "merge", "of", "the", "OLAP", "shard", "with", "the", "given", "name", "belonging", "to", "this", "session", "s", "application", ".", "Optionally", "set", "the", "shard", "s", "expire", "-", "date", "to", "the", "given", "value", ".", "Tr...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/OLAPSession.java#L219-L239
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.allAlphaNumUnderscore
public static boolean allAlphaNumUnderscore(String string) { if (string == null || string.length() == 0) { return false; } for (int index = 0; index < string.length(); index++) { char ch = string.charAt(index); if (!isLetter(ch) && !isDigit(ch) && ch != '_') { return false; } } return true; }
java
public static boolean allAlphaNumUnderscore(String string) { if (string == null || string.length() == 0) { return false; } for (int index = 0; index < string.length(); index++) { char ch = string.charAt(index); if (!isLetter(ch) && !isDigit(ch) && ch != '_') { return false; } } return true; }
[ "public", "static", "boolean", "allAlphaNumUnderscore", "(", "String", "string", ")", "{", "if", "(", "string", "==", "null", "||", "string", ".", "length", "(", ")", "==", "0", ")", "{", "return", "false", ";", "}", "for", "(", "int", "index", "=", ...
Return true if the given string contains only letters, digits, and underscores. @param string String to be tested. @return True if the string is not null, not empty, and contains only letters, digits, and underscores.
[ "Return", "true", "if", "the", "given", "string", "contains", "only", "letters", "digits", "and", "underscores", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L97-L108
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.base64ToHex
public static String base64ToHex(String base64Value) throws IllegalArgumentException { byte[] binary = base64ToBinary(base64Value); return DatatypeConverter.printHexBinary(binary); }
java
public static String base64ToHex(String base64Value) throws IllegalArgumentException { byte[] binary = base64ToBinary(base64Value); return DatatypeConverter.printHexBinary(binary); }
[ "public", "static", "String", "base64ToHex", "(", "String", "base64Value", ")", "throws", "IllegalArgumentException", "{", "byte", "[", "]", "binary", "=", "base64ToBinary", "(", "base64Value", ")", ";", "return", "DatatypeConverter", ".", "printHexBinary", "(", "...
Decode the given Base64-encoded String to binary and then return as a string of hex digits. @param base64Value Base64-encoded string. @return Decoded binary value re-encoded as a hex string. @throws IllegalArgumentException If the given string is not a valid Base64 value.
[ "Decode", "the", "given", "Base64", "-", "encoded", "String", "to", "binary", "and", "then", "return", "as", "a", "string", "of", "hex", "digits", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L151-L154
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.base64FromHex
public static String base64FromHex(String hexValue) throws IllegalArgumentException { byte[] binary = DatatypeConverter.parseHexBinary(hexValue); return base64FromBinary(binary); }
java
public static String base64FromHex(String hexValue) throws IllegalArgumentException { byte[] binary = DatatypeConverter.parseHexBinary(hexValue); return base64FromBinary(binary); }
[ "public", "static", "String", "base64FromHex", "(", "String", "hexValue", ")", "throws", "IllegalArgumentException", "{", "byte", "[", "]", "binary", "=", "DatatypeConverter", ".", "parseHexBinary", "(", "hexValue", ")", ";", "return", "base64FromBinary", "(", "bi...
Decode the given hex string to binary and then re-encoded it as a Base64 string. @param hexValue String of hexadecimal characters. @return Decoded binary value re-encoded with Base64. @throws IllegalArgumentException If the given value is null or invalid.
[ "Decode", "the", "given", "hex", "string", "to", "binary", "and", "then", "re", "-", "encoded", "it", "as", "a", "Base64", "string", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L174-L177
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.base64ToString
public static String base64ToString(String base64Value) { Utils.require(base64Value.length() % 4 == 0, "Invalid base64 value (must be a multiple of 4 chars): " + base64Value); byte[] utf8String = DatatypeConverter.parseBase64Binary(base64Value); return toString(utf8String); }
java
public static String base64ToString(String base64Value) { Utils.require(base64Value.length() % 4 == 0, "Invalid base64 value (must be a multiple of 4 chars): " + base64Value); byte[] utf8String = DatatypeConverter.parseBase64Binary(base64Value); return toString(utf8String); }
[ "public", "static", "String", "base64ToString", "(", "String", "base64Value", ")", "{", "Utils", ".", "require", "(", "base64Value", ".", "length", "(", ")", "%", "4", "==", "0", ",", "\"Invalid base64 value (must be a multiple of 4 chars): \"", "+", "base64Value", ...
Decode the given base64 value to binary, then decode the result as a UTF-8 sequence and return the resulting String. @param base64Value Base64-encoded value of a UTF-8 encoded string. @return Decoded string value.
[ "Decode", "the", "given", "base64", "value", "to", "binary", "then", "decode", "the", "result", "as", "a", "UTF", "-", "8", "sequence", "and", "return", "the", "resulting", "String", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L212-L217
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.getTimeMicros
public static long getTimeMicros() { // Use use a dedicated lock object rather than synchronizing on the method, which // would synchronize on the Utils.class object, which is too coarse-grained. synchronized (g_lastMicroLock) { // We use System.currentTimeMillis() * 1000 for compatibility with the CLI and // other tools. This makes our timestamps "milliseconds since the epoch". long newValue = System.currentTimeMillis() * 1000; if (newValue <= g_lastMicroValue) { // Either two threads called us very quickly or the system clock was set // back a little. Just return the last value allocated + 1. Eventually, // the system clock will catch up. newValue = g_lastMicroValue + 1; } g_lastMicroValue = newValue; return newValue; } }
java
public static long getTimeMicros() { // Use use a dedicated lock object rather than synchronizing on the method, which // would synchronize on the Utils.class object, which is too coarse-grained. synchronized (g_lastMicroLock) { // We use System.currentTimeMillis() * 1000 for compatibility with the CLI and // other tools. This makes our timestamps "milliseconds since the epoch". long newValue = System.currentTimeMillis() * 1000; if (newValue <= g_lastMicroValue) { // Either two threads called us very quickly or the system clock was set // back a little. Just return the last value allocated + 1. Eventually, // the system clock will catch up. newValue = g_lastMicroValue + 1; } g_lastMicroValue = newValue; return newValue; } }
[ "public", "static", "long", "getTimeMicros", "(", ")", "{", "// Use use a dedicated lock object rather than synchronizing on the method, which\r", "// would synchronize on the Utils.class object, which is too coarse-grained.\r", "synchronized", "(", "g_lastMicroLock", ")", "{", "// We us...
Get the current time in microseconds since the epoch. This method is synchronized and guarantees that each successive call, even by different threads, returns increasing values. @return Current time in microseconds (though not necessarily with microsecond precision).
[ "Get", "the", "current", "time", "in", "microseconds", "since", "the", "epoch", ".", "This", "method", "is", "synchronized", "and", "guarantees", "that", "each", "successive", "call", "even", "by", "different", "threads", "returns", "increasing", "values", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L285-L301
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.deWhite
public static String deWhite(byte[] value) { // If the value contains anything less than a space. StringBuilder buffer = new StringBuilder(); boolean bAllPrintable = true; for (byte b : value) { if ((int)(b & 0xFF) < ' ') { bAllPrintable = false; break; } } if (bAllPrintable) { // All >= space; convert directly to chars. for (byte b : value) { buffer.append((char)b); } } else { // At least one non-printable. Convert to hex. buffer.append("0x"); for (byte b : value) { buffer.append(toHexChar(((int)b & 0xF0) >> 4)); buffer.append(toHexChar(((int)b & 0xF))); } } return buffer.toString(); }
java
public static String deWhite(byte[] value) { // If the value contains anything less than a space. StringBuilder buffer = new StringBuilder(); boolean bAllPrintable = true; for (byte b : value) { if ((int)(b & 0xFF) < ' ') { bAllPrintable = false; break; } } if (bAllPrintable) { // All >= space; convert directly to chars. for (byte b : value) { buffer.append((char)b); } } else { // At least one non-printable. Convert to hex. buffer.append("0x"); for (byte b : value) { buffer.append(toHexChar(((int)b & 0xF0) >> 4)); buffer.append(toHexChar(((int)b & 0xF))); } } return buffer.toString(); }
[ "public", "static", "String", "deWhite", "(", "byte", "[", "]", "value", ")", "{", "// If the value contains anything less than a space.\r", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "bAllPrintable", "=", "true", ";", "for", ...
Create a String by converting each byte directly into a character. However, if any byte in the given value is less than a space, a hex string is returned instead. @param value A byte[] to convert. @return A String of the same values as characters replaced 1-to-1 or converted into a hex string.
[ "Create", "a", "String", "by", "converting", "each", "byte", "directly", "into", "a", "character", ".", "However", "if", "any", "byte", "in", "the", "given", "value", "is", "less", "than", "a", "space", "a", "hex", "string", "is", "returned", "instead", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L593-L617
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.getBooleanValue
public static boolean getBooleanValue(String value) throws IllegalArgumentException { require("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value), "'true' or 'false' expected: " + value); return "true".equalsIgnoreCase(value); }
java
public static boolean getBooleanValue(String value) throws IllegalArgumentException { require("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value), "'true' or 'false' expected: " + value); return "true".equalsIgnoreCase(value); }
[ "public", "static", "boolean", "getBooleanValue", "(", "String", "value", ")", "throws", "IllegalArgumentException", "{", "require", "(", "\"true\"", ".", "equalsIgnoreCase", "(", "value", ")", "||", "\"false\"", ".", "equalsIgnoreCase", "(", "value", ")", ",", ...
Verify that the given value is either "true" or "false" and return the corresponding boolean value. If the value is invalid, an IllegalArgumentException is thrown. @param value Candidate boolean value in string form. @return Boolean value of string if valid. @throws IllegalArgumentException If the valie is not "true" or "false".
[ "Verify", "that", "the", "given", "value", "is", "either", "true", "or", "false", "and", "return", "the", "corresponding", "boolean", "value", ".", "If", "the", "value", "is", "invalid", "an", "IllegalArgumentException", "is", "thrown", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L955-L959
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.getElementText
public static String getElementText(Element elem) { StringBuilder result = new StringBuilder(); NodeList nodeList = elem.getChildNodes(); for (int index = 0; index < nodeList.getLength(); index++) { Node childNode = nodeList.item(index); if (childNode != null && (childNode instanceof Text)) { result.append(" "); result.append(((Text)childNode).getData()); } } return result.toString().trim(); }
java
public static String getElementText(Element elem) { StringBuilder result = new StringBuilder(); NodeList nodeList = elem.getChildNodes(); for (int index = 0; index < nodeList.getLength(); index++) { Node childNode = nodeList.item(index); if (childNode != null && (childNode instanceof Text)) { result.append(" "); result.append(((Text)childNode).getData()); } } return result.toString().trim(); }
[ "public", "static", "String", "getElementText", "(", "Element", "elem", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "NodeList", "nodeList", "=", "elem", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "index", "...
Get the concatenated value of all Text nodes that are immediate children of the given Element. If the element has no content, it will not have a child Text node. If it does have content, it will usually have a single child Text node. But in rare cases it could have multiple child Text nodes. If multiple child Text nodes are found, their content is concatenated into a single string, each separated by a single space. The value returned is trimmed of beginning and ending whitespace. If the element has no child Text nodes, or if all child Text nodes are empty or have whitespace-only values, an empty string is returned. @param elem Element to examine. @return Concatenated text of all child Text nodes. An empty string is returned if there are no child Text nodes or they are all empty or contain only whitespace.
[ "Get", "the", "concatenated", "value", "of", "all", "Text", "nodes", "that", "are", "immediate", "children", "of", "the", "given", "Element", ".", "If", "the", "element", "has", "no", "content", "it", "will", "not", "have", "a", "child", "Text", "node", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1025-L1036
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.md5Encode
public static String md5Encode(String strIn) { try { MessageDigest md5 = MessageDigest.getInstance("md5"); byte[] bin = toBytes(strIn); byte[] bout = md5.digest(bin); String strOut = javax.xml.bind.DatatypeConverter.printBase64Binary(bout); return strOut; }catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
java
public static String md5Encode(String strIn) { try { MessageDigest md5 = MessageDigest.getInstance("md5"); byte[] bin = toBytes(strIn); byte[] bout = md5.digest(bin); String strOut = javax.xml.bind.DatatypeConverter.printBase64Binary(bout); return strOut; }catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
[ "public", "static", "String", "md5Encode", "(", "String", "strIn", ")", "{", "try", "{", "MessageDigest", "md5", "=", "MessageDigest", ".", "getInstance", "(", "\"md5\"", ")", ";", "byte", "[", "]", "bin", "=", "toBytes", "(", "strIn", ")", ";", "byte", ...
Compute the MD5 of the given string and return it as a Base64-encoded value. The string is first converted to bytes using UTF-8, and the MD5 is computed on that value. The MD5 value is 16 bytes, but the Base64-encoded string is 24 chars. @param strIn A Unicode string. @return Base64-encoded value of the strings UTF-8 encoded value.
[ "Compute", "the", "MD5", "of", "the", "given", "string", "and", "return", "it", "as", "a", "Base64", "-", "encoded", "value", ".", "The", "string", "is", "first", "converted", "to", "bytes", "using", "UTF", "-", "8", "and", "the", "MD5", "is", "compute...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1246-L1256
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.parseXMLDocument
public static Element parseXMLDocument(String xmlDoc) throws IllegalArgumentException { // Parse the given XML document returning its root document Element if it parses. // Wrap the document payload as an InputSource. Reader stringReader = new StringReader(xmlDoc); InputSource inputSource = new InputSource(stringReader); // Parse the document into a DOM tree. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; Document doc = null; try { parser = dbf.newDocumentBuilder(); doc = parser.parse(inputSource); } catch (Exception ex) { // Turn ParserConfigurationException, SAXException, etc. into an IllegalArgumentException throw new IllegalArgumentException("Error parsing XML document: " + ex.getMessage()); } return doc.getDocumentElement(); }
java
public static Element parseXMLDocument(String xmlDoc) throws IllegalArgumentException { // Parse the given XML document returning its root document Element if it parses. // Wrap the document payload as an InputSource. Reader stringReader = new StringReader(xmlDoc); InputSource inputSource = new InputSource(stringReader); // Parse the document into a DOM tree. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; Document doc = null; try { parser = dbf.newDocumentBuilder(); doc = parser.parse(inputSource); } catch (Exception ex) { // Turn ParserConfigurationException, SAXException, etc. into an IllegalArgumentException throw new IllegalArgumentException("Error parsing XML document: " + ex.getMessage()); } return doc.getDocumentElement(); }
[ "public", "static", "Element", "parseXMLDocument", "(", "String", "xmlDoc", ")", "throws", "IllegalArgumentException", "{", "// Parse the given XML document returning its root document Element if it parses.\r", "// Wrap the document payload as an InputSource.\r", "Reader", "stringReader"...
Parse the given XML document, creating a DOM tree whose root Document object is returned. An IllegalArgumentException is thrown if the XML is malformed. @param xmlDoc XML document as a String. @return Root document element of the parsed DOM tree. @throws IllegalArgumentException If the XML is malformed.
[ "Parse", "the", "given", "XML", "document", "creating", "a", "DOM", "tree", "whose", "root", "Document", "object", "is", "returned", ".", "An", "IllegalArgumentException", "is", "thrown", "if", "the", "XML", "is", "malformed", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1391-L1409
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.requireEmptyText
public static void requireEmptyText(Node node, String errMsg) throws IllegalArgumentException { require((node instanceof Text) || (node instanceof Comment), errMsg + ": " + node.toString()); if (node instanceof Text) { Text text = (Text)node; String textValue = text.getData(); require(textValue.trim().length() == 0, errMsg + ": " + textValue); } }
java
public static void requireEmptyText(Node node, String errMsg) throws IllegalArgumentException { require((node instanceof Text) || (node instanceof Comment), errMsg + ": " + node.toString()); if (node instanceof Text) { Text text = (Text)node; String textValue = text.getData(); require(textValue.trim().length() == 0, errMsg + ": " + textValue); } }
[ "public", "static", "void", "requireEmptyText", "(", "Node", "node", ",", "String", "errMsg", ")", "throws", "IllegalArgumentException", "{", "require", "(", "(", "node", "instanceof", "Text", ")", "||", "(", "node", "instanceof", "Comment", ")", ",", "errMsg"...
Assert that the given org.w3c.doc.Node is a comment element or a Text element and that it ontains whitespace only, otherwise throw an IllegalArgumentException using the given error message. This is helpful when nothing is expected at a certain place in a DOM tree, yet comments or whitespace text nodes can appear. @param node A DOM Node object. @param errMsg String used to in the IllegalArgumentException constructor if thrown. @throws IllegalArgumentException If the expression is false.
[ "Assert", "that", "the", "given", "org", ".", "w3c", ".", "doc", ".", "Node", "is", "a", "comment", "element", "or", "a", "Text", "element", "and", "that", "it", "ontains", "whitespace", "only", "otherwise", "throw", "an", "IllegalArgumentException", "using"...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1510-L1519
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.toAsciiBytes
private static byte[] toAsciiBytes(String str) { for(int i = 0; i < str.length(); i++) { if(str.charAt(i) > 127) return null; } byte[] bytes = new byte[str.length()]; for(int i = 0; i < str.length(); i++) { bytes[i] = (byte)str.charAt(i); } return bytes; }
java
private static byte[] toAsciiBytes(String str) { for(int i = 0; i < str.length(); i++) { if(str.charAt(i) > 127) return null; } byte[] bytes = new byte[str.length()]; for(int i = 0; i < str.length(); i++) { bytes[i] = (byte)str.charAt(i); } return bytes; }
[ "private", "static", "byte", "[", "]", "toAsciiBytes", "(", "String", "str", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "str", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "str", ".", "charAt", "(", "i", ")", ...
return string as bytes if it has only ascii symbols, or null
[ "return", "string", "as", "bytes", "if", "it", "has", "only", "ascii", "symbols", "or", "null" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1793-L1802
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.toAsciiString
private static String toAsciiString(byte[] bytes) { for(int i = 0; i < bytes.length; i++) { if(bytes[i] < 0) return null; } char[] chars = new char[bytes.length]; for(int i = 0; i < bytes.length; i++) { chars[i] = (char)bytes[i]; } return new String(chars); }
java
private static String toAsciiString(byte[] bytes) { for(int i = 0; i < bytes.length; i++) { if(bytes[i] < 0) return null; } char[] chars = new char[bytes.length]; for(int i = 0; i < bytes.length; i++) { chars[i] = (char)bytes[i]; } return new String(chars); }
[ "private", "static", "String", "toAsciiString", "(", "byte", "[", "]", "bytes", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "bytes", "[", "i", "]", "<", "0", ")", "re...
return string if bytes have only ascii symbols, or null
[ "return", "string", "if", "bytes", "have", "only", "ascii", "symbols", "or", "null" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L1939-L1948
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/Utils.java
Utils.truncateToWeek
public static GregorianCalendar truncateToWeek(GregorianCalendar date) { // Round the date down to the MONDAY of the same week. GregorianCalendar result = (GregorianCalendar)date.clone(); switch (result.get(Calendar.DAY_OF_WEEK)) { case Calendar.TUESDAY: result.add(Calendar.DAY_OF_MONTH, -1); break; case Calendar.WEDNESDAY: result.add(Calendar.DAY_OF_MONTH, -2); break; case Calendar.THURSDAY: result.add(Calendar.DAY_OF_MONTH, -3); break; case Calendar.FRIDAY: result.add(Calendar.DAY_OF_MONTH, -4); break; case Calendar.SATURDAY: result.add(Calendar.DAY_OF_MONTH, -5); break; case Calendar.SUNDAY: result.add(Calendar.DAY_OF_MONTH, -6); break; default: break; } return result; }
java
public static GregorianCalendar truncateToWeek(GregorianCalendar date) { // Round the date down to the MONDAY of the same week. GregorianCalendar result = (GregorianCalendar)date.clone(); switch (result.get(Calendar.DAY_OF_WEEK)) { case Calendar.TUESDAY: result.add(Calendar.DAY_OF_MONTH, -1); break; case Calendar.WEDNESDAY: result.add(Calendar.DAY_OF_MONTH, -2); break; case Calendar.THURSDAY: result.add(Calendar.DAY_OF_MONTH, -3); break; case Calendar.FRIDAY: result.add(Calendar.DAY_OF_MONTH, -4); break; case Calendar.SATURDAY: result.add(Calendar.DAY_OF_MONTH, -5); break; case Calendar.SUNDAY: result.add(Calendar.DAY_OF_MONTH, -6); break; default: break; } return result; }
[ "public", "static", "GregorianCalendar", "truncateToWeek", "(", "GregorianCalendar", "date", ")", "{", "// Round the date down to the MONDAY of the same week.\r", "GregorianCalendar", "result", "=", "(", "GregorianCalendar", ")", "date", ".", "clone", "(", ")", ";", "swit...
Truncate the given GregorianCalendar date to the nearest week. This is done by cloning it and rounding the value down to the closest Monday. If the given date already occurs on a Monday, a copy of the same date is returned. @param date A GregorianCalendar object. @return A copy of the same value, truncated to the nearest Monday.
[ "Truncate", "the", "given", "GregorianCalendar", "date", "to", "the", "nearest", "week", ".", "This", "is", "done", "by", "cloning", "it", "and", "rounding", "the", "value", "down", "to", "the", "closest", "Monday", ".", "If", "the", "given", "date", "alre...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/Utils.java#L2020-L2033
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.validateAndExecuteRequest
private RESTResponse validateAndExecuteRequest(HttpServletRequest request) { Map<String, String> variableMap = new HashMap<String, String>(); String query = extractQueryParam(request, variableMap); Tenant tenant = getTenant(variableMap); // Command matching expects an encoded URI but without the servlet context, if any. String uri = request.getRequestURI(); String context = request.getContextPath(); if (!Utils.isEmpty(context)) { uri = uri.substring(context.length()); } ApplicationDefinition appDef = getApplication(uri, tenant); HttpMethod method = HttpMethod.methodFromString(request.getMethod()); if (method == null) { throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL()); } RegisteredCommand cmd = RESTService.instance().findCommand(appDef, method, uri, query, variableMap); if (cmd == null) { throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL()); } validateTenantAccess(request, tenant, cmd); RESTCallback callback = cmd.getNewCallback(); callback.setRequest(new RESTRequest(tenant, appDef, request, variableMap)); return callback.invoke(); }
java
private RESTResponse validateAndExecuteRequest(HttpServletRequest request) { Map<String, String> variableMap = new HashMap<String, String>(); String query = extractQueryParam(request, variableMap); Tenant tenant = getTenant(variableMap); // Command matching expects an encoded URI but without the servlet context, if any. String uri = request.getRequestURI(); String context = request.getContextPath(); if (!Utils.isEmpty(context)) { uri = uri.substring(context.length()); } ApplicationDefinition appDef = getApplication(uri, tenant); HttpMethod method = HttpMethod.methodFromString(request.getMethod()); if (method == null) { throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL()); } RegisteredCommand cmd = RESTService.instance().findCommand(appDef, method, uri, query, variableMap); if (cmd == null) { throw new NotFoundException("Request does not match a known URI: " + request.getRequestURL()); } validateTenantAccess(request, tenant, cmd); RESTCallback callback = cmd.getNewCallback(); callback.setRequest(new RESTRequest(tenant, appDef, request, variableMap)); return callback.invoke(); }
[ "private", "RESTResponse", "validateAndExecuteRequest", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "String", ">", "variableMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "String", "query", "=", ...
Execute the given request and return a RESTResponse or throw an appropriate error.
[ "Execute", "the", "given", "request", "and", "return", "a", "RESTResponse", "or", "throw", "an", "appropriate", "error", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L170-L197
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.getApplication
private ApplicationDefinition getApplication(String uri, Tenant tenant) { if (uri.length() < 2 || uri.startsWith("/_")) { return null; // Non-application request } String[] pathNodes = uri.substring(1).split("/"); String appName = Utils.urlDecode(pathNodes[0]); ApplicationDefinition appDef = SchemaService.instance().getApplication(tenant, appName); if (appDef == null) { throw new NotFoundException("Unknown application: " + appName); } return appDef; }
java
private ApplicationDefinition getApplication(String uri, Tenant tenant) { if (uri.length() < 2 || uri.startsWith("/_")) { return null; // Non-application request } String[] pathNodes = uri.substring(1).split("/"); String appName = Utils.urlDecode(pathNodes[0]); ApplicationDefinition appDef = SchemaService.instance().getApplication(tenant, appName); if (appDef == null) { throw new NotFoundException("Unknown application: " + appName); } return appDef; }
[ "private", "ApplicationDefinition", "getApplication", "(", "String", "uri", ",", "Tenant", "tenant", ")", "{", "if", "(", "uri", ".", "length", "(", ")", "<", "2", "||", "uri", ".", "startsWith", "(", "\"/_\"", ")", ")", "{", "return", "null", ";", "//...
Get the definition of the referenced application or null if there is none.
[ "Get", "the", "definition", "of", "the", "referenced", "application", "or", "null", "if", "there", "is", "none", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L200-L211
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.getTenant
private Tenant getTenant(Map<String, String> variableMap) { String tenantName = variableMap.get("tenant"); if (Utils.isEmpty(tenantName)) { tenantName = TenantService.instance().getDefaultTenantName(); } Tenant tenant = TenantService.instance().getTenant(tenantName); if (tenant == null) { throw new NotFoundException("Unknown tenant: " + tenantName); } return tenant; }
java
private Tenant getTenant(Map<String, String> variableMap) { String tenantName = variableMap.get("tenant"); if (Utils.isEmpty(tenantName)) { tenantName = TenantService.instance().getDefaultTenantName(); } Tenant tenant = TenantService.instance().getTenant(tenantName); if (tenant == null) { throw new NotFoundException("Unknown tenant: " + tenantName); } return tenant; }
[ "private", "Tenant", "getTenant", "(", "Map", "<", "String", ",", "String", ">", "variableMap", ")", "{", "String", "tenantName", "=", "variableMap", ".", "get", "(", "\"tenant\"", ")", ";", "if", "(", "Utils", ".", "isEmpty", "(", "tenantName", ")", ")"...
Get the Tenant context for this command and multi-tenant configuration options.
[ "Get", "the", "Tenant", "context", "for", "this", "command", "and", "multi", "-", "tenant", "configuration", "options", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L214-L224
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.validateTenantAccess
private void validateTenantAccess(HttpServletRequest request, Tenant tenant, RegisteredCommand cmdModel) { String authString = request.getHeader("Authorization"); StringBuilder userID = new StringBuilder(); StringBuilder password = new StringBuilder(); decodeAuthorizationHeader(authString, userID, password); Permission perm = permissionForMethod(request.getMethod()); TenantService.instance().validateTenantAccess(tenant, userID.toString(), password.toString(), perm, cmdModel.isPrivileged()); }
java
private void validateTenantAccess(HttpServletRequest request, Tenant tenant, RegisteredCommand cmdModel) { String authString = request.getHeader("Authorization"); StringBuilder userID = new StringBuilder(); StringBuilder password = new StringBuilder(); decodeAuthorizationHeader(authString, userID, password); Permission perm = permissionForMethod(request.getMethod()); TenantService.instance().validateTenantAccess(tenant, userID.toString(), password.toString(), perm, cmdModel.isPrivileged()); }
[ "private", "void", "validateTenantAccess", "(", "HttpServletRequest", "request", ",", "Tenant", "tenant", ",", "RegisteredCommand", "cmdModel", ")", "{", "String", "authString", "=", "request", ".", "getHeader", "(", "\"Authorization\"", ")", ";", "StringBuilder", "...
Extract Authorization header, if any, and validate this command for the given tenant.
[ "Extract", "Authorization", "header", "if", "any", "and", "validate", "this", "command", "for", "the", "given", "tenant", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L227-L235
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.permissionForMethod
private Permission permissionForMethod(String method) { switch (method.toUpperCase()) { case "GET": return Permission.READ; case "PUT": case "DELETE": return Permission.UPDATE; case "POST": return Permission.APPEND; default: throw new RuntimeException("Unexpected REST method: " + method); } }
java
private Permission permissionForMethod(String method) { switch (method.toUpperCase()) { case "GET": return Permission.READ; case "PUT": case "DELETE": return Permission.UPDATE; case "POST": return Permission.APPEND; default: throw new RuntimeException("Unexpected REST method: " + method); } }
[ "private", "Permission", "permissionForMethod", "(", "String", "method", ")", "{", "switch", "(", "method", ".", "toUpperCase", "(", ")", ")", "{", "case", "\"GET\"", ":", "return", "Permission", ".", "READ", ";", "case", "\"PUT\"", ":", "case", "\"DELETE\""...
Map an HTTP method to the permission needed to execute it.
[ "Map", "an", "HTTP", "method", "to", "the", "permission", "needed", "to", "execute", "it", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L238-L250
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.extractQueryParam
private String extractQueryParam(HttpServletRequest request, Map<String, String> restParams) { String query = request.getQueryString(); if (Utils.isEmpty(query)) { return ""; } StringBuilder buffer = new StringBuilder(query); // Split query component into decoded, &-separate components. String[] parts = Utils.splitURIQuery(buffer.toString()); List<Pair<String, String>> unusedList = new ArrayList<Pair<String,String>>(); boolean bRewrite = false; for (String part : parts) { Pair<String, String> param = extractParam(part); switch (param.firstItemInPair.toLowerCase()) { case "api": bRewrite = true; restParams.put("api", param.secondItemInPair); break; case "format": bRewrite = true; if (param.secondItemInPair.equalsIgnoreCase("xml")) { restParams.put("format", "text/xml"); } else if (param.secondItemInPair.equalsIgnoreCase("json")) { restParams.put("format", "application/json"); } break; case "tenant": bRewrite = true; restParams.put("tenant", param.secondItemInPair); break; default: unusedList.add(param); } } // If we extracted any fixed params, rewrite the query parameter. if (bRewrite) { buffer.setLength(0); for (Pair<String, String> pair : unusedList) { if (buffer.length() > 0) { buffer.append("&"); } buffer.append(Utils.urlEncode(pair.firstItemInPair)); if (pair.secondItemInPair != null) { buffer.append("="); buffer.append(Utils.urlEncode(pair.secondItemInPair)); } } } return buffer.toString(); }
java
private String extractQueryParam(HttpServletRequest request, Map<String, String> restParams) { String query = request.getQueryString(); if (Utils.isEmpty(query)) { return ""; } StringBuilder buffer = new StringBuilder(query); // Split query component into decoded, &-separate components. String[] parts = Utils.splitURIQuery(buffer.toString()); List<Pair<String, String>> unusedList = new ArrayList<Pair<String,String>>(); boolean bRewrite = false; for (String part : parts) { Pair<String, String> param = extractParam(part); switch (param.firstItemInPair.toLowerCase()) { case "api": bRewrite = true; restParams.put("api", param.secondItemInPair); break; case "format": bRewrite = true; if (param.secondItemInPair.equalsIgnoreCase("xml")) { restParams.put("format", "text/xml"); } else if (param.secondItemInPair.equalsIgnoreCase("json")) { restParams.put("format", "application/json"); } break; case "tenant": bRewrite = true; restParams.put("tenant", param.secondItemInPair); break; default: unusedList.add(param); } } // If we extracted any fixed params, rewrite the query parameter. if (bRewrite) { buffer.setLength(0); for (Pair<String, String> pair : unusedList) { if (buffer.length() > 0) { buffer.append("&"); } buffer.append(Utils.urlEncode(pair.firstItemInPair)); if (pair.secondItemInPair != null) { buffer.append("="); buffer.append(Utils.urlEncode(pair.secondItemInPair)); } } } return buffer.toString(); }
[ "private", "String", "extractQueryParam", "(", "HttpServletRequest", "request", ",", "Map", "<", "String", ",", "String", ">", "restParams", ")", "{", "String", "query", "=", "request", ".", "getQueryString", "(", ")", ";", "if", "(", "Utils", ".", "isEmpty"...
"format=y", and "tenant=z", if present, to rest parameters.
[ "format", "=", "y", "and", "tenant", "=", "z", "if", "present", "to", "rest", "parameters", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L300-L350
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java
RESTServlet.getFullURI
private String getFullURI(HttpServletRequest request) { StringBuilder buffer = new StringBuilder(request.getMethod()); buffer.append(" "); buffer.append(request.getRequestURI()); String queryParam = request.getQueryString(); if (!Utils.isEmpty(queryParam)) { buffer.append("?"); buffer.append(queryParam); } return buffer.toString(); }
java
private String getFullURI(HttpServletRequest request) { StringBuilder buffer = new StringBuilder(request.getMethod()); buffer.append(" "); buffer.append(request.getRequestURI()); String queryParam = request.getQueryString(); if (!Utils.isEmpty(queryParam)) { buffer.append("?"); buffer.append(queryParam); } return buffer.toString(); }
[ "private", "String", "getFullURI", "(", "HttpServletRequest", "request", ")", "{", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "request", ".", "getMethod", "(", ")", ")", ";", "buffer", ".", "append", "(", "\" \"", ")", ";", "buffer", ".", ...
Reconstruct the entire URI from the given request.
[ "Reconstruct", "the", "entire", "URI", "from", "the", "given", "request", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTServlet.java#L368-L378
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.setLegacy
private static void setLegacy(String moduleName, String legacyParamName) { String oldValue = g_legacyToModuleMap.put(legacyParamName, moduleName); if (oldValue != null) { logger.warn("Legacy parameter name used twice: {}", legacyParamName); } }
java
private static void setLegacy(String moduleName, String legacyParamName) { String oldValue = g_legacyToModuleMap.put(legacyParamName, moduleName); if (oldValue != null) { logger.warn("Legacy parameter name used twice: {}", legacyParamName); } }
[ "private", "static", "void", "setLegacy", "(", "String", "moduleName", ",", "String", "legacyParamName", ")", "{", "String", "oldValue", "=", "g_legacyToModuleMap", ".", "put", "(", "legacyParamName", ",", "moduleName", ")", ";", "if", "(", "oldValue", "!=", "...
Register the given legacy parameter name as owned by the given module name.
[ "Register", "the", "given", "legacy", "parameter", "name", "as", "owned", "by", "the", "given", "module", "name", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L63-L68
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.setLegacy
private static void setLegacy(String moduleName, String... legacyParamNames) { for (String legacyParamName : legacyParamNames) { setLegacy(moduleName, legacyParamName); } }
java
private static void setLegacy(String moduleName, String... legacyParamNames) { for (String legacyParamName : legacyParamNames) { setLegacy(moduleName, legacyParamName); } }
[ "private", "static", "void", "setLegacy", "(", "String", "moduleName", ",", "String", "...", "legacyParamNames", ")", "{", "for", "(", "String", "legacyParamName", ":", "legacyParamNames", ")", "{", "setLegacy", "(", "moduleName", ",", "legacyParamName", ")", ";...
Register the given legacy parameter names as owned by the given module name.
[ "Register", "the", "given", "legacy", "parameter", "names", "as", "owned", "by", "the", "given", "module", "name", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L71-L75
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.getConfigUrl
private static URL getConfigUrl() throws ConfigurationException { String spec = System.getProperty(CONFIG_URL_PROPERTY_NAME); if (spec == null) { spec = DEFAULT_CONFIG_URL; } URL configUrl = null; try { configUrl = new URL(spec); configUrl.openStream().close(); // catches well-formed but bogus URLs } catch (Exception e) { try { File f = new File(spec); if (f.exists()) { configUrl = new URL("file:///" + f.getCanonicalPath()); } } catch( Exception ex) { } } if (configUrl == null) { ClassLoader loader = ServerParams.class.getClassLoader(); configUrl = loader.getResource(spec); if (configUrl == null) { throw new ConfigurationException("Can't find file/resource: \"" + spec + "\"."); } } return configUrl; }
java
private static URL getConfigUrl() throws ConfigurationException { String spec = System.getProperty(CONFIG_URL_PROPERTY_NAME); if (spec == null) { spec = DEFAULT_CONFIG_URL; } URL configUrl = null; try { configUrl = new URL(spec); configUrl.openStream().close(); // catches well-formed but bogus URLs } catch (Exception e) { try { File f = new File(spec); if (f.exists()) { configUrl = new URL("file:///" + f.getCanonicalPath()); } } catch( Exception ex) { } } if (configUrl == null) { ClassLoader loader = ServerParams.class.getClassLoader(); configUrl = loader.getResource(spec); if (configUrl == null) { throw new ConfigurationException("Can't find file/resource: \"" + spec + "\"."); } } return configUrl; }
[ "private", "static", "URL", "getConfigUrl", "(", ")", "throws", "ConfigurationException", "{", "String", "spec", "=", "System", ".", "getProperty", "(", "CONFIG_URL_PROPERTY_NAME", ")", ";", "if", "(", "spec", "==", "null", ")", "{", "spec", "=", "DEFAULT_CONF...
Inspect the classpath to find configuration file
[ "Inspect", "the", "classpath", "to", "find", "configuration", "file" ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L435-L465
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.updateMap
@SuppressWarnings("unchecked") private void updateMap(Map<String, Object> parentMap, String paramName, Object paramValue) { Object currentValue = parentMap.get(paramName); if (currentValue == null || !(currentValue instanceof Map)) { if (paramValue instanceof Map) { parentMap.put(paramName, paramValue); } else { parentMap.put(paramName, paramValue.toString()); } } else { Utils.require(paramValue instanceof Map, "Parameter '%s' must be a map: %s", paramName, paramValue.toString()); Map<String, Object> currentMap = (Map<String, Object>)currentValue; Map<String, Object> updateMap = (Map<String, Object>)paramValue; for (String subParam : updateMap.keySet()) { updateMap(currentMap, subParam, updateMap.get(subParam)); } } }
java
@SuppressWarnings("unchecked") private void updateMap(Map<String, Object> parentMap, String paramName, Object paramValue) { Object currentValue = parentMap.get(paramName); if (currentValue == null || !(currentValue instanceof Map)) { if (paramValue instanceof Map) { parentMap.put(paramName, paramValue); } else { parentMap.put(paramName, paramValue.toString()); } } else { Utils.require(paramValue instanceof Map, "Parameter '%s' must be a map: %s", paramName, paramValue.toString()); Map<String, Object> currentMap = (Map<String, Object>)currentValue; Map<String, Object> updateMap = (Map<String, Object>)paramValue; for (String subParam : updateMap.keySet()) { updateMap(currentMap, subParam, updateMap.get(subParam)); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "void", "updateMap", "(", "Map", "<", "String", ",", "Object", ">", "parentMap", ",", "String", "paramName", ",", "Object", "paramValue", ")", "{", "Object", "currentValue", "=", "parentMap", ".", ...
Replace or add the given parameter name and value to the given map.
[ "Replace", "or", "add", "the", "given", "parameter", "name", "and", "value", "to", "the", "given", "map", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L501-L519
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.setLegacyParam
private void setLegacyParam(String legacyParamName, Object paramValue) { if (!m_bWarnedLegacyParam) { logger.warn("Parameter '{}': Legacy parameter format is being phased-out. " + "Please use new module/parameter format.", legacyParamName); m_bWarnedLegacyParam = true; } String moduleName = g_legacyToModuleMap.get(legacyParamName); if (moduleName == null) { logger.warn("Skipping unknown legacy parameter: {}", legacyParamName); } else { setModuleParam(moduleName, legacyParamName, paramValue); } }
java
private void setLegacyParam(String legacyParamName, Object paramValue) { if (!m_bWarnedLegacyParam) { logger.warn("Parameter '{}': Legacy parameter format is being phased-out. " + "Please use new module/parameter format.", legacyParamName); m_bWarnedLegacyParam = true; } String moduleName = g_legacyToModuleMap.get(legacyParamName); if (moduleName == null) { logger.warn("Skipping unknown legacy parameter: {}", legacyParamName); } else { setModuleParam(moduleName, legacyParamName, paramValue); } }
[ "private", "void", "setLegacyParam", "(", "String", "legacyParamName", ",", "Object", "paramValue", ")", "{", "if", "(", "!", "m_bWarnedLegacyParam", ")", "{", "logger", ".", "warn", "(", "\"Parameter '{}': Legacy parameter format is being phased-out. \"", "+", "\"Pleas...
Sets a parameter using a legacy name.
[ "Sets", "a", "parameter", "using", "a", "legacy", "name", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L522-L534
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.parse
public void parse(UNode tableNode) { assert tableNode != null; // Verify table name and save it. setTableName(tableNode.getName()); // Examine table node's children. for (String childName : tableNode.getMemberNames()) { UNode childNode = tableNode.getMember(childName); // "fields" if (childName.equals("fields")) { // Process field definitions. for (String fieldName : childNode.getMemberNames()) { // Create a FieldDefinition and parse the node's value into it. // This will throw if the definition is invalid. FieldDefinition fieldDef = new FieldDefinition(); fieldDef.parse(childNode.getMember(fieldName)); // Ensure field name is unique and add it to the table's field map. addFieldDefinition(fieldDef); } // "options" } else if (childName.equals("options")) { // Examine each option. for (String optName : childNode.getMemberNames()) { // Each option must be a simple value and specified only once. UNode optNode = childNode.getMember(optName); Utils.require(optNode.isValue(), "'option' must be a value: " + optNode); Utils.require(getOption(optName) == null, "Option '" + optName + "' can only be specified once"); // Add option to option map, which performs some immediate validation. setOption(optName, optNode.getValue()); } // "aliases" } else if (childName.equals("aliases")) { // Parse and add each AliasDefinition. for (String aliasName : childNode.getMemberNames()) { AliasDefinition aliasDef = new AliasDefinition(m_tableName); aliasDef.parse(childNode.getMember(aliasName)); addAliasDefinition(aliasDef); } // Unrecognized } else { Utils.require(false, "Unrecognized 'table' element: " + childName); } } verify(); }
java
public void parse(UNode tableNode) { assert tableNode != null; // Verify table name and save it. setTableName(tableNode.getName()); // Examine table node's children. for (String childName : tableNode.getMemberNames()) { UNode childNode = tableNode.getMember(childName); // "fields" if (childName.equals("fields")) { // Process field definitions. for (String fieldName : childNode.getMemberNames()) { // Create a FieldDefinition and parse the node's value into it. // This will throw if the definition is invalid. FieldDefinition fieldDef = new FieldDefinition(); fieldDef.parse(childNode.getMember(fieldName)); // Ensure field name is unique and add it to the table's field map. addFieldDefinition(fieldDef); } // "options" } else if (childName.equals("options")) { // Examine each option. for (String optName : childNode.getMemberNames()) { // Each option must be a simple value and specified only once. UNode optNode = childNode.getMember(optName); Utils.require(optNode.isValue(), "'option' must be a value: " + optNode); Utils.require(getOption(optName) == null, "Option '" + optName + "' can only be specified once"); // Add option to option map, which performs some immediate validation. setOption(optName, optNode.getValue()); } // "aliases" } else if (childName.equals("aliases")) { // Parse and add each AliasDefinition. for (String aliasName : childNode.getMemberNames()) { AliasDefinition aliasDef = new AliasDefinition(m_tableName); aliasDef.parse(childNode.getMember(aliasName)); addAliasDefinition(aliasDef); } // Unrecognized } else { Utils.require(false, "Unrecognized 'table' element: " + childName); } } verify(); }
[ "public", "void", "parse", "(", "UNode", "tableNode", ")", "{", "assert", "tableNode", "!=", "null", ";", "// Verify table name and save it.\r", "setTableName", "(", "tableNode", ".", "getName", "(", ")", ")", ";", "// Examine table node's children.\r", "for", "(", ...
Parse a table definition rooted at the given UNode. The given node is the table definition, hence its name is the table name. The node must be a MAP whose child nodes are table definitions such as "options" and "fields". @param tableNode {@link UNode} whose name is the table's name and whose child nodes define the tables features.
[ "Parse", "a", "table", "definition", "rooted", "at", "the", "given", "UNode", ".", "The", "given", "node", "is", "the", "table", "definition", "hence", "its", "name", "is", "the", "table", "name", ".", "The", "node", "must", "be", "a", "MAP", "whose", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L132-L185
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.isValidTableName
public static boolean isValidTableName(String tableName) { return tableName != null && tableName.length() > 0 && Utils.isLetter(tableName.charAt(0)) && Utils.allAlphaNumUnderscore(tableName); }
java
public static boolean isValidTableName(String tableName) { return tableName != null && tableName.length() > 0 && Utils.isLetter(tableName.charAt(0)) && Utils.allAlphaNumUnderscore(tableName); }
[ "public", "static", "boolean", "isValidTableName", "(", "String", "tableName", ")", "{", "return", "tableName", "!=", "null", "&&", "tableName", ".", "length", "(", ")", ">", "0", "&&", "Utils", ".", "isLetter", "(", "tableName", ".", "charAt", "(", "0", ...
Indicate if the given string is a valid table name. Table names must begin with a letter and consist of all letters, digits, and underscores. @param tableName Candidate table name. @return True if the name is not null, not empty, starts with a letter, and consists of only letters, digits, and underscores.
[ "Indicate", "if", "the", "given", "string", "is", "a", "valid", "table", "name", ".", "Table", "names", "must", "begin", "with", "a", "letter", "and", "consist", "of", "all", "letters", "digits", "and", "underscores", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L195-L200
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.computeShardStart
public Date computeShardStart(int shardNumber) { assert isSharded(); assert shardNumber > 0; assert m_shardingStartDate != null; // Shard #1 always starts on the sharding-start date. Date result = null; if (shardNumber == 1) { result = m_shardingStartDate.getTime(); } else { // Clone m_shardingStartDate and adjust by shard number. GregorianCalendar shardDate = (GregorianCalendar)m_shardingStartDate.clone(); switch (m_shardingGranularity) { case HOUR: // Increment start date HOUR by shard number - 1. shardDate.add(Calendar.HOUR_OF_DAY, shardNumber - 1); break; case DAY: // Increment start date DAY by shard number - 1. shardDate.add(Calendar.DAY_OF_MONTH, shardNumber - 1); break; case WEEK: // Round the sharding-start date down to the MONDAY of the same week. // Then increment it's DAY by (shard number - 1) * 7. shardDate = Utils.truncateToWeek(m_shardingStartDate); shardDate.add(Calendar.DAY_OF_MONTH, (shardNumber - 1) * 7); break; case MONTH: // Increment start date MONTH by shard number - 1, but the day is always 1. shardDate.add(Calendar.MONTH, shardNumber - 1); shardDate.set(Calendar.DAY_OF_MONTH, 1); break; } result = shardDate.getTime(); } assert computeShardNumber(result) == shardNumber; return result; }
java
public Date computeShardStart(int shardNumber) { assert isSharded(); assert shardNumber > 0; assert m_shardingStartDate != null; // Shard #1 always starts on the sharding-start date. Date result = null; if (shardNumber == 1) { result = m_shardingStartDate.getTime(); } else { // Clone m_shardingStartDate and adjust by shard number. GregorianCalendar shardDate = (GregorianCalendar)m_shardingStartDate.clone(); switch (m_shardingGranularity) { case HOUR: // Increment start date HOUR by shard number - 1. shardDate.add(Calendar.HOUR_OF_DAY, shardNumber - 1); break; case DAY: // Increment start date DAY by shard number - 1. shardDate.add(Calendar.DAY_OF_MONTH, shardNumber - 1); break; case WEEK: // Round the sharding-start date down to the MONDAY of the same week. // Then increment it's DAY by (shard number - 1) * 7. shardDate = Utils.truncateToWeek(m_shardingStartDate); shardDate.add(Calendar.DAY_OF_MONTH, (shardNumber - 1) * 7); break; case MONTH: // Increment start date MONTH by shard number - 1, but the day is always 1. shardDate.add(Calendar.MONTH, shardNumber - 1); shardDate.set(Calendar.DAY_OF_MONTH, 1); break; } result = shardDate.getTime(); } assert computeShardNumber(result) == shardNumber; return result; }
[ "public", "Date", "computeShardStart", "(", "int", "shardNumber", ")", "{", "assert", "isSharded", "(", ")", ";", "assert", "shardNumber", ">", "0", ";", "assert", "m_shardingStartDate", "!=", "null", ";", "// Shard #1 always starts on the sharding-start date.\r", "Da...
Compute and return the date at which the shard with the given number starts based on this table's sharding options. For example, if sharding-granularity is MONTH and the sharding-start is 2012-10-15, then shard 2 starts on 2012-11-01. @param shardNumber Shard number (&gt; 0). @return Date on which the given shard starts. It will &gt;= this table's sharding-start option.
[ "Compute", "and", "return", "the", "date", "at", "which", "the", "shard", "with", "the", "given", "number", "starts", "based", "on", "this", "table", "s", "sharding", "options", ".", "For", "example", "if", "sharding", "-", "granularity", "is", "MONTH", "a...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L213-L253
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.computeShardNumber
public int computeShardNumber(Date shardingFieldValue) { assert shardingFieldValue != null; assert isSharded(); assert m_shardingStartDate != null; // Convert the sharding field value into a calendar object. Note that this value // will have non-zero time elements. GregorianCalendar objectDate = new GregorianCalendar(Utils.UTC_TIMEZONE); objectDate.setTime(shardingFieldValue); // Since the start date has no time elements, if the result is negative, the object's // date is before the start date. if (objectDate.getTimeInMillis() < m_shardingStartDate.getTimeInMillis()) { // Object date occurs before sharding start. Shard number -> 0. return 0; } // Determine the shard number based on the granularity. int shardNumber = 1; switch (m_shardingGranularity) { case HOUR: // Increment shard number by difference in millis-per-hours. shardNumber += (objectDate.getTimeInMillis() - m_shardingStartDate.getTimeInMillis()) / MILLIS_IN_HOUR; break; case DAY: // Since the dates are in UTC, which doesn't have DST, the difference in days // is simply the difference in whole number of millis-per-day. shardNumber += (objectDate.getTimeInMillis() - m_shardingStartDate.getTimeInMillis()) / MILLIS_IN_DAY; break; case WEEK: // Truncate the sharding-start date to MONDAY. The difference in weeks is then // the shard increment. GregorianCalendar shard1week = Utils.truncateToWeek(m_shardingStartDate); shardNumber += (objectDate.getTimeInMillis() - shard1week.getTimeInMillis()) / MILLIS_IN_WEEK; break; case MONTH: // Difference in months is 12 * (difference in years) + (difference in months) int diffInMonths = ((objectDate.get(Calendar.YEAR) - m_shardingStartDate.get(Calendar.YEAR)) * 12) + (objectDate.get(Calendar.MONTH) - m_shardingStartDate.get(Calendar.MONTH)); shardNumber += diffInMonths; break; default: Utils.require(false, "Unknown sharding-granularity: " + m_shardingGranularity); } return shardNumber; }
java
public int computeShardNumber(Date shardingFieldValue) { assert shardingFieldValue != null; assert isSharded(); assert m_shardingStartDate != null; // Convert the sharding field value into a calendar object. Note that this value // will have non-zero time elements. GregorianCalendar objectDate = new GregorianCalendar(Utils.UTC_TIMEZONE); objectDate.setTime(shardingFieldValue); // Since the start date has no time elements, if the result is negative, the object's // date is before the start date. if (objectDate.getTimeInMillis() < m_shardingStartDate.getTimeInMillis()) { // Object date occurs before sharding start. Shard number -> 0. return 0; } // Determine the shard number based on the granularity. int shardNumber = 1; switch (m_shardingGranularity) { case HOUR: // Increment shard number by difference in millis-per-hours. shardNumber += (objectDate.getTimeInMillis() - m_shardingStartDate.getTimeInMillis()) / MILLIS_IN_HOUR; break; case DAY: // Since the dates are in UTC, which doesn't have DST, the difference in days // is simply the difference in whole number of millis-per-day. shardNumber += (objectDate.getTimeInMillis() - m_shardingStartDate.getTimeInMillis()) / MILLIS_IN_DAY; break; case WEEK: // Truncate the sharding-start date to MONDAY. The difference in weeks is then // the shard increment. GregorianCalendar shard1week = Utils.truncateToWeek(m_shardingStartDate); shardNumber += (objectDate.getTimeInMillis() - shard1week.getTimeInMillis()) / MILLIS_IN_WEEK; break; case MONTH: // Difference in months is 12 * (difference in years) + (difference in months) int diffInMonths = ((objectDate.get(Calendar.YEAR) - m_shardingStartDate.get(Calendar.YEAR)) * 12) + (objectDate.get(Calendar.MONTH) - m_shardingStartDate.get(Calendar.MONTH)); shardNumber += diffInMonths; break; default: Utils.require(false, "Unknown sharding-granularity: " + m_shardingGranularity); } return shardNumber; }
[ "public", "int", "computeShardNumber", "(", "Date", "shardingFieldValue", ")", "{", "assert", "shardingFieldValue", "!=", "null", ";", "assert", "isSharded", "(", ")", ";", "assert", "m_shardingStartDate", "!=", "null", ";", "// Convert the sharding field value into a c...
Compute the shard number of an object belong to this table with the given sharding-field value. This method should only be called on a sharded table for which the sharding-field, sharding-granularity, and sharding-start options have been set. The value returned will be 0 if the given date falls before the sharding-start date. Otherwise it will be &gt;= 1, representing the shard in which the object should reside. @param shardingFieldValue Value of an object's sharding-field as a Date in the UTC time zone. @return Shard number representing the shard in which the object should reside.
[ "Compute", "the", "shard", "number", "of", "an", "object", "belong", "to", "this", "table", "with", "the", "given", "sharding", "-", "field", "value", ".", "This", "method", "should", "only", "be", "called", "on", "a", "sharded", "table", "for", "which", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L268-L317
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.isCollection
public boolean isCollection(String fieldName) { FieldDefinition fieldDef = m_fieldDefMap.get(fieldName); return fieldDef != null && fieldDef.isScalarField() && fieldDef.isCollection(); }
java
public boolean isCollection(String fieldName) { FieldDefinition fieldDef = m_fieldDefMap.get(fieldName); return fieldDef != null && fieldDef.isScalarField() && fieldDef.isCollection(); }
[ "public", "boolean", "isCollection", "(", "String", "fieldName", ")", "{", "FieldDefinition", "fieldDef", "=", "m_fieldDefMap", ".", "get", "(", "fieldName", ")", ";", "return", "fieldDef", "!=", "null", "&&", "fieldDef", ".", "isScalarField", "(", ")", "&&", ...
Return true if the given field name is an MV scalar field. Since scalar fields must be declared as MV, only predefined fields can be MV. @param fieldName Candidate field name. @return True if the name is a known MV scalar field, otherwise false.
[ "Return", "true", "if", "the", "given", "field", "name", "is", "an", "MV", "scalar", "field", ".", "Since", "scalar", "fields", "must", "be", "declared", "as", "MV", "only", "predefined", "fields", "can", "be", "MV", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L472-L475
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.isLinkField
public boolean isLinkField(String fieldName) { FieldDefinition fieldDef = m_fieldDefMap.get(fieldName); return fieldDef != null && fieldDef.isLinkField(); }
java
public boolean isLinkField(String fieldName) { FieldDefinition fieldDef = m_fieldDefMap.get(fieldName); return fieldDef != null && fieldDef.isLinkField(); }
[ "public", "boolean", "isLinkField", "(", "String", "fieldName", ")", "{", "FieldDefinition", "fieldDef", "=", "m_fieldDefMap", ".", "get", "(", "fieldName", ")", ";", "return", "fieldDef", "!=", "null", "&&", "fieldDef", ".", "isLinkField", "(", ")", ";", "}...
Return true if this table definition possesses a FieldDefinition with the given name that defines a Link field. @param fieldName Candidate field name. @return True if the name is a known Link field, otherwise false.
[ "Return", "true", "if", "this", "table", "definition", "possesses", "a", "FieldDefinition", "with", "the", "given", "name", "that", "defines", "a", "Link", "field", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L484-L487
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.setOption
public void setOption(String optionName, String optionValue) { // Ensure option value is not empty and trim excess whitespace. Utils.require(optionName != null, "optionName"); Utils.require(optionValue != null && optionValue.trim().length() > 0, "Value for option '" + optionName + "' can not be empty"); optionValue = optionValue.trim(); m_optionMap.put(optionName.toLowerCase(), optionValue); // sharding-granularity and sharding-start are validated here since we must set // local members when the table's definition is parsed. if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_GRANULARITY)) { m_shardingGranularity = ShardingGranularity.fromString(optionValue); Utils.require(m_shardingGranularity != null, "Unrecognized 'sharding-granularity' value: " + optionValue); } else if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_START)) { Utils.require(isValidShardDate(optionValue), "'sharding-start' must be YYYY-MM-DD: " + optionValue); m_shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE); m_shardingStartDate.setTime(Utils.dateFromString(optionValue)); } }
java
public void setOption(String optionName, String optionValue) { // Ensure option value is not empty and trim excess whitespace. Utils.require(optionName != null, "optionName"); Utils.require(optionValue != null && optionValue.trim().length() > 0, "Value for option '" + optionName + "' can not be empty"); optionValue = optionValue.trim(); m_optionMap.put(optionName.toLowerCase(), optionValue); // sharding-granularity and sharding-start are validated here since we must set // local members when the table's definition is parsed. if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_GRANULARITY)) { m_shardingGranularity = ShardingGranularity.fromString(optionValue); Utils.require(m_shardingGranularity != null, "Unrecognized 'sharding-granularity' value: " + optionValue); } else if (optionName.equalsIgnoreCase(CommonDefs.OPT_SHARDING_START)) { Utils.require(isValidShardDate(optionValue), "'sharding-start' must be YYYY-MM-DD: " + optionValue); m_shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE); m_shardingStartDate.setTime(Utils.dateFromString(optionValue)); } }
[ "public", "void", "setOption", "(", "String", "optionName", ",", "String", "optionValue", ")", "{", "// Ensure option value is not empty and trim excess whitespace.\r", "Utils", ".", "require", "(", "optionName", "!=", "null", ",", "\"optionName\"", ")", ";", "Utils", ...
Set the option with the given name to the given value. This method does not validate that the given option name and value are valid since options are storage service-specific. @param optionName Option name. This is down-cased when stored. @param optionValue Option value. Cannot be null.
[ "Set", "the", "option", "with", "the", "given", "name", "to", "the", "given", "value", ".", "This", "method", "does", "not", "validate", "that", "the", "given", "option", "name", "and", "value", "are", "valid", "since", "options", "are", "storage", "servic...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L599-L619
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.getLinkExtentTableDef
public TableDefinition getLinkExtentTableDef(FieldDefinition linkDef) { assert linkDef != null; assert linkDef.isLinkType(); assert m_appDef != null; TableDefinition tableDef = m_appDef.getTableDef(linkDef.getLinkExtent()); assert tableDef != null; return tableDef; }
java
public TableDefinition getLinkExtentTableDef(FieldDefinition linkDef) { assert linkDef != null; assert linkDef.isLinkType(); assert m_appDef != null; TableDefinition tableDef = m_appDef.getTableDef(linkDef.getLinkExtent()); assert tableDef != null; return tableDef; }
[ "public", "TableDefinition", "getLinkExtentTableDef", "(", "FieldDefinition", "linkDef", ")", "{", "assert", "linkDef", "!=", "null", ";", "assert", "linkDef", ".", "isLinkType", "(", ")", ";", "assert", "m_appDef", "!=", "null", ";", "TableDefinition", "tableDef"...
Get the TableDefinition of the "extent" table for the given link field. @param linkDef {@link FieldDefinition} for a link field. @return {@link TableDefinition} for link's extent (target) table.
[ "Get", "the", "TableDefinition", "of", "the", "extent", "table", "for", "the", "given", "link", "field", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L650-L658
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.extractLinkValue
public boolean extractLinkValue(String colName, Map<String, Set<String>> mvLinkValueMap) { // Link column names always begin with '~'. if (colName.length() == 0 || colName.charAt(0) != '~') { return false; } // A '/' should separate the field name and object value. int slashInx = colName.indexOf('/'); if (slashInx < 0) { return false; } // Extract the field name and ensure we know about this field. String fieldName = colName.substring(1, slashInx); // Extract the link value's target object ID and add it to the value set for the field. String linkValue = colName.substring(slashInx + 1); Set<String> valueSet = mvLinkValueMap.get(fieldName); if (valueSet == null) { // First value for this field. valueSet = new HashSet<String>(); mvLinkValueMap.put(fieldName, valueSet); } valueSet.add(linkValue); return true; }
java
public boolean extractLinkValue(String colName, Map<String, Set<String>> mvLinkValueMap) { // Link column names always begin with '~'. if (colName.length() == 0 || colName.charAt(0) != '~') { return false; } // A '/' should separate the field name and object value. int slashInx = colName.indexOf('/'); if (slashInx < 0) { return false; } // Extract the field name and ensure we know about this field. String fieldName = colName.substring(1, slashInx); // Extract the link value's target object ID and add it to the value set for the field. String linkValue = colName.substring(slashInx + 1); Set<String> valueSet = mvLinkValueMap.get(fieldName); if (valueSet == null) { // First value for this field. valueSet = new HashSet<String>(); mvLinkValueMap.put(fieldName, valueSet); } valueSet.add(linkValue); return true; }
[ "public", "boolean", "extractLinkValue", "(", "String", "colName", ",", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "mvLinkValueMap", ")", "{", "// Link column names always begin with '~'.\r", "if", "(", "colName", ".", "length", "(", ")", "==", ...
Examine the given column name and, if it represents an MV link value, add it to the given MV link value map. If a link value is successfully extracted, true is returned. If the column name is not in the format used for MV link values, false is returned. @param colName Column name from an object record belonging to this table (in string form). @param mvLinkValueMap Link value map to be updated if the column represents a valid link value. @return True if a link value is extracted and added to the map; false means the column name was not a link value.
[ "Examine", "the", "given", "column", "name", "and", "if", "it", "represents", "an", "MV", "link", "value", "add", "it", "to", "the", "given", "MV", "link", "value", "map", ".", "If", "a", "link", "value", "is", "successfully", "extracted", "true", "is", ...
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L672-L697
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.addAliasDefinition
private void addAliasDefinition(AliasDefinition aliasDef) { // Prerequisites: assert aliasDef != null; assert !m_aliasDefMap.containsKey(aliasDef.getName()); assert aliasDef.getTableName().equals(this.getTableName()); m_aliasDefMap.put(aliasDef.getName(), aliasDef); }
java
private void addAliasDefinition(AliasDefinition aliasDef) { // Prerequisites: assert aliasDef != null; assert !m_aliasDefMap.containsKey(aliasDef.getName()); assert aliasDef.getTableName().equals(this.getTableName()); m_aliasDefMap.put(aliasDef.getName(), aliasDef); }
[ "private", "void", "addAliasDefinition", "(", "AliasDefinition", "aliasDef", ")", "{", "// Prerequisites:\r", "assert", "aliasDef", "!=", "null", ";", "assert", "!", "m_aliasDefMap", ".", "containsKey", "(", "aliasDef", ".", "getName", "(", ")", ")", ";", "asser...
Add the given alias definition to this table definition.
[ "Add", "the", "given", "alias", "definition", "to", "this", "table", "definition", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L775-L782
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java
TableDefinition.verifyJunctionField
private void verifyJunctionField(FieldDefinition xlinkDef) { String juncField = xlinkDef.getXLinkJunction(); if (!"_ID".equals(juncField)) { FieldDefinition juncFieldDef = m_fieldDefMap.get(juncField); Utils.require(juncFieldDef != null, String.format("Junction field for xlink '%s' has not been defined: %s", xlinkDef.getName(), xlinkDef.getXLinkJunction())); Utils.require(juncFieldDef.getType() == FieldType.TEXT, String.format("Junction field for xlink '%s' must be a text field: ", xlinkDef.getName(), xlinkDef.getXLinkJunction())); } }
java
private void verifyJunctionField(FieldDefinition xlinkDef) { String juncField = xlinkDef.getXLinkJunction(); if (!"_ID".equals(juncField)) { FieldDefinition juncFieldDef = m_fieldDefMap.get(juncField); Utils.require(juncFieldDef != null, String.format("Junction field for xlink '%s' has not been defined: %s", xlinkDef.getName(), xlinkDef.getXLinkJunction())); Utils.require(juncFieldDef.getType() == FieldType.TEXT, String.format("Junction field for xlink '%s' must be a text field: ", xlinkDef.getName(), xlinkDef.getXLinkJunction())); } }
[ "private", "void", "verifyJunctionField", "(", "FieldDefinition", "xlinkDef", ")", "{", "String", "juncField", "=", "xlinkDef", ".", "getXLinkJunction", "(", ")", ";", "if", "(", "!", "\"_ID\"", ".", "equals", "(", "juncField", ")", ")", "{", "FieldDefinition"...
Verify that the given xlink's junction field is either _ID or an SV text field.
[ "Verify", "that", "the", "given", "xlink", "s", "junction", "field", "is", "either", "_ID", "or", "an", "SV", "text", "field", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/TableDefinition.java#L806-L817
train
QSFT/Doradus
doradus-dynamodb/src/main/java/com/dell/doradus/db/dynamodb/DDBTransaction.java
DDBTransaction.mapColumnValue
private AttributeValue mapColumnValue(String storeName, DColumn col) { AttributeValue attrValue = new AttributeValue(); if (!DBService.isSystemTable(storeName)) { if (col.getRawValue().length == 0) { attrValue.setS(DynamoDBService.NULL_COLUMN_MARKER); } else { attrValue.setB(ByteBuffer.wrap(col.getRawValue())); } } else { String strValue = col.getValue(); if (strValue.length() == 0) { strValue = DynamoDBService.NULL_COLUMN_MARKER; } attrValue.setS(strValue); } return attrValue; }
java
private AttributeValue mapColumnValue(String storeName, DColumn col) { AttributeValue attrValue = new AttributeValue(); if (!DBService.isSystemTable(storeName)) { if (col.getRawValue().length == 0) { attrValue.setS(DynamoDBService.NULL_COLUMN_MARKER); } else { attrValue.setB(ByteBuffer.wrap(col.getRawValue())); } } else { String strValue = col.getValue(); if (strValue.length() == 0) { strValue = DynamoDBService.NULL_COLUMN_MARKER; } attrValue.setS(strValue); } return attrValue; }
[ "private", "AttributeValue", "mapColumnValue", "(", "String", "storeName", ",", "DColumn", "col", ")", "{", "AttributeValue", "attrValue", "=", "new", "AttributeValue", "(", ")", ";", "if", "(", "!", "DBService", ".", "isSystemTable", "(", "storeName", ")", ")...
Create the appropriate AttributeValue for the given column value type and length.
[ "Create", "the", "appropriate", "AttributeValue", "for", "the", "given", "column", "value", "type", "and", "length", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-dynamodb/src/main/java/com/dell/doradus/db/dynamodb/DDBTransaction.java#L120-L136
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/fieldanalyzer/FieldAnalyzer.java
FieldAnalyzer.extractTerms
public Set<String> extractTerms(String value) { try { Set<String> result = new HashSet<String>(); Set<String> split = Utils.split(value.toLowerCase(), CommonDefs.MV_SCALAR_SEP_CHAR); for(String s : split) { String[] tokens = tokenize(s); for (String token : tokens) { if (token.length() == 0) continue; result.add(token); } } return result; } catch (Exception e) { // Turn into an IllegalArgumentException throw new IllegalArgumentException("Error parsing field value: " + e.getLocalizedMessage()); } }
java
public Set<String> extractTerms(String value) { try { Set<String> result = new HashSet<String>(); Set<String> split = Utils.split(value.toLowerCase(), CommonDefs.MV_SCALAR_SEP_CHAR); for(String s : split) { String[] tokens = tokenize(s); for (String token : tokens) { if (token.length() == 0) continue; result.add(token); } } return result; } catch (Exception e) { // Turn into an IllegalArgumentException throw new IllegalArgumentException("Error parsing field value: " + e.getLocalizedMessage()); } }
[ "public", "Set", "<", "String", ">", "extractTerms", "(", "String", "value", ")", "{", "try", "{", "Set", "<", "String", ">", "result", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "Set", "<", "String", ">", "split", "=", "Utils", ".",...
Analyze the given String value and return the set of terms that should be indexed. @param value Field value to be indexed as a binary value. @return Set of terms that should be indexed.
[ "Analyze", "the", "given", "String", "value", "and", "return", "the", "set", "of", "terms", "that", "should", "be", "indexed", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/fieldanalyzer/FieldAnalyzer.java#L198-L214
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java
BatchResult.newErrorResult
public static BatchResult newErrorResult(String errMsg) { BatchResult result = new BatchResult(); result.setStatus(Status.ERROR); result.setErrorMessage(errMsg); return result; }
java
public static BatchResult newErrorResult(String errMsg) { BatchResult result = new BatchResult(); result.setStatus(Status.ERROR); result.setErrorMessage(errMsg); return result; }
[ "public", "static", "BatchResult", "newErrorResult", "(", "String", "errMsg", ")", "{", "BatchResult", "result", "=", "new", "BatchResult", "(", ")", ";", "result", ".", "setStatus", "(", "Status", ".", "ERROR", ")", ";", "result", ".", "setErrorMessage", "(...
Create a new BatchResult with an ERROR status and the given error message. @param errMsg Error message. @return New BatchResult object with ERROR status and given error message.
[ "Create", "a", "new", "BatchResult", "with", "an", "ERROR", "status", "and", "the", "given", "error", "message", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java#L50-L55
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java
BatchResult.hasUpdates
public boolean hasUpdates() { String hasUpdates = m_resultFields.get(HAS_UPDATES); return hasUpdates != null && Boolean.parseBoolean(hasUpdates); }
java
public boolean hasUpdates() { String hasUpdates = m_resultFields.get(HAS_UPDATES); return hasUpdates != null && Boolean.parseBoolean(hasUpdates); }
[ "public", "boolean", "hasUpdates", "(", ")", "{", "String", "hasUpdates", "=", "m_resultFields", ".", "get", "(", "HAS_UPDATES", ")", ";", "return", "hasUpdates", "!=", "null", "&&", "Boolean", ".", "parseBoolean", "(", "hasUpdates", ")", ";", "}" ]
Return true if this batch result has at least one object that was updated. @return True if at least one object was updated by the batch that created this result.
[ "Return", "true", "if", "this", "batch", "result", "has", "at", "least", "one", "object", "that", "was", "updated", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java#L255-L258
train
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java
BatchResult.toDoc
public UNode toDoc() { // Root node is map with 1 child per result field and optionally "docs". UNode result = UNode.createMapNode("batch-result"); for (String fieldName : m_resultFields.keySet()) { result.addValueNode(fieldName, m_resultFields.get(fieldName)); } if (m_objResultList.size() > 0) { UNode docsNode = result.addArrayNode("docs"); for (ObjectResult objResult : m_objResultList) { docsNode.addChildNode(objResult.toDoc()); } } return result; }
java
public UNode toDoc() { // Root node is map with 1 child per result field and optionally "docs". UNode result = UNode.createMapNode("batch-result"); for (String fieldName : m_resultFields.keySet()) { result.addValueNode(fieldName, m_resultFields.get(fieldName)); } if (m_objResultList.size() > 0) { UNode docsNode = result.addArrayNode("docs"); for (ObjectResult objResult : m_objResultList) { docsNode.addChildNode(objResult.toDoc()); } } return result; }
[ "public", "UNode", "toDoc", "(", ")", "{", "// Root node is map with 1 child per result field and optionally \"docs\".\r", "UNode", "result", "=", "UNode", ".", "createMapNode", "(", "\"batch-result\"", ")", ";", "for", "(", "String", "fieldName", ":", "m_resultFields", ...
Serialize this BatchResult result into a UNode tree. The root node is called "batch-result". @return This object serialized into a UNode tree.
[ "Serialize", "this", "BatchResult", "result", "into", "a", "UNode", "tree", ".", "The", "root", "node", "is", "called", "batch", "-", "result", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/BatchResult.java#L276-L289
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.registerTaskStarted
void registerTaskStarted(Task task) { synchronized (m_activeTasks) { String mapKey = createMapKey(task.getTenant(), task.getTaskID()); if (m_activeTasks.put(mapKey, task) != null) { m_logger.warn("Task {} registered as started but was already running", mapKey); } } }
java
void registerTaskStarted(Task task) { synchronized (m_activeTasks) { String mapKey = createMapKey(task.getTenant(), task.getTaskID()); if (m_activeTasks.put(mapKey, task) != null) { m_logger.warn("Task {} registered as started but was already running", mapKey); } } }
[ "void", "registerTaskStarted", "(", "Task", "task", ")", "{", "synchronized", "(", "m_activeTasks", ")", "{", "String", "mapKey", "=", "createMapKey", "(", "task", ".", "getTenant", "(", ")", ",", "task", ".", "getTaskID", "(", ")", ")", ";", "if", "(", ...
Called by a Task when it's thread starts. This lets the task manager know which tasks are its own. @param task {@link Task} that is executing task.
[ "Called", "by", "a", "Task", "when", "it", "s", "thread", "starts", ".", "This", "lets", "the", "task", "manager", "know", "which", "tasks", "are", "its", "own", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L206-L213
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.registerTaskEnded
void registerTaskEnded(Task task) { synchronized (m_activeTasks) { String mapKey = createMapKey(task.getTenant(), task.getTaskID()); if (m_activeTasks.remove(mapKey) == null) { m_logger.warn("Task {} registered as ended but was not running", mapKey); } } }
java
void registerTaskEnded(Task task) { synchronized (m_activeTasks) { String mapKey = createMapKey(task.getTenant(), task.getTaskID()); if (m_activeTasks.remove(mapKey) == null) { m_logger.warn("Task {} registered as ended but was not running", mapKey); } } }
[ "void", "registerTaskEnded", "(", "Task", "task", ")", "{", "synchronized", "(", "m_activeTasks", ")", "{", "String", "mapKey", "=", "createMapKey", "(", "task", ".", "getTenant", "(", ")", ",", "task", ".", "getTaskID", "(", ")", ")", ";", "if", "(", ...
Called by a Task when it's thread finishes. This lets the task manager know that another slot has opened-up. @param task {@link Task} that just finished.
[ "Called", "by", "a", "Task", "when", "it", "s", "thread", "finishes", ".", "This", "lets", "the", "task", "manager", "know", "that", "another", "slot", "has", "opened", "-", "up", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L221-L228
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.updateTaskStatus
void updateTaskStatus(Tenant tenant, TaskRecord taskRecord, boolean bDeleteClaimRecord) { String taskID = taskRecord.getTaskID(); DBTransaction dbTran = DBService.instance(tenant).startTransaction(); Map<String, String> propMap = taskRecord.getProperties(); for (String name : propMap.keySet()) { String value = propMap.get(name); if (Utils.isEmpty(value)) { dbTran.deleteColumn(TaskManagerService.TASKS_STORE_NAME, taskID, name); } else { dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, taskID, name, value); } } if (bDeleteClaimRecord) { dbTran.deleteRow(TaskManagerService.TASKS_STORE_NAME, "_claim/" + taskID); } DBService.instance(tenant).commit(dbTran); }
java
void updateTaskStatus(Tenant tenant, TaskRecord taskRecord, boolean bDeleteClaimRecord) { String taskID = taskRecord.getTaskID(); DBTransaction dbTran = DBService.instance(tenant).startTransaction(); Map<String, String> propMap = taskRecord.getProperties(); for (String name : propMap.keySet()) { String value = propMap.get(name); if (Utils.isEmpty(value)) { dbTran.deleteColumn(TaskManagerService.TASKS_STORE_NAME, taskID, name); } else { dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, taskID, name, value); } } if (bDeleteClaimRecord) { dbTran.deleteRow(TaskManagerService.TASKS_STORE_NAME, "_claim/" + taskID); } DBService.instance(tenant).commit(dbTran); }
[ "void", "updateTaskStatus", "(", "Tenant", "tenant", ",", "TaskRecord", "taskRecord", ",", "boolean", "bDeleteClaimRecord", ")", "{", "String", "taskID", "=", "taskRecord", ".", "getTaskID", "(", ")", ";", "DBTransaction", "dbTran", "=", "DBService", ".", "insta...
Add or update a task status record and optionally delete the task's claim record at the same time. @param tenant {@link Tenant} that owns the task's application. @param taskRecord {@link TaskRecord} containing task properties to be written to the database. A null/empty property value causes the corresponding column to be deleted. @param bDeleteClaimRecord True to delete the task's claim record in the same transaction.
[ "Add", "or", "update", "a", "task", "status", "record", "and", "optionally", "delete", "the", "task", "s", "claim", "record", "at", "the", "same", "time", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L263-L279
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.waitForTaskStatus
private TaskRecord waitForTaskStatus(Tenant tenant, Task task, Predicate<TaskStatus> pred) { TaskRecord taskRecord = null; while (true) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (pred.test(taskRecord.getStatus())) { break; } try { Thread.sleep(TASK_CHECK_MILLIS); } catch (InterruptedException e) { } }; return taskRecord; }
java
private TaskRecord waitForTaskStatus(Tenant tenant, Task task, Predicate<TaskStatus> pred) { TaskRecord taskRecord = null; while (true) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (pred.test(taskRecord.getStatus())) { break; } try { Thread.sleep(TASK_CHECK_MILLIS); } catch (InterruptedException e) { } }; return taskRecord; }
[ "private", "TaskRecord", "waitForTaskStatus", "(", "Tenant", "tenant", ",", "Task", "task", ",", "Predicate", "<", "TaskStatus", ">", "pred", ")", "{", "TaskRecord", "taskRecord", "=", "null", ";", "while", "(", "true", ")", "{", "Iterator", "<", "DColumn", ...
latest status record. If it has never run, a never-run task record is stored.
[ "latest", "status", "record", ".", "If", "it", "has", "never", "run", "a", "never", "-", "run", "task", "record", "is", "stored", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L285-L301
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.manageTasks
private void manageTasks() { setHostAddress(); while (!m_bShutdown) { checkAllTasks(); checkForDeadTasks(); try { Thread.sleep(SLEEP_TIME_MILLIS); } catch (InterruptedException e) { } } m_executor.shutdown(); }
java
private void manageTasks() { setHostAddress(); while (!m_bShutdown) { checkAllTasks(); checkForDeadTasks(); try { Thread.sleep(SLEEP_TIME_MILLIS); } catch (InterruptedException e) { } } m_executor.shutdown(); }
[ "private", "void", "manageTasks", "(", ")", "{", "setHostAddress", "(", ")", ";", "while", "(", "!", "m_bShutdown", ")", "{", "checkAllTasks", "(", ")", ";", "checkForDeadTasks", "(", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "SLEEP_TIME_MILLIS", ...
tasks we can run. Shutdown when told to do so.
[ "tasks", "we", "can", "run", ".", "Shutdown", "when", "told", "to", "do", "so", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L305-L316
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.checkTenantTasks
private void checkTenantTasks(Tenant tenant) { m_logger.debug("Checking tenant '{}' for needy tasks", tenant); try { for (ApplicationDefinition appDef : SchemaService.instance().getAllApplications(tenant)) { for (Task task : getAppTasks(appDef)) { checkTaskForExecution(appDef, task); } } } catch (Throwable e) { m_logger.warn("Could not check tasks for tenant '{}': {}", tenant.getName(), e); } }
java
private void checkTenantTasks(Tenant tenant) { m_logger.debug("Checking tenant '{}' for needy tasks", tenant); try { for (ApplicationDefinition appDef : SchemaService.instance().getAllApplications(tenant)) { for (Task task : getAppTasks(appDef)) { checkTaskForExecution(appDef, task); } } } catch (Throwable e) { m_logger.warn("Could not check tasks for tenant '{}': {}", tenant.getName(), e); } }
[ "private", "void", "checkTenantTasks", "(", "Tenant", "tenant", ")", "{", "m_logger", ".", "debug", "(", "\"Checking tenant '{}' for needy tasks\"", ",", "tenant", ")", ";", "try", "{", "for", "(", "ApplicationDefinition", "appDef", ":", "SchemaService", ".", "ins...
Check the given tenant for tasks that need execution.
[ "Check", "the", "given", "tenant", "for", "tasks", "that", "need", "execution", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L329-L340
train
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.checkTaskForExecution
private void checkTaskForExecution(ApplicationDefinition appDef, Task task) { Tenant tenant = Tenant.getTenant(appDef); m_logger.debug("Checking task '{}' in tenant '{}'", task.getTaskID(), tenant); synchronized (m_executeLock) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); TaskRecord taskRecord = null; if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (taskShouldExecute(task, taskRecord) && canHandleMoreTasks()) { attemptToExecuteTask(appDef, task, taskRecord); } } }
java
private void checkTaskForExecution(ApplicationDefinition appDef, Task task) { Tenant tenant = Tenant.getTenant(appDef); m_logger.debug("Checking task '{}' in tenant '{}'", task.getTaskID(), tenant); synchronized (m_executeLock) { Iterator<DColumn> colIter = DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, task.getTaskID()).iterator(); TaskRecord taskRecord = null; if (!colIter.hasNext()) { taskRecord = storeTaskRecord(tenant, task); } else { taskRecord = buildTaskRecord(task.getTaskID(), colIter); } if (taskShouldExecute(task, taskRecord) && canHandleMoreTasks()) { attemptToExecuteTask(appDef, task, taskRecord); } } }
[ "private", "void", "checkTaskForExecution", "(", "ApplicationDefinition", "appDef", ",", "Task", "task", ")", "{", "Tenant", "tenant", "=", "Tenant", ".", "getTenant", "(", "appDef", ")", ";", "m_logger", ".", "debug", "(", "\"Checking task '{}' in tenant '{}'\"", ...
Check the given task to see if we should and can execute it.
[ "Check", "the", "given", "task", "to", "see", "if", "we", "should", "and", "can", "execute", "it", "." ]
ad64d3c37922eefda68ec8869ef089c1ca604b70
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L343-L359
train