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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/model/variable/Variable.java | Variable.getJson | public JSONObject getJson() throws JSONException {
JSONObject json = create();
json.put("type", type);
json.put("category", getCategory());
if (label != null && !label.isEmpty())
json.put("label", label);
if (displaySequence != null && displaySequence > 0)
json.put("sequence", displaySequence);
if (display != null)
json.put("display", display.toString());
return json;
} | java | public JSONObject getJson() throws JSONException {
JSONObject json = create();
json.put("type", type);
json.put("category", getCategory());
if (label != null && !label.isEmpty())
json.put("label", label);
if (displaySequence != null && displaySequence > 0)
json.put("sequence", displaySequence);
if (display != null)
json.put("display", display.toString());
return json;
} | [
"public",
"JSONObject",
"getJson",
"(",
")",
"throws",
"JSONException",
"{",
"JSONObject",
"json",
"=",
"create",
"(",
")",
";",
"json",
".",
"put",
"(",
"\"type\"",
",",
"type",
")",
";",
"json",
".",
"put",
"(",
"\"category\"",
",",
"getCategory",
"(",... | Serialized as an object, so name is not included. | [
"Serialized",
"as",
"an",
"object",
"so",
"name",
"is",
"not",
"included",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/variable/Variable.java#L240-L251 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/log/LoggerUtil.java | LoggerUtil.initializeLogging | public static String initializeLogging() throws IOException {
System.setProperty("org.slf4j.simpleLogger.logFile", "System.out");
System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyyMMdd.HH:mm:ss.SSS");
// Peek at mdw.yaml to find default logging level, but do not initialize PropertyManager
// which could initialize slf4j prematurely. (Works only with yaml config file).
String mdwLogLevel = null;
File mdwYaml = getConfigurationFile("mdw.yaml");
if (mdwYaml.exists()) {
YamlProperties yamlProps = new YamlProperties("mdw", mdwYaml);
mdwLogLevel = yamlProps.getString("mdw.logging.level");
if (mdwLogLevel != null) {
if (mdwLogLevel.equals("MDW_DEBUG"))
mdwLogLevel = "TRACE";
System.setProperty("org.slf4j.simpleLogger.log.com.centurylink.mdw", mdwLogLevel.toLowerCase());
}
}
return mdwLogLevel;
} | java | public static String initializeLogging() throws IOException {
System.setProperty("org.slf4j.simpleLogger.logFile", "System.out");
System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyyMMdd.HH:mm:ss.SSS");
// Peek at mdw.yaml to find default logging level, but do not initialize PropertyManager
// which could initialize slf4j prematurely. (Works only with yaml config file).
String mdwLogLevel = null;
File mdwYaml = getConfigurationFile("mdw.yaml");
if (mdwYaml.exists()) {
YamlProperties yamlProps = new YamlProperties("mdw", mdwYaml);
mdwLogLevel = yamlProps.getString("mdw.logging.level");
if (mdwLogLevel != null) {
if (mdwLogLevel.equals("MDW_DEBUG"))
mdwLogLevel = "TRACE";
System.setProperty("org.slf4j.simpleLogger.log.com.centurylink.mdw", mdwLogLevel.toLowerCase());
}
}
return mdwLogLevel;
} | [
"public",
"static",
"String",
"initializeLogging",
"(",
")",
"throws",
"IOException",
"{",
"System",
".",
"setProperty",
"(",
"\"org.slf4j.simpleLogger.logFile\"",
",",
"\"System.out\"",
")",
";",
"System",
".",
"setProperty",
"(",
"\"org.slf4j.simpleLogger.showDateTime\"... | For Spring Boot with slf4j SimpleLogger, an opportunity to initialize logging before Spring starts logging.
Otherwise for slf4j, properties have already been defaulted before we have a chance to set them.
See mdw-spring-boot AutoConfig for initialization of logback for pure Spring Boot apps. | [
"For",
"Spring",
"Boot",
"with",
"slf4j",
"SimpleLogger",
"an",
"opportunity",
"to",
"initialize",
"logging",
"before",
"Spring",
"starts",
"logging",
".",
"Otherwise",
"for",
"slf4j",
"properties",
"have",
"already",
"been",
"defaulted",
"before",
"we",
"have",
... | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/log/LoggerUtil.java#L51-L69 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java | TaskDataAccess.getSubtaskInstances | public List<TaskInstance> getSubtaskInstances(Long masterTaskInstId) throws DataAccessException {
try {
db.openConnection();
String query = "select " + getTaskInstanceSelect() +
" from TASK_INSTANCE ti where TASK_INST_SECONDARY_OWNER = ? and TASK_INST_SECONDARY_OWNER_ID = ?";
Object[] args = new Object[2];
args[0] = OwnerType.TASK_INSTANCE;
args[1] = masterTaskInstId;
ResultSet rs = db.runSelect(query, args);
List<TaskInstance> taskInsts = new ArrayList<TaskInstance>();
while (rs.next()) {
taskInsts.add(getTaskInstanceSub(rs, false));
}
return taskInsts;
} catch (Exception e) {
throw new DataAccessException(0, "failed to get task instances", e);
} finally {
db.closeConnection();
}
} | java | public List<TaskInstance> getSubtaskInstances(Long masterTaskInstId) throws DataAccessException {
try {
db.openConnection();
String query = "select " + getTaskInstanceSelect() +
" from TASK_INSTANCE ti where TASK_INST_SECONDARY_OWNER = ? and TASK_INST_SECONDARY_OWNER_ID = ?";
Object[] args = new Object[2];
args[0] = OwnerType.TASK_INSTANCE;
args[1] = masterTaskInstId;
ResultSet rs = db.runSelect(query, args);
List<TaskInstance> taskInsts = new ArrayList<TaskInstance>();
while (rs.next()) {
taskInsts.add(getTaskInstanceSub(rs, false));
}
return taskInsts;
} catch (Exception e) {
throw new DataAccessException(0, "failed to get task instances", e);
} finally {
db.closeConnection();
}
} | [
"public",
"List",
"<",
"TaskInstance",
">",
"getSubtaskInstances",
"(",
"Long",
"masterTaskInstId",
")",
"throws",
"DataAccessException",
"{",
"try",
"{",
"db",
".",
"openConnection",
"(",
")",
";",
"String",
"query",
"=",
"\"select \"",
"+",
"getTaskInstanceSelec... | Returns shallow TaskInstances. | [
"Returns",
"shallow",
"TaskInstances",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java#L180-L199 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java | TaskDataAccess.setTaskInstanceGroups | public void setTaskInstanceGroups(Long taskInstId, String[] groups)
throws DataAccessException {
try {
db.openConnection();
// get group IDs
StringBuffer sb = new StringBuffer();
sb.append("select USER_GROUP_ID from USER_GROUP where GROUP_NAME in (");
for (int i=0; i<groups.length; i++) {
if (i>0) sb.append(",");
sb.append("'").append(groups[i]).append("'");
}
sb.append(")");
ResultSet rs = db.runSelect(sb.toString());
List<Long> groupIds = new ArrayList<Long>();
while (rs.next()) {
groupIds.add(rs.getLong(1));
}
// delete existing groups
String query = "";
if (db.isMySQL())
query = "delete TG1 from TASK_INST_GRP_MAPP TG1 join TASK_INST_GRP_MAPP TG2 " +
"using (TASK_INSTANCE_ID, USER_GROUP_ID) " +
"where TG2.TASK_INSTANCE_ID=?";
else
query = "delete from TASK_INST_GRP_MAPP where TASK_INSTANCE_ID=?";
db.runUpdate(query, taskInstId);
if (db.isMySQL()) db.commit(); // MySQL will lock even when no rows were deleted and using unique index, so commit so that multiple session inserts aren't deadlocked
// insert groups
query = "insert into TASK_INST_GRP_MAPP " +
"(TASK_INSTANCE_ID,USER_GROUP_ID,CREATE_DT) values (?,?," + now() + ")";
db.prepareStatement(query);
Object[] args = new Object[2];
args[0] = taskInstId;
for (Long group : groupIds) {
args[1] = group;
db.runUpdateWithPreparedStatement(args);
}
db.commit();
} catch (Exception e) {
db.rollback();
throw new DataAccessException(0,"failed to associate task instance groups", e);
} finally {
db.closeConnection();
}
} | java | public void setTaskInstanceGroups(Long taskInstId, String[] groups)
throws DataAccessException {
try {
db.openConnection();
// get group IDs
StringBuffer sb = new StringBuffer();
sb.append("select USER_GROUP_ID from USER_GROUP where GROUP_NAME in (");
for (int i=0; i<groups.length; i++) {
if (i>0) sb.append(",");
sb.append("'").append(groups[i]).append("'");
}
sb.append(")");
ResultSet rs = db.runSelect(sb.toString());
List<Long> groupIds = new ArrayList<Long>();
while (rs.next()) {
groupIds.add(rs.getLong(1));
}
// delete existing groups
String query = "";
if (db.isMySQL())
query = "delete TG1 from TASK_INST_GRP_MAPP TG1 join TASK_INST_GRP_MAPP TG2 " +
"using (TASK_INSTANCE_ID, USER_GROUP_ID) " +
"where TG2.TASK_INSTANCE_ID=?";
else
query = "delete from TASK_INST_GRP_MAPP where TASK_INSTANCE_ID=?";
db.runUpdate(query, taskInstId);
if (db.isMySQL()) db.commit(); // MySQL will lock even when no rows were deleted and using unique index, so commit so that multiple session inserts aren't deadlocked
// insert groups
query = "insert into TASK_INST_GRP_MAPP " +
"(TASK_INSTANCE_ID,USER_GROUP_ID,CREATE_DT) values (?,?," + now() + ")";
db.prepareStatement(query);
Object[] args = new Object[2];
args[0] = taskInstId;
for (Long group : groupIds) {
args[1] = group;
db.runUpdateWithPreparedStatement(args);
}
db.commit();
} catch (Exception e) {
db.rollback();
throw new DataAccessException(0,"failed to associate task instance groups", e);
} finally {
db.closeConnection();
}
} | [
"public",
"void",
"setTaskInstanceGroups",
"(",
"Long",
"taskInstId",
",",
"String",
"[",
"]",
"groups",
")",
"throws",
"DataAccessException",
"{",
"try",
"{",
"db",
".",
"openConnection",
"(",
")",
";",
"// get group IDs",
"StringBuffer",
"sb",
"=",
"new",
"S... | new task instance group mapping | [
"new",
"task",
"instance",
"group",
"mapping"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java#L403-L447 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java | TaskDataAccess.setTaskInstanceIndices | public void setTaskInstanceIndices(Long taskInstId, Map<String,String> indices)
throws DataAccessException {
try {
db.openConnection();
// delete existing indices
String query = "delete from INSTANCE_INDEX where INSTANCE_ID=? and OWNER_TYPE='TASK_INSTANCE'";
// insert new ones
db.runUpdate(query, taskInstId);
query = "insert into INSTANCE_INDEX " +
"(INSTANCE_ID,OWNER_TYPE,INDEX_KEY,INDEX_VALUE,CREATE_DT) values (?,'TASK_INSTANCE',?,?,"+now()+")";
db.prepareStatement(query);
Object[] args = new Object[3];
args[0] = taskInstId;
for (String key : indices.keySet()) {
args[1] = key;
args[2] = indices.get(key);
if (!StringHelper.isEmpty((String)args[2])) db.runUpdateWithPreparedStatement(args);
}
db.commit();
} catch (Exception e) {
db.rollback();
throw new DataAccessException(0,"failed to add task instance indices", e);
} finally {
db.closeConnection();
}
} | java | public void setTaskInstanceIndices(Long taskInstId, Map<String,String> indices)
throws DataAccessException {
try {
db.openConnection();
// delete existing indices
String query = "delete from INSTANCE_INDEX where INSTANCE_ID=? and OWNER_TYPE='TASK_INSTANCE'";
// insert new ones
db.runUpdate(query, taskInstId);
query = "insert into INSTANCE_INDEX " +
"(INSTANCE_ID,OWNER_TYPE,INDEX_KEY,INDEX_VALUE,CREATE_DT) values (?,'TASK_INSTANCE',?,?,"+now()+")";
db.prepareStatement(query);
Object[] args = new Object[3];
args[0] = taskInstId;
for (String key : indices.keySet()) {
args[1] = key;
args[2] = indices.get(key);
if (!StringHelper.isEmpty((String)args[2])) db.runUpdateWithPreparedStatement(args);
}
db.commit();
} catch (Exception e) {
db.rollback();
throw new DataAccessException(0,"failed to add task instance indices", e);
} finally {
db.closeConnection();
}
} | [
"public",
"void",
"setTaskInstanceIndices",
"(",
"Long",
"taskInstId",
",",
"Map",
"<",
"String",
",",
"String",
">",
"indices",
")",
"throws",
"DataAccessException",
"{",
"try",
"{",
"db",
".",
"openConnection",
"(",
")",
";",
"// delete existing indices",
"Str... | new task instance indices | [
"new",
"task",
"instance",
"indices"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/data/task/TaskDataAccess.java#L450-L475 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/rest/Solutions.java | Solutions.get | @Override
@Path("/{solutionId}")
@ApiOperation(value="Retrieve a solution or all solutions",
notes="If {solutionId} is not present, returns all solutions.",
response=Solution.class, responseContainer="List")
public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
SolutionServices solutionServices = ServiceLocator.getSolutionServices();
String id = getSegment(path, 1);
if (id != null) {
Solution solution = solutionServices.getSolution(id);
if (solution == null)
throw new ServiceException(404, "Solution not found: " + id);
else
return solution.getJson();
}
else {
Query query = getQuery(path, headers);
return solutionServices.getSolutions(query).getJson();
}
} | java | @Override
@Path("/{solutionId}")
@ApiOperation(value="Retrieve a solution or all solutions",
notes="If {solutionId} is not present, returns all solutions.",
response=Solution.class, responseContainer="List")
public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
SolutionServices solutionServices = ServiceLocator.getSolutionServices();
String id = getSegment(path, 1);
if (id != null) {
Solution solution = solutionServices.getSolution(id);
if (solution == null)
throw new ServiceException(404, "Solution not found: " + id);
else
return solution.getJson();
}
else {
Query query = getQuery(path, headers);
return solutionServices.getSolutions(query).getJson();
}
} | [
"@",
"Override",
"@",
"Path",
"(",
"\"/{solutionId}\"",
")",
"@",
"ApiOperation",
"(",
"value",
"=",
"\"Retrieve a solution or all solutions\"",
",",
"notes",
"=",
"\"If {solutionId} is not present, returns all solutions.\"",
",",
"response",
"=",
"Solution",
".",
"class"... | Retrieve a solution or the solutions list. | [
"Retrieve",
"a",
"solution",
"or",
"the",
"solutions",
"list",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/rest/Solutions.java#L63-L82 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/task/AutoFormTaskValuesProvider.java | AutoFormTaskValuesProvider.getDefinedValues | protected List<Value> getDefinedValues(TaskRuntimeContext runtimeContext) {
List<Value> values = new ArrayList<Value>();
String varAttr = runtimeContext.getTaskAttribute(TaskAttributeConstant.VARIABLES);
if (!StringHelper.isEmpty(varAttr)) {
List<String[]> parsed = StringHelper.parseTable(varAttr, ',', ';', 5);
for (String[] one : parsed) {
String name = one[0];
Value value = new Value(name);
if (one[1] != null && !one[1].isEmpty())
value.setLabel(one[1]);
value.setDisplay(Value.getDisplay(one[2]));
if (one[3] != null && !one[3].isEmpty())
value.setSequence(Integer.parseInt(one[3]));
if (one[4] != null && !one[4].isEmpty())
value.setIndexKey(one[4]);
if (value.isExpression()) {
value.setType(String.class.getName());
}
else {
Variable var = runtimeContext.getProcess().getVariable(name);
if (var != null)
value.setType(var.getType());
}
values.add(value);
}
}
return values;
} | java | protected List<Value> getDefinedValues(TaskRuntimeContext runtimeContext) {
List<Value> values = new ArrayList<Value>();
String varAttr = runtimeContext.getTaskAttribute(TaskAttributeConstant.VARIABLES);
if (!StringHelper.isEmpty(varAttr)) {
List<String[]> parsed = StringHelper.parseTable(varAttr, ',', ';', 5);
for (String[] one : parsed) {
String name = one[0];
Value value = new Value(name);
if (one[1] != null && !one[1].isEmpty())
value.setLabel(one[1]);
value.setDisplay(Value.getDisplay(one[2]));
if (one[3] != null && !one[3].isEmpty())
value.setSequence(Integer.parseInt(one[3]));
if (one[4] != null && !one[4].isEmpty())
value.setIndexKey(one[4]);
if (value.isExpression()) {
value.setType(String.class.getName());
}
else {
Variable var = runtimeContext.getProcess().getVariable(name);
if (var != null)
value.setType(var.getType());
}
values.add(value);
}
}
return values;
} | [
"protected",
"List",
"<",
"Value",
">",
"getDefinedValues",
"(",
"TaskRuntimeContext",
"runtimeContext",
")",
"{",
"List",
"<",
"Value",
">",
"values",
"=",
"new",
"ArrayList",
"<",
"Value",
">",
"(",
")",
";",
"String",
"varAttr",
"=",
"runtimeContext",
"."... | Minus runtime values. | [
"Minus",
"runtime",
"values",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/task/AutoFormTaskValuesProvider.java#L114-L141 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/log/log4j/Log4JStandardLoggerImpl.java | Log4JStandardLoggerImpl.getCallingClassName | private String getCallingClassName() {
StackTraceElement[] stack = (new Throwable()).getStackTrace();
String className = stack[4].getClassName();
if (className == null || !(className.startsWith("com.centurylink") || className.startsWith("com.qwest"))) {
className = stack[3].getClassName(); // try next level up
if (className == null || !(className.startsWith("com.centurylink") || className.startsWith("com.qwest"))) {
selfLogger.debug("Unfamiliar Log4J Logger: '" + className + "'; using Default '" + DEFAULT_LOGGER_NAME + "'");
className = DEFAULT_LOGGER_NAME;
}
}
return className;
} | java | private String getCallingClassName() {
StackTraceElement[] stack = (new Throwable()).getStackTrace();
String className = stack[4].getClassName();
if (className == null || !(className.startsWith("com.centurylink") || className.startsWith("com.qwest"))) {
className = stack[3].getClassName(); // try next level up
if (className == null || !(className.startsWith("com.centurylink") || className.startsWith("com.qwest"))) {
selfLogger.debug("Unfamiliar Log4J Logger: '" + className + "'; using Default '" + DEFAULT_LOGGER_NAME + "'");
className = DEFAULT_LOGGER_NAME;
}
}
return className;
} | [
"private",
"String",
"getCallingClassName",
"(",
")",
"{",
"StackTraceElement",
"[",
"]",
"stack",
"=",
"(",
"new",
"Throwable",
"(",
")",
")",
".",
"getStackTrace",
"(",
")",
";",
"String",
"className",
"=",
"stack",
"[",
"4",
"]",
".",
"getClassName",
... | Get the name of the class to use as the Logger name | [
"Get",
"the",
"name",
"of",
"the",
"class",
"to",
"use",
"as",
"the",
"Logger",
"name"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/log/log4j/Log4JStandardLoggerImpl.java#L99-L112 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/HttpConnection.java | HttpConnection.readInput | protected HttpResponse readInput() throws IOException {
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[2048];
try {
is = connection.getInputStream();
while (maxBytes == -1 || baos.size() < maxBytes) {
int bytesRead = is.read(buffer);
if (bytesRead == -1)
break;
baos.write(buffer, 0, bytesRead);
}
response = new HttpResponse(baos.toByteArray());
return response;
}
catch (IOException ex) {
InputStream eis = null;
try {
eis = connection.getErrorStream();
while (maxBytes == -1 || baos.size() < maxBytes) {
int bytesRead = eis.read(buffer);
if (bytesRead == -1)
break;
baos.write(buffer, 0, bytesRead);
}
response = new HttpResponse(baos.toByteArray());
return response;
}
catch (Exception ex2) {
// throw original exception
}
finally {
if (eis != null) {
eis.close();
}
}
throw ex;
}
}
finally {
if (is != null)
is.close();
connection.disconnect();
if (response != null) {
response.setCode(connection.getResponseCode());
response.setMessage(connection.getResponseMessage());
}
headers = new HashMap<String,String>();
for (String headerKey : connection.getHeaderFields().keySet()) {
if (headerKey == null)
headers.put("HTTP", connection.getHeaderField(headerKey));
else
headers.put(headerKey, connection.getHeaderField(headerKey));
}
}
} | java | protected HttpResponse readInput() throws IOException {
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[2048];
try {
is = connection.getInputStream();
while (maxBytes == -1 || baos.size() < maxBytes) {
int bytesRead = is.read(buffer);
if (bytesRead == -1)
break;
baos.write(buffer, 0, bytesRead);
}
response = new HttpResponse(baos.toByteArray());
return response;
}
catch (IOException ex) {
InputStream eis = null;
try {
eis = connection.getErrorStream();
while (maxBytes == -1 || baos.size() < maxBytes) {
int bytesRead = eis.read(buffer);
if (bytesRead == -1)
break;
baos.write(buffer, 0, bytesRead);
}
response = new HttpResponse(baos.toByteArray());
return response;
}
catch (Exception ex2) {
// throw original exception
}
finally {
if (eis != null) {
eis.close();
}
}
throw ex;
}
}
finally {
if (is != null)
is.close();
connection.disconnect();
if (response != null) {
response.setCode(connection.getResponseCode());
response.setMessage(connection.getResponseMessage());
}
headers = new HashMap<String,String>();
for (String headerKey : connection.getHeaderFields().keySet()) {
if (headerKey == null)
headers.put("HTTP", connection.getHeaderField(headerKey));
else
headers.put(headerKey, connection.getHeaderField(headerKey));
}
}
} | [
"protected",
"HttpResponse",
"readInput",
"(",
")",
"throws",
"IOException",
"{",
"InputStream",
"is",
"=",
"null",
";",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"try",
"{",
"byte",
"[",
"]",
"buffer",
"=",
"new",
... | Populates the response member. Closes the connection. | [
"Populates",
"the",
"response",
"member",
".",
"Closes",
"the",
"connection",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/HttpConnection.java#L186-L242 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/HttpConnection.java | HttpConnection.extractBasicAuthCredentials | public static String[] extractBasicAuthCredentials(String authHeader) {
return new String(Base64.decodeBase64(authHeader.substring("Basic ".length()).getBytes())).split(":");
} | java | public static String[] extractBasicAuthCredentials(String authHeader) {
return new String(Base64.decodeBase64(authHeader.substring("Basic ".length()).getBytes())).split(":");
} | [
"public",
"static",
"String",
"[",
"]",
"extractBasicAuthCredentials",
"(",
"String",
"authHeader",
")",
"{",
"return",
"new",
"String",
"(",
"Base64",
".",
"decodeBase64",
"(",
"authHeader",
".",
"substring",
"(",
"\"Basic \"",
".",
"length",
"(",
")",
")",
... | In return array, zeroth element is user and first is password. | [
"In",
"return",
"array",
"zeroth",
"element",
"is",
"user",
"and",
"first",
"is",
"password",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/HttpConnection.java#L256-L258 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java | Checkpoint.retrieveRef | public AssetRef retrieveRef(String name) throws IOException, SQLException {
String select = "select definition_id, name, ref from ASSET_REF where name = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
stmt.setString(1, name);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return new AssetRef(name, rs.getLong("definition_id"), rs.getString("ref"));
}
}
}
return null;
} | java | public AssetRef retrieveRef(String name) throws IOException, SQLException {
String select = "select definition_id, name, ref from ASSET_REF where name = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
stmt.setString(1, name);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return new AssetRef(name, rs.getLong("definition_id"), rs.getString("ref"));
}
}
}
return null;
} | [
"public",
"AssetRef",
"retrieveRef",
"(",
"String",
"name",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"String",
"select",
"=",
"\"select definition_id, name, ref from ASSET_REF where name = ?\"",
";",
"try",
"(",
"Connection",
"conn",
"=",
"getDbConnection",... | Finds an asset ref from the database by asset name. | [
"Finds",
"an",
"asset",
"ref",
"from",
"the",
"database",
"by",
"asset",
"name",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java#L125-L137 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java | Checkpoint.retrieveRef | public AssetRef retrieveRef(Long id) throws IOException, SQLException {
String select = "select definition_id, name, ref from ASSET_REF where definition_id = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return new AssetRef(rs.getString("name"), id, rs.getString("ref"));
}
}
}
return null;
} | java | public AssetRef retrieveRef(Long id) throws IOException, SQLException {
String select = "select definition_id, name, ref from ASSET_REF where definition_id = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return new AssetRef(rs.getString("name"), id, rs.getString("ref"));
}
}
}
return null;
} | [
"public",
"AssetRef",
"retrieveRef",
"(",
"Long",
"id",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"String",
"select",
"=",
"\"select definition_id, name, ref from ASSET_REF where definition_id = ?\"",
";",
"try",
"(",
"Connection",
"conn",
"=",
"getDbConnect... | Finds an asset ref from the database by definitionID. | [
"Finds",
"an",
"asset",
"ref",
"from",
"the",
"database",
"by",
"definitionID",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java#L142-L154 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java | Checkpoint.retrieveAllRefs | public List<AssetRef> retrieveAllRefs(Date cutoffDate) throws IOException, SQLException {
List<AssetRef> assetRefList = null;
String select = "select definition_id, name, ref from ASSET_REF ";
if (cutoffDate != null)
select += "where ARCHIVE_DT >= ? ";
select += "order by ARCHIVE_DT desc";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
if (cutoffDate != null)
stmt.setTimestamp(1, new Timestamp(cutoffDate.getTime()));
try (ResultSet rs = stmt.executeQuery()) {
assetRefList = new ArrayList<AssetRef>();
while (rs.next()) {
String name = rs.getString("name");
if (name != null && !name.endsWith("v0")) // Ignore version 0 assets
assetRefList.add(new AssetRef(rs.getString("name"), rs.getLong("definition_id"), rs.getString("ref")));
}
}
}
return assetRefList;
} | java | public List<AssetRef> retrieveAllRefs(Date cutoffDate) throws IOException, SQLException {
List<AssetRef> assetRefList = null;
String select = "select definition_id, name, ref from ASSET_REF ";
if (cutoffDate != null)
select += "where ARCHIVE_DT >= ? ";
select += "order by ARCHIVE_DT desc";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
if (cutoffDate != null)
stmt.setTimestamp(1, new Timestamp(cutoffDate.getTime()));
try (ResultSet rs = stmt.executeQuery()) {
assetRefList = new ArrayList<AssetRef>();
while (rs.next()) {
String name = rs.getString("name");
if (name != null && !name.endsWith("v0")) // Ignore version 0 assets
assetRefList.add(new AssetRef(rs.getString("name"), rs.getLong("definition_id"), rs.getString("ref")));
}
}
}
return assetRefList;
} | [
"public",
"List",
"<",
"AssetRef",
">",
"retrieveAllRefs",
"(",
"Date",
"cutoffDate",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"List",
"<",
"AssetRef",
">",
"assetRefList",
"=",
"null",
";",
"String",
"select",
"=",
"\"select definition_id, name, re... | Finds all asset refs from the database since cutoffDate, or all if cutoffDate is null. | [
"Finds",
"all",
"asset",
"refs",
"from",
"the",
"database",
"since",
"cutoffDate",
"or",
"all",
"if",
"cutoffDate",
"is",
"null",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java#L159-L179 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java | Checkpoint.updateRefs | public void updateRefs(boolean assetImport) throws SQLException, IOException {
List<AssetRef> refs = getCurrentRefs();
if (refs == null || refs.isEmpty())
getOut().println("Skipping ASSET_REF table insert/update due to empty current assets");
else {
String select = "select name, ref from ASSET_REF where definition_id = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
for (AssetRef ref : refs) {
stmt.setLong(1, ref.getDefinitionId());
try (ResultSet rs = stmt.executeQuery()) {
// DO NOT update existing refs with newer commitID
// Doing so can obliterate previous commitID from ASSET_REF table
// which will prevent auto-import detection in cluster envs
if (!rs.next()) {
String insert = "insert into ASSET_REF (definition_id, name, ref) values (?, ?, ?)";
try (PreparedStatement insertStmt = conn.prepareStatement(insert)) {
insertStmt.setLong(1, ref.getDefinitionId());
insertStmt.setString(2, ref.getName());
insertStmt.setString(3, ref.getRef());
insertStmt.executeUpdate();
if (!conn.getAutoCommit()) conn.commit();
}
}
}
}
if (assetImport)
updateRefValue();
}
}
} | java | public void updateRefs(boolean assetImport) throws SQLException, IOException {
List<AssetRef> refs = getCurrentRefs();
if (refs == null || refs.isEmpty())
getOut().println("Skipping ASSET_REF table insert/update due to empty current assets");
else {
String select = "select name, ref from ASSET_REF where definition_id = ?";
try (Connection conn = getDbConnection();
PreparedStatement stmt = conn.prepareStatement(select)) {
for (AssetRef ref : refs) {
stmt.setLong(1, ref.getDefinitionId());
try (ResultSet rs = stmt.executeQuery()) {
// DO NOT update existing refs with newer commitID
// Doing so can obliterate previous commitID from ASSET_REF table
// which will prevent auto-import detection in cluster envs
if (!rs.next()) {
String insert = "insert into ASSET_REF (definition_id, name, ref) values (?, ?, ?)";
try (PreparedStatement insertStmt = conn.prepareStatement(insert)) {
insertStmt.setLong(1, ref.getDefinitionId());
insertStmt.setString(2, ref.getName());
insertStmt.setString(3, ref.getRef());
insertStmt.executeUpdate();
if (!conn.getAutoCommit()) conn.commit();
}
}
}
}
if (assetImport)
updateRefValue();
}
}
} | [
"public",
"void",
"updateRefs",
"(",
"boolean",
"assetImport",
")",
"throws",
"SQLException",
",",
"IOException",
"{",
"List",
"<",
"AssetRef",
">",
"refs",
"=",
"getCurrentRefs",
"(",
")",
";",
"if",
"(",
"refs",
"==",
"null",
"||",
"refs",
".",
"isEmpty"... | Update refs in db. | [
"Update",
"refs",
"in",
"db",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/cli/Checkpoint.java#L187-L217 | train |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/zipkin/TraceHelper.java | TraceHelper.getTracing | public static Tracing getTracing(String serviceName, CurrentTraceContext context) {
Tracing tracing = Tracing.current();
if (tracing == null) {
// TODO reporter based on prop/config
tracing = getBuilder(serviceName, context).build();
}
return tracing;
} | java | public static Tracing getTracing(String serviceName, CurrentTraceContext context) {
Tracing tracing = Tracing.current();
if (tracing == null) {
// TODO reporter based on prop/config
tracing = getBuilder(serviceName, context).build();
}
return tracing;
} | [
"public",
"static",
"Tracing",
"getTracing",
"(",
"String",
"serviceName",
",",
"CurrentTraceContext",
"context",
")",
"{",
"Tracing",
"tracing",
"=",
"Tracing",
".",
"current",
"(",
")",
";",
"if",
"(",
"tracing",
"==",
"null",
")",
"{",
"// TODO reporter bas... | Get or build tracing. | [
"Get",
"or",
"build",
"tracing",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/zipkin/TraceHelper.java#L17-L24 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/auth/AuthExcludePattern.java | AuthExcludePattern.match | public boolean match(String accessPath) {
if (extension != null) {
for (int i = accessPath.length() - 1; i >= 0; i--) {
if (accessPath.charAt(i) == '.') {
String ext = accessPath.substring(i + 1);
if (extension.equals(ext)) {
return true;
}
break;
}
}
}
if (accessPath.equals(path)) {
return true;
}
if (prefix != null && accessPath.startsWith(prefix)) {
return true;
}
return false;
} | java | public boolean match(String accessPath) {
if (extension != null) {
for (int i = accessPath.length() - 1; i >= 0; i--) {
if (accessPath.charAt(i) == '.') {
String ext = accessPath.substring(i + 1);
if (extension.equals(ext)) {
return true;
}
break;
}
}
}
if (accessPath.equals(path)) {
return true;
}
if (prefix != null && accessPath.startsWith(prefix)) {
return true;
}
return false;
} | [
"public",
"boolean",
"match",
"(",
"String",
"accessPath",
")",
"{",
"if",
"(",
"extension",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"accessPath",
".",
"length",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"i... | Checks for a match.
@param accessPath
@return true if the url fits any of the patterns | [
"Checks",
"for",
"a",
"match",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/auth/AuthExcludePattern.java#L46-L65 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/common/service/WebSocketMessenger.java | WebSocketMessenger.send | public boolean send(String topic, String message) throws IOException {
List<Session> sessions = topicSubscribers.get(topic);
if (sessions != null) {
for (Session session : sessions) {
session.getBasicRemote().sendText(message);
}
}
return sessions != null;
} | java | public boolean send(String topic, String message) throws IOException {
List<Session> sessions = topicSubscribers.get(topic);
if (sessions != null) {
for (Session session : sessions) {
session.getBasicRemote().sendText(message);
}
}
return sessions != null;
} | [
"public",
"boolean",
"send",
"(",
"String",
"topic",
",",
"String",
"message",
")",
"throws",
"IOException",
"{",
"List",
"<",
"Session",
">",
"sessions",
"=",
"topicSubscribers",
".",
"get",
"(",
"topic",
")",
";",
"if",
"(",
"sessions",
"!=",
"null",
"... | Returns true if any subscribers. | [
"Returns",
"true",
"if",
"any",
"subscribers",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/common/service/WebSocketMessenger.java#L114-L122 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.get | @GET
public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "GET not implemented");
} | java | @GET
public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "GET not implemented");
} | [
"@",
"GET",
"public",
"JSONObject",
"get",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"ServiceException",
",",
"JSONException",
"{",
"throw",
"new",
"ServiceException",
"(",
"ServiceException",
".",
"NOT_ALL... | Retrieve an existing entity or relationship. | [
"Retrieve",
"an",
"existing",
"entity",
"or",
"relationship",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L112-L115 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.post | @POST
public JSONObject post(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "POST not implemented");
} | java | @POST
public JSONObject post(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "POST not implemented");
} | [
"@",
"POST",
"public",
"JSONObject",
"post",
"(",
"String",
"path",
",",
"JSONObject",
"content",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"ServiceException",
",",
"JSONException",
"{",
"throw",
"new",
"ServiceException",
"(",
... | Create a new entity or relationship.
Or perform other action requests that cannot be categorized into put or delete. | [
"Create",
"a",
"new",
"entity",
"or",
"relationship",
".",
"Or",
"perform",
"other",
"action",
"requests",
"that",
"cannot",
"be",
"categorized",
"into",
"put",
"or",
"delete",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L121-L124 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.put | @PUT
public JSONObject put(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "PUT not implemented");
} | java | @PUT
public JSONObject put(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "PUT not implemented");
} | [
"@",
"PUT",
"public",
"JSONObject",
"put",
"(",
"String",
"path",
",",
"JSONObject",
"content",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"ServiceException",
",",
"JSONException",
"{",
"throw",
"new",
"ServiceException",
"(",
"... | Update an existing entity with different data. | [
"Update",
"an",
"existing",
"entity",
"with",
"different",
"data",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L129-L132 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.delete | @DELETE
public JSONObject delete(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "DELETE not implemented");
} | java | @DELETE
public JSONObject delete(String path, JSONObject content, Map<String,String> headers) throws ServiceException, JSONException {
throw new ServiceException(ServiceException.NOT_ALLOWED, "DELETE not implemented");
} | [
"@",
"DELETE",
"public",
"JSONObject",
"delete",
"(",
"String",
"path",
",",
"JSONObject",
"content",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"ServiceException",
",",
"JSONException",
"{",
"throw",
"new",
"ServiceException",
"(... | Delete an existing entity or relationship. | [
"Delete",
"an",
"existing",
"entity",
"or",
"relationship",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L137-L140 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.export | public String export(String downloadFormat, Map<String,String> headers) throws ServiceException {
try {
JsonExport exporter = getExporter(headers);
if (Listener.DOWNLOAD_FORMAT_EXCEL.equals(downloadFormat))
return exporter.exportXlsxBase64();
else if (Listener.DOWNLOAD_FORMAT_ZIP.equals(downloadFormat))
return exporter.exportZipBase64();
else
throw new ServiceException(HTTP_400_BAD_REQUEST, "Unsupported download format: " + downloadFormat);
}
catch (ServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
} | java | public String export(String downloadFormat, Map<String,String> headers) throws ServiceException {
try {
JsonExport exporter = getExporter(headers);
if (Listener.DOWNLOAD_FORMAT_EXCEL.equals(downloadFormat))
return exporter.exportXlsxBase64();
else if (Listener.DOWNLOAD_FORMAT_ZIP.equals(downloadFormat))
return exporter.exportZipBase64();
else
throw new ServiceException(HTTP_400_BAD_REQUEST, "Unsupported download format: " + downloadFormat);
}
catch (ServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
} | [
"public",
"String",
"export",
"(",
"String",
"downloadFormat",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throws",
"ServiceException",
"{",
"try",
"{",
"JsonExport",
"exporter",
"=",
"getExporter",
"(",
"headers",
")",
";",
"if",
"(",
... | Binary content must be Base64 encoded for API compatibility. | [
"Binary",
"content",
"must",
"be",
"Base64",
"encoded",
"for",
"API",
"compatibility",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L192-L208 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java | JsonRestService.invokeServiceProcess | protected JSONObject invokeServiceProcess(String name, Object request, String requestId,
Map<String,Object> parameters, Map<String,String> headers) throws ServiceException {
JSONObject responseJson;
Map<String,String> responseHeaders = new HashMap<>();
Object responseObject = ServiceLocator.getWorkflowServices().invokeServiceProcess(name,
request, requestId, parameters, headers, responseHeaders);
if (responseObject instanceof JSONObject)
responseJson = (JSONObject) responseObject;
else if (responseObject instanceof Jsonable)
responseJson = ((Jsonable) responseObject).getJson();
else
throw new ServiceException(HTTP_500_INTERNAL_ERROR,
"Unsupported response type: " + (responseObject == null ? null : responseObject.getClass()));
for (String key : responseHeaders.keySet())
headers.put(key, responseHeaders.get(key));
return responseJson;
} | java | protected JSONObject invokeServiceProcess(String name, Object request, String requestId,
Map<String,Object> parameters, Map<String,String> headers) throws ServiceException {
JSONObject responseJson;
Map<String,String> responseHeaders = new HashMap<>();
Object responseObject = ServiceLocator.getWorkflowServices().invokeServiceProcess(name,
request, requestId, parameters, headers, responseHeaders);
if (responseObject instanceof JSONObject)
responseJson = (JSONObject) responseObject;
else if (responseObject instanceof Jsonable)
responseJson = ((Jsonable) responseObject).getJson();
else
throw new ServiceException(HTTP_500_INTERNAL_ERROR,
"Unsupported response type: " + (responseObject == null ? null : responseObject.getClass()));
for (String key : responseHeaders.keySet())
headers.put(key, responseHeaders.get(key));
return responseJson;
} | [
"protected",
"JSONObject",
"invokeServiceProcess",
"(",
"String",
"name",
",",
"Object",
"request",
",",
"String",
"requestId",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
")",
"throw... | Helper method for invoking a service process. Populates response headers from variable value. | [
"Helper",
"method",
"for",
"invoking",
"a",
"service",
"process",
".",
"Populates",
"response",
"headers",
"from",
"variable",
"value",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/rest/JsonRestService.java#L213-L229 | train |
CenturyLinkCloud/mdw | mdw-workflow/src/com/centurylink/mdw/workflow/activity/timer/TimerWaitActivity.java | TimerWaitActivity.getWaitPeriodInSeconds | protected int getWaitPeriodInSeconds() throws ActivityException {
String unit = super.getAttributeValue(WAIT_UNIT);
int factor;
if (MINUTES.equals(unit)) factor = 60;
else if (HOURS.equals(unit)) factor = 3600;
else if (DAYS.equals(unit)) factor = 86400;
else factor = 1; // Means specified value is already in seconds
int retTime;
String timeAttr;
try {
timeAttr = super.getAttributeValueSmart(WorkAttributeConstant.TIMER_WAIT);
} catch (PropertyException e) {
throw new ActivityException(-1, "failed to evaluate time expression", e);
}
retTime = StringHelper.getInteger(timeAttr, DEFAULT_WAIT);
return retTime*factor;
} | java | protected int getWaitPeriodInSeconds() throws ActivityException {
String unit = super.getAttributeValue(WAIT_UNIT);
int factor;
if (MINUTES.equals(unit)) factor = 60;
else if (HOURS.equals(unit)) factor = 3600;
else if (DAYS.equals(unit)) factor = 86400;
else factor = 1; // Means specified value is already in seconds
int retTime;
String timeAttr;
try {
timeAttr = super.getAttributeValueSmart(WorkAttributeConstant.TIMER_WAIT);
} catch (PropertyException e) {
throw new ActivityException(-1, "failed to evaluate time expression", e);
}
retTime = StringHelper.getInteger(timeAttr, DEFAULT_WAIT);
return retTime*factor;
} | [
"protected",
"int",
"getWaitPeriodInSeconds",
"(",
")",
"throws",
"ActivityException",
"{",
"String",
"unit",
"=",
"super",
".",
"getAttributeValue",
"(",
"WAIT_UNIT",
")",
";",
"int",
"factor",
";",
"if",
"(",
"MINUTES",
".",
"equals",
"(",
"unit",
")",
")"... | Method that returns the wait period for the activity
@return Wait period | [
"Method",
"that",
"returns",
"the",
"wait",
"period",
"for",
"the",
"activity"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/activity/timer/TimerWaitActivity.java#L135-L151 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/model/task/TaskAction.java | TaskAction.isRoleMapped | public boolean isRoleMapped(Long pRoleId){
if(userRoles == null || userRoles.length == 0){
return false;
}
for(int i=0; i<userRoles.length; i++){
if(userRoles[i].getId().longValue() == pRoleId.longValue()){
return true;
}
}
return false;
} | java | public boolean isRoleMapped(Long pRoleId){
if(userRoles == null || userRoles.length == 0){
return false;
}
for(int i=0; i<userRoles.length; i++){
if(userRoles[i].getId().longValue() == pRoleId.longValue()){
return true;
}
}
return false;
} | [
"public",
"boolean",
"isRoleMapped",
"(",
"Long",
"pRoleId",
")",
"{",
"if",
"(",
"userRoles",
"==",
"null",
"||",
"userRoles",
".",
"length",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"userR... | Checked if the passed in RoleId is mapped to this TaskAction
@param pRoleId
@return boolean results | [
"Checked",
"if",
"the",
"passed",
"in",
"RoleId",
"is",
"mapped",
"to",
"this",
"TaskAction"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/task/TaskAction.java#L160-L170 | train |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/microservice/OrchestratorActivity.java | OrchestratorActivity.getSubflow | protected Process getSubflow(Microservice service) throws ActivityException {
AssetVersionSpec spec = new AssetVersionSpec(service.getSubflow());
try {
Process process = ProcessCache.getProcessSmart(spec);
if (process == null)
throw new ActivityException("Subflow not found: " + service.getSubflow());
return process;
}
catch (DataAccessException ex) {
throw new ActivityException(ex.getMessage(), ex);
}
} | java | protected Process getSubflow(Microservice service) throws ActivityException {
AssetVersionSpec spec = new AssetVersionSpec(service.getSubflow());
try {
Process process = ProcessCache.getProcessSmart(spec);
if (process == null)
throw new ActivityException("Subflow not found: " + service.getSubflow());
return process;
}
catch (DataAccessException ex) {
throw new ActivityException(ex.getMessage(), ex);
}
} | [
"protected",
"Process",
"getSubflow",
"(",
"Microservice",
"service",
")",
"throws",
"ActivityException",
"{",
"AssetVersionSpec",
"spec",
"=",
"new",
"AssetVersionSpec",
"(",
"service",
".",
"getSubflow",
"(",
")",
")",
";",
"try",
"{",
"Process",
"process",
"=... | Can be a process or template. | [
"Can",
"be",
"a",
"process",
"or",
"template",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/microservice/OrchestratorActivity.java#L150-L161 | train |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/microservice/OrchestratorActivity.java | OrchestratorActivity.createBindings | protected Map<String,String> createBindings(List<Variable> childVars, int index, Microservice service,
boolean passDocumentContent) throws ActivityException {
Map<String,String> parameters = new HashMap<>();
for (int i = 0; i < childVars.size(); i++) {
Variable childVar = childVars.get(i);
if (childVar.isInput()) {
String subflowVarName = childVar.getName();
Object value = service.getBindings().get(subflowVarName);
if (value != null) {
String stringValue = String.valueOf(value);
if (passDocumentContent) {
if (VariableTranslator.isDocumentReferenceVariable(getPackage(),
childVar.getType()) && stringValue.startsWith("DOCUMENT:")) {
stringValue = getDocumentContent(new DocumentReference(stringValue));
}
}
parameters.put(subflowVarName, stringValue);
}
}
}
String processName = getSubflow(service).getName();
if (processName.startsWith("$") && parameters.get(processName) == null) {
// template variable will populate process name
parameters.put(processName, service.getName());
}
if (parameters.get("i") == null)
parameters.put("i", String.valueOf(index));
return parameters;
} | java | protected Map<String,String> createBindings(List<Variable> childVars, int index, Microservice service,
boolean passDocumentContent) throws ActivityException {
Map<String,String> parameters = new HashMap<>();
for (int i = 0; i < childVars.size(); i++) {
Variable childVar = childVars.get(i);
if (childVar.isInput()) {
String subflowVarName = childVar.getName();
Object value = service.getBindings().get(subflowVarName);
if (value != null) {
String stringValue = String.valueOf(value);
if (passDocumentContent) {
if (VariableTranslator.isDocumentReferenceVariable(getPackage(),
childVar.getType()) && stringValue.startsWith("DOCUMENT:")) {
stringValue = getDocumentContent(new DocumentReference(stringValue));
}
}
parameters.put(subflowVarName, stringValue);
}
}
}
String processName = getSubflow(service).getName();
if (processName.startsWith("$") && parameters.get(processName) == null) {
// template variable will populate process name
parameters.put(processName, service.getName());
}
if (parameters.get("i") == null)
parameters.put("i", String.valueOf(index));
return parameters;
} | [
"protected",
"Map",
"<",
"String",
",",
"String",
">",
"createBindings",
"(",
"List",
"<",
"Variable",
">",
"childVars",
",",
"int",
"index",
",",
"Microservice",
"service",
",",
"boolean",
"passDocumentContent",
")",
"throws",
"ActivityException",
"{",
"Map",
... | Returns variable bindings to be passed into subprocess. | [
"Returns",
"variable",
"bindings",
"to",
"be",
"passed",
"into",
"subprocess",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/microservice/OrchestratorActivity.java#L179-L207 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/constant/WorkAttributeConstant.java | WorkAttributeConstant.getOverrideAttributeName | public static String getOverrideAttributeName(String rawName, String subType, String subId) {
if (OwnerType.ACTIVITY.equals(subType))
return OVERRIDE_ACTIVITY + subId + ":" + rawName;
else if (OwnerType.WORK_TRANSITION.equals(subType))
return OVERRIDE_TRANSITION + subId + ":" + rawName;
else if (OwnerType.PROCESS.equals(subType))
return OVERRIDE_SUBPROC + subId + ":" + rawName;
else
return rawName;
} | java | public static String getOverrideAttributeName(String rawName, String subType, String subId) {
if (OwnerType.ACTIVITY.equals(subType))
return OVERRIDE_ACTIVITY + subId + ":" + rawName;
else if (OwnerType.WORK_TRANSITION.equals(subType))
return OVERRIDE_TRANSITION + subId + ":" + rawName;
else if (OwnerType.PROCESS.equals(subType))
return OVERRIDE_SUBPROC + subId + ":" + rawName;
else
return rawName;
} | [
"public",
"static",
"String",
"getOverrideAttributeName",
"(",
"String",
"rawName",
",",
"String",
"subType",
",",
"String",
"subId",
")",
"{",
"if",
"(",
"OwnerType",
".",
"ACTIVITY",
".",
"equals",
"(",
"subType",
")",
")",
"return",
"OVERRIDE_ACTIVITY",
"+"... | Returns raw name if subtype is null. | [
"Returns",
"raw",
"name",
"if",
"subtype",
"is",
"null",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/constant/WorkAttributeConstant.java#L126-L135 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/EmbeddedDataAccess.java | EmbeddedDataAccess.run | public void run() throws SQLException {
if (ApplicationContext.isDevelopment() && embeddedDb.checkRunning()) {
// only checked in development (otherwise let db startup file due to locked resources)
logger.severe("\n***WARNING***\nEmbedded DB appears to be running already. This can happen due to an unclean previous shutdown.\n***WARNING***");
return;
}
if (shutdownHook != null) {
embeddedDb.shutdown();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
shutdownHook = new Thread(new Runnable() {
public void run() {
try {
embeddedDb.shutdown();
}
catch (SQLException ex) {
System.err.println("ERROR: Cannot shut down embedded db cleanly");
ex.printStackTrace();
}
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
embeddedDb.startup();
if (!embeddedDb.checkMdwSchema()) {
embeddedDb.createMdwSchema();
// seed users
try {
String usersJson = JsonUtil.read("seed_users.json");
if (usersJson != null) {
logger.info("Loading seed users into " + MDW_EMBEDDED_DB_CLASS + ":");
JSONObject usersObj = new JsonObject(usersJson);
if (usersObj.has("users")) {
JSONArray usersArr = usersObj.getJSONArray("users");
for (int i = 0; i < usersArr.length(); i++) {
User user = new User(usersArr.getJSONObject(i));
logger.info(" creating user: '" + user.getCuid() + "'");
embeddedDb.insertUser(user);
}
}
}
}
catch (Exception ex) {
throw new SQLException("Error inserting from seed_users.json", ex);
}
extensionsNeedInitialization = true;
}
} | java | public void run() throws SQLException {
if (ApplicationContext.isDevelopment() && embeddedDb.checkRunning()) {
// only checked in development (otherwise let db startup file due to locked resources)
logger.severe("\n***WARNING***\nEmbedded DB appears to be running already. This can happen due to an unclean previous shutdown.\n***WARNING***");
return;
}
if (shutdownHook != null) {
embeddedDb.shutdown();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
shutdownHook = new Thread(new Runnable() {
public void run() {
try {
embeddedDb.shutdown();
}
catch (SQLException ex) {
System.err.println("ERROR: Cannot shut down embedded db cleanly");
ex.printStackTrace();
}
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
embeddedDb.startup();
if (!embeddedDb.checkMdwSchema()) {
embeddedDb.createMdwSchema();
// seed users
try {
String usersJson = JsonUtil.read("seed_users.json");
if (usersJson != null) {
logger.info("Loading seed users into " + MDW_EMBEDDED_DB_CLASS + ":");
JSONObject usersObj = new JsonObject(usersJson);
if (usersObj.has("users")) {
JSONArray usersArr = usersObj.getJSONArray("users");
for (int i = 0; i < usersArr.length(); i++) {
User user = new User(usersArr.getJSONObject(i));
logger.info(" creating user: '" + user.getCuid() + "'");
embeddedDb.insertUser(user);
}
}
}
}
catch (Exception ex) {
throw new SQLException("Error inserting from seed_users.json", ex);
}
extensionsNeedInitialization = true;
}
} | [
"public",
"void",
"run",
"(",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"ApplicationContext",
".",
"isDevelopment",
"(",
")",
"&&",
"embeddedDb",
".",
"checkRunning",
"(",
")",
")",
"{",
"// only checked in development (otherwise let db startup file due to locked r... | Starts the db if not running and connects to confirm process_instance table exists,
and creates the schema if the table is not found. | [
"Starts",
"the",
"db",
"if",
"not",
"running",
"and",
"connects",
"to",
"confirm",
"process_instance",
"table",
"exists",
"and",
"creates",
"the",
"schema",
"if",
"the",
"table",
"is",
"not",
"found",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/EmbeddedDataAccess.java#L71-L124 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.getId | public long getId(File file) throws IOException {
Long id = file2id.get(file);
if (id == null) {
id = gitHash(file);
file2id.put(file, id);
id2file.put(id, file);
}
return id;
} | java | public long getId(File file) throws IOException {
Long id = file2id.get(file);
if (id == null) {
id = gitHash(file);
file2id.put(file, id);
id2file.put(id, file);
}
return id;
} | [
"public",
"long",
"getId",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"Long",
"id",
"=",
"file2id",
".",
"get",
"(",
"file",
")",
";",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"id",
"=",
"gitHash",
"(",
"file",
")",
";",
"file2id",
"... | Cannot use git object hash since identical files would return duplicate
ids. Hash using git algorithm based on the relative file path. | [
"Cannot",
"use",
"git",
"object",
"hash",
"since",
"identical",
"files",
"would",
"return",
"duplicate",
"ids",
".",
"Hash",
"using",
"git",
"algorithm",
"based",
"on",
"the",
"relative",
"file",
"path",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L128-L136 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.getGitId | public String getGitId(File input) throws IOException {
String hash = "";
if (input.isFile()) {
FileInputStream fis = null;
try {
int fileSize = (int)input.length();
fis = new FileInputStream(input);
byte[] fileBytes = new byte[fileSize];
fis.read(fileBytes);
//hash = localRepo.newObjectInserter().idFor(Constants.OBJ_BLOB, fileBytes).getName(); // This is slower than below code (even if reusing ObjectInserter instance)
String blob = "blob " + fileSize + "\0" + new String(fileBytes);
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] bytes = md.digest(blob.getBytes());
hash = byteArrayToHexString(bytes);
}
catch (Throwable ex) {
throw new IOException(ex.getMessage(), ex);
}
finally {
if (fis != null)
fis.close();
}
}
return hash;
} | java | public String getGitId(File input) throws IOException {
String hash = "";
if (input.isFile()) {
FileInputStream fis = null;
try {
int fileSize = (int)input.length();
fis = new FileInputStream(input);
byte[] fileBytes = new byte[fileSize];
fis.read(fileBytes);
//hash = localRepo.newObjectInserter().idFor(Constants.OBJ_BLOB, fileBytes).getName(); // This is slower than below code (even if reusing ObjectInserter instance)
String blob = "blob " + fileSize + "\0" + new String(fileBytes);
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] bytes = md.digest(blob.getBytes());
hash = byteArrayToHexString(bytes);
}
catch (Throwable ex) {
throw new IOException(ex.getMessage(), ex);
}
finally {
if (fis != null)
fis.close();
}
}
return hash;
} | [
"public",
"String",
"getGitId",
"(",
"File",
"input",
")",
"throws",
"IOException",
"{",
"String",
"hash",
"=",
"\"\"",
";",
"if",
"(",
"input",
".",
"isFile",
"(",
")",
")",
"{",
"FileInputStream",
"fis",
"=",
"null",
";",
"try",
"{",
"int",
"fileSize... | This produces the same hash for a given object that Git 'hash-object' creates | [
"This",
"produces",
"the",
"same",
"hash",
"for",
"a",
"given",
"object",
"that",
"Git",
"hash",
"-",
"object",
"creates"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L141-L165 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.getRemoteCommit | public String getRemoteCommit(String branch) throws Exception {
fetch();
ObjectId commit = localRepo.resolve("origin/" + branch);
if (commit != null)
return commit.getName();
else
return null;
} | java | public String getRemoteCommit(String branch) throws Exception {
fetch();
ObjectId commit = localRepo.resolve("origin/" + branch);
if (commit != null)
return commit.getName();
else
return null;
} | [
"public",
"String",
"getRemoteCommit",
"(",
"String",
"branch",
")",
"throws",
"Exception",
"{",
"fetch",
"(",
")",
";",
"ObjectId",
"commit",
"=",
"localRepo",
".",
"resolve",
"(",
"\"origin/\"",
"+",
"branch",
")",
";",
"if",
"(",
"commit",
"!=",
"null",... | Get remote HEAD commit. | [
"Get",
"remote",
"HEAD",
"commit",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L322-L329 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.checkout | public void checkout(String branch) throws Exception {
if (!branch.equals(getBranch())) {
createBranchIfNeeded(branch);
git.checkout().setName(branch).setStartPoint("origin/" + branch)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
// for some reason jgit needs this when branch is switched
git.checkout().setName(branch).call();
}
} | java | public void checkout(String branch) throws Exception {
if (!branch.equals(getBranch())) {
createBranchIfNeeded(branch);
git.checkout().setName(branch).setStartPoint("origin/" + branch)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
// for some reason jgit needs this when branch is switched
git.checkout().setName(branch).call();
}
} | [
"public",
"void",
"checkout",
"(",
"String",
"branch",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"branch",
".",
"equals",
"(",
"getBranch",
"(",
")",
")",
")",
"{",
"createBranchIfNeeded",
"(",
"branch",
")",
";",
"git",
".",
"checkout",
"(",
")... | Does not do anything if already on target branch. | [
"Does",
"not",
"do",
"anything",
"if",
"already",
"on",
"target",
"branch",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L344-L352 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.createBranchIfNeeded | protected void createBranchIfNeeded(String branch) throws Exception {
fetch(); // in case the branch is not known locally
if (localRepo.findRef(branch) == null) {
git.branchCreate()
.setName(branch)
.setUpstreamMode(SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + branch)
.call();
}
} | java | protected void createBranchIfNeeded(String branch) throws Exception {
fetch(); // in case the branch is not known locally
if (localRepo.findRef(branch) == null) {
git.branchCreate()
.setName(branch)
.setUpstreamMode(SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + branch)
.call();
}
} | [
"protected",
"void",
"createBranchIfNeeded",
"(",
"String",
"branch",
")",
"throws",
"Exception",
"{",
"fetch",
"(",
")",
";",
"// in case the branch is not known locally",
"if",
"(",
"localRepo",
".",
"findRef",
"(",
"branch",
")",
"==",
"null",
")",
"{",
"git"... | Create a local branch for remote tracking if it doesn't exist already. | [
"Create",
"a",
"local",
"branch",
"for",
"remote",
"tracking",
"if",
"it",
"doesn",
"t",
"exist",
"already",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L414-L423 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java | VersionControlGit.getCommitInfo | public CommitInfo getCommitInfo(String path) throws Exception {
Iterator<RevCommit> revCommits = git.log().addPath(path).setMaxCount(1).call().iterator();
if (revCommits.hasNext()) {
RevCommit revCommit = revCommits.next();
CommitInfo commitInfo = new CommitInfo(revCommit.getId().name());
PersonIdent committerIdent = revCommit.getCommitterIdent();
commitInfo.setCommitter(committerIdent.getName());
commitInfo.setEmail(committerIdent.getEmailAddress());
if ((commitInfo.getCommitter() == null || commitInfo.getCommitter().isEmpty()) && commitInfo.getEmail() != null)
commitInfo.setCommitter(commitInfo.getEmail());
commitInfo.setDate(committerIdent.getWhen());
commitInfo.setMessage(revCommit.getShortMessage());
return commitInfo;
}
return null;
} | java | public CommitInfo getCommitInfo(String path) throws Exception {
Iterator<RevCommit> revCommits = git.log().addPath(path).setMaxCount(1).call().iterator();
if (revCommits.hasNext()) {
RevCommit revCommit = revCommits.next();
CommitInfo commitInfo = new CommitInfo(revCommit.getId().name());
PersonIdent committerIdent = revCommit.getCommitterIdent();
commitInfo.setCommitter(committerIdent.getName());
commitInfo.setEmail(committerIdent.getEmailAddress());
if ((commitInfo.getCommitter() == null || commitInfo.getCommitter().isEmpty()) && commitInfo.getEmail() != null)
commitInfo.setCommitter(commitInfo.getEmail());
commitInfo.setDate(committerIdent.getWhen());
commitInfo.setMessage(revCommit.getShortMessage());
return commitInfo;
}
return null;
} | [
"public",
"CommitInfo",
"getCommitInfo",
"(",
"String",
"path",
")",
"throws",
"Exception",
"{",
"Iterator",
"<",
"RevCommit",
">",
"revCommits",
"=",
"git",
".",
"log",
"(",
")",
".",
"addPath",
"(",
"path",
")",
".",
"setMaxCount",
"(",
"1",
")",
".",
... | Does not fetch. | [
"Does",
"not",
"fetch",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/dataaccess/file/VersionControlGit.java#L663-L678 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/discovery/GitLabDiscoverer.java | GitLabDiscoverer.getPackageName | protected String getPackageName(String path) throws IOException {
return path.substring(getAssetPath().length() + 1, path.length() - 5).replace('/', '.');
} | java | protected String getPackageName(String path) throws IOException {
return path.substring(getAssetPath().length() + 1, path.length() - 5).replace('/', '.');
} | [
"protected",
"String",
"getPackageName",
"(",
"String",
"path",
")",
"throws",
"IOException",
"{",
"return",
"path",
".",
"substring",
"(",
"getAssetPath",
"(",
")",
".",
"length",
"(",
")",
"+",
"1",
",",
"path",
".",
"length",
"(",
")",
"-",
"5",
")"... | Paths are relative to the repository base. | [
"Paths",
"are",
"relative",
"to",
"the",
"repository",
"base",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/discovery/GitLabDiscoverer.java#L116-L118 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/data/process/EngineDataAccessCache.java | EngineDataAccessCache.setActivityInstanceStatus | public synchronized void setActivityInstanceStatus(ActivityInstance actInst,
Integer status, String statusMessage)
throws SQLException {
if (cache_activity_transition==CACHE_ONLY) {
actInst.setStatusCode(status);
actInst.setMessage(statusMessage);
} else {
edadb.setActivityInstanceStatus(actInst, status, statusMessage);
}
} | java | public synchronized void setActivityInstanceStatus(ActivityInstance actInst,
Integer status, String statusMessage)
throws SQLException {
if (cache_activity_transition==CACHE_ONLY) {
actInst.setStatusCode(status);
actInst.setMessage(statusMessage);
} else {
edadb.setActivityInstanceStatus(actInst, status, statusMessage);
}
} | [
"public",
"synchronized",
"void",
"setActivityInstanceStatus",
"(",
"ActivityInstance",
"actInst",
",",
"Integer",
"status",
",",
"String",
"statusMessage",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"cache_activity_transition",
"==",
"CACHE_ONLY",
")",
"{",
"actI... | changed to append in all cases | [
"changed",
"to",
"append",
"in",
"all",
"cases"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/data/process/EngineDataAccessCache.java#L310-L319 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/model/request/ServicePath.java | ServicePath.compareTo | @Override
public int compareTo(ServicePath servicePath) {
// longer paths come first
if (segments.length != servicePath.segments.length) {
return servicePath.segments.length - segments.length;
}
else {
for (int i = 0; i < segments.length; i++) {
boolean segmentIsParam = isParam(segments[i]);
boolean serviceSegmentIsParam = isParam(servicePath.segments[i]);
// non-params first
if (segmentIsParam && !serviceSegmentIsParam)
return 1;
else if (serviceSegmentIsParam && !segmentIsParam)
return -1;
}
return path.compareTo(servicePath.path);
}
} | java | @Override
public int compareTo(ServicePath servicePath) {
// longer paths come first
if (segments.length != servicePath.segments.length) {
return servicePath.segments.length - segments.length;
}
else {
for (int i = 0; i < segments.length; i++) {
boolean segmentIsParam = isParam(segments[i]);
boolean serviceSegmentIsParam = isParam(servicePath.segments[i]);
// non-params first
if (segmentIsParam && !serviceSegmentIsParam)
return 1;
else if (serviceSegmentIsParam && !segmentIsParam)
return -1;
}
return path.compareTo(servicePath.path);
}
} | [
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"ServicePath",
"servicePath",
")",
"{",
"// longer paths come first",
"if",
"(",
"segments",
".",
"length",
"!=",
"servicePath",
".",
"segments",
".",
"length",
")",
"{",
"return",
"servicePath",
".",
"segments... | Sorting such that best match is found first. | [
"Sorting",
"such",
"that",
"best",
"match",
"is",
"found",
"first",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/request/ServicePath.java#L49-L67 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/service/rest/Workgroups.java | Workgroups.get | @Override
@Path("/{groupName}")
@ApiOperation(value="Retrieve a workgroup or all workgroups",
notes="If groupName is not present, returns all workgroups.",
response=Workgroup.class, responseContainer="List")
public JSONObject get(String path, Map<String,String> headers)
throws ServiceException, JSONException {
UserServices userServices = ServiceLocator.getUserServices();
try {
String groupName = getSegment(path, 1);
if (groupName == null) // check parameter
groupName = getParameters(headers).get("name");
if (groupName != null) {
Workgroup group = userServices.getWorkgroup(groupName);
if (group == null)
throw new ServiceException(ServiceException.NOT_FOUND, "Workgroup not found: " + groupName);
return group.getJson();
}
else {
return userServices.getWorkgroups().getJson();
}
}
catch (ServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new ServiceException(ex.getMessage(), ex);
}
} | java | @Override
@Path("/{groupName}")
@ApiOperation(value="Retrieve a workgroup or all workgroups",
notes="If groupName is not present, returns all workgroups.",
response=Workgroup.class, responseContainer="List")
public JSONObject get(String path, Map<String,String> headers)
throws ServiceException, JSONException {
UserServices userServices = ServiceLocator.getUserServices();
try {
String groupName = getSegment(path, 1);
if (groupName == null) // check parameter
groupName = getParameters(headers).get("name");
if (groupName != null) {
Workgroup group = userServices.getWorkgroup(groupName);
if (group == null)
throw new ServiceException(ServiceException.NOT_FOUND, "Workgroup not found: " + groupName);
return group.getJson();
}
else {
return userServices.getWorkgroups().getJson();
}
}
catch (ServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new ServiceException(ex.getMessage(), ex);
}
} | [
"@",
"Override",
"@",
"Path",
"(",
"\"/{groupName}\"",
")",
"@",
"ApiOperation",
"(",
"value",
"=",
"\"Retrieve a workgroup or all workgroups\"",
",",
"notes",
"=",
"\"If groupName is not present, returns all workgroups.\"",
",",
"response",
"=",
"Workgroup",
".",
"class"... | Retrieve a workgroup or all workgroups. | [
"Retrieve",
"a",
"workgroup",
"or",
"all",
"workgroups",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/service/rest/Workgroups.java#L76-L104 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/cli/Dependency.java | Dependency.getLibDir | static File getLibDir() throws IOException {
String mdwHome = System.getenv("MDW_HOME");
if (mdwHome == null)
mdwHome = System.getProperty("mdw.home");
if (mdwHome == null)
throw new IOException("Missing environment variable: MDW_HOME");
File mdwDir = new File(mdwHome);
if (!mdwDir.isDirectory())
throw new IOException("MDW_HOME is not a directory: " + mdwDir.getAbsolutePath());
File libDir = new File (mdwDir + "/lib");
if (!libDir.exists() && !libDir.mkdirs())
throw new IOException("Cannot create lib dir: " + libDir.getAbsolutePath());
return libDir;
} | java | static File getLibDir() throws IOException {
String mdwHome = System.getenv("MDW_HOME");
if (mdwHome == null)
mdwHome = System.getProperty("mdw.home");
if (mdwHome == null)
throw new IOException("Missing environment variable: MDW_HOME");
File mdwDir = new File(mdwHome);
if (!mdwDir.isDirectory())
throw new IOException("MDW_HOME is not a directory: " + mdwDir.getAbsolutePath());
File libDir = new File (mdwDir + "/lib");
if (!libDir.exists() && !libDir.mkdirs())
throw new IOException("Cannot create lib dir: " + libDir.getAbsolutePath());
return libDir;
} | [
"static",
"File",
"getLibDir",
"(",
")",
"throws",
"IOException",
"{",
"String",
"mdwHome",
"=",
"System",
".",
"getenv",
"(",
"\"MDW_HOME\"",
")",
";",
"if",
"(",
"mdwHome",
"==",
"null",
")",
"mdwHome",
"=",
"System",
".",
"getProperty",
"(",
"\"mdw.home... | Creates libDir and throws IOException if unable. | [
"Creates",
"libDir",
"and",
"throws",
"IOException",
"if",
"unable",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/cli/Dependency.java#L42-L55 | train |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/kafka/MDWKafkaListener.java | MDWKafkaListener.init | public void init(String listenerName, Properties parameters) throws PropertyException {
try {
if (!parameters.containsKey(HOST_LIST))
throw new Exception("Missing bootstrap.servers property for Kafka listener");
else {
String[] hostarray = parameters.getProperty(HOST_LIST).split(",");
if (hostarray != null && hostarray.length > 0)
hostList = Arrays.asList(hostarray);
else
throw new Exception("Missing value for bootstrap.servers property for Kafka listener");
}
}
catch (Exception e) {
throw new PropertyException(e.getMessage());
}
// STANDALONE logger = StandaloneLogger.getSingleton();
/* WITHENGINE */logger = LoggerUtil.getStandardLogger();
logger.info("Starting Kafka consumer Listener name = " + listenerName);
kafkaListenerName = listenerName;
if (!parameters.containsKey(TOPIC_LIST))
topics = Arrays.asList(listenerName);
else
{
String[] topicList = parameters.getProperty(TOPIC_LIST).split(",");
if (topicList != null && topicList.length > 0)
topics = Arrays.asList(topicList);
else
topics = Arrays.asList(listenerName);
}
if (!parameters.containsKey(GROUP_ID)) {
logger.warn("No group.id property specified for Kafka consumer " + kafkaListenerName + ", using \"" + kafkaListenerName + "\"...");
parameters.put(GROUP_ID, kafkaListenerName);
}
if (!parameters.containsKey(AUTO_COMMIT))
parameters.put(AUTO_COMMIT, "true");
if (!parameters.containsKey(KEY_DESERIALIZER))
parameters.put(KEY_DESERIALIZER, "org.apache.kafka.common.serialization.StringDeserializer");
if (!parameters.containsKey(VALUE_DESERIALIZER))
parameters.put(VALUE_DESERIALIZER, "org.apache.kafka.common.serialization.StringDeserializer");
// hostList = parameters.getProperty(HOST_LIST);
auto_commit = getBooleanProperty(parameters, AUTO_COMMIT, true);
poll_timeout = 1000 * getIntegerProperty(parameters, POLL_TIMEOUT, 60);
use_thread_pool = getBooleanProperty(parameters, USE_THREAD_POOL, false);
xmlWrapper = parameters.getProperty(XML_WRAPPER);
initParameters = parameters;
// Remove non-Kafka properties
initParameters.remove(KAFKAPOOL_CLASS_NAME);
initParameters.remove(USE_THREAD_POOL);
initParameters.remove(TOPIC_LIST);
initParameters.remove(POLL_TIMEOUT);
initParameters.remove(XML_WRAPPER);
} | java | public void init(String listenerName, Properties parameters) throws PropertyException {
try {
if (!parameters.containsKey(HOST_LIST))
throw new Exception("Missing bootstrap.servers property for Kafka listener");
else {
String[] hostarray = parameters.getProperty(HOST_LIST).split(",");
if (hostarray != null && hostarray.length > 0)
hostList = Arrays.asList(hostarray);
else
throw new Exception("Missing value for bootstrap.servers property for Kafka listener");
}
}
catch (Exception e) {
throw new PropertyException(e.getMessage());
}
// STANDALONE logger = StandaloneLogger.getSingleton();
/* WITHENGINE */logger = LoggerUtil.getStandardLogger();
logger.info("Starting Kafka consumer Listener name = " + listenerName);
kafkaListenerName = listenerName;
if (!parameters.containsKey(TOPIC_LIST))
topics = Arrays.asList(listenerName);
else
{
String[] topicList = parameters.getProperty(TOPIC_LIST).split(",");
if (topicList != null && topicList.length > 0)
topics = Arrays.asList(topicList);
else
topics = Arrays.asList(listenerName);
}
if (!parameters.containsKey(GROUP_ID)) {
logger.warn("No group.id property specified for Kafka consumer " + kafkaListenerName + ", using \"" + kafkaListenerName + "\"...");
parameters.put(GROUP_ID, kafkaListenerName);
}
if (!parameters.containsKey(AUTO_COMMIT))
parameters.put(AUTO_COMMIT, "true");
if (!parameters.containsKey(KEY_DESERIALIZER))
parameters.put(KEY_DESERIALIZER, "org.apache.kafka.common.serialization.StringDeserializer");
if (!parameters.containsKey(VALUE_DESERIALIZER))
parameters.put(VALUE_DESERIALIZER, "org.apache.kafka.common.serialization.StringDeserializer");
// hostList = parameters.getProperty(HOST_LIST);
auto_commit = getBooleanProperty(parameters, AUTO_COMMIT, true);
poll_timeout = 1000 * getIntegerProperty(parameters, POLL_TIMEOUT, 60);
use_thread_pool = getBooleanProperty(parameters, USE_THREAD_POOL, false);
xmlWrapper = parameters.getProperty(XML_WRAPPER);
initParameters = parameters;
// Remove non-Kafka properties
initParameters.remove(KAFKAPOOL_CLASS_NAME);
initParameters.remove(USE_THREAD_POOL);
initParameters.remove(TOPIC_LIST);
initParameters.remove(POLL_TIMEOUT);
initParameters.remove(XML_WRAPPER);
} | [
"public",
"void",
"init",
"(",
"String",
"listenerName",
",",
"Properties",
"parameters",
")",
"throws",
"PropertyException",
"{",
"try",
"{",
"if",
"(",
"!",
"parameters",
".",
"containsKey",
"(",
"HOST_LIST",
")",
")",
"throw",
"new",
"Exception",
"(",
"\"... | null if processing using the same thread | [
"null",
"if",
"processing",
"using",
"the",
"same",
"thread"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/kafka/MDWKafkaListener.java#L80-L142 | train |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/zipkin/TraceActivityMonitor.java | TraceActivityMonitor.startSpan | private void startSpan(ActivityRuntimeContext context) {
Tracing tracing = TraceHelper.getTracing("mdw-activity");
Tracer tracer = tracing.tracer();
Span span = tracer.currentSpan();
if (span == null) {
// async brave server if b3 requestHeaders populated (subspan)
Object requestHeaders = context.getValue("requestHeaders");
if (requestHeaders instanceof Map) {
Map<?, ?> headers = (Map<?, ?>) requestHeaders;
if (headers.containsKey("x-b3-traceid")) {
TraceContext.Extractor<Map<?, ?>> extractor =
tracing.propagation().extractor((map, key) -> {
Object val = map.get(key.toLowerCase());
return val == null ? null : val.toString();
});
TraceContextOrSamplingFlags extracted = extractor.extract(headers);
span = extracted.context() != null
? tracer.joinSpan(extracted.context())
: tracer.nextSpan(extracted);
span.name("m" + context.getMasterRequestId()).kind(Span.Kind.SERVER);
span = tracer.newChild(span.context()).name("p" + context.getProcessInstanceId());
}
}
}
if (span == null) {
// create a new root span for async start
span = tracer.nextSpan().name("a" + context.getActivityInstanceId());
}
span.start().flush(); // async
Tracer.SpanInScope spanInScope = tracer.withSpanInScope(span);
context.getRuntimeAttributes().put(Tracer.SpanInScope.class, spanInScope);
} | java | private void startSpan(ActivityRuntimeContext context) {
Tracing tracing = TraceHelper.getTracing("mdw-activity");
Tracer tracer = tracing.tracer();
Span span = tracer.currentSpan();
if (span == null) {
// async brave server if b3 requestHeaders populated (subspan)
Object requestHeaders = context.getValue("requestHeaders");
if (requestHeaders instanceof Map) {
Map<?, ?> headers = (Map<?, ?>) requestHeaders;
if (headers.containsKey("x-b3-traceid")) {
TraceContext.Extractor<Map<?, ?>> extractor =
tracing.propagation().extractor((map, key) -> {
Object val = map.get(key.toLowerCase());
return val == null ? null : val.toString();
});
TraceContextOrSamplingFlags extracted = extractor.extract(headers);
span = extracted.context() != null
? tracer.joinSpan(extracted.context())
: tracer.nextSpan(extracted);
span.name("m" + context.getMasterRequestId()).kind(Span.Kind.SERVER);
span = tracer.newChild(span.context()).name("p" + context.getProcessInstanceId());
}
}
}
if (span == null) {
// create a new root span for async start
span = tracer.nextSpan().name("a" + context.getActivityInstanceId());
}
span.start().flush(); // async
Tracer.SpanInScope spanInScope = tracer.withSpanInScope(span);
context.getRuntimeAttributes().put(Tracer.SpanInScope.class, spanInScope);
} | [
"private",
"void",
"startSpan",
"(",
"ActivityRuntimeContext",
"context",
")",
"{",
"Tracing",
"tracing",
"=",
"TraceHelper",
".",
"getTracing",
"(",
"\"mdw-activity\"",
")",
";",
"Tracer",
"tracer",
"=",
"tracing",
".",
"tracer",
"(",
")",
";",
"Span",
"span"... | Resumes or forks | [
"Resumes",
"or",
"forks"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/assets/com/centurylink/mdw/zipkin/TraceActivityMonitor.java#L31-L62 | train |
CenturyLinkCloud/mdw | mdw-hub/src/com/centurylink/mdw/hub/servlet/ServiceServlet.java | ServiceServlet.populateResponseHeaders | protected void populateResponseHeaders(Set<String> requestHeaderKeys, Map<String,String> metaInfo, HttpServletResponse response) {
for (String key : metaInfo.keySet()) {
if (!Listener.AUTHENTICATED_USER_HEADER.equals(key)
&& !Listener.AUTHENTICATED_JWT.equals(key)
&& !Listener.METAINFO_HTTP_STATUS_CODE.equals(key)
&& !Listener.METAINFO_ACCEPT.equals(key)
&& !Listener.METAINFO_CONTENT_TYPE.equals(key)
&& !Listener.METAINFO_DOWNLOAD_FORMAT.equals(key)
&& !Listener.METAINFO_MDW_REQUEST_ID.equals(key)
&& !requestHeaderKeys.contains(key))
response.setHeader(key, metaInfo.get(key));
}
// these always get populated if present
if (metaInfo.get(Listener.METAINFO_REQUEST_ID) != null)
response.setHeader(Listener.METAINFO_REQUEST_ID, metaInfo.get(Listener.METAINFO_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID) != null && !metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID).equals("0"))
response.setHeader(Listener.METAINFO_MDW_REQUEST_ID, metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_CORRELATION_ID) != null)
response.setHeader(Listener.METAINFO_CORRELATION_ID, metaInfo.get(Listener.METAINFO_CORRELATION_ID));
if (metaInfo.get(Listener.METAINFO_DOCUMENT_ID) != null)
response.setHeader(Listener.METAINFO_DOCUMENT_ID, metaInfo.get(Listener.METAINFO_DOCUMENT_ID));
} | java | protected void populateResponseHeaders(Set<String> requestHeaderKeys, Map<String,String> metaInfo, HttpServletResponse response) {
for (String key : metaInfo.keySet()) {
if (!Listener.AUTHENTICATED_USER_HEADER.equals(key)
&& !Listener.AUTHENTICATED_JWT.equals(key)
&& !Listener.METAINFO_HTTP_STATUS_CODE.equals(key)
&& !Listener.METAINFO_ACCEPT.equals(key)
&& !Listener.METAINFO_CONTENT_TYPE.equals(key)
&& !Listener.METAINFO_DOWNLOAD_FORMAT.equals(key)
&& !Listener.METAINFO_MDW_REQUEST_ID.equals(key)
&& !requestHeaderKeys.contains(key))
response.setHeader(key, metaInfo.get(key));
}
// these always get populated if present
if (metaInfo.get(Listener.METAINFO_REQUEST_ID) != null)
response.setHeader(Listener.METAINFO_REQUEST_ID, metaInfo.get(Listener.METAINFO_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID) != null && !metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID).equals("0"))
response.setHeader(Listener.METAINFO_MDW_REQUEST_ID, metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_CORRELATION_ID) != null)
response.setHeader(Listener.METAINFO_CORRELATION_ID, metaInfo.get(Listener.METAINFO_CORRELATION_ID));
if (metaInfo.get(Listener.METAINFO_DOCUMENT_ID) != null)
response.setHeader(Listener.METAINFO_DOCUMENT_ID, metaInfo.get(Listener.METAINFO_DOCUMENT_ID));
} | [
"protected",
"void",
"populateResponseHeaders",
"(",
"Set",
"<",
"String",
">",
"requestHeaderKeys",
",",
"Map",
"<",
"String",
",",
"String",
">",
"metaInfo",
",",
"HttpServletResponse",
"response",
")",
"{",
"for",
"(",
"String",
"key",
":",
"metaInfo",
".",... | Populates response headers with values added by event handling. | [
"Populates",
"response",
"headers",
"with",
"values",
"added",
"by",
"event",
"handling",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-hub/src/com/centurylink/mdw/hub/servlet/ServiceServlet.java#L50-L72 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java | ListenerHelper.createResponseMeta | private JSONObject createResponseMeta(Map<String,String> metaInfo, Set<String> reqMetaInfo, Long ownerId, long requestTime)
throws EventHandlerException, JSONException, ServiceException {
JSONObject meta = new JsonObject();
JSONObject headers = new JsonObject();
for (String key : metaInfo.keySet()) {
if (!Listener.AUTHENTICATED_USER_HEADER.equals(key)
&& !Listener.METAINFO_HTTP_STATUS_CODE.equals(key)
&& !Listener.METAINFO_ACCEPT.equals(key)
&& !Listener.METAINFO_DOWNLOAD_FORMAT.equals(key)
&& !Listener.METAINFO_MDW_REQUEST_ID.equals(key)
&& !reqMetaInfo.contains(key)) {
headers.put(key, metaInfo.get(key));
}
}
// these always get populated if present
if (metaInfo.get(Listener.METAINFO_REQUEST_ID) != null)
headers.put(Listener.METAINFO_REQUEST_ID, metaInfo.get(Listener.METAINFO_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID) != null && !metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID).equals("0"))
headers.put(Listener.METAINFO_MDW_REQUEST_ID, metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_CORRELATION_ID) != null)
headers.put(Listener.METAINFO_CORRELATION_ID, metaInfo.get(Listener.METAINFO_CORRELATION_ID));
if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) != null)
headers.put(Listener.METAINFO_CONTENT_TYPE, metaInfo.get(Listener.METAINFO_CONTENT_TYPE));
if (!headers.has(Listener.METAINFO_CONTENT_TYPE))
headers.put(Listener.METAINFO_CONTENT_TYPE, "application/json");
meta.put("headers", headers);
createDocument(JSONObject.class.getName(), meta, OwnerType.LISTENER_RESPONSE_META, ownerId);
ServiceLocator.getRequestServices().setElapsedTime(OwnerType.LISTENER_RESPONSE, ownerId,
System.currentTimeMillis() - requestTime);
return meta;
} | java | private JSONObject createResponseMeta(Map<String,String> metaInfo, Set<String> reqMetaInfo, Long ownerId, long requestTime)
throws EventHandlerException, JSONException, ServiceException {
JSONObject meta = new JsonObject();
JSONObject headers = new JsonObject();
for (String key : metaInfo.keySet()) {
if (!Listener.AUTHENTICATED_USER_HEADER.equals(key)
&& !Listener.METAINFO_HTTP_STATUS_CODE.equals(key)
&& !Listener.METAINFO_ACCEPT.equals(key)
&& !Listener.METAINFO_DOWNLOAD_FORMAT.equals(key)
&& !Listener.METAINFO_MDW_REQUEST_ID.equals(key)
&& !reqMetaInfo.contains(key)) {
headers.put(key, metaInfo.get(key));
}
}
// these always get populated if present
if (metaInfo.get(Listener.METAINFO_REQUEST_ID) != null)
headers.put(Listener.METAINFO_REQUEST_ID, metaInfo.get(Listener.METAINFO_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID) != null && !metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID).equals("0"))
headers.put(Listener.METAINFO_MDW_REQUEST_ID, metaInfo.get(Listener.METAINFO_MDW_REQUEST_ID));
if (metaInfo.get(Listener.METAINFO_CORRELATION_ID) != null)
headers.put(Listener.METAINFO_CORRELATION_ID, metaInfo.get(Listener.METAINFO_CORRELATION_ID));
if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) != null)
headers.put(Listener.METAINFO_CONTENT_TYPE, metaInfo.get(Listener.METAINFO_CONTENT_TYPE));
if (!headers.has(Listener.METAINFO_CONTENT_TYPE))
headers.put(Listener.METAINFO_CONTENT_TYPE, "application/json");
meta.put("headers", headers);
createDocument(JSONObject.class.getName(), meta, OwnerType.LISTENER_RESPONSE_META, ownerId);
ServiceLocator.getRequestServices().setElapsedTime(OwnerType.LISTENER_RESPONSE, ownerId,
System.currentTimeMillis() - requestTime);
return meta;
} | [
"private",
"JSONObject",
"createResponseMeta",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"metaInfo",
",",
"Set",
"<",
"String",
">",
"reqMetaInfo",
",",
"Long",
"ownerId",
",",
"long",
"requestTime",
")",
"throws",
"EventHandlerException",
",",
"JSONExcepti... | Inserts the response meta DOCUMENT, as well as INSTANCE_TIMING. | [
"Inserts",
"the",
"response",
"meta",
"DOCUMENT",
"as",
"well",
"as",
"INSTANCE_TIMING",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java#L586-L624 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java | ListenerHelper.createErrorResponse | public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) {
Request request = new Request(0L);
request.setContent(req);
Response response = new Response();
String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE);
if (contentType == null && req != null && !req.isEmpty())
contentType = req.trim().startsWith("{") ? Listener.CONTENT_TYPE_JSON : Listener.CONTENT_TYPE_XML;
if (contentType == null)
contentType = Listener.CONTENT_TYPE_XML; // compatibility
metaInfo.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(ex.getCode()));
StatusMessage statusMsg = new StatusMessage();
statusMsg.setCode(ex.getCode());
statusMsg.setMessage(ex.getMessage());
response.setStatusCode(statusMsg.getCode());
response.setStatusMessage(statusMsg.getMessage());
response.setPath(ServicePaths.getInboundResponsePath(metaInfo));
if (contentType.equals(Listener.CONTENT_TYPE_JSON)) {
response.setContent(statusMsg.getJsonString());
}
else {
response.setContent(statusMsg.getXml());
}
return response;
} | java | public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) {
Request request = new Request(0L);
request.setContent(req);
Response response = new Response();
String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE);
if (contentType == null && req != null && !req.isEmpty())
contentType = req.trim().startsWith("{") ? Listener.CONTENT_TYPE_JSON : Listener.CONTENT_TYPE_XML;
if (contentType == null)
contentType = Listener.CONTENT_TYPE_XML; // compatibility
metaInfo.put(Listener.METAINFO_HTTP_STATUS_CODE, String.valueOf(ex.getCode()));
StatusMessage statusMsg = new StatusMessage();
statusMsg.setCode(ex.getCode());
statusMsg.setMessage(ex.getMessage());
response.setStatusCode(statusMsg.getCode());
response.setStatusMessage(statusMsg.getMessage());
response.setPath(ServicePaths.getInboundResponsePath(metaInfo));
if (contentType.equals(Listener.CONTENT_TYPE_JSON)) {
response.setContent(statusMsg.getJsonString());
}
else {
response.setContent(statusMsg.getXml());
}
return response;
} | [
"public",
"Response",
"createErrorResponse",
"(",
"String",
"req",
",",
"Map",
"<",
"String",
",",
"String",
">",
"metaInfo",
",",
"ServiceException",
"ex",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"0L",
")",
";",
"request",
".",
"setCon... | Create a default error message. To customized this response use a ServiceMonitor. | [
"Create",
"a",
"default",
"error",
"message",
".",
"To",
"customized",
"this",
"response",
"use",
"a",
"ServiceMonitor",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java#L629-L655 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java | ListenerHelper.buildProcessStartMessage | public InternalEvent buildProcessStartMessage(Long processId, Long eventInstId,
String masterRequestId, Map<String, String> parameters) {
InternalEvent evMsg = InternalEvent.createProcessStartMessage(processId,
OwnerType.DOCUMENT, eventInstId, masterRequestId, null, null, null);
evMsg.setParameters(parameters);
evMsg.setCompletionCode(StartActivity.STANDARD_START); // completion
// code -
// indicating
// standard start
return evMsg;
} | java | public InternalEvent buildProcessStartMessage(Long processId, Long eventInstId,
String masterRequestId, Map<String, String> parameters) {
InternalEvent evMsg = InternalEvent.createProcessStartMessage(processId,
OwnerType.DOCUMENT, eventInstId, masterRequestId, null, null, null);
evMsg.setParameters(parameters);
evMsg.setCompletionCode(StartActivity.STANDARD_START); // completion
// code -
// indicating
// standard start
return evMsg;
} | [
"public",
"InternalEvent",
"buildProcessStartMessage",
"(",
"Long",
"processId",
",",
"Long",
"eventInstId",
",",
"String",
"masterRequestId",
",",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
")",
"{",
"InternalEvent",
"evMsg",
"=",
"InternalEvent",
".... | A utility method to build process start JMS message.
@param processId
@param eventInstId
@param masterRequestId
@param parameters
@return | [
"A",
"utility",
"method",
"to",
"build",
"process",
"start",
"JMS",
"message",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java#L785-L795 | train |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java | ListenerHelper.getProcessId | public Long getProcessId(String procname) throws Exception {
Process proc = ProcessCache.getProcess(procname, 0);
if (proc == null)
throw new DataAccessException(0, "Cannot find process with name "
+ procname + ", version 0");
return proc.getId();
} | java | public Long getProcessId(String procname) throws Exception {
Process proc = ProcessCache.getProcess(procname, 0);
if (proc == null)
throw new DataAccessException(0, "Cannot find process with name "
+ procname + ", version 0");
return proc.getId();
} | [
"public",
"Long",
"getProcessId",
"(",
"String",
"procname",
")",
"throws",
"Exception",
"{",
"Process",
"proc",
"=",
"ProcessCache",
".",
"getProcess",
"(",
"procname",
",",
"0",
")",
";",
"if",
"(",
"proc",
"==",
"null",
")",
"throw",
"new",
"DataAccessE... | Helper method to obtain process ID from process name.
@param procname
@return process ID of the latest version of the process with the given
name
@throws Exception | [
"Helper",
"method",
"to",
"obtain",
"process",
"ID",
"from",
"process",
"name",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/listener/ListenerHelper.java#L805-L812 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.Replace | public static String Replace(String aSrcStr, String aSearchStr, String aReplaceStr) {
if (aSrcStr == null || aSearchStr == null || aReplaceStr == null)
return aSrcStr;
if (aSearchStr.length() == 0
|| aSrcStr.length() == 0
|| aSrcStr.indexOf(aSearchStr) == -1) {
return aSrcStr;
}
StringBuffer mBuff = new StringBuffer();
int mSrcStrLen, mSearchStrLen;
mSrcStrLen = aSrcStr.length();
mSearchStrLen = aSearchStr.length();
for (int i = 0, j = 0; i < mSrcStrLen; i = j + mSearchStrLen) {
j = aSrcStr.indexOf(aSearchStr, i);
if (j == -1) {
mBuff.append(aSrcStr.substring(i));
break;
}
mBuff.append(aSrcStr.substring(i, j));
mBuff.append(aReplaceStr);
}
return mBuff.toString();
} | java | public static String Replace(String aSrcStr, String aSearchStr, String aReplaceStr) {
if (aSrcStr == null || aSearchStr == null || aReplaceStr == null)
return aSrcStr;
if (aSearchStr.length() == 0
|| aSrcStr.length() == 0
|| aSrcStr.indexOf(aSearchStr) == -1) {
return aSrcStr;
}
StringBuffer mBuff = new StringBuffer();
int mSrcStrLen, mSearchStrLen;
mSrcStrLen = aSrcStr.length();
mSearchStrLen = aSearchStr.length();
for (int i = 0, j = 0; i < mSrcStrLen; i = j + mSearchStrLen) {
j = aSrcStr.indexOf(aSearchStr, i);
if (j == -1) {
mBuff.append(aSrcStr.substring(i));
break;
}
mBuff.append(aSrcStr.substring(i, j));
mBuff.append(aReplaceStr);
}
return mBuff.toString();
} | [
"public",
"static",
"String",
"Replace",
"(",
"String",
"aSrcStr",
",",
"String",
"aSearchStr",
",",
"String",
"aReplaceStr",
")",
"{",
"if",
"(",
"aSrcStr",
"==",
"null",
"||",
"aSearchStr",
"==",
"null",
"||",
"aReplaceStr",
"==",
"null",
")",
"return",
... | Replaces the 'search string' with 'replace string' in a given 'source string'
@param aSrcStr A source String value.
@param aSearchStr A String value to be searched for in the source String.
@param aReplaceStr A String value that replaces the search String.
@return A String with the 'search string' replaced by 'replace string'. | [
"Replaces",
"the",
"search",
"string",
"with",
"replace",
"string",
"in",
"a",
"given",
"source",
"string"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L817-L842 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.isEqualIgnoreCase | public static boolean isEqualIgnoreCase(String pStr1, String pStr2) {
if (pStr1 == null && pStr2 == null) {
return true;
} else if (pStr1 == null || pStr2 == null) {
return false;
} else if (pStr1.equalsIgnoreCase(pStr2)) {
return true;
}
return false;
} | java | public static boolean isEqualIgnoreCase(String pStr1, String pStr2) {
if (pStr1 == null && pStr2 == null) {
return true;
} else if (pStr1 == null || pStr2 == null) {
return false;
} else if (pStr1.equalsIgnoreCase(pStr2)) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isEqualIgnoreCase",
"(",
"String",
"pStr1",
",",
"String",
"pStr2",
")",
"{",
"if",
"(",
"pStr1",
"==",
"null",
"&&",
"pStr2",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"pStr1",
"==",
"null",... | Checks if both the strings are equal for value - Not Case sensitive.
@param pStr1 A String value.
@param pStr2 A String value.
@return boolean A boolean <code>true</code> if the Strings are equal,
otherwise <code>false</code>.
@see String#equalsIgnoreCase(java.lang.String) | [
"Checks",
"if",
"both",
"the",
"strings",
"are",
"equal",
"for",
"value",
"-",
"Not",
"Case",
"sensitive",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L878-L887 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.isEqual | public static boolean isEqual(String pStr1, String pStr2) {
if (pStr1 == null && pStr2 == null) {
return true;
} else if (pStr1 == null || pStr2 == null) {
return false;
} else if (pStr1.equals(pStr2)) {
return true;
}
return false;
} | java | public static boolean isEqual(String pStr1, String pStr2) {
if (pStr1 == null && pStr2 == null) {
return true;
} else if (pStr1 == null || pStr2 == null) {
return false;
} else if (pStr1.equals(pStr2)) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isEqual",
"(",
"String",
"pStr1",
",",
"String",
"pStr2",
")",
"{",
"if",
"(",
"pStr1",
"==",
"null",
"&&",
"pStr2",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"pStr1",
"==",
"null",
"||",
... | Checks if both the strings are equal for value - Case Sensitive.
@param pStr1 A String value.
@param pStr2 A String value.
@return boolean A boolean <code>true</code> if the Strings are equal,
otherwise <code>false</code>.
@see String#equals(java.lang.Object) | [
"Checks",
"if",
"both",
"the",
"strings",
"are",
"equal",
"for",
"value",
"-",
"Case",
"Sensitive",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L899-L908 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.cleanString | public static String cleanString(String pStr) {
if (pStr == null || pStr.equals("")) {
return pStr;
}
StringBuffer buff = new StringBuffer();
for (int i = 0; i < pStr.length(); i++) {
char aChar = pStr.charAt(i);
if (Character.isLetterOrDigit(aChar)) {
buff.append(aChar);
}
}
return buff.toString();
} | java | public static String cleanString(String pStr) {
if (pStr == null || pStr.equals("")) {
return pStr;
}
StringBuffer buff = new StringBuffer();
for (int i = 0; i < pStr.length(); i++) {
char aChar = pStr.charAt(i);
if (Character.isLetterOrDigit(aChar)) {
buff.append(aChar);
}
}
return buff.toString();
} | [
"public",
"static",
"String",
"cleanString",
"(",
"String",
"pStr",
")",
"{",
"if",
"(",
"pStr",
"==",
"null",
"||",
"pStr",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"return",
"pStr",
";",
"}",
"StringBuffer",
"buff",
"=",
"new",
"StringBuffer",
"(",... | Removes all the spcial charactes and spaces from the passed in string - none
letters or digits.
@param pStr A String value.
@return A cleaned String.
@see Character#isLetterOrDigit(char) | [
"Removes",
"all",
"the",
"spcial",
"charactes",
"and",
"spaces",
"from",
"the",
"passed",
"in",
"string",
"-",
"none",
"letters",
"or",
"digits",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L920-L932 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.stripNewLineChar | public static String stripNewLineChar(String pString) {
String tmpFidValue = pString;
StringTokenizer aTokenizer = new StringTokenizer(pString, "\n");
if (aTokenizer.countTokens() > 1) {
StringBuffer nameBuffer = new StringBuffer();
while (aTokenizer.hasMoreTokens()) {
nameBuffer.append(aTokenizer.nextToken());
}
tmpFidValue = nameBuffer.toString();
}
return tmpFidValue;
} | java | public static String stripNewLineChar(String pString) {
String tmpFidValue = pString;
StringTokenizer aTokenizer = new StringTokenizer(pString, "\n");
if (aTokenizer.countTokens() > 1) {
StringBuffer nameBuffer = new StringBuffer();
while (aTokenizer.hasMoreTokens()) {
nameBuffer.append(aTokenizer.nextToken());
}
tmpFidValue = nameBuffer.toString();
}
return tmpFidValue;
} | [
"public",
"static",
"String",
"stripNewLineChar",
"(",
"String",
"pString",
")",
"{",
"String",
"tmpFidValue",
"=",
"pString",
";",
"StringTokenizer",
"aTokenizer",
"=",
"new",
"StringTokenizer",
"(",
"pString",
",",
"\"\\n\"",
")",
";",
"if",
"(",
"aTokenizer",... | This method strips out all new line characters from the passed String.
@param pString A String value.
@return A clean String.
@see StringTokenizer | [
"This",
"method",
"strips",
"out",
"all",
"new",
"line",
"characters",
"from",
"the",
"passed",
"String",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L943-L954 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.getDouble | public static double getDouble(String pStr) {
if (isEmpty(pStr)) {
return 0.0;
}
double value = 0.0;
pStr = pStr.substring(0, pStr.length() - 2) + "." + pStr.substring(pStr.length() - 2);
try {
value = Double.parseDouble(pStr);
} catch (NumberFormatException ex) {
}
return value;
} | java | public static double getDouble(String pStr) {
if (isEmpty(pStr)) {
return 0.0;
}
double value = 0.0;
pStr = pStr.substring(0, pStr.length() - 2) + "." + pStr.substring(pStr.length() - 2);
try {
value = Double.parseDouble(pStr);
} catch (NumberFormatException ex) {
}
return value;
} | [
"public",
"static",
"double",
"getDouble",
"(",
"String",
"pStr",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"pStr",
")",
")",
"{",
"return",
"0.0",
";",
"}",
"double",
"value",
"=",
"0.0",
";",
"pStr",
"=",
"pStr",
".",
"substring",
"(",
"0",
",",
"pStr... | Returns the parsed double value out of the passed in String
@param pStr A String value.
@return A double value.
@see Double#parseDouble(java.lang.String) | [
"Returns",
"the",
"parsed",
"double",
"value",
"out",
"of",
"the",
"passed",
"in",
"String"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L965-L976 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.getLong | public static long getLong(String pStr) {
if (isEmpty(pStr)) {
return 0;
}
long value = 0;
try {
value = Long.parseLong(pStr);
} catch (NumberFormatException nm) {
}
return value;
} | java | public static long getLong(String pStr) {
if (isEmpty(pStr)) {
return 0;
}
long value = 0;
try {
value = Long.parseLong(pStr);
} catch (NumberFormatException nm) {
}
return value;
} | [
"public",
"static",
"long",
"getLong",
"(",
"String",
"pStr",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"pStr",
")",
")",
"{",
"return",
"0",
";",
"}",
"long",
"value",
"=",
"0",
";",
"try",
"{",
"value",
"=",
"Long",
".",
"parseLong",
"(",
"pStr",
")... | Returns the parsed long value for the passed in String.
@param pStr A String value.
@return A long value.
@see Long#parseLong(java.lang.String) | [
"Returns",
"the",
"parsed",
"long",
"value",
"for",
"the",
"passed",
"in",
"String",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L987-L997 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.getInteger | public static int getInteger(String pStr, int defval) {
if (isEmpty(pStr)) return defval;
try {
return Integer.parseInt(pStr);
} catch (NumberFormatException nm) {
return defval;
}
} | java | public static int getInteger(String pStr, int defval) {
if (isEmpty(pStr)) return defval;
try {
return Integer.parseInt(pStr);
} catch (NumberFormatException nm) {
return defval;
}
} | [
"public",
"static",
"int",
"getInteger",
"(",
"String",
"pStr",
",",
"int",
"defval",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"pStr",
")",
")",
"return",
"defval",
";",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"pStr",
")",
";",
"}",
"catch... | Returns the parsed integer value for the passed in String.
@param pStr A String value.
@return An integer value.
@see Integer#parseInt(java.lang.String) | [
"Returns",
"the",
"parsed",
"integer",
"value",
"for",
"the",
"passed",
"in",
"String",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1008-L1015 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.isContainedIn | public static boolean isContainedIn(String strToBeSearched, String compositeStr,
String regex) {
if ((null == strToBeSearched) || (null == compositeStr) || (null == regex))
return false;
String[] splitValues = compositeStr.split(regex);
boolean isFound = false;
for(int i=0; i<splitValues.length; i++) {
if(strToBeSearched.equals(splitValues[i].trim())) {
isFound = true;
break;
}
}
return isFound;
} | java | public static boolean isContainedIn(String strToBeSearched, String compositeStr,
String regex) {
if ((null == strToBeSearched) || (null == compositeStr) || (null == regex))
return false;
String[] splitValues = compositeStr.split(regex);
boolean isFound = false;
for(int i=0; i<splitValues.length; i++) {
if(strToBeSearched.equals(splitValues[i].trim())) {
isFound = true;
break;
}
}
return isFound;
} | [
"public",
"static",
"boolean",
"isContainedIn",
"(",
"String",
"strToBeSearched",
",",
"String",
"compositeStr",
",",
"String",
"regex",
")",
"{",
"if",
"(",
"(",
"null",
"==",
"strToBeSearched",
")",
"||",
"(",
"null",
"==",
"compositeStr",
")",
"||",
"(",
... | Method which checks whether a string which is having many values
separated by a delimiter contains a particular value or not
If the compositeStr is "QC, ATT, L3" & strToBeSearched is "QC"
& regex is "," then the method will return true.
@param strToBeSearched the value which needs to be searched for in the
composite String
@param compositeStr the String which contains all the values
separated by a delimiter
@param regex the delimiting regular expression
@return | [
"Method",
"which",
"checks",
"whether",
"a",
"string",
"which",
"is",
"having",
"many",
"values",
"separated",
"by",
"a",
"delimiter",
"contains",
"a",
"particular",
"value",
"or",
"not",
"If",
"the",
"compositeStr",
"is",
"QC",
"ATT",
"L3",
"&",
"strToBeSea... | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1074-L1088 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.escapeWithBackslash | public static String escapeWithBackslash(String value, String metachars) {
StringBuffer sb = new StringBuffer();
int i, n = value.length();
char ch;
for (i=0; i<n; i++) {
ch = value.charAt(i);
if (ch=='\\' || metachars.indexOf(ch)>=0) {
sb.append('\\');
}
sb.append(ch);
}
return sb.toString();
} | java | public static String escapeWithBackslash(String value, String metachars) {
StringBuffer sb = new StringBuffer();
int i, n = value.length();
char ch;
for (i=0; i<n; i++) {
ch = value.charAt(i);
if (ch=='\\' || metachars.indexOf(ch)>=0) {
sb.append('\\');
}
sb.append(ch);
}
return sb.toString();
} | [
"public",
"static",
"String",
"escapeWithBackslash",
"(",
"String",
"value",
",",
"String",
"metachars",
")",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"int",
"i",
",",
"n",
"=",
"value",
".",
"length",
"(",
")",
";",
"char",
... | Escape meta characters with backslash.
@param value original string
@param metachars characters that need to be escaped
@return modified string with meta characters escaped with backslashes | [
"Escape",
"meta",
"characters",
"with",
"backslash",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1109-L1121 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.removeBackslashEscape | public static String removeBackslashEscape(String value) {
StringBuffer sb = new StringBuffer();
int i, n = value.length();
char ch;
boolean lastIsEscape = false;
for (i=0; i<n; i++) {
ch = value.charAt(i);
if (lastIsEscape) {
sb.append(ch);
lastIsEscape = false;
} else {
if (ch=='\\') lastIsEscape = true;
else sb.append(ch);
}
}
return sb.toString();
} | java | public static String removeBackslashEscape(String value) {
StringBuffer sb = new StringBuffer();
int i, n = value.length();
char ch;
boolean lastIsEscape = false;
for (i=0; i<n; i++) {
ch = value.charAt(i);
if (lastIsEscape) {
sb.append(ch);
lastIsEscape = false;
} else {
if (ch=='\\') lastIsEscape = true;
else sb.append(ch);
}
}
return sb.toString();
} | [
"public",
"static",
"String",
"removeBackslashEscape",
"(",
"String",
"value",
")",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"int",
"i",
",",
"n",
"=",
"value",
".",
"length",
"(",
")",
";",
"char",
"ch",
";",
"boolean",
"l... | Remove backslashes that are used as escape characters
@param value
@return | [
"Remove",
"backslashes",
"that",
"are",
"used",
"as",
"escape",
"characters"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1128-L1144 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.compress | public static String compress(String uncompressedValue) throws IOException {
if (uncompressedValue == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(uncompressedValue.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
}
finally {
if (gzip != null)
gzip.close();
}
} | java | public static String compress(String uncompressedValue) throws IOException {
if (uncompressedValue == null)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(uncompressedValue.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
}
finally {
if (gzip != null)
gzip.close();
}
} | [
"public",
"static",
"String",
"compress",
"(",
"String",
"uncompressedValue",
")",
"throws",
"IOException",
"{",
"if",
"(",
"uncompressedValue",
"==",
"null",
")",
"return",
"null",
";",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")"... | Compress a string value using GZIP. | [
"Compress",
"a",
"string",
"value",
"using",
"GZIP",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1494-L1509 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.uncompress | public static String uncompress(String compressedValue) throws IOException {
if (compressedValue == null)
return null;
ByteArrayInputStream in = new ByteArrayInputStream(compressedValue.getBytes("ISO-8859-1"));
GZIPInputStream gzip = null;
Reader reader = null;
try {
String value = "";
gzip = new GZIPInputStream(in);
reader = new InputStreamReader(gzip, "ISO-8859-1");
int i;
while ((i = reader.read()) != -1)
value += (char) i;
return value;
}
finally {
if (gzip != null)
gzip.close();
if (reader != null)
reader.close();
}
} | java | public static String uncompress(String compressedValue) throws IOException {
if (compressedValue == null)
return null;
ByteArrayInputStream in = new ByteArrayInputStream(compressedValue.getBytes("ISO-8859-1"));
GZIPInputStream gzip = null;
Reader reader = null;
try {
String value = "";
gzip = new GZIPInputStream(in);
reader = new InputStreamReader(gzip, "ISO-8859-1");
int i;
while ((i = reader.read()) != -1)
value += (char) i;
return value;
}
finally {
if (gzip != null)
gzip.close();
if (reader != null)
reader.close();
}
} | [
"public",
"static",
"String",
"uncompress",
"(",
"String",
"compressedValue",
")",
"throws",
"IOException",
"{",
"if",
"(",
"compressedValue",
"==",
"null",
")",
"return",
"null",
";",
"ByteArrayInputStream",
"in",
"=",
"new",
"ByteArrayInputStream",
"(",
"compres... | Uncompress a string value that was compressed using GZIP. | [
"Uncompress",
"a",
"string",
"value",
"that",
"was",
"compressed",
"using",
"GZIP",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1514-L1536 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/StringHelper.java | StringHelper.delimiterColumnCount | public static int delimiterColumnCount(String row, String delimeterChar, String escapeChar) {
if (row.indexOf(escapeChar) > 0)
return row.replace(escapeChar, " ").length() - row.replace(",", "").length();
else
return row.length() - row.replace(",", "").length();
} | java | public static int delimiterColumnCount(String row, String delimeterChar, String escapeChar) {
if (row.indexOf(escapeChar) > 0)
return row.replace(escapeChar, " ").length() - row.replace(",", "").length();
else
return row.length() - row.replace(",", "").length();
} | [
"public",
"static",
"int",
"delimiterColumnCount",
"(",
"String",
"row",
",",
"String",
"delimeterChar",
",",
"String",
"escapeChar",
")",
"{",
"if",
"(",
"row",
".",
"indexOf",
"(",
"escapeChar",
")",
">",
"0",
")",
"return",
"row",
".",
"replace",
"(",
... | To count comma separated columns in a row to maintain compatibility | [
"To",
"count",
"comma",
"separated",
"columns",
"in",
"a",
"row",
"to",
"maintain",
"compatibility"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/StringHelper.java#L1543-L1548 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java | MDWMessageProducer.sendMessage | public void sendMessage(String requestMessage, String queueName, String correlationId,
final Queue replyQueue, int delaySeconds, int deliveryMode) throws JMSException {
/**
* If it's an internal message then always use jmsTemplate for ActiveMQ
*/
if (jmsTemplate != null) {
jmsTemplate.setDeliveryMode(deliveryMode);
if (!StringUtils.isEmpty(queueName)) {
jmsTemplate.send(queueName, new MDWMessageCreator(requestMessage, correlationId,
replyQueue, delaySeconds));
}
else {
jmsTemplate.send(new MDWMessageCreator(requestMessage, correlationId, replyQueue));
}
}
} | java | public void sendMessage(String requestMessage, String queueName, String correlationId,
final Queue replyQueue, int delaySeconds, int deliveryMode) throws JMSException {
/**
* If it's an internal message then always use jmsTemplate for ActiveMQ
*/
if (jmsTemplate != null) {
jmsTemplate.setDeliveryMode(deliveryMode);
if (!StringUtils.isEmpty(queueName)) {
jmsTemplate.send(queueName, new MDWMessageCreator(requestMessage, correlationId,
replyQueue, delaySeconds));
}
else {
jmsTemplate.send(new MDWMessageCreator(requestMessage, correlationId, replyQueue));
}
}
} | [
"public",
"void",
"sendMessage",
"(",
"String",
"requestMessage",
",",
"String",
"queueName",
",",
"String",
"correlationId",
",",
"final",
"Queue",
"replyQueue",
",",
"int",
"delaySeconds",
",",
"int",
"deliveryMode",
")",
"throws",
"JMSException",
"{",
"/**\n ... | Send a message to a queue with corrId, delay and potential replyQueue
@param requestMessage
@param queueName
@param correlationId
@param replyQueue
@param delaySeconds
@throws JMSException | [
"Send",
"a",
"message",
"to",
"a",
"queue",
"with",
"corrId",
"delay",
"and",
"potential",
"replyQueue"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java#L49-L66 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java | MDWMessageProducer.broadcastMessageToTopic | public void broadcastMessageToTopic(String dest, String requestMessage) {
jmsTopicTemplate.setDeliveryPersistent(true);
jmsTopicTemplate.send(dest, new MDWMessageCreator(requestMessage));
} | java | public void broadcastMessageToTopic(String dest, String requestMessage) {
jmsTopicTemplate.setDeliveryPersistent(true);
jmsTopicTemplate.send(dest, new MDWMessageCreator(requestMessage));
} | [
"public",
"void",
"broadcastMessageToTopic",
"(",
"String",
"dest",
",",
"String",
"requestMessage",
")",
"{",
"jmsTopicTemplate",
".",
"setDeliveryPersistent",
"(",
"true",
")",
";",
"jmsTopicTemplate",
".",
"send",
"(",
"dest",
",",
"new",
"MDWMessageCreator",
"... | Broadcast a message to a specific topic
@param dest
@param requestMessage | [
"Broadcast",
"a",
"message",
"to",
"a",
"specific",
"topic"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/util/MDWMessageProducer.java#L85-L89 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java | VariableTranslator.getTranslator | public static final com.centurylink.mdw.variable.VariableTranslator getTranslator(Package packageVO, String type) {
com.centurylink.mdw.variable.VariableTranslator trans = null;
try {
VariableType vo = VariableTypeCache.getVariableTypeVO(Compatibility.getVariableType(type));
if (vo == null)
return null;
// try dynamic java first (preferred in case patch override is needed / Exclude MDW built-in translators)
if (!mdwVariableTypes.contains(vo)) {
ClassLoader parentLoader = packageVO == null ? VariableTranslator.class.getClassLoader() : packageVO.getClassLoader();
trans = ProviderRegistry.getInstance().getDynamicVariableTranslator(vo.getTranslatorClass(), parentLoader);
}
if (trans == null) {
com.centurylink.mdw.variable.VariableTranslator injected
= SpringAppContext.getInstance().getVariableTranslator(vo.getTranslatorClass(), packageVO);
if (injected != null)
trans = injected;
if (trans == null) {
Class<?> cl = Class.forName(vo.getTranslatorClass());
trans = (VariableTranslator)cl.newInstance();
}
}
} catch (Throwable th) {
th.printStackTrace();
trans = null;
}
if (trans != null)
trans.setPackage(packageVO);
return trans;
} | java | public static final com.centurylink.mdw.variable.VariableTranslator getTranslator(Package packageVO, String type) {
com.centurylink.mdw.variable.VariableTranslator trans = null;
try {
VariableType vo = VariableTypeCache.getVariableTypeVO(Compatibility.getVariableType(type));
if (vo == null)
return null;
// try dynamic java first (preferred in case patch override is needed / Exclude MDW built-in translators)
if (!mdwVariableTypes.contains(vo)) {
ClassLoader parentLoader = packageVO == null ? VariableTranslator.class.getClassLoader() : packageVO.getClassLoader();
trans = ProviderRegistry.getInstance().getDynamicVariableTranslator(vo.getTranslatorClass(), parentLoader);
}
if (trans == null) {
com.centurylink.mdw.variable.VariableTranslator injected
= SpringAppContext.getInstance().getVariableTranslator(vo.getTranslatorClass(), packageVO);
if (injected != null)
trans = injected;
if (trans == null) {
Class<?> cl = Class.forName(vo.getTranslatorClass());
trans = (VariableTranslator)cl.newInstance();
}
}
} catch (Throwable th) {
th.printStackTrace();
trans = null;
}
if (trans != null)
trans.setPackage(packageVO);
return trans;
} | [
"public",
"static",
"final",
"com",
".",
"centurylink",
".",
"mdw",
".",
"variable",
".",
"VariableTranslator",
"getTranslator",
"(",
"Package",
"packageVO",
",",
"String",
"type",
")",
"{",
"com",
".",
"centurylink",
".",
"mdw",
".",
"variable",
".",
"Varia... | Returns the translator for the passed in pType
@param type
@return Translator | [
"Returns",
"the",
"translator",
"for",
"the",
"passed",
"in",
"pType"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java#L63-L92 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java | VariableTranslator.toObject | public static Object toObject(String type, String value){
if(StringHelper.isEmpty(value) || EMPTY_STRING.equals(value)){
return null;
}
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(type);
return trans.toObject(value);
} | java | public static Object toObject(String type, String value){
if(StringHelper.isEmpty(value) || EMPTY_STRING.equals(value)){
return null;
}
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(type);
return trans.toObject(value);
} | [
"public",
"static",
"Object",
"toObject",
"(",
"String",
"type",
",",
"String",
"value",
")",
"{",
"if",
"(",
"StringHelper",
".",
"isEmpty",
"(",
"value",
")",
"||",
"EMPTY_STRING",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"null",
";",
"}... | Translates the Passed in String value based on the
Passed in type
@param type
@param value
@return Translated Object | [
"Translates",
"the",
"Passed",
"in",
"String",
"value",
"based",
"on",
"the",
"Passed",
"in",
"type"
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java#L105-L111 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java | VariableTranslator.realToString | public static String realToString(Package pkg, String type, Object value) {
if (value == null)
return "";
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
if (trans instanceof DocumentReferenceTranslator)
return ((DocumentReferenceTranslator)trans).realToString(value);
else
return trans.toString(value);
} | java | public static String realToString(Package pkg, String type, Object value) {
if (value == null)
return "";
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
if (trans instanceof DocumentReferenceTranslator)
return ((DocumentReferenceTranslator)trans).realToString(value);
else
return trans.toString(value);
} | [
"public",
"static",
"String",
"realToString",
"(",
"Package",
"pkg",
",",
"String",
"type",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"\"\"",
";",
"com",
".",
"centurylink",
".",
"mdw",
".",
"variable",
".",
"Va... | Serializes a runtime variable object to its string value. Documents are expanded.
@param pkg workflow package
@param type variable type
@param value object value
@return serialized string value | [
"Serializes",
"a",
"runtime",
"variable",
"object",
"to",
"its",
"string",
"value",
".",
"Documents",
"are",
"expanded",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java#L139-L147 | train |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java | VariableTranslator.realToObject | public static Object realToObject(Package pkg, String type, String value) {
if (StringHelper.isEmpty(value))
return null;
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
if (trans instanceof DocumentReferenceTranslator)
return ((DocumentReferenceTranslator)trans).realToObject(value);
else
return trans.toObject(value);
} | java | public static Object realToObject(Package pkg, String type, String value) {
if (StringHelper.isEmpty(value))
return null;
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
if (trans instanceof DocumentReferenceTranslator)
return ((DocumentReferenceTranslator)trans).realToObject(value);
else
return trans.toObject(value);
} | [
"public",
"static",
"Object",
"realToObject",
"(",
"Package",
"pkg",
",",
"String",
"type",
",",
"String",
"value",
")",
"{",
"if",
"(",
"StringHelper",
".",
"isEmpty",
"(",
"value",
")",
")",
"return",
"null",
";",
"com",
".",
"centurylink",
".",
"mdw",... | Deserializes variable string values to runtime objects.
@param pkg workflow package
@param type variable type
@param value string value
@return deserialized object | [
"Deserializes",
"variable",
"string",
"values",
"to",
"runtime",
"objects",
"."
] | 91167fe65a25a5d7022cdcf8b0fae8506f5b87ce | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java#L157-L165 | train |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java | CreateXAnnotations.createId | public XAnnotation<javax.persistence.Id> createId(Boolean source) {
return source == null ? null : createId(source.booleanValue());
} | java | public XAnnotation<javax.persistence.Id> createId(Boolean source) {
return source == null ? null : createId(source.booleanValue());
} | [
"public",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".",
"Id",
">",
"createId",
"(",
"Boolean",
"source",
")",
"{",
"return",
"source",
"==",
"null",
"?",
"null",
":",
"createId",
"(",
"source",
".",
"booleanValue",
"(",
")",
")",
";",
"}"
] | 9.1.8 | [
"9",
".",
"1",
".",
"8"
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java#L49-L51 | train |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java | CreateXAnnotations.createOneToOne | public XAnnotation<javax.persistence.OneToOne> createOneToOne(
OneToOne cOneToOne) {
return cOneToOne == null ? null :
//
new XAnnotation<javax.persistence.OneToOne>(
javax.persistence.OneToOne.class,
//
cOneToOne.getTargetEntity() == null ? null :
new XSingleAnnotationField<Class<Object>>(
"targetEntity", Class.class,
new XClassByNameAnnotationValue<Object>(
cOneToOne.getTargetEntity())),
//
AnnotationUtils.create("cascade",
getCascadeType(cOneToOne.getCascade())),
//
AnnotationUtils.create("fetch",
getFetchType(cOneToOne.getFetch())),
//
AnnotationUtils.create("optional",
cOneToOne.isOptional()),
//
AnnotationUtils.create("mappedBy",
cOneToOne.getMappedBy()),
//
AnnotationUtils.create("orphanRemoval",
cOneToOne.isOrphanRemoval())
//
);
} | java | public XAnnotation<javax.persistence.OneToOne> createOneToOne(
OneToOne cOneToOne) {
return cOneToOne == null ? null :
//
new XAnnotation<javax.persistence.OneToOne>(
javax.persistence.OneToOne.class,
//
cOneToOne.getTargetEntity() == null ? null :
new XSingleAnnotationField<Class<Object>>(
"targetEntity", Class.class,
new XClassByNameAnnotationValue<Object>(
cOneToOne.getTargetEntity())),
//
AnnotationUtils.create("cascade",
getCascadeType(cOneToOne.getCascade())),
//
AnnotationUtils.create("fetch",
getFetchType(cOneToOne.getFetch())),
//
AnnotationUtils.create("optional",
cOneToOne.isOptional()),
//
AnnotationUtils.create("mappedBy",
cOneToOne.getMappedBy()),
//
AnnotationUtils.create("orphanRemoval",
cOneToOne.isOrphanRemoval())
//
);
} | [
"public",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".",
"OneToOne",
">",
"createOneToOne",
"(",
"OneToOne",
"cOneToOne",
")",
"{",
"return",
"cOneToOne",
"==",
"null",
"?",
"null",
":",
"//",
"new",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".... | 9.1.23 | [
"9",
".",
"1",
".",
"23"
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java#L220-L250 | train |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java | CreateXAnnotations.createNamedQuery | public XAnnotation<javax.persistence.NamedQuery> createNamedQuery(
NamedQuery source) {
return source == null ? null :
//
new XAnnotation<javax.persistence.NamedQuery>(
javax.persistence.NamedQuery.class,
//
AnnotationUtils.create("query", source.getQuery()),
//
AnnotationUtils.create("hints",
createQueryHint(source.getHint()),
QueryHint.class),
//
AnnotationUtils.create("name", source.getName()),
AnnotationUtils.create("lockMode",
createLockMode(source.getLockMode()))
//
);
} | java | public XAnnotation<javax.persistence.NamedQuery> createNamedQuery(
NamedQuery source) {
return source == null ? null :
//
new XAnnotation<javax.persistence.NamedQuery>(
javax.persistence.NamedQuery.class,
//
AnnotationUtils.create("query", source.getQuery()),
//
AnnotationUtils.create("hints",
createQueryHint(source.getHint()),
QueryHint.class),
//
AnnotationUtils.create("name", source.getName()),
AnnotationUtils.create("lockMode",
createLockMode(source.getLockMode()))
//
);
} | [
"public",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".",
"NamedQuery",
">",
"createNamedQuery",
"(",
"NamedQuery",
"source",
")",
"{",
"return",
"source",
"==",
"null",
"?",
"null",
":",
"//",
"new",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".... | 8.3.1 | [
"8",
".",
"3",
".",
"1"
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java#L312-L332 | train |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java | CreateXAnnotations.createAssociationOverride | public XAnnotation<javax.persistence.AssociationOverride> createAssociationOverride(
AssociationOverride source) {
return source == null ? null :
//
new XAnnotation<javax.persistence.AssociationOverride>(
javax.persistence.AssociationOverride.class,
//
AnnotationUtils.create("name", source.getName()),
//
AnnotationUtils.create("joinColumns",
createJoinColumn(source.getJoinColumn()),
JoinColumn.class),
//
AnnotationUtils.create("joinTable",
createJoinTable(source.getJoinTable()))
//
);
} | java | public XAnnotation<javax.persistence.AssociationOverride> createAssociationOverride(
AssociationOverride source) {
return source == null ? null :
//
new XAnnotation<javax.persistence.AssociationOverride>(
javax.persistence.AssociationOverride.class,
//
AnnotationUtils.create("name", source.getName()),
//
AnnotationUtils.create("joinColumns",
createJoinColumn(source.getJoinColumn()),
JoinColumn.class),
//
AnnotationUtils.create("joinTable",
createJoinTable(source.getJoinTable()))
//
);
} | [
"public",
"XAnnotation",
"<",
"javax",
".",
"persistence",
".",
"AssociationOverride",
">",
"createAssociationOverride",
"(",
"AssociationOverride",
"source",
")",
"{",
"return",
"source",
"==",
"null",
"?",
"null",
":",
"//",
"new",
"XAnnotation",
"<",
"javax",
... | 9.1.12 | [
"9",
".",
"1",
".",
"12"
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/ejb/jpa2/strategy/annotate/CreateXAnnotations.java#L618-L636 | train |
highsource/hyperjaxb3 | ejb/runtime/src/main/java/org/jvnet/hyperjaxb3/xml/bind/annotation/adapters/AbstractXMLGregorianCalendarAdapter.java | AbstractXMLGregorianCalendarAdapter.setDay | public void setDay(Calendar source, XMLGregorianCalendar target) {
target.setDay(source.get(Calendar.DAY_OF_MONTH));
} | java | public void setDay(Calendar source, XMLGregorianCalendar target) {
target.setDay(source.get(Calendar.DAY_OF_MONTH));
} | [
"public",
"void",
"setDay",
"(",
"Calendar",
"source",
",",
"XMLGregorianCalendar",
"target",
")",
"{",
"target",
".",
"setDay",
"(",
"source",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_MONTH",
")",
")",
";",
"}"
] | target); | [
"target",
")",
";"
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/runtime/src/main/java/org/jvnet/hyperjaxb3/xml/bind/annotation/adapters/AbstractXMLGregorianCalendarAdapter.java#L47-L49 | train |
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/xjc/reader/TypeUtil.java | TypeUtil.getCommonBaseType | public static JType getCommonBaseType( JCodeModel codeModel, Collection<? extends JType> types ) {
return getCommonBaseType( codeModel, types.toArray(new JType[types.size()]) );
} | java | public static JType getCommonBaseType( JCodeModel codeModel, Collection<? extends JType> types ) {
return getCommonBaseType( codeModel, types.toArray(new JType[types.size()]) );
} | [
"public",
"static",
"JType",
"getCommonBaseType",
"(",
"JCodeModel",
"codeModel",
",",
"Collection",
"<",
"?",
"extends",
"JType",
">",
"types",
")",
"{",
"return",
"getCommonBaseType",
"(",
"codeModel",
",",
"types",
".",
"toArray",
"(",
"new",
"JType",
"[",
... | Computes the common base type of two types.
@param types
set of {@link JType} objects. | [
"Computes",
"the",
"common",
"base",
"type",
"of",
"two",
"types",
"."
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/xjc/reader/TypeUtil.java#L51-L53 | train |
highsource/hyperjaxb3 | maven/plugin/src/main/java/org/jvnet/hyperjaxb3/maven2/Hyperjaxb3Mojo.java | Hyperjaxb3Mojo.setupLogging | protected void setupLogging() {
super.setupLogging();
final Logger rootLogger = LogManager.getRootLogger();
rootLogger.addAppender(new NullAppender());
final Logger logger = LogManager.getLogger("org.jvnet.hyperjaxb3");
final Log log = getLog();
logger.addAppender(new Appender(getLog(), new PatternLayout(
"%m%n %c%n")));
if (this.getDebug()) {
log.debug("Logger level set to [debug].");
logger.setLevel(Level.DEBUG);
} else if (this.getVerbose())
logger.setLevel(Level.INFO);
else if (log.isWarnEnabled())
logger.setLevel(Level.WARN);
else
logger.setLevel(Level.ERROR);
} | java | protected void setupLogging() {
super.setupLogging();
final Logger rootLogger = LogManager.getRootLogger();
rootLogger.addAppender(new NullAppender());
final Logger logger = LogManager.getLogger("org.jvnet.hyperjaxb3");
final Log log = getLog();
logger.addAppender(new Appender(getLog(), new PatternLayout(
"%m%n %c%n")));
if (this.getDebug()) {
log.debug("Logger level set to [debug].");
logger.setLevel(Level.DEBUG);
} else if (this.getVerbose())
logger.setLevel(Level.INFO);
else if (log.isWarnEnabled())
logger.setLevel(Level.WARN);
else
logger.setLevel(Level.ERROR);
} | [
"protected",
"void",
"setupLogging",
"(",
")",
"{",
"super",
".",
"setupLogging",
"(",
")",
";",
"final",
"Logger",
"rootLogger",
"=",
"LogManager",
".",
"getRootLogger",
"(",
")",
";",
"rootLogger",
".",
"addAppender",
"(",
"new",
"NullAppender",
"(",
")",
... | Sets up the verbose and debug mode depending on mvn logging level, and
sets up hyperjaxb logging. | [
"Sets",
"up",
"the",
"verbose",
"and",
"debug",
"mode",
"depending",
"on",
"mvn",
"logging",
"level",
"and",
"sets",
"up",
"hyperjaxb",
"logging",
"."
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/maven/plugin/src/main/java/org/jvnet/hyperjaxb3/maven2/Hyperjaxb3Mojo.java#L135-L155 | train |
highsource/hyperjaxb3 | maven/plugin/src/main/java/org/jvnet/hyperjaxb3/maven2/Hyperjaxb3Mojo.java | Hyperjaxb3Mojo.logConfiguration | protected void logConfiguration() throws MojoExecutionException {
super.logConfiguration();
getLog().info("target:" + target);
getLog().info("roundtripTestClassName:" + roundtripTestClassName);
getLog().info("resourceIncludes:" + resourceIncludes);
getLog().info("variant:" + variant);
getLog().info("persistenceUnitName:" + persistenceUnitName);
getLog().info("persistenceXml:" + persistenceXml);
getLog().info("generateHashCode:" + generateHashCode);
getLog().info("generateEquals:" + generateEquals);
getLog().info("generateTransientId:" + generateTransientId);
getLog().info("result:" + result);
getLog().info("preArgs:" + Arrays.toString(preArgs));
getLog().info("postArgs:" + Arrays.toString(postArgs));
try {
getLog().info(
"XJC loaded from:"
+ Options.class.getResource("Options.class")
.toURI().toURL().toExternalForm());
} catch (IOException ignored) {
} catch (URISyntaxException ignored) {
}
} | java | protected void logConfiguration() throws MojoExecutionException {
super.logConfiguration();
getLog().info("target:" + target);
getLog().info("roundtripTestClassName:" + roundtripTestClassName);
getLog().info("resourceIncludes:" + resourceIncludes);
getLog().info("variant:" + variant);
getLog().info("persistenceUnitName:" + persistenceUnitName);
getLog().info("persistenceXml:" + persistenceXml);
getLog().info("generateHashCode:" + generateHashCode);
getLog().info("generateEquals:" + generateEquals);
getLog().info("generateTransientId:" + generateTransientId);
getLog().info("result:" + result);
getLog().info("preArgs:" + Arrays.toString(preArgs));
getLog().info("postArgs:" + Arrays.toString(postArgs));
try {
getLog().info(
"XJC loaded from:"
+ Options.class.getResource("Options.class")
.toURI().toURL().toExternalForm());
} catch (IOException ignored) {
} catch (URISyntaxException ignored) {
}
} | [
"protected",
"void",
"logConfiguration",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"super",
".",
"logConfiguration",
"(",
")",
";",
"getLog",
"(",
")",
".",
"info",
"(",
"\"target:\"",
"+",
"target",
")",
";",
"getLog",
"(",
")",
".",
"info",
"(",... | Logs options defined directly as mojo parameters. | [
"Logs",
"options",
"defined",
"directly",
"as",
"mojo",
"parameters",
"."
] | c645d1628b8c26a844858d221fc9affe9c18543e | https://github.com/highsource/hyperjaxb3/blob/c645d1628b8c26a844858d221fc9affe9c18543e/maven/plugin/src/main/java/org/jvnet/hyperjaxb3/maven2/Hyperjaxb3Mojo.java#L160-L184 | train |
braintree/browser-switch-android | browser-switch/src/main/java/com/braintreepayments/browserswitch/ChromeCustomTabs.java | ChromeCustomTabs.isAvailable | public static boolean isAvailable(Context context) {
if (SDK_INT < JELLY_BEAN_MR2) {
return false;
}
Intent serviceIntent = new Intent("android.support.customtabs.action.CustomTabsService")
.setPackage("com.android.chrome");
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
boolean available = context.bindService(serviceIntent, connection,
Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY);
context.unbindService(connection);
return available;
} | java | public static boolean isAvailable(Context context) {
if (SDK_INT < JELLY_BEAN_MR2) {
return false;
}
Intent serviceIntent = new Intent("android.support.customtabs.action.CustomTabsService")
.setPackage("com.android.chrome");
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
boolean available = context.bindService(serviceIntent, connection,
Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY);
context.unbindService(connection);
return available;
} | [
"public",
"static",
"boolean",
"isAvailable",
"(",
"Context",
"context",
")",
"{",
"if",
"(",
"SDK_INT",
"<",
"JELLY_BEAN_MR2",
")",
"{",
"return",
"false",
";",
"}",
"Intent",
"serviceIntent",
"=",
"new",
"Intent",
"(",
"\"android.support.customtabs.action.Custom... | Checks to see if this device supports Chrome Custom Tabs and if Chrome Custom Tabs are available.
@param context
@return {@code true} if Chrome Custom Tabs are supported and available. | [
"Checks",
"to",
"see",
"if",
"this",
"device",
"supports",
"Chrome",
"Custom",
"Tabs",
"and",
"if",
"Chrome",
"Custom",
"Tabs",
"are",
"available",
"."
] | d830de21bc732b51e658e7296aad7b9037842a19 | https://github.com/braintree/browser-switch-android/blob/d830de21bc732b51e658e7296aad7b9037842a19/browser-switch/src/main/java/com/braintreepayments/browserswitch/ChromeCustomTabs.java#L24-L44 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/DatabaseContentReader.java | DatabaseContentReader.parseMetadata | private String parseMetadata(DocumentMetadata metadata) throws IOException {
ResultItem item = result.next();
String uri = item.asString();
if (uri == null) {
throw new IOException("Missing document URI for metadata.");
}
item = result.next();
//node-kind, must exist
String nKind = item.asString();
metadata.setFormat(nKind);
item = result.next();
// handle collections, may not be present
while (item != null && item.getItemType() == ValueType.XS_STRING) {
if (!copyCollection) {
item = result.next();
continue;
}
metadata.addCollection(item.asString());
item = result.next();
}
// handle permissions, may not be present
StringBuilder buf = new StringBuilder();
buf.append("<perms>");
while (item != null && ValueType.ELEMENT == item.getItemType()) {
if (!copyPermission) {
item = result.next();
continue;
}
try {
readPermission((XdmElement) item.getItem(), metadata, buf);
} catch (Exception e) {
throw new IOException(e);
}
item = result.next();
}
buf.append("</perms>");
metadata.setPermString(buf.toString());
// handle quality, always present even if not requested (barrier)
metadata.setQuality((XSInteger) item.getItem());
// handle metadata
item = result.next();
if (copyMetadata) {
XdmItem metaItem = item.getItem();
if (metaItem instanceof JsonItem) {
JsonNode node = ((JsonItem)metaItem).asJsonNode();
metadata.meta = new HashMap<String, String>(node.size());
for (Iterator<String> names = node.fieldNames();
names.hasNext();) {
String key = names.next();
JsonNode nodeVal = node.get(key);
metadata.meta.put(key, nodeVal.asText());
}
item = result.next();
}
}
// handle prop:properties node, optional
// if not present, there will be a 0 as a marker
if (copyProperties && ValueType.ELEMENT == item.getItemType()) {
String pString = item.asString();
if (pString != null) {
metadata.setProperties(pString);
}
item = result.next();
}
if (ValueType.XS_INTEGER != item.getItemType()) {
throw new IOException(uri + " unexpected " + item.getItemType() + " "
+ item.asString() + ", expected " + ValueType.XS_INTEGER
+ " 0");
}
return uri;
} | java | private String parseMetadata(DocumentMetadata metadata) throws IOException {
ResultItem item = result.next();
String uri = item.asString();
if (uri == null) {
throw new IOException("Missing document URI for metadata.");
}
item = result.next();
//node-kind, must exist
String nKind = item.asString();
metadata.setFormat(nKind);
item = result.next();
// handle collections, may not be present
while (item != null && item.getItemType() == ValueType.XS_STRING) {
if (!copyCollection) {
item = result.next();
continue;
}
metadata.addCollection(item.asString());
item = result.next();
}
// handle permissions, may not be present
StringBuilder buf = new StringBuilder();
buf.append("<perms>");
while (item != null && ValueType.ELEMENT == item.getItemType()) {
if (!copyPermission) {
item = result.next();
continue;
}
try {
readPermission((XdmElement) item.getItem(), metadata, buf);
} catch (Exception e) {
throw new IOException(e);
}
item = result.next();
}
buf.append("</perms>");
metadata.setPermString(buf.toString());
// handle quality, always present even if not requested (barrier)
metadata.setQuality((XSInteger) item.getItem());
// handle metadata
item = result.next();
if (copyMetadata) {
XdmItem metaItem = item.getItem();
if (metaItem instanceof JsonItem) {
JsonNode node = ((JsonItem)metaItem).asJsonNode();
metadata.meta = new HashMap<String, String>(node.size());
for (Iterator<String> names = node.fieldNames();
names.hasNext();) {
String key = names.next();
JsonNode nodeVal = node.get(key);
metadata.meta.put(key, nodeVal.asText());
}
item = result.next();
}
}
// handle prop:properties node, optional
// if not present, there will be a 0 as a marker
if (copyProperties && ValueType.ELEMENT == item.getItemType()) {
String pString = item.asString();
if (pString != null) {
metadata.setProperties(pString);
}
item = result.next();
}
if (ValueType.XS_INTEGER != item.getItemType()) {
throw new IOException(uri + " unexpected " + item.getItemType() + " "
+ item.asString() + ", expected " + ValueType.XS_INTEGER
+ " 0");
}
return uri;
} | [
"private",
"String",
"parseMetadata",
"(",
"DocumentMetadata",
"metadata",
")",
"throws",
"IOException",
"{",
"ResultItem",
"item",
"=",
"result",
".",
"next",
"(",
")",
";",
"String",
"uri",
"=",
"item",
".",
"asString",
"(",
")",
";",
"if",
"(",
"uri",
... | Parse metadata from the sequence, store it into the DocumentMetadata
object passed in
@param metadata
@return uri of the document with this metadata
@throws IOException | [
"Parse",
"metadata",
"from",
"the",
"sequence",
"store",
"it",
"into",
"the",
"DocumentMetadata",
"object",
"passed",
"in"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/DatabaseContentReader.java#L431-L507 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/dom/DocumentImpl.java | DocumentImpl.getDocumentType | private int getDocumentType() {
NodeList children = getChildNodes();
int elemCount = 0;
for (int i = 0; i < children.getLength(); i++) {
Node n = children.item(i);
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
elemCount++;
break;
case Node.PROCESSING_INSTRUCTION_NODE:
case Node.COMMENT_NODE:
continue;
default:
return NON_XML;
}
}
return elemCount <= 1 ? VALID_XML : NON_XML;
} | java | private int getDocumentType() {
NodeList children = getChildNodes();
int elemCount = 0;
for (int i = 0; i < children.getLength(); i++) {
Node n = children.item(i);
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
elemCount++;
break;
case Node.PROCESSING_INSTRUCTION_NODE:
case Node.COMMENT_NODE:
continue;
default:
return NON_XML;
}
}
return elemCount <= 1 ? VALID_XML : NON_XML;
} | [
"private",
"int",
"getDocumentType",
"(",
")",
"{",
"NodeList",
"children",
"=",
"getChildNodes",
"(",
")",
";",
"int",
"elemCount",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"getLength",
"(",
")",
";",
"i",
"... | Check root node of a document to see if it conform to DOM Structure
Model. The root node can only be ELEMENT_NODE,
PROCESSING_INSTRUCTION_NODE or COMMENT_NODE.
@return 1(NON_XML) if root node violates DOM Structure Model; otherwise
0(VALID_XML). | [
"Check",
"root",
"node",
"of",
"a",
"document",
"to",
"see",
"if",
"it",
"conform",
"to",
"DOM",
"Structure",
"Model",
".",
"The",
"root",
"node",
"can",
"only",
"be",
"ELEMENT_NODE",
"PROCESSING_INSTRUCTION_NODE",
"or",
"COMMENT_NODE",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/dom/DocumentImpl.java#L139-L156 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/utilities/PermissionUtil.java | PermissionUtil.getPermissions | public static List<ContentPermission> getPermissions(String[] perms) {
List<ContentPermission> permissions = null;
if (perms != null && perms.length > 0) {
int i = 0;
while (i + 1 < perms.length) {
String roleName = perms[i++];
if (roleName == null || roleName.isEmpty()) {
LOG.error("Illegal role name: " + roleName);
continue;
}
String perm = perms[i].trim();
ContentCapability capability = getCapbility(perm);
if (capability != null) {
if (permissions == null) {
permissions = new ArrayList<ContentPermission>();
}
permissions
.add(new ContentPermission(capability, roleName));
}
i++;
}
}
return permissions;
} | java | public static List<ContentPermission> getPermissions(String[] perms) {
List<ContentPermission> permissions = null;
if (perms != null && perms.length > 0) {
int i = 0;
while (i + 1 < perms.length) {
String roleName = perms[i++];
if (roleName == null || roleName.isEmpty()) {
LOG.error("Illegal role name: " + roleName);
continue;
}
String perm = perms[i].trim();
ContentCapability capability = getCapbility(perm);
if (capability != null) {
if (permissions == null) {
permissions = new ArrayList<ContentPermission>();
}
permissions
.add(new ContentPermission(capability, roleName));
}
i++;
}
}
return permissions;
} | [
"public",
"static",
"List",
"<",
"ContentPermission",
">",
"getPermissions",
"(",
"String",
"[",
"]",
"perms",
")",
"{",
"List",
"<",
"ContentPermission",
">",
"permissions",
"=",
"null",
";",
"if",
"(",
"perms",
"!=",
"null",
"&&",
"perms",
".",
"length",... | Get a list of ContentPermission from given string
@param perms a string of role-name,capability pais, separated by commna
@return | [
"Get",
"a",
"list",
"of",
"ContentPermission",
"from",
"given",
"string"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/utilities/PermissionUtil.java#L50-L73 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/utilities/XMLUtil.java | XMLUtil.getValidName | public static String getValidName(String name) {
StringBuilder validname = new StringBuilder();
char ch = name.charAt(0);
if (!XML11Char.isXML11NameStart(ch)) {
LOG.warn("Prepend _ to " + name);
validname.append("_");
}
for (int i = 0; i < name.length(); i++) {
ch = name.charAt(i);
if (!XML11Char.isXML11Name(ch)) {
LOG.warn("Character " + ch + " in " + name
+ " is converted to _");
validname.append("_");
} else {
validname.append(ch);
}
}
return validname.toString();
} | java | public static String getValidName(String name) {
StringBuilder validname = new StringBuilder();
char ch = name.charAt(0);
if (!XML11Char.isXML11NameStart(ch)) {
LOG.warn("Prepend _ to " + name);
validname.append("_");
}
for (int i = 0; i < name.length(); i++) {
ch = name.charAt(i);
if (!XML11Char.isXML11Name(ch)) {
LOG.warn("Character " + ch + " in " + name
+ " is converted to _");
validname.append("_");
} else {
validname.append(ch);
}
}
return validname.toString();
} | [
"public",
"static",
"String",
"getValidName",
"(",
"String",
"name",
")",
"{",
"StringBuilder",
"validname",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"char",
"ch",
"=",
"name",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"!",
"XML11Char",
".",
"is... | Get valid element name from a given string
@param name
@return | [
"Get",
"valid",
"element",
"name",
"from",
"a",
"given",
"string"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/utilities/XMLUtil.java#L30-L49 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/ContentWriter.java | ContentWriter.insertBatch | protected void insertBatch(Content[] batch, int id)
throws IOException {
retry = 0;
sleepTime = 500;
while (retry < maxRetries) {
try {
if (retry == 1) {
LOG.info("Retrying document insert");
}
List<RequestException> errors =
sessions[id].insertContentCollectErrors(batch);
if (errors != null) {
for (RequestException ex : errors) {
Throwable cause = ex.getCause();
if (cause != null) {
if (cause instanceof QueryException) {
LOG.error(
((QueryException)cause).getFormatString());
} else {
LOG.error(cause.getMessage());
}
}
if (ex instanceof ContentInsertException) {
Content content =
((ContentInsertException)ex).getContent();
DocumentURI failedUri =
pendingUris[id].remove(content);
failed++;
if (failedUri != null) {
LOG.warn("Failed document " + failedUri);
}
}
}
}
if (retry > 0) {
LOG.debug("Retry successful");
}
} catch (Exception e) {
boolean retryable = true;
if (e instanceof QueryException) {
LOG.error("QueryException:" + ((QueryException)e).getFormatString());
retryable = ((QueryException)e).isRetryable();
} else if (e instanceof RequestServerException) {
// log error and continue on RequestServerException
// not retryable so trying to connect to the replica
LOG.error("RequestServerException:" + e.getMessage());
} else {
LOG.error("Exception:" + e.getMessage());
}
// necessary to roll back in certain scenarios.
if (needCommit) {
rollback(id);
}
if (retryable && ++retry < maxRetries) {
// necessary to close the session too.
sessions[id].close();
try {
InternalUtilities.sleep(sleepTime);
} catch (Exception e2) {
}
sleepTime = sleepTime * 2;
if (sleepTime > maxSleepTime)
sleepTime = maxSleepTime;
// We need to switch host even for RetryableQueryException
// because it could be "sync replicating" (bug:45785)
sessions[id] = getSession(id, true);
continue;
} else if (retryable) {
LOG.info("Exceeded max retry");
}
failed += batch.length;
// remove the failed content from pendingUris
for (Content fc : batch) {
DocumentURI failedUri = pendingUris[id].remove(fc);
LOG.warn("Failed document " + failedUri);
}
throw new IOException(e);
}
break;
}
if (needCommit) {
// move uris from pending to commit
for (DocumentURI uri : pendingUris[id].values()) {
commitUris[id].add(uri);
}
} else {
succeeded += pendingUris[id].size();
}
pendingUris[id].clear();
} | java | protected void insertBatch(Content[] batch, int id)
throws IOException {
retry = 0;
sleepTime = 500;
while (retry < maxRetries) {
try {
if (retry == 1) {
LOG.info("Retrying document insert");
}
List<RequestException> errors =
sessions[id].insertContentCollectErrors(batch);
if (errors != null) {
for (RequestException ex : errors) {
Throwable cause = ex.getCause();
if (cause != null) {
if (cause instanceof QueryException) {
LOG.error(
((QueryException)cause).getFormatString());
} else {
LOG.error(cause.getMessage());
}
}
if (ex instanceof ContentInsertException) {
Content content =
((ContentInsertException)ex).getContent();
DocumentURI failedUri =
pendingUris[id].remove(content);
failed++;
if (failedUri != null) {
LOG.warn("Failed document " + failedUri);
}
}
}
}
if (retry > 0) {
LOG.debug("Retry successful");
}
} catch (Exception e) {
boolean retryable = true;
if (e instanceof QueryException) {
LOG.error("QueryException:" + ((QueryException)e).getFormatString());
retryable = ((QueryException)e).isRetryable();
} else if (e instanceof RequestServerException) {
// log error and continue on RequestServerException
// not retryable so trying to connect to the replica
LOG.error("RequestServerException:" + e.getMessage());
} else {
LOG.error("Exception:" + e.getMessage());
}
// necessary to roll back in certain scenarios.
if (needCommit) {
rollback(id);
}
if (retryable && ++retry < maxRetries) {
// necessary to close the session too.
sessions[id].close();
try {
InternalUtilities.sleep(sleepTime);
} catch (Exception e2) {
}
sleepTime = sleepTime * 2;
if (sleepTime > maxSleepTime)
sleepTime = maxSleepTime;
// We need to switch host even for RetryableQueryException
// because it could be "sync replicating" (bug:45785)
sessions[id] = getSession(id, true);
continue;
} else if (retryable) {
LOG.info("Exceeded max retry");
}
failed += batch.length;
// remove the failed content from pendingUris
for (Content fc : batch) {
DocumentURI failedUri = pendingUris[id].remove(fc);
LOG.warn("Failed document " + failedUri);
}
throw new IOException(e);
}
break;
}
if (needCommit) {
// move uris from pending to commit
for (DocumentURI uri : pendingUris[id].values()) {
commitUris[id].add(uri);
}
} else {
succeeded += pendingUris[id].size();
}
pendingUris[id].clear();
} | [
"protected",
"void",
"insertBatch",
"(",
"Content",
"[",
"]",
"batch",
",",
"int",
"id",
")",
"throws",
"IOException",
"{",
"retry",
"=",
"0",
";",
"sleepTime",
"=",
"500",
";",
"while",
"(",
"retry",
"<",
"maxRetries",
")",
"{",
"try",
"{",
"if",
"(... | Insert batch, log errors and update stats.
@param batch batch of content to insert
@param id forest Id | [
"Insert",
"batch",
"log",
"errors",
"and",
"update",
"stats",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/ContentWriter.java#L466-L559 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/dom/AttributeNodeMapImpl.java | AttributeNodeMapImpl.item | public Node item(int index) {
try {
return item(index, null);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
} | java | public Node item(int index) {
try {
return item(index, null);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
} | [
"public",
"Node",
"item",
"(",
"int",
"index",
")",
"{",
"try",
"{",
"return",
"item",
"(",
"index",
",",
"null",
")",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
... | Returns the indexth item in the map. If index is greater than or equal to
the number of nodes in this map, this returns null; if the item returned
is a namespace declaration, it is represented as an attribute whose owner
document is a document containing the attribute only. | [
"Returns",
"the",
"indexth",
"item",
"in",
"the",
"map",
".",
"If",
"index",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"number",
"of",
"nodes",
"in",
"this",
"map",
"this",
"returns",
"null",
";",
"if",
"the",
"item",
"returned",
"is",
"a",
... | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/dom/AttributeNodeMapImpl.java#L109-L115 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/dom/NodeImpl.java | NodeImpl.hasTextContent | private boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE
&& child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
} | java | private boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE
&& child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
} | [
"private",
"boolean",
"hasTextContent",
"(",
"Node",
"child",
")",
"{",
"return",
"child",
".",
"getNodeType",
"(",
")",
"!=",
"Node",
".",
"COMMENT_NODE",
"&&",
"child",
".",
"getNodeType",
"(",
")",
"!=",
"Node",
".",
"PROCESSING_INSTRUCTION_NODE",
";",
"}... | PROCESSING_INSTRUCTION_NODE nodes. | [
"PROCESSING_INSTRUCTION_NODE",
"nodes",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/dom/NodeImpl.java#L238-L241 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/dom/NodeImpl.java | NodeImpl.getTextContent | private void getTextContent(StringBuilder sb) throws DOMException {
NodeList children = getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (hasTextContent(child)) {
sb.append(child.getTextContent());
}
}
} | java | private void getTextContent(StringBuilder sb) throws DOMException {
NodeList children = getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (hasTextContent(child)) {
sb.append(child.getTextContent());
}
}
} | [
"private",
"void",
"getTextContent",
"(",
"StringBuilder",
"sb",
")",
"throws",
"DOMException",
"{",
"NodeList",
"children",
"=",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"getLength",
"(",
")",
";"... | internal method taking a StringBuffer in parameter | [
"internal",
"method",
"taking",
"a",
"StringBuffer",
"in",
"parameter"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/dom/NodeImpl.java#L254-L262 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/ImportRecordReader.java | ImportRecordReader.setKey | protected boolean setKey(String uri, int line, int col, boolean encode) {
if (key == null) {
key = new DocumentURIWithSourceInfo(uri, srcId);
}
// apply prefix, suffix and replace for URI
if (uri != null && !uri.isEmpty()) {
uri = URIUtil.applyUriReplace(uri, conf);
key.setSkipReason("");
if (encode) {
try {
URI uriObj = new URI(null, null, null, 0, uri, null, null);
uri = uriObj.toString();
} catch (URISyntaxException e) {
uri = null;
key.setSkipReason(e.getMessage());
}
}
uri = URIUtil.applyPrefixSuffix(uri, conf);
} else {
key.setSkipReason("empty uri value");
}
key.setUri(uri);
key.setSrcId(srcId);
key.setSubId(subId);
key.setColNumber(col);
key.setLineNumber(line);
if (LOG.isTraceEnabled()) {
LOG.trace("Set key: " + key);
}
return key.isSkip();
} | java | protected boolean setKey(String uri, int line, int col, boolean encode) {
if (key == null) {
key = new DocumentURIWithSourceInfo(uri, srcId);
}
// apply prefix, suffix and replace for URI
if (uri != null && !uri.isEmpty()) {
uri = URIUtil.applyUriReplace(uri, conf);
key.setSkipReason("");
if (encode) {
try {
URI uriObj = new URI(null, null, null, 0, uri, null, null);
uri = uriObj.toString();
} catch (URISyntaxException e) {
uri = null;
key.setSkipReason(e.getMessage());
}
}
uri = URIUtil.applyPrefixSuffix(uri, conf);
} else {
key.setSkipReason("empty uri value");
}
key.setUri(uri);
key.setSrcId(srcId);
key.setSubId(subId);
key.setColNumber(col);
key.setLineNumber(line);
if (LOG.isTraceEnabled()) {
LOG.trace("Set key: " + key);
}
return key.isSkip();
} | [
"protected",
"boolean",
"setKey",
"(",
"String",
"uri",
",",
"int",
"line",
",",
"int",
"col",
",",
"boolean",
"encode",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"key",
"=",
"new",
"DocumentURIWithSourceInfo",
"(",
"uri",
",",
"srcId",
")",
... | Apply URI replace option, encode URI if specified, apply URI prefix and
suffix configuration options and set the result as DocumentURI key.
@param uri Source string of document URI.
@param line Line number in the source if applicable; 0 otherwise.
@param col Column number in the source if applicable; 0 otherwise.
@param encode Encode uri if set to true.
@return true if key indicates the record is to be skipped; false
otherwise. | [
"Apply",
"URI",
"replace",
"option",
"encode",
"URI",
"if",
"specified",
"apply",
"URI",
"prefix",
"and",
"suffix",
"configuration",
"options",
"and",
"set",
"the",
"result",
"as",
"DocumentURI",
"key",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/ImportRecordReader.java#L75-L106 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/ContentPump.java | ContentPump.setClassLoader | private static void setClassLoader(File hdConfDir, Configuration conf)
throws Exception {
ClassLoader parent = conf.getClassLoader();
URL url = hdConfDir.toURI().toURL();
URL[] urls = new URL[1];
urls[0] = url;
ClassLoader classLoader = new URLClassLoader(urls, parent);
Thread.currentThread().setContextClassLoader(classLoader);
conf.setClassLoader(classLoader);
} | java | private static void setClassLoader(File hdConfDir, Configuration conf)
throws Exception {
ClassLoader parent = conf.getClassLoader();
URL url = hdConfDir.toURI().toURL();
URL[] urls = new URL[1];
urls[0] = url;
ClassLoader classLoader = new URLClassLoader(urls, parent);
Thread.currentThread().setContextClassLoader(classLoader);
conf.setClassLoader(classLoader);
} | [
"private",
"static",
"void",
"setClassLoader",
"(",
"File",
"hdConfDir",
",",
"Configuration",
"conf",
")",
"throws",
"Exception",
"{",
"ClassLoader",
"parent",
"=",
"conf",
".",
"getClassLoader",
"(",
")",
";",
"URL",
"url",
"=",
"hdConfDir",
".",
"toURI",
... | Set class loader for current thread and for Confifguration based on
Hadoop home.
@param hdConfDir Hadoop home directory
@param conf Hadoop configuration
@throws MalformedURLException | [
"Set",
"class",
"loader",
"for",
"current",
"thread",
"and",
"for",
"Confifguration",
"based",
"on",
"Hadoop",
"home",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/ContentPump.java#L261-L270 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.getInputContentSource | public static ContentSource getInputContentSource(Configuration conf)
throws URISyntaxException, XccConfigException, IOException {
String host = conf.getStrings(INPUT_HOST)[0];
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException(INPUT_HOST +
" is not specified.");
}
return getInputContentSource(conf, host);
} | java | public static ContentSource getInputContentSource(Configuration conf)
throws URISyntaxException, XccConfigException, IOException {
String host = conf.getStrings(INPUT_HOST)[0];
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException(INPUT_HOST +
" is not specified.");
}
return getInputContentSource(conf, host);
} | [
"public",
"static",
"ContentSource",
"getInputContentSource",
"(",
"Configuration",
"conf",
")",
"throws",
"URISyntaxException",
",",
"XccConfigException",
",",
"IOException",
"{",
"String",
"host",
"=",
"conf",
".",
"getStrings",
"(",
"INPUT_HOST",
")",
"[",
"0",
... | Get content source for input server.
@param conf job configuration.
@return ContentSource for input server.
@throws URISyntaxException
@throws XccConfigException
@throws IOException | [
"Get",
"content",
"source",
"for",
"input",
"server",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L94-L103 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.getInputContentSource | public static ContentSource getInputContentSource(Configuration conf,
String host)
throws XccConfigException, IOException {
String user = conf.get(INPUT_USERNAME, "");
String password = conf.get(INPUT_PASSWORD, "");
String port = conf.get(INPUT_PORT,"8000");
String db = conf.get(INPUT_DATABASE_NAME);
int portInt = Integer.parseInt(port);
boolean useSsl = conf.getBoolean(INPUT_USE_SSL, false);
if (useSsl) {
return getSecureContentSource(host, portInt, user, password,
db, getInputSslOptions(conf));
}
return ContentSourceFactory.newContentSource(host, portInt,
user, password, db);
} | java | public static ContentSource getInputContentSource(Configuration conf,
String host)
throws XccConfigException, IOException {
String user = conf.get(INPUT_USERNAME, "");
String password = conf.get(INPUT_PASSWORD, "");
String port = conf.get(INPUT_PORT,"8000");
String db = conf.get(INPUT_DATABASE_NAME);
int portInt = Integer.parseInt(port);
boolean useSsl = conf.getBoolean(INPUT_USE_SSL, false);
if (useSsl) {
return getSecureContentSource(host, portInt, user, password,
db, getInputSslOptions(conf));
}
return ContentSourceFactory.newContentSource(host, portInt,
user, password, db);
} | [
"public",
"static",
"ContentSource",
"getInputContentSource",
"(",
"Configuration",
"conf",
",",
"String",
"host",
")",
"throws",
"XccConfigException",
",",
"IOException",
"{",
"String",
"user",
"=",
"conf",
".",
"get",
"(",
"INPUT_USERNAME",
",",
"\"\"",
")",
"... | Get input content source.
@param conf job configuration
@param host host to connect to
@return content source
@throws IOException
@throws XccConfigException | [
"Get",
"input",
"content",
"source",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L114-L129 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.getOutputContentSource | public static ContentSource getOutputContentSource(Configuration conf,
String hostName)
throws XccConfigException, IOException {
String user = conf.get(OUTPUT_USERNAME, "");
String password = conf.get(OUTPUT_PASSWORD, "");
String port = conf.get(OUTPUT_PORT,"8000");
String db = conf.get(OUTPUT_DATABASE_NAME);
int portInt = Integer.parseInt(port);
boolean useSsl = conf.getBoolean(OUTPUT_USE_SSL, false);
if (useSsl) {
return getSecureContentSource(hostName, portInt, user, password,
db, getOutputSslOptions(conf));
}
return ContentSourceFactory.newContentSource(hostName, portInt,
user, password, db);
} | java | public static ContentSource getOutputContentSource(Configuration conf,
String hostName)
throws XccConfigException, IOException {
String user = conf.get(OUTPUT_USERNAME, "");
String password = conf.get(OUTPUT_PASSWORD, "");
String port = conf.get(OUTPUT_PORT,"8000");
String db = conf.get(OUTPUT_DATABASE_NAME);
int portInt = Integer.parseInt(port);
boolean useSsl = conf.getBoolean(OUTPUT_USE_SSL, false);
if (useSsl) {
return getSecureContentSource(hostName, portInt, user, password,
db, getOutputSslOptions(conf));
}
return ContentSourceFactory.newContentSource(hostName, portInt,
user, password, db);
} | [
"public",
"static",
"ContentSource",
"getOutputContentSource",
"(",
"Configuration",
"conf",
",",
"String",
"hostName",
")",
"throws",
"XccConfigException",
",",
"IOException",
"{",
"String",
"user",
"=",
"conf",
".",
"get",
"(",
"OUTPUT_USERNAME",
",",
"\"\"",
")... | Get output content source.
@param conf job configuration
@param hostName host name
@return content source
@throws IOException
@throws XccConfigException
@throws IOException | [
"Get",
"output",
"content",
"source",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L326-L341 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.getHost | public static String getHost(TextArrayWritable hosts) throws IOException {
String [] hostStrings = hosts.toStrings();
if(hostStrings == null || hostStrings.length==0)
throw new IOException("Number of forests is 0: "
+ "check forests in database");
int count = hostStrings.length;
int position = (int)(Math.random() * count);
return hostStrings[position];
} | java | public static String getHost(TextArrayWritable hosts) throws IOException {
String [] hostStrings = hosts.toStrings();
if(hostStrings == null || hostStrings.length==0)
throw new IOException("Number of forests is 0: "
+ "check forests in database");
int count = hostStrings.length;
int position = (int)(Math.random() * count);
return hostStrings[position];
} | [
"public",
"static",
"String",
"getHost",
"(",
"TextArrayWritable",
"hosts",
")",
"throws",
"IOException",
"{",
"String",
"[",
"]",
"hostStrings",
"=",
"hosts",
".",
"toStrings",
"(",
")",
";",
"if",
"(",
"hostStrings",
"==",
"null",
"||",
"hostStrings",
".",... | Return the host from the host array based on a random fashion
@param hosts a WritableArray of host names
@return the host name
@throws IOException | [
"Return",
"the",
"host",
"from",
"the",
"host",
"array",
"based",
"on",
"a",
"random",
"fashion"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L349-L357 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.newValue | public static XdmValue newValue(ValueType valueType, Object value) {
if (value instanceof Text) {
return ValueFactory.newValue(valueType, ((Text)value).toString());
} else if (value instanceof BytesWritable) {
return ValueFactory.newValue(valueType, ((BytesWritable)value).getBytes());
} else if (value instanceof IntWritable) {
return ValueFactory.newValue(valueType, ((IntWritable)value).get());
} else if (value instanceof LongWritable) {
return ValueFactory.newValue(valueType, ((LongWritable)value).get());
} else if (value instanceof VIntWritable) {
return ValueFactory.newValue(valueType, ((VIntWritable)value).get());
} else if (value instanceof VLongWritable) {
return ValueFactory.newValue(valueType, ((VLongWritable)value).get());
} else if (value instanceof BooleanWritable) {
return ValueFactory.newValue(valueType, ((BooleanWritable)value).get());
} else if (value instanceof FloatWritable) {
return ValueFactory.newValue(valueType, ((FloatWritable)value).get());
} else if (value instanceof DoubleWritable) {
return ValueFactory.newValue(valueType, ((DoubleWritable)value).get());
} else if (value instanceof MarkLogicNode) {
return ValueFactory.newValue(valueType, ((MarkLogicNode)value).get());
} else {
throw new UnsupportedOperationException("Value " +
value.getClass().getName() + " is unsupported.");
}
} | java | public static XdmValue newValue(ValueType valueType, Object value) {
if (value instanceof Text) {
return ValueFactory.newValue(valueType, ((Text)value).toString());
} else if (value instanceof BytesWritable) {
return ValueFactory.newValue(valueType, ((BytesWritable)value).getBytes());
} else if (value instanceof IntWritable) {
return ValueFactory.newValue(valueType, ((IntWritable)value).get());
} else if (value instanceof LongWritable) {
return ValueFactory.newValue(valueType, ((LongWritable)value).get());
} else if (value instanceof VIntWritable) {
return ValueFactory.newValue(valueType, ((VIntWritable)value).get());
} else if (value instanceof VLongWritable) {
return ValueFactory.newValue(valueType, ((VLongWritable)value).get());
} else if (value instanceof BooleanWritable) {
return ValueFactory.newValue(valueType, ((BooleanWritable)value).get());
} else if (value instanceof FloatWritable) {
return ValueFactory.newValue(valueType, ((FloatWritable)value).get());
} else if (value instanceof DoubleWritable) {
return ValueFactory.newValue(valueType, ((DoubleWritable)value).get());
} else if (value instanceof MarkLogicNode) {
return ValueFactory.newValue(valueType, ((MarkLogicNode)value).get());
} else {
throw new UnsupportedOperationException("Value " +
value.getClass().getName() + " is unsupported.");
}
} | [
"public",
"static",
"XdmValue",
"newValue",
"(",
"ValueType",
"valueType",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Text",
")",
"{",
"return",
"ValueFactory",
".",
"newValue",
"(",
"valueType",
",",
"(",
"(",
"Text",
")",
"value... | Create new XdmValue from value type and Writables. | [
"Create",
"new",
"XdmValue",
"from",
"value",
"type",
"and",
"Writables",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L363-L388 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.getUriWithOutputDir | public static String getUriWithOutputDir(DocumentURI key, String outputDir){
String uri = key.getUri();
if (outputDir != null && !outputDir.isEmpty()) {
uri = outputDir.endsWith("/") || uri.startsWith("/") ?
outputDir + uri : outputDir + '/' + uri;
key.setUri(uri);
key.validate();
}
return uri;
} | java | public static String getUriWithOutputDir(DocumentURI key, String outputDir){
String uri = key.getUri();
if (outputDir != null && !outputDir.isEmpty()) {
uri = outputDir.endsWith("/") || uri.startsWith("/") ?
outputDir + uri : outputDir + '/' + uri;
key.setUri(uri);
key.validate();
}
return uri;
} | [
"public",
"static",
"String",
"getUriWithOutputDir",
"(",
"DocumentURI",
"key",
",",
"String",
"outputDir",
")",
"{",
"String",
"uri",
"=",
"key",
".",
"getUri",
"(",
")",
";",
"if",
"(",
"outputDir",
"!=",
"null",
"&&",
"!",
"outputDir",
".",
"isEmpty",
... | If outputDir is available and valid, modify DocumentURI, and return uri
in string
@param key
@param outputDir
@return URI | [
"If",
"outputDir",
"is",
"available",
"and",
"valid",
"modify",
"DocumentURI",
"and",
"return",
"uri",
"in",
"string"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L424-L433 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java | InternalUtilities.sleep | public static void sleep(long millis) throws InterruptedException {
while (millis > 0) {
// abort if the user kills mlcp in local mode
String shutdown = System.getProperty("mlcp.shutdown");
if (shutdown != null) {
break;
}
if (millis > 1000) {
Thread.sleep(1000);
millis -= 1000;
} else {
Thread.sleep(millis);
millis = 0;
}
}
} | java | public static void sleep(long millis) throws InterruptedException {
while (millis > 0) {
// abort if the user kills mlcp in local mode
String shutdown = System.getProperty("mlcp.shutdown");
if (shutdown != null) {
break;
}
if (millis > 1000) {
Thread.sleep(1000);
millis -= 1000;
} else {
Thread.sleep(millis);
millis = 0;
}
}
} | [
"public",
"static",
"void",
"sleep",
"(",
"long",
"millis",
")",
"throws",
"InterruptedException",
"{",
"while",
"(",
"millis",
">",
"0",
")",
"{",
"// abort if the user kills mlcp in local mode",
"String",
"shutdown",
"=",
"System",
".",
"getProperty",
"(",
"\"ml... | Wake up every 1 second to check whether to abort
@param millis
@throws InterruptedException | [
"Wake",
"up",
"every",
"1",
"second",
"to",
"check",
"whether",
"to",
"abort"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/InternalUtilities.java#L462-L477 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/StatisticalAssignmentPolicy.java | StatisticalAssignmentPolicy.updateStats | public void updateStats(int fIdx, long count) {
synchronized (pq) {
frmtCount[fIdx] += count;
Stats tmp = new Stats(fIdx, frmtCount[fIdx]);
// remove the stats object with the same fIdx
pq.remove(tmp);
pq.offer(tmp);
}
if (LOG.isTraceEnabled()) {
LOG.trace("update forest " + fIdx);
}
} | java | public void updateStats(int fIdx, long count) {
synchronized (pq) {
frmtCount[fIdx] += count;
Stats tmp = new Stats(fIdx, frmtCount[fIdx]);
// remove the stats object with the same fIdx
pq.remove(tmp);
pq.offer(tmp);
}
if (LOG.isTraceEnabled()) {
LOG.trace("update forest " + fIdx);
}
} | [
"public",
"void",
"updateStats",
"(",
"int",
"fIdx",
",",
"long",
"count",
")",
"{",
"synchronized",
"(",
"pq",
")",
"{",
"frmtCount",
"[",
"fIdx",
"]",
"+=",
"count",
";",
"Stats",
"tmp",
"=",
"new",
"Stats",
"(",
"fIdx",
",",
"frmtCount",
"[",
"fId... | add count to forest with index fIdx, which may not be the forest with
minimum frmtCount. Used by fragment count rollback.
@param fIdx
@param count | [
"add",
"count",
"to",
"forest",
"with",
"index",
"fIdx",
"which",
"may",
"not",
"be",
"the",
"forest",
"with",
"minimum",
"frmtCount",
".",
"Used",
"by",
"fragment",
"count",
"rollback",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/StatisticalAssignmentPolicy.java#L76-L87 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/utilities/StatisticalAssignmentPolicy.java | StatisticalAssignmentPolicy.getPlacementForestIndex | @Override
public int getPlacementForestIndex(DocumentURI uri) {
int idx = 0;
try {
idx = popAndInsert();
} catch (InterruptedException e) {
LOG.error("Statistical assignment gets interrupted");
}
return idx;
} | java | @Override
public int getPlacementForestIndex(DocumentURI uri) {
int idx = 0;
try {
idx = popAndInsert();
} catch (InterruptedException e) {
LOG.error("Statistical assignment gets interrupted");
}
return idx;
} | [
"@",
"Override",
"public",
"int",
"getPlacementForestIndex",
"(",
"DocumentURI",
"uri",
")",
"{",
"int",
"idx",
"=",
"0",
";",
"try",
"{",
"idx",
"=",
"popAndInsert",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"LOG",
".",
... | get the index of the forest with smallest number of docs | [
"get",
"the",
"index",
"of",
"the",
"forest",
"with",
"smallest",
"number",
"of",
"docs"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/utilities/StatisticalAssignmentPolicy.java#L94-L103 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/ForestReader.java | ForestReader.setKey | protected void setKey(String uri, String sub, int line, int col) {
if (srcId == null) {
srcId = split.getPath().toString();
}
// apply prefix and suffix for URI
uri = URIUtil.applyUriReplace(uri, conf);
uri = URIUtil.applyPrefixSuffix(uri, conf);
if (key == null) {
key = new DocumentURIWithSourceInfo(uri, srcId, sub, line, col);
} else {
key.setSkipReason("");
key.setUri(uri);
key.setSrcId(srcId);
key.setSubId(sub);
key.setColNumber(col);
key.setLineNumber(line);
}
} | java | protected void setKey(String uri, String sub, int line, int col) {
if (srcId == null) {
srcId = split.getPath().toString();
}
// apply prefix and suffix for URI
uri = URIUtil.applyUriReplace(uri, conf);
uri = URIUtil.applyPrefixSuffix(uri, conf);
if (key == null) {
key = new DocumentURIWithSourceInfo(uri, srcId, sub, line, col);
} else {
key.setSkipReason("");
key.setUri(uri);
key.setSrcId(srcId);
key.setSubId(sub);
key.setColNumber(col);
key.setLineNumber(line);
}
} | [
"protected",
"void",
"setKey",
"(",
"String",
"uri",
",",
"String",
"sub",
",",
"int",
"line",
",",
"int",
"col",
")",
"{",
"if",
"(",
"srcId",
"==",
"null",
")",
"{",
"srcId",
"=",
"split",
".",
"getPath",
"(",
")",
".",
"toString",
"(",
")",
";... | Apply URI prefix and suffix configuration options and set the result as
DocumentURI key.
@param uri Source string of document URI.
@param sub Sub-entry of the source of the document origin.
@param line Line number in the source if applicable; -1 otherwise.
@param col Column number in the source if applicable; -1 otherwise. | [
"Apply",
"URI",
"prefix",
"and",
"suffix",
"configuration",
"options",
"and",
"set",
"the",
"result",
"as",
"DocumentURI",
"key",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/ForestReader.java#L195-L212 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/TransformOutputFormat.java | TransformOutputFormat.getMimetypesMap | private LinkedMapWritable getMimetypesMap() throws IOException {
if (mimetypeMap != null)
return mimetypeMap;
String mtmap = conf.get(ConfigConstants.CONF_MIMETYPES);
if (mtmap != null) {
mimetypeMap = DefaultStringifier.load(conf,
ConfigConstants.CONF_MIMETYPES, LinkedMapWritable.class);
return mimetypeMap;
}
String[] hosts = conf.getStrings(OUTPUT_HOST);
Session session = null;
ResultSequence result = null;
for (int i = 0; i < hosts.length; i++) {
try {
String host = hosts[i];
ContentSource cs = InternalUtilities.getOutputContentSource(conf,
host);
session = cs.newSession();
AdhocQuery query = session.newAdhocQuery(MIMETYPES_QUERY);
RequestOptions options = new RequestOptions();
options.setDefaultXQueryVersion("1.0-ml");
query.setOptions(options);
result = session.submitRequest(query);
if (!result.hasNext())
throw new IOException(
"Server-side transform requires MarkLogic 7 or later");
mimetypeMap = new LinkedMapWritable();
while (result.hasNext()) {
String suffs = result.next().asString();
Text format = new Text(result.next().asString());
// some extensions are in a space separated string
for (String s : suffs.split(" ")) {
Text suff = new Text(s);
mimetypeMap.put(suff, format);
}
}
return mimetypeMap;
} catch (Exception e) {
if (e.getCause() instanceof ServerConnectionException) {
LOG.warn("Unable to connect to " + hosts[i]
+ " to query destination information");
continue;
}
LOG.error(e.getMessage(), e);
throw new IOException(e);
} finally {
if (result != null) {
result.close();
}
if (session != null) {
session.close();
}
}
}
return null;
} | java | private LinkedMapWritable getMimetypesMap() throws IOException {
if (mimetypeMap != null)
return mimetypeMap;
String mtmap = conf.get(ConfigConstants.CONF_MIMETYPES);
if (mtmap != null) {
mimetypeMap = DefaultStringifier.load(conf,
ConfigConstants.CONF_MIMETYPES, LinkedMapWritable.class);
return mimetypeMap;
}
String[] hosts = conf.getStrings(OUTPUT_HOST);
Session session = null;
ResultSequence result = null;
for (int i = 0; i < hosts.length; i++) {
try {
String host = hosts[i];
ContentSource cs = InternalUtilities.getOutputContentSource(conf,
host);
session = cs.newSession();
AdhocQuery query = session.newAdhocQuery(MIMETYPES_QUERY);
RequestOptions options = new RequestOptions();
options.setDefaultXQueryVersion("1.0-ml");
query.setOptions(options);
result = session.submitRequest(query);
if (!result.hasNext())
throw new IOException(
"Server-side transform requires MarkLogic 7 or later");
mimetypeMap = new LinkedMapWritable();
while (result.hasNext()) {
String suffs = result.next().asString();
Text format = new Text(result.next().asString());
// some extensions are in a space separated string
for (String s : suffs.split(" ")) {
Text suff = new Text(s);
mimetypeMap.put(suff, format);
}
}
return mimetypeMap;
} catch (Exception e) {
if (e.getCause() instanceof ServerConnectionException) {
LOG.warn("Unable to connect to " + hosts[i]
+ " to query destination information");
continue;
}
LOG.error(e.getMessage(), e);
throw new IOException(e);
} finally {
if (result != null) {
result.close();
}
if (session != null) {
session.close();
}
}
}
return null;
} | [
"private",
"LinkedMapWritable",
"getMimetypesMap",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"mimetypeMap",
"!=",
"null",
")",
"return",
"mimetypeMap",
";",
"String",
"mtmap",
"=",
"conf",
".",
"get",
"(",
"ConfigConstants",
".",
"CONF_MIMETYPES",
")",
... | initialize mimetype map if not initialized, return the map
@return
@throws IOException | [
"initialize",
"mimetype",
"map",
"if",
"not",
"initialized",
"return",
"the",
"map"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/TransformOutputFormat.java#L67-L123 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/MultithreadedMapper.java | MultithreadedMapper.setNumberOfThreads | public static void setNumberOfThreads(Job job, int threads) {
job.getConfiguration().setInt(ConfigConstants.CONF_THREADS_PER_SPLIT,
threads);
} | java | public static void setNumberOfThreads(Job job, int threads) {
job.getConfiguration().setInt(ConfigConstants.CONF_THREADS_PER_SPLIT,
threads);
} | [
"public",
"static",
"void",
"setNumberOfThreads",
"(",
"Job",
"job",
",",
"int",
"threads",
")",
"{",
"job",
".",
"getConfiguration",
"(",
")",
".",
"setInt",
"(",
"ConfigConstants",
".",
"CONF_THREADS_PER_SPLIT",
",",
"threads",
")",
";",
"}"
] | Set the number of threads in the pool for running maps.
@param job
the job to modify
@param threads
the new number of threads | [
"Set",
"the",
"number",
"of",
"threads",
"in",
"the",
"pool",
"for",
"running",
"maps",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/MultithreadedMapper.java#L115-L118 | train |
marklogic/marklogic-contentpump | mapreduce/src/main/java/com/marklogic/mapreduce/MarkLogicRecordWriter.java | MarkLogicRecordWriter.getSession | protected Session getSession() throws IOException {
if (session == null) {
// start a session
try {
ContentSource cs = InternalUtilities.getOutputContentSource(
conf, hostName);
session = cs.newSession();
if (LOG.isDebugEnabled()) {
LOG.debug("Connect to " + session.getConnectionUri().getHost());
}
if (txnSize > 1) {
session.setTransactionMode(TransactionMode.UPDATE);
}
} catch (XccConfigException e) {
LOG.error("Error creating a new session: ", e);
throw new IOException(e);
}
}
return session;
} | java | protected Session getSession() throws IOException {
if (session == null) {
// start a session
try {
ContentSource cs = InternalUtilities.getOutputContentSource(
conf, hostName);
session = cs.newSession();
if (LOG.isDebugEnabled()) {
LOG.debug("Connect to " + session.getConnectionUri().getHost());
}
if (txnSize > 1) {
session.setTransactionMode(TransactionMode.UPDATE);
}
} catch (XccConfigException e) {
LOG.error("Error creating a new session: ", e);
throw new IOException(e);
}
}
return session;
} | [
"protected",
"Session",
"getSession",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"// start a session",
"try",
"{",
"ContentSource",
"cs",
"=",
"InternalUtilities",
".",
"getOutputContentSource",
"(",
"conf",
",",
"hostN... | Get the session for this writer. One writer only maintains one session.
@return Session for this writer.
@throws IOException | [
"Get",
"the",
"session",
"for",
"this",
"writer",
".",
"One",
"writer",
"only",
"maintains",
"one",
"session",
"."
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mapreduce/src/main/java/com/marklogic/mapreduce/MarkLogicRecordWriter.java#L81-L100 | train |
marklogic/marklogic-contentpump | mlcp/src/main/java/com/marklogic/contentpump/DatabaseContentWriter.java | DatabaseContentWriter.newContentCreateOptions | protected static ContentCreateOptions newContentCreateOptions(
DocumentMetadata meta, ContentCreateOptions options,
boolean isCopyColls, boolean isCopyQuality, boolean isCopyMeta,
boolean isCopyPerms, long effectiveVersion) {
ContentCreateOptions opt = (ContentCreateOptions)options.clone();
if (meta != null) {
if (isCopyQuality && opt.getQuality() == 0) {
opt.setQuality(meta.quality);
}
if (isCopyColls) {
if (opt.getCollections() != null) {
HashSet<String> colSet =
new HashSet<String>(meta.collectionsList);
// union copy_collection and output_collection
for (String s : opt.getCollections()) {
colSet.add(s);
}
opt.setCollections(
colSet.toArray(new String[colSet.size()]));
} else {
opt.setCollections(meta.getCollections());
}
}
if (isCopyPerms) {
if (effectiveVersion < MarkLogicConstants.MIN_NODEUPDATE_VERSION &&
meta.isNakedProps()) {
boolean reset = false;
Vector<ContentPermission> perms = new Vector<>();
for (ContentPermission perm : meta.permissionsList) {
if (!perm.getCapability().toString().equals(
ContentPermission.NODE_UPDATE.toString())) {
perms.add(perm);
} else {
reset = true;
}
}
if (reset) {
meta.clearPermissions();
meta.addPermissions(perms);
meta.setPermString(null);
}
}
if (opt.getPermissions() != null) {
HashSet<ContentPermission> pSet =
new HashSet<ContentPermission>(meta.permissionsList);
// union of output_permission & copy_permission
for (ContentPermission p : opt.getPermissions()) {
pSet.add(p);
}
opt.setPermissions(
pSet.toArray(new ContentPermission[pSet.size()]));
} else {
opt.setPermissions(meta.getPermissions());
}
}
if (isCopyMeta) {
opt.setMetadata(meta.meta);
}
}
return opt;
} | java | protected static ContentCreateOptions newContentCreateOptions(
DocumentMetadata meta, ContentCreateOptions options,
boolean isCopyColls, boolean isCopyQuality, boolean isCopyMeta,
boolean isCopyPerms, long effectiveVersion) {
ContentCreateOptions opt = (ContentCreateOptions)options.clone();
if (meta != null) {
if (isCopyQuality && opt.getQuality() == 0) {
opt.setQuality(meta.quality);
}
if (isCopyColls) {
if (opt.getCollections() != null) {
HashSet<String> colSet =
new HashSet<String>(meta.collectionsList);
// union copy_collection and output_collection
for (String s : opt.getCollections()) {
colSet.add(s);
}
opt.setCollections(
colSet.toArray(new String[colSet.size()]));
} else {
opt.setCollections(meta.getCollections());
}
}
if (isCopyPerms) {
if (effectiveVersion < MarkLogicConstants.MIN_NODEUPDATE_VERSION &&
meta.isNakedProps()) {
boolean reset = false;
Vector<ContentPermission> perms = new Vector<>();
for (ContentPermission perm : meta.permissionsList) {
if (!perm.getCapability().toString().equals(
ContentPermission.NODE_UPDATE.toString())) {
perms.add(perm);
} else {
reset = true;
}
}
if (reset) {
meta.clearPermissions();
meta.addPermissions(perms);
meta.setPermString(null);
}
}
if (opt.getPermissions() != null) {
HashSet<ContentPermission> pSet =
new HashSet<ContentPermission>(meta.permissionsList);
// union of output_permission & copy_permission
for (ContentPermission p : opt.getPermissions()) {
pSet.add(p);
}
opt.setPermissions(
pSet.toArray(new ContentPermission[pSet.size()]));
} else {
opt.setPermissions(meta.getPermissions());
}
}
if (isCopyMeta) {
opt.setMetadata(meta.meta);
}
}
return opt;
} | [
"protected",
"static",
"ContentCreateOptions",
"newContentCreateOptions",
"(",
"DocumentMetadata",
"meta",
",",
"ContentCreateOptions",
"options",
",",
"boolean",
"isCopyColls",
",",
"boolean",
"isCopyQuality",
",",
"boolean",
"isCopyMeta",
",",
"boolean",
"isCopyPerms",
... | fetch the options information from conf and metadata, set to the field
"options" | [
"fetch",
"the",
"options",
"information",
"from",
"conf",
"and",
"metadata",
"set",
"to",
"the",
"field",
"options"
] | 4c41e4a953301f81a4c655efb2a847603dee8afc | https://github.com/marklogic/marklogic-contentpump/blob/4c41e4a953301f81a4c655efb2a847603dee8afc/mlcp/src/main/java/com/marklogic/contentpump/DatabaseContentWriter.java#L99-L159 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.