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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ReflectionUtils.java | ReflectionUtils.setFieldValue | public static void setFieldValue(Object obj, ReflectedInfo info, Object value) throws Siren4JException {
if (obj == null) {
throw new IllegalArgumentException("obj cannot be null");
}
if (info == null) {
throw new IllegalArgumentException("info cannot be null");
}
if (info.getSetter() != null) {
Method setter = info.getSetter();
setter.setAccessible(true);
try {
setter.invoke(obj, new Object[]{value});
} catch (Exception e) {
throw new Siren4JException(e);
}
} else {
// No setter set field directly
try {
info.getField().set(obj, value);
} catch (Exception e) {
throw new Siren4JException(e);
}
}
} | java | public static void setFieldValue(Object obj, ReflectedInfo info, Object value) throws Siren4JException {
if (obj == null) {
throw new IllegalArgumentException("obj cannot be null");
}
if (info == null) {
throw new IllegalArgumentException("info cannot be null");
}
if (info.getSetter() != null) {
Method setter = info.getSetter();
setter.setAccessible(true);
try {
setter.invoke(obj, new Object[]{value});
} catch (Exception e) {
throw new Siren4JException(e);
}
} else {
// No setter set field directly
try {
info.getField().set(obj, value);
} catch (Exception e) {
throw new Siren4JException(e);
}
}
} | [
"public",
"static",
"void",
"setFieldValue",
"(",
"Object",
"obj",
",",
"ReflectedInfo",
"info",
",",
"Object",
"value",
")",
"throws",
"Siren4JException",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"obj c... | Sets the fields value, first by attempting to call the setter method if it exists and then
falling back to setting the field directly.
@param obj the object instance to set the value on, cannot be <code>null</code>.
@param info the fields reflected info object, cannot be <code>null</code>.
@param value the value to set on the field, may be <code>null</code>.
@throws Siren4JException upon reflection error. | [
"Sets",
"the",
"fields",
"value",
"first",
"by",
"attempting",
"to",
"call",
"the",
"setter",
"method",
"if",
"it",
"exists",
"and",
"then",
"falling",
"back",
"to",
"setting",
"the",
"field",
"directly",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ReflectionUtils.java#L529-L553 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/converter/ResourceRegistryImpl.java | ResourceRegistryImpl.init | @SuppressWarnings("deprecation")
private void init(String... packages) throws Siren4JException {
LOG.info("Siren4J scanning classpath for resource entries...");
Reflections reflections = null;
ConfigurationBuilder builder = new ConfigurationBuilder();
Collection<URL> urls = new HashSet<URL>();
if (packages != null && packages.length > 0) {
//limit scan to packages
for (String pkg : packages) {
urls.addAll(ClasspathHelper.forPackage(pkg));
}
} else {
urls.addAll(ClasspathHelper.forPackage("com."));
urls.addAll(ClasspathHelper.forPackage("org."));
urls.addAll(ClasspathHelper.forPackage("net."));
}
//Always add Siren4J Resources by default, this will add the collection resource
//and what ever other resource gets added to this package and has the entity annotation.
urls.addAll(ClasspathHelper.forPackage("com.google.code.siren4j.resource"));
builder.setUrls(urls);
reflections = new Reflections(builder);
Set<Class<?>> types = reflections.getTypesAnnotatedWith(Siren4JEntity.class);
for (Class<?> c : types) {
Siren4JEntity anno = c.getAnnotation(Siren4JEntity.class);
String name = StringUtils
.defaultIfBlank(anno.name(), anno.entityClass().length > 0 ? anno.entityClass()[0] : c.getName());
putEntry(StringUtils.defaultIfEmpty(name, c.getName()), c, false);
// Always add the class name as an entry in the index if it does not already exist.
if (!containsEntityEntry(c.getName())) {
putEntry(StringUtils.defaultIfEmpty(c.getName(), c.getName()), c, false);
}
}
} | java | @SuppressWarnings("deprecation")
private void init(String... packages) throws Siren4JException {
LOG.info("Siren4J scanning classpath for resource entries...");
Reflections reflections = null;
ConfigurationBuilder builder = new ConfigurationBuilder();
Collection<URL> urls = new HashSet<URL>();
if (packages != null && packages.length > 0) {
//limit scan to packages
for (String pkg : packages) {
urls.addAll(ClasspathHelper.forPackage(pkg));
}
} else {
urls.addAll(ClasspathHelper.forPackage("com."));
urls.addAll(ClasspathHelper.forPackage("org."));
urls.addAll(ClasspathHelper.forPackage("net."));
}
//Always add Siren4J Resources by default, this will add the collection resource
//and what ever other resource gets added to this package and has the entity annotation.
urls.addAll(ClasspathHelper.forPackage("com.google.code.siren4j.resource"));
builder.setUrls(urls);
reflections = new Reflections(builder);
Set<Class<?>> types = reflections.getTypesAnnotatedWith(Siren4JEntity.class);
for (Class<?> c : types) {
Siren4JEntity anno = c.getAnnotation(Siren4JEntity.class);
String name = StringUtils
.defaultIfBlank(anno.name(), anno.entityClass().length > 0 ? anno.entityClass()[0] : c.getName());
putEntry(StringUtils.defaultIfEmpty(name, c.getName()), c, false);
// Always add the class name as an entry in the index if it does not already exist.
if (!containsEntityEntry(c.getName())) {
putEntry(StringUtils.defaultIfEmpty(c.getName(), c.getName()), c, false);
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"void",
"init",
"(",
"String",
"...",
"packages",
")",
"throws",
"Siren4JException",
"{",
"LOG",
".",
"info",
"(",
"\"Siren4J scanning classpath for resource entries...\"",
")",
";",
"Reflections",
"refl... | Scans the classpath for resources.
@param packages
@throws Siren4JException | [
"Scans",
"the",
"classpath",
"for",
"resources",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ResourceRegistryImpl.java#L124-L158 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/component/builder/BaseBuilder.java | BaseBuilder.callMethod | private void callMethod(Object obj, Step step) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class<?> clazz = obj.getClass();
Method method = ReflectionUtils.findMethod(clazz, step.getMethodName(), step.getArgTypes());
method.invoke(obj, step.getArguments());
} | java | private void callMethod(Object obj, Step step) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class<?> clazz = obj.getClass();
Method method = ReflectionUtils.findMethod(clazz, step.getMethodName(), step.getArgTypes());
method.invoke(obj, step.getArguments());
} | [
"private",
"void",
"callMethod",
"(",
"Object",
"obj",
",",
"Step",
"step",
")",
"throws",
"SecurityException",
",",
"NoSuchMethodException",
",",
"IllegalArgumentException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"Class",
"<",
"?",
">",... | Finds and calls the method specified by the step passed in.
@param obj assumed not <code>null</code>.
@param step assumed not <code>null</code>.
@throws SecurityException
@throws NoSuchMethodException
@throws IllegalArgumentException
@throws IllegalAccessException
@throws InvocationTargetException | [
"Finds",
"and",
"calls",
"the",
"method",
"specified",
"by",
"the",
"step",
"passed",
"in",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/BaseBuilder.java#L171-L177 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/component/builder/BaseBuilder.java | BaseBuilder.getTypes | private Class<?>[] getTypes(Object[] args) {
if (args == null || args.length == 0) {
return null;
}
List<Class<?>> classList = new ArrayList<Class<?>>();
for (Object obj : args) {
classList.add(obj == null ? Object.class : obj.getClass());
}
return classList.toArray(new Class[] {});
} | java | private Class<?>[] getTypes(Object[] args) {
if (args == null || args.length == 0) {
return null;
}
List<Class<?>> classList = new ArrayList<Class<?>>();
for (Object obj : args) {
classList.add(obj == null ? Object.class : obj.getClass());
}
return classList.toArray(new Class[] {});
} | [
"private",
"Class",
"<",
"?",
">",
"[",
"]",
"getTypes",
"(",
"Object",
"[",
"]",
"args",
")",
"{",
"if",
"(",
"args",
"==",
"null",
"||",
"args",
".",
"length",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"List",
"<",
"Class",
"<",
"?",
... | Attempts to determine the argument types based on the passed in object instances.
@param args assumed not <code>null</code>.
@return array of argument types. | [
"Attempts",
"to",
"determine",
"the",
"argument",
"types",
"based",
"on",
"the",
"passed",
"in",
"object",
"instances",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/component/builder/BaseBuilder.java#L186-L195 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ComponentUtils.java | ComponentUtils.getSubEntityByRel | public static Entity getSubEntityByRel(Entity entity, String... rel) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(ArrayUtils.isEmpty(rel)) {
throw new IllegalArgumentException("rel cannot be null or empty");
}
List<Entity> entities = entity.getEntities();
if (entities == null)
return null;
Entity ent = null;
for (Entity e : entities) {
if (ArrayUtils.isNotEmpty(e.getRel()) && ArrayUtils.toString(rel).equals(ArrayUtils.toString(e.getRel()))) {
ent = e;
break;
}
}
return ent;
} | java | public static Entity getSubEntityByRel(Entity entity, String... rel) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(ArrayUtils.isEmpty(rel)) {
throw new IllegalArgumentException("rel cannot be null or empty");
}
List<Entity> entities = entity.getEntities();
if (entities == null)
return null;
Entity ent = null;
for (Entity e : entities) {
if (ArrayUtils.isNotEmpty(e.getRel()) && ArrayUtils.toString(rel).equals(ArrayUtils.toString(e.getRel()))) {
ent = e;
break;
}
}
return ent;
} | [
"public",
"static",
"Entity",
"getSubEntityByRel",
"(",
"Entity",
"entity",
",",
"String",
"...",
"rel",
")",
"{",
"if",
"(",
"entity",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"entity cannot be null.\"",
")",
";",
"}",
"if",
... | Retrieve a sub entity by its relationship.
@param entity cannot be <code>null</code>.
@param rel cannot be <code>null</code> or empty.
@return the located entity or <code>null</code> if not found. | [
"Retrieve",
"a",
"sub",
"entity",
"by",
"its",
"relationship",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ComponentUtils.java#L50-L68 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ComponentUtils.java | ComponentUtils.getLinkByRel | public static Link getLinkByRel(Entity entity, String... rel) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(ArrayUtils.isEmpty(rel)) {
throw new IllegalArgumentException("rel cannot be null or empty");
}
List<Link> links = entity.getLinks();
if (links == null)
return null;
Link link = null;
for (Link l : links) {
if (ArrayUtils.isNotEmpty(l.getRel()) && ArrayUtils.toString(rel).equals(ArrayUtils.toString(l.getRel()))) {
link = l;
break;
}
}
return link;
} | java | public static Link getLinkByRel(Entity entity, String... rel) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(ArrayUtils.isEmpty(rel)) {
throw new IllegalArgumentException("rel cannot be null or empty");
}
List<Link> links = entity.getLinks();
if (links == null)
return null;
Link link = null;
for (Link l : links) {
if (ArrayUtils.isNotEmpty(l.getRel()) && ArrayUtils.toString(rel).equals(ArrayUtils.toString(l.getRel()))) {
link = l;
break;
}
}
return link;
} | [
"public",
"static",
"Link",
"getLinkByRel",
"(",
"Entity",
"entity",
",",
"String",
"...",
"rel",
")",
"{",
"if",
"(",
"entity",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"entity cannot be null.\"",
")",
";",
"}",
"if",
"(",
... | Retrieve a link by its relationship.
@param entity cannot be <code>null</code>.
@param rel cannot be <code>null</code> or empty.
@return the located link or <code>null</code> if not found. | [
"Retrieve",
"a",
"link",
"by",
"its",
"relationship",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ComponentUtils.java#L76-L94 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ComponentUtils.java | ComponentUtils.getActionByName | public static Action getActionByName(Entity entity, String name) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name cannot be null or empty.");
}
List<Action> actions = entity.getActions();
if (actions == null)
return null;
Action action = null;
for (Action a : actions) {
if (a.getName().equals(name)) {
action = a;
break;
}
}
return action;
} | java | public static Action getActionByName(Entity entity, String name) {
if(entity == null) {
throw new IllegalArgumentException("entity cannot be null.");
}
if(StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name cannot be null or empty.");
}
List<Action> actions = entity.getActions();
if (actions == null)
return null;
Action action = null;
for (Action a : actions) {
if (a.getName().equals(name)) {
action = a;
break;
}
}
return action;
} | [
"public",
"static",
"Action",
"getActionByName",
"(",
"Entity",
"entity",
",",
"String",
"name",
")",
"{",
"if",
"(",
"entity",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"entity cannot be null.\"",
")",
";",
"}",
"if",
"(",
"... | Retrieve an action by its name.
@param entity cannot be <code>null</code>.
@param name cannot be <code>null</code> or empty.
@return the located action or <code>null</code> if not found. | [
"Retrieve",
"an",
"action",
"by",
"its",
"name",
"."
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ComponentUtils.java#L102-L120 | train |
eserating/siren4j | src/main/java/com/google/code/siren4j/util/ComponentUtils.java | ComponentUtils.isStringArrayEmpty | public static boolean isStringArrayEmpty(String[] arr) {
boolean empty = true;
if (arr != null) {
if (arr.length > 0) {
for (String s : arr) {
if (StringUtils.isNotBlank(s)) {
empty = false;
break;
}
}
}
}
return empty;
} | java | public static boolean isStringArrayEmpty(String[] arr) {
boolean empty = true;
if (arr != null) {
if (arr.length > 0) {
for (String s : arr) {
if (StringUtils.isNotBlank(s)) {
empty = false;
break;
}
}
}
}
return empty;
} | [
"public",
"static",
"boolean",
"isStringArrayEmpty",
"(",
"String",
"[",
"]",
"arr",
")",
"{",
"boolean",
"empty",
"=",
"true",
";",
"if",
"(",
"arr",
"!=",
"null",
")",
"{",
"if",
"(",
"arr",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"String"... | Determine if the string array is empty. It is considered empty if zero length or all items are blank strings;
@param arr
@return | [
"Determine",
"if",
"the",
"string",
"array",
"is",
"empty",
".",
"It",
"is",
"considered",
"empty",
"if",
"zero",
"length",
"or",
"all",
"items",
"are",
"blank",
"strings",
";"
] | f12e3185076ad920352ec4f6eb2a071a3683505f | https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/util/ComponentUtils.java#L128-L141 | train |
yshavit/antlr-denter | core/src/main/java/com/yuvalshavit/antlr4/DenterHelper.java | DenterHelper.unwindTo | private Token unwindTo(int targetIndent, Token copyFrom) {
assert dentsBuffer.isEmpty() : dentsBuffer;
dentsBuffer.add(createToken(nlToken, copyFrom));
// To make things easier, we'll queue up ALL of the dedents, and then pop off the first one.
// For example, here's how some text is analyzed:
//
// Text : Indentation : Action : Indents Deque
// [ baseline ] : 0 : nothing : [0]
// [ foo ] : 2 : INDENT : [0, 2]
// [ bar ] : 3 : INDENT : [0, 2, 3]
// [ baz ] : 0 : DEDENT x2 : [0]
while (true) {
int prevIndent = indentations.pop();
if (prevIndent == targetIndent) {
break;
}
if (targetIndent > prevIndent) {
// "weird" condition above
indentations.push(prevIndent); // restore previous indentation, since we've indented from it
dentsBuffer.add(createToken(indentToken, copyFrom));
break;
}
dentsBuffer.add(createToken(dedentToken, copyFrom));
}
indentations.push(targetIndent);
return dentsBuffer.remove();
} | java | private Token unwindTo(int targetIndent, Token copyFrom) {
assert dentsBuffer.isEmpty() : dentsBuffer;
dentsBuffer.add(createToken(nlToken, copyFrom));
// To make things easier, we'll queue up ALL of the dedents, and then pop off the first one.
// For example, here's how some text is analyzed:
//
// Text : Indentation : Action : Indents Deque
// [ baseline ] : 0 : nothing : [0]
// [ foo ] : 2 : INDENT : [0, 2]
// [ bar ] : 3 : INDENT : [0, 2, 3]
// [ baz ] : 0 : DEDENT x2 : [0]
while (true) {
int prevIndent = indentations.pop();
if (prevIndent == targetIndent) {
break;
}
if (targetIndent > prevIndent) {
// "weird" condition above
indentations.push(prevIndent); // restore previous indentation, since we've indented from it
dentsBuffer.add(createToken(indentToken, copyFrom));
break;
}
dentsBuffer.add(createToken(dedentToken, copyFrom));
}
indentations.push(targetIndent);
return dentsBuffer.remove();
} | [
"private",
"Token",
"unwindTo",
"(",
"int",
"targetIndent",
",",
"Token",
"copyFrom",
")",
"{",
"assert",
"dentsBuffer",
".",
"isEmpty",
"(",
")",
":",
"dentsBuffer",
";",
"dentsBuffer",
".",
"add",
"(",
"createToken",
"(",
"nlToken",
",",
"copyFrom",
")",
... | Returns a DEDENT token, and also queues up additional DEDENTS as necessary.
@param targetIndent the "size" of the indentation (number of spaces) by the end
@param copyFrom the triggering token
@return a DEDENT token | [
"Returns",
"a",
"DEDENT",
"token",
"and",
"also",
"queues",
"up",
"additional",
"DEDENTS",
"as",
"necessary",
"."
] | 65ab8d2f491cc044cee873078fb063c021a8a708 | https://github.com/yshavit/antlr-denter/blob/65ab8d2f491cc044cee873078fb063c021a8a708/core/src/main/java/com/yuvalshavit/antlr4/DenterHelper.java#L141-L168 | train |
MindscapeHQ/raygun4java | webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunClient.java | RaygunClient.initialize | public static void initialize(HttpServletRequest request) {
if (factory == null) {
throw new RuntimeException("RaygunClient is not initialized. Call RaygunClient.Initialize()");
}
client.set(factory.newClient(request));
} | java | public static void initialize(HttpServletRequest request) {
if (factory == null) {
throw new RuntimeException("RaygunClient is not initialized. Call RaygunClient.Initialize()");
}
client.set(factory.newClient(request));
} | [
"public",
"static",
"void",
"initialize",
"(",
"HttpServletRequest",
"request",
")",
"{",
"if",
"(",
"factory",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"RaygunClient is not initialized. Call RaygunClient.Initialize()\"",
")",
";",
"}",
"clie... | Initialize the static accessor for the given request
@param request | [
"Initialize",
"the",
"static",
"accessor",
"for",
"the",
"given",
"request"
] | 284a818446cfc6f0c2f83b5365514bc1bfc129b0 | https://github.com/MindscapeHQ/raygun4java/blob/284a818446cfc6f0c2f83b5365514bc1bfc129b0/webprovider/src/main/java/com/mindscapehq/raygun4java/webprovider/RaygunClient.java#L46-L51 | train |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/RaygunClientFactory.java | RaygunClientFactory.withData | public RaygunClientFactory withData(Object key, Object value) {
factoryData.put(key, value);
return this;
} | java | public RaygunClientFactory withData(Object key, Object value) {
factoryData.put(key, value);
return this;
} | [
"public",
"RaygunClientFactory",
"withData",
"(",
"Object",
"key",
",",
"Object",
"value",
")",
"{",
"factoryData",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | This data will be added to every error sent
@param key
@param value
@return factory | [
"This",
"data",
"will",
"be",
"added",
"to",
"every",
"error",
"sent"
] | 284a818446cfc6f0c2f83b5365514bc1bfc129b0 | https://github.com/MindscapeHQ/raygun4java/blob/284a818446cfc6f0c2f83b5365514bc1bfc129b0/core/src/main/java/com/mindscapehq/raygun4java/core/RaygunClientFactory.java#L178-L181 | train |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/RaygunClient.java | RaygunClient.withData | public RaygunClient withData(Object key, Object value) {
clientData.put(key, value);
return this;
} | java | public RaygunClient withData(Object key, Object value) {
clientData.put(key, value);
return this;
} | [
"public",
"RaygunClient",
"withData",
"(",
"Object",
"key",
",",
"Object",
"value",
")",
"{",
"clientData",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | This data will be added to all errors sent from this instance of the client
@param key
@param value
@return | [
"This",
"data",
"will",
"be",
"added",
"to",
"all",
"errors",
"sent",
"from",
"this",
"instance",
"of",
"the",
"client"
] | 284a818446cfc6f0c2f83b5365514bc1bfc129b0 | https://github.com/MindscapeHQ/raygun4java/blob/284a818446cfc6f0c2f83b5365514bc1bfc129b0/core/src/main/java/com/mindscapehq/raygun4java/core/RaygunClient.java#L310-L313 | train |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunDuplicateErrorFilterFactory.java | RaygunDuplicateErrorFilterFactory.create | public RaygunDuplicateErrorFilter create() {
RaygunDuplicateErrorFilter filter = instance.get();
if (filter == null) {
filter = new RaygunDuplicateErrorFilter();
instance.set(filter);
return filter;
} else {
instance.remove();
return filter;
}
} | java | public RaygunDuplicateErrorFilter create() {
RaygunDuplicateErrorFilter filter = instance.get();
if (filter == null) {
filter = new RaygunDuplicateErrorFilter();
instance.set(filter);
return filter;
} else {
instance.remove();
return filter;
}
} | [
"public",
"RaygunDuplicateErrorFilter",
"create",
"(",
")",
"{",
"RaygunDuplicateErrorFilter",
"filter",
"=",
"instance",
".",
"get",
"(",
")",
";",
"if",
"(",
"filter",
"==",
"null",
")",
"{",
"filter",
"=",
"new",
"RaygunDuplicateErrorFilter",
"(",
")",
";",... | this will haunt me for eternity | [
"this",
"will",
"haunt",
"me",
"for",
"eternity"
] | 284a818446cfc6f0c2f83b5365514bc1bfc129b0 | https://github.com/MindscapeHQ/raygun4java/blob/284a818446cfc6f0c2f83b5365514bc1bfc129b0/core/src/main/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunDuplicateErrorFilterFactory.java#L24-L34 | train |
MindscapeHQ/raygun4java | sampleapp/src/main/java/com/mindscapehq/raygun4java/sampleapp/SampleApp.java | SampleApp.main | public static void main(String[] args) throws Throwable {
final Exception exceptionToThrowLater = new Exception("Raygun4Java test exception");
// sets the global unhandled exception handler
Thread.setDefaultUncaughtExceptionHandler(MyExceptionHandler.instance());
MyExceptionHandler.getClient().recordBreadcrumb("App starting up");
RaygunIdentifier userIdentity = new RaygunIdentifier("a@b.com")
.withEmail("a@b.com")
.withFirstName("Foo")
.withFullName("Foo Bar")
.withAnonymous(false)
.withUuid(UUID.randomUUID().toString());
MyExceptionHandler.getClient().setUser(userIdentity);
new Thread(new Runnable() {
@Override
public void run() {
MyExceptionHandler.getClient().recordBreadcrumb("different thread starting");
// note that use info not set on this thread
try {
MyExceptionHandler.getClient().recordBreadcrumb("throwing exception");
throw exceptionToThrowLater;
} catch (Exception e) {
MyExceptionHandler.getClient().recordBreadcrumb("handling exception");
Map<String, String> customData = new HashMap<String, String>();
customData.put("thread id", "" + Thread.currentThread().getId());
MyExceptionHandler.getClient()
.withTag("thrown from thread")
.withTag("no user withData")
.withData("thread id", "" + Thread.currentThread().getId())
.send(exceptionToThrowLater);
// this should appear in the raygun console as its already been sed
MyExceptionHandler.getClient().recordBreadcrumb("This should not appear because we're sending the same exception on the same thread");
Set<String> tags = new HashSet<String>();
tags.add("should not appear in console");
MyExceptionHandler.getClient().send(exceptionToThrowLater, tags);
}
// test offline storage by breaking the proxy
RaygunSettings.getSettings().setHttpProxy("nothing here", 80);
System.out.println("No Send below this line");
MyExceptionHandler.getClient().send(new Exception("occurred while offline offline"));
System.out.println("No Send above this lines ^");
// fix the proxy and send offline data
RaygunSettings.getSettings().setHttpProxy(null, 80);
MyExceptionHandler.getClient().send(new Exception("This should trigger offline"));
}
}).start();
MyExceptionHandler.getClient().recordBreadcrumb("Throwing exception on main thread");
throw exceptionToThrowLater;
} | java | public static void main(String[] args) throws Throwable {
final Exception exceptionToThrowLater = new Exception("Raygun4Java test exception");
// sets the global unhandled exception handler
Thread.setDefaultUncaughtExceptionHandler(MyExceptionHandler.instance());
MyExceptionHandler.getClient().recordBreadcrumb("App starting up");
RaygunIdentifier userIdentity = new RaygunIdentifier("a@b.com")
.withEmail("a@b.com")
.withFirstName("Foo")
.withFullName("Foo Bar")
.withAnonymous(false)
.withUuid(UUID.randomUUID().toString());
MyExceptionHandler.getClient().setUser(userIdentity);
new Thread(new Runnable() {
@Override
public void run() {
MyExceptionHandler.getClient().recordBreadcrumb("different thread starting");
// note that use info not set on this thread
try {
MyExceptionHandler.getClient().recordBreadcrumb("throwing exception");
throw exceptionToThrowLater;
} catch (Exception e) {
MyExceptionHandler.getClient().recordBreadcrumb("handling exception");
Map<String, String> customData = new HashMap<String, String>();
customData.put("thread id", "" + Thread.currentThread().getId());
MyExceptionHandler.getClient()
.withTag("thrown from thread")
.withTag("no user withData")
.withData("thread id", "" + Thread.currentThread().getId())
.send(exceptionToThrowLater);
// this should appear in the raygun console as its already been sed
MyExceptionHandler.getClient().recordBreadcrumb("This should not appear because we're sending the same exception on the same thread");
Set<String> tags = new HashSet<String>();
tags.add("should not appear in console");
MyExceptionHandler.getClient().send(exceptionToThrowLater, tags);
}
// test offline storage by breaking the proxy
RaygunSettings.getSettings().setHttpProxy("nothing here", 80);
System.out.println("No Send below this line");
MyExceptionHandler.getClient().send(new Exception("occurred while offline offline"));
System.out.println("No Send above this lines ^");
// fix the proxy and send offline data
RaygunSettings.getSettings().setHttpProxy(null, 80);
MyExceptionHandler.getClient().send(new Exception("This should trigger offline"));
}
}).start();
MyExceptionHandler.getClient().recordBreadcrumb("Throwing exception on main thread");
throw exceptionToThrowLater;
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Throwable",
"{",
"final",
"Exception",
"exceptionToThrowLater",
"=",
"new",
"Exception",
"(",
"\"Raygun4Java test exception\"",
")",
";",
"// sets the global unhandled exception handler... | An example of how to use Raygun4Java | [
"An",
"example",
"of",
"how",
"to",
"use",
"Raygun4Java"
] | 284a818446cfc6f0c2f83b5365514bc1bfc129b0 | https://github.com/MindscapeHQ/raygun4java/blob/284a818446cfc6f0c2f83b5365514bc1bfc129b0/sampleapp/src/main/java/com/mindscapehq/raygun4java/sampleapp/SampleApp.java#L32-L93 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parse | public ParsedPolicy parse(File file) throws Exception {
if (file == null || !file.exists()) {
if (debug) {
if (file == null) {
ProGradePolicyDebugger.log("Given File is null");
} else {
if (!file.exists()) {
ProGradePolicyDebugger.log("Policy file " + file.getCanonicalPath() + " doesn't exists.");
}
}
}
throw new Exception("ER007: File with policy doesn't exists!");
}
if (debug) {
ProGradePolicyDebugger.log("Parsing policy " + file.getCanonicalPath());
}
final InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
try {
return parse(reader);
} finally {
reader.close();
}
} | java | public ParsedPolicy parse(File file) throws Exception {
if (file == null || !file.exists()) {
if (debug) {
if (file == null) {
ProGradePolicyDebugger.log("Given File is null");
} else {
if (!file.exists()) {
ProGradePolicyDebugger.log("Policy file " + file.getCanonicalPath() + " doesn't exists.");
}
}
}
throw new Exception("ER007: File with policy doesn't exists!");
}
if (debug) {
ProGradePolicyDebugger.log("Parsing policy " + file.getCanonicalPath());
}
final InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
try {
return parse(reader);
} finally {
reader.close();
}
} | [
"public",
"ParsedPolicy",
"parse",
"(",
"File",
"file",
")",
"throws",
"Exception",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"debug",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{... | Parse content of text policy file to ParsedPolicy object which represent this policy.
@param file text file with policy file
@return parsed policy file which is represented by ParsedPolicy
@throws throw Exception when any problem occurred during parsing file (file doesn't exist, incompatible policy file etc.) | [
"Parse",
"content",
"of",
"text",
"policy",
"file",
"to",
"ParsedPolicy",
"object",
"which",
"represent",
"this",
"policy",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L73-L97 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parsePrincipal | private ParsedPrincipal parsePrincipal() throws Exception {
lookahead = st.nextToken();
switch (lookahead) {
case '*':
lookahead = st.nextToken();
if (lookahead == '*') {
return new ParsedPrincipal(null, null);
} else {
throw new Exception("ER018: There have to be name wildcard after type wildcard.");
}
case '\"':
return new ParsedPrincipal(st.sval);
case StreamTokenizer.TT_WORD:
String principalClass = st.sval;
lookahead = st.nextToken();
switch (lookahead) {
case '*':
return new ParsedPrincipal(principalClass, null);
case '\"':
return new ParsedPrincipal(principalClass, st.sval);
default:
throw new Exception("ER019: Principal name or * expected.");
}
default:
throw new Exception("ER020: Principal type, *, or keystore alias expected.");
}
} | java | private ParsedPrincipal parsePrincipal() throws Exception {
lookahead = st.nextToken();
switch (lookahead) {
case '*':
lookahead = st.nextToken();
if (lookahead == '*') {
return new ParsedPrincipal(null, null);
} else {
throw new Exception("ER018: There have to be name wildcard after type wildcard.");
}
case '\"':
return new ParsedPrincipal(st.sval);
case StreamTokenizer.TT_WORD:
String principalClass = st.sval;
lookahead = st.nextToken();
switch (lookahead) {
case '*':
return new ParsedPrincipal(principalClass, null);
case '\"':
return new ParsedPrincipal(principalClass, st.sval);
default:
throw new Exception("ER019: Principal name or * expected.");
}
default:
throw new Exception("ER020: Principal type, *, or keystore alias expected.");
}
} | [
"private",
"ParsedPrincipal",
"parsePrincipal",
"(",
")",
"throws",
"Exception",
"{",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"switch",
"(",
"lookahead",
")",
"{",
"case",
"'",
"'",
":",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")"... | Private method for parsing principal part of policy entry.
@return parsed principal part of policy entry
@throws throws Exception when any problem occurred during parsing principal | [
"Private",
"method",
"for",
"parsing",
"principal",
"part",
"of",
"policy",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L281-L307 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parsePermission | private ParsedPermission parsePermission() throws Exception {
ParsedPermission permission = new ParsedPermission();
lookahead = st.nextToken();
if (lookahead == StreamTokenizer.TT_WORD) {
permission.setPermissionType(st.sval);
} else {
throw new Exception("ER021: Permission type expected.");
}
lookahead = st.nextToken();
if (lookahead == '\"') {
permission.setPermissionName(st.sval);
} else {
// java.security.AllPermission possibility
if (lookahead == ';') {
return permission;
}
throw new Exception("ER022: Permission name or or [;] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
boolean shouldBeSigned = false;
if (lookahead == '\"') {
String actionsWords = st.sval;
permission.setActions(actionsWords);
lookahead = st.nextToken();
switch (lookahead) {
case ',':
shouldBeSigned = true;
break;
case ';':
return permission;
default:
throw new Exception("ER023: Unexpected symbol, expected [,] or [;].");
}
lookahead = st.nextToken();
}
if (lookahead == StreamTokenizer.TT_WORD) {
String signedByWord = st.sval;
if (!signedByWord.toLowerCase().equals("signedby")) {
throw new Exception("ER024: [signedBy] expected but was [" + signedByWord + "].");
}
} else if (shouldBeSigned) {
throw new Exception("ER025: [signedBy] expected after [,].");
} else {
throw new Exception("ER026: Actions or [signedBy] expected after [,].");
}
lookahead = st.nextToken();
if (lookahead == '\"') {
permission.setSignedBy(st.sval);
} else {
throw new Exception("ER027: signedBy attribute expected.");
}
lookahead = st.nextToken();
}
if (lookahead == ';') {
return permission;
} else {
throw new Exception("ER028: [;] expected.");
}
} | java | private ParsedPermission parsePermission() throws Exception {
ParsedPermission permission = new ParsedPermission();
lookahead = st.nextToken();
if (lookahead == StreamTokenizer.TT_WORD) {
permission.setPermissionType(st.sval);
} else {
throw new Exception("ER021: Permission type expected.");
}
lookahead = st.nextToken();
if (lookahead == '\"') {
permission.setPermissionName(st.sval);
} else {
// java.security.AllPermission possibility
if (lookahead == ';') {
return permission;
}
throw new Exception("ER022: Permission name or or [;] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
boolean shouldBeSigned = false;
if (lookahead == '\"') {
String actionsWords = st.sval;
permission.setActions(actionsWords);
lookahead = st.nextToken();
switch (lookahead) {
case ',':
shouldBeSigned = true;
break;
case ';':
return permission;
default:
throw new Exception("ER023: Unexpected symbol, expected [,] or [;].");
}
lookahead = st.nextToken();
}
if (lookahead == StreamTokenizer.TT_WORD) {
String signedByWord = st.sval;
if (!signedByWord.toLowerCase().equals("signedby")) {
throw new Exception("ER024: [signedBy] expected but was [" + signedByWord + "].");
}
} else if (shouldBeSigned) {
throw new Exception("ER025: [signedBy] expected after [,].");
} else {
throw new Exception("ER026: Actions or [signedBy] expected after [,].");
}
lookahead = st.nextToken();
if (lookahead == '\"') {
permission.setSignedBy(st.sval);
} else {
throw new Exception("ER027: signedBy attribute expected.");
}
lookahead = st.nextToken();
}
if (lookahead == ';') {
return permission;
} else {
throw new Exception("ER028: [;] expected.");
}
} | [
"private",
"ParsedPermission",
"parsePermission",
"(",
")",
"throws",
"Exception",
"{",
"ParsedPermission",
"permission",
"=",
"new",
"ParsedPermission",
"(",
")",
";",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"lookahead",
"==",
"Str... | Private method for parsing permission part of policy entry.
@return parsed permission part of policy entry
@throws throws Exception when any problem occurred during parsing permission | [
"Private",
"method",
"for",
"parsing",
"permission",
"part",
"of",
"policy",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L315-L382 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parseKeystore | private void parseKeystore() throws Exception {
String tempKeystoreURL = null;
String tempKeystoreType = null;
String tempKeystoreProvider = null;
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreURL = st.sval;
} else {
throw new Exception("ER029: [\"keystore_URL\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreType = st.sval;
} else {
throw new Exception("ER030: [\"keystore_type\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreProvider = st.sval;
} else {
throw new Exception("ER031: [\"keystore_provider\"] expected.");
}
lookahead = st.nextToken();
}
}
if (lookahead == ';') {
if (keystoreEntry == null) {
keystoreEntry = new ParsedKeystoreEntry(tempKeystoreURL, tempKeystoreType, tempKeystoreProvider);
}
} else {
throw new Exception("ER032: [;] expected at the end of keystore entry.");
}
} | java | private void parseKeystore() throws Exception {
String tempKeystoreURL = null;
String tempKeystoreType = null;
String tempKeystoreProvider = null;
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreURL = st.sval;
} else {
throw new Exception("ER029: [\"keystore_URL\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreType = st.sval;
} else {
throw new Exception("ER030: [\"keystore_type\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ',') {
lookahead = st.nextToken();
if (lookahead == '\"') {
tempKeystoreProvider = st.sval;
} else {
throw new Exception("ER031: [\"keystore_provider\"] expected.");
}
lookahead = st.nextToken();
}
}
if (lookahead == ';') {
if (keystoreEntry == null) {
keystoreEntry = new ParsedKeystoreEntry(tempKeystoreURL, tempKeystoreType, tempKeystoreProvider);
}
} else {
throw new Exception("ER032: [;] expected at the end of keystore entry.");
}
} | [
"private",
"void",
"parseKeystore",
"(",
")",
"throws",
"Exception",
"{",
"String",
"tempKeystoreURL",
"=",
"null",
";",
"String",
"tempKeystoreType",
"=",
"null",
";",
"String",
"tempKeystoreProvider",
"=",
"null",
";",
"lookahead",
"=",
"st",
".",
"nextToken",... | Private method for parsing keystore entry.
@throws throws Exception when any problem occurred during parsing keystore entry | [
"Private",
"method",
"for",
"parsing",
"keystore",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L389-L427 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parseKeystorePassword | private void parseKeystorePassword() throws Exception {
lookahead = st.nextToken();
if (lookahead == '\"') {
if (keystorePasswordURL == null) {
keystorePasswordURL = st.sval;
}
} else {
throw new Exception("ER033: [\"keystore_password\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ';') {
return;
} else {
throw new Exception("ER034: [;] expected at the end of keystorePasswordURL entry.");
}
} | java | private void parseKeystorePassword() throws Exception {
lookahead = st.nextToken();
if (lookahead == '\"') {
if (keystorePasswordURL == null) {
keystorePasswordURL = st.sval;
}
} else {
throw new Exception("ER033: [\"keystore_password\"] expected.");
}
lookahead = st.nextToken();
if (lookahead == ';') {
return;
} else {
throw new Exception("ER034: [;] expected at the end of keystorePasswordURL entry.");
}
} | [
"private",
"void",
"parseKeystorePassword",
"(",
")",
"throws",
"Exception",
"{",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"lookahead",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"keystorePasswordURL",
"==",
"null",
")",
"{",
"keysto... | Private method for parsing keystorePasswordURL entry.
@throws throws Exception when any problem occurred during parsing keystorePasswordURL entry | [
"Private",
"method",
"for",
"parsing",
"keystorePasswordURL",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L434-L449 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policyparser/Parser.java | Parser.parsePriority | private void parsePriority() throws Exception {
lookahead = st.nextToken();
if (lookahead == '\"') {
if (priority == null) {
String pr = st.sval;
if (pr.toLowerCase().equals("grant")) {
priority = Priority.GRANT;
} else {
if (pr.toLowerCase().equals("deny")) {
priority = Priority.DENY;
} else {
throw new Exception("ER035: grant or deny priority expected.");
}
}
}
} else {
throw new Exception("ER036: quotes expected after priority keyword.");
}
lookahead = st.nextToken();
if (lookahead == ';') {
return;
} else {
throw new Exception("ER037: [;] expected at the end of priority entry.");
}
} | java | private void parsePriority() throws Exception {
lookahead = st.nextToken();
if (lookahead == '\"') {
if (priority == null) {
String pr = st.sval;
if (pr.toLowerCase().equals("grant")) {
priority = Priority.GRANT;
} else {
if (pr.toLowerCase().equals("deny")) {
priority = Priority.DENY;
} else {
throw new Exception("ER035: grant or deny priority expected.");
}
}
}
} else {
throw new Exception("ER036: quotes expected after priority keyword.");
}
lookahead = st.nextToken();
if (lookahead == ';') {
return;
} else {
throw new Exception("ER037: [;] expected at the end of priority entry.");
}
} | [
"private",
"void",
"parsePriority",
"(",
")",
"throws",
"Exception",
"{",
"lookahead",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"lookahead",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"priority",
"==",
"null",
")",
"{",
"String",
"pr",
"=",
... | Private method for parsing priority entry.
@throws throws Exception when any problem occurred during parsing priority entry | [
"Private",
"method",
"for",
"parsing",
"priority",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policyparser/Parser.java#L456-L480 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/generator/SecurityActions.java | SecurityActions.getPolicy | static Policy getPolicy() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new PrivilegedAction<Policy>() {
public Policy run() {
return Policy.getPolicy();
}
});
} else {
return Policy.getPolicy();
}
} | java | static Policy getPolicy() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new PrivilegedAction<Policy>() {
public Policy run() {
return Policy.getPolicy();
}
});
} else {
return Policy.getPolicy();
}
} | [
"static",
"Policy",
"getPolicy",
"(",
")",
"{",
"final",
"SecurityManager",
"sm",
"=",
"System",
".",
"getSecurityManager",
"(",
")",
";",
"if",
"(",
"sm",
"!=",
"null",
")",
"{",
"return",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedActi... | Returns the installed policy object.
@return | [
"Returns",
"the",
"installed",
"policy",
"object",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/generator/SecurityActions.java#L58-L70 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.refresh | @Override
public void refresh() {
FileReader fr = null;
if (file != null) {
try {
fr = new FileReader(file);
} catch (Exception e) {
System.err.println("Unable to read policy file " + file + ": " + e.getMessage());
}
}
loadPolicy(fr, skipDefaultPolicies);
} | java | @Override
public void refresh() {
FileReader fr = null;
if (file != null) {
try {
fr = new FileReader(file);
} catch (Exception e) {
System.err.println("Unable to read policy file " + file + ": " + e.getMessage());
}
}
loadPolicy(fr, skipDefaultPolicies);
} | [
"@",
"Override",
"public",
"void",
"refresh",
"(",
")",
"{",
"FileReader",
"fr",
"=",
"null",
";",
"if",
"(",
"file",
"!=",
"null",
")",
"{",
"try",
"{",
"fr",
"=",
"new",
"FileReader",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
... | Method which loads policy data from policy file. | [
"Method",
"which",
"loads",
"policy",
"data",
"from",
"policy",
"file",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L123-L134 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.addParsedPolicyEntries | private void addParsedPolicyEntries(List<ParsedPolicyEntry> parsedEntries, List<ProGradePolicyEntry> entries,
KeyStore keystore, boolean grant) throws Exception {
for (ParsedPolicyEntry p : parsedEntries) {
try {
entries.add(initializePolicyEntry(p, keystore, grant));
} catch (Exception e) {
System.err.println("Unable to initialize policy entry: " + e.getMessage());
}
}
} | java | private void addParsedPolicyEntries(List<ParsedPolicyEntry> parsedEntries, List<ProGradePolicyEntry> entries,
KeyStore keystore, boolean grant) throws Exception {
for (ParsedPolicyEntry p : parsedEntries) {
try {
entries.add(initializePolicyEntry(p, keystore, grant));
} catch (Exception e) {
System.err.println("Unable to initialize policy entry: " + e.getMessage());
}
}
} | [
"private",
"void",
"addParsedPolicyEntries",
"(",
"List",
"<",
"ParsedPolicyEntry",
">",
"parsedEntries",
",",
"List",
"<",
"ProGradePolicyEntry",
">",
"entries",
",",
"KeyStore",
"keystore",
",",
"boolean",
"grant",
")",
"throws",
"Exception",
"{",
"for",
"(",
... | Private method which adds parsedEntries to entries.
@param parsedEntries parsed entries from policy file which will be added to entries
@param entries entries will add parsed entries to themselves
@param keystore KeyStore which is used by this policy file
@param grant true for priority grant, false for priority deny
@throws Exception when there was any problem during adding entries to policy | [
"Private",
"method",
"which",
"adds",
"parsedEntries",
"to",
"entries",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L223-L232 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.initializePolicyEntry | private ProGradePolicyEntry initializePolicyEntry(ParsedPolicyEntry parsedEntry, KeyStore keystore, boolean grant)
throws Exception {
ProGradePolicyEntry entry = new ProGradePolicyEntry(grant, debug);
// codesource
if (parsedEntry.getCodebase() != null || parsedEntry.getSignedBy() != null) {
CodeSource cs = createCodeSource(parsedEntry, keystore);
if (cs != null) {
entry.setCodeSource(cs);
} else {
// it happens if there is signedBy which isn't contain in keystore
entry.setNeverImplies(true);
// any next isn't needed because entry will never implies anything
return entry;
}
}
// principals
for (ParsedPrincipal p : parsedEntry.getPrincipals()) {
if (p.hasAlias()) {
String principal = gainPrincipalFromAlias(expandStringWithProperty(p.getAlias()), keystore);
if (principal != null) {
entry.addPrincipal(new ProGradePrincipal("javax.security.auth.x500.X500Principal", principal, false, false));
} else {
// it happens if there is alias which isn't contain in keystore
entry.setNeverImplies(true);
// any next isn't needed because entry will never implies anything
return entry;
}
} else {
entry.addPrincipal(new ProGradePrincipal(p.getPrincipalClass(), expandStringWithProperty(p.getPrincipalName()),
p.hasClassWildcard(), p.hasNameWildcard()));
}
}
// permissions
for (ParsedPermission p : parsedEntry.getPermissions()) {
Permission perm = createPermission(p, keystore);
if (perm != null) {
entry.addPermission(perm);
}
}
return entry;
} | java | private ProGradePolicyEntry initializePolicyEntry(ParsedPolicyEntry parsedEntry, KeyStore keystore, boolean grant)
throws Exception {
ProGradePolicyEntry entry = new ProGradePolicyEntry(grant, debug);
// codesource
if (parsedEntry.getCodebase() != null || parsedEntry.getSignedBy() != null) {
CodeSource cs = createCodeSource(parsedEntry, keystore);
if (cs != null) {
entry.setCodeSource(cs);
} else {
// it happens if there is signedBy which isn't contain in keystore
entry.setNeverImplies(true);
// any next isn't needed because entry will never implies anything
return entry;
}
}
// principals
for (ParsedPrincipal p : parsedEntry.getPrincipals()) {
if (p.hasAlias()) {
String principal = gainPrincipalFromAlias(expandStringWithProperty(p.getAlias()), keystore);
if (principal != null) {
entry.addPrincipal(new ProGradePrincipal("javax.security.auth.x500.X500Principal", principal, false, false));
} else {
// it happens if there is alias which isn't contain in keystore
entry.setNeverImplies(true);
// any next isn't needed because entry will never implies anything
return entry;
}
} else {
entry.addPrincipal(new ProGradePrincipal(p.getPrincipalClass(), expandStringWithProperty(p.getPrincipalName()),
p.hasClassWildcard(), p.hasNameWildcard()));
}
}
// permissions
for (ParsedPermission p : parsedEntry.getPermissions()) {
Permission perm = createPermission(p, keystore);
if (perm != null) {
entry.addPermission(perm);
}
}
return entry;
} | [
"private",
"ProGradePolicyEntry",
"initializePolicyEntry",
"(",
"ParsedPolicyEntry",
"parsedEntry",
",",
"KeyStore",
"keystore",
",",
"boolean",
"grant",
")",
"throws",
"Exception",
"{",
"ProGradePolicyEntry",
"entry",
"=",
"new",
"ProGradePolicyEntry",
"(",
"grant",
",... | Private method for initializing one policy entry.
@param parsedEntry parsed entry using for creating new entry ProgradePolicyEntry
@param keystore KeyStore which is used by this policy file
@param grant true for priority grant, false for priority deny
@return ProgradePolicyEntry which represents this parsedEntry
@throws Exception when there was any problem during initializing of policy entry | [
"Private",
"method",
"for",
"initializing",
"one",
"policy",
"entry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L243-L287 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.entriesImplyPermission | private boolean entriesImplyPermission(List<ProGradePolicyEntry> policyEntriesList, ProtectionDomain domain,
Permission permission) {
for (ProGradePolicyEntry entry : policyEntriesList) {
if (entry.implies(domain, permission)) {
return true;
}
}
return false;
} | java | private boolean entriesImplyPermission(List<ProGradePolicyEntry> policyEntriesList, ProtectionDomain domain,
Permission permission) {
for (ProGradePolicyEntry entry : policyEntriesList) {
if (entry.implies(domain, permission)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"entriesImplyPermission",
"(",
"List",
"<",
"ProGradePolicyEntry",
">",
"policyEntriesList",
",",
"ProtectionDomain",
"domain",
",",
"Permission",
"permission",
")",
"{",
"for",
"(",
"ProGradePolicyEntry",
"entry",
":",
"policyEntriesList",
")",
... | Private method for determining whether grant or deny entries of ProgradePolicyFile imply given Permission.
@param domain active ProtectionDomain to test
@param permission Permission which need to be determined
@return true if grant or deny entries of this ProgradePolicyFile imply given Permission, false otherwise | [
"Private",
"method",
"for",
"determining",
"whether",
"grant",
"or",
"deny",
"entries",
"of",
"ProgradePolicyFile",
"imply",
"given",
"Permission",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L388-L396 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.expandStringWithProperty | private String expandStringWithProperty(String s) throws Exception {
// if expandProperties is false, don't expand property
if (!expandProperties) {
return s;
}
// if string doesn't contain property, returns original string
if (s == null || s.indexOf("${") == -1) {
return s;
}
String toReturn = "";
String[] split = s.split(Pattern.quote("${"));
toReturn += split[0];
for (int i = 1; i < split.length; i++) {
String part = split[i];
// don't expand ${{...}}
if (part.startsWith("{")) {
toReturn += ("${" + part);
continue;
}
String[] splitPart = part.split("}", 2);
if (splitPart.length < 2) {
throw new Exception("ER001: Expand property without end } or inner property expansion!");
} else {
// add expanded property
// ${/} = file.separator
if (splitPart[0].equals("/")) {
toReturn += File.separator;
} else {
toReturn += SecurityActions.getSystemProperty(splitPart[0]);
}
toReturn += splitPart[1];
}
}
return toReturn;
} | java | private String expandStringWithProperty(String s) throws Exception {
// if expandProperties is false, don't expand property
if (!expandProperties) {
return s;
}
// if string doesn't contain property, returns original string
if (s == null || s.indexOf("${") == -1) {
return s;
}
String toReturn = "";
String[] split = s.split(Pattern.quote("${"));
toReturn += split[0];
for (int i = 1; i < split.length; i++) {
String part = split[i];
// don't expand ${{...}}
if (part.startsWith("{")) {
toReturn += ("${" + part);
continue;
}
String[] splitPart = part.split("}", 2);
if (splitPart.length < 2) {
throw new Exception("ER001: Expand property without end } or inner property expansion!");
} else {
// add expanded property
// ${/} = file.separator
if (splitPart[0].equals("/")) {
toReturn += File.separator;
} else {
toReturn += SecurityActions.getSystemProperty(splitPart[0]);
}
toReturn += splitPart[1];
}
}
return toReturn;
} | [
"private",
"String",
"expandStringWithProperty",
"(",
"String",
"s",
")",
"throws",
"Exception",
"{",
"// if expandProperties is false, don't expand property",
"if",
"(",
"!",
"expandProperties",
")",
"{",
"return",
"s",
";",
"}",
"// if string doesn't contain property, ret... | Private method for expanding String which contains any property.
@param s String for expanding
@return expanded String
@throws Exception when any ends without '}' or contains inner property expansion | [
"Private",
"method",
"for",
"expanding",
"String",
"which",
"contains",
"any",
"property",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L514-L548 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.createCodeSource | private CodeSource createCodeSource(ParsedPolicyEntry parsedEntry, KeyStore keystore) throws Exception {
String parsedCodebase = expandStringWithProperty(parsedEntry.getCodebase());
String parsedCertificates = expandStringWithProperty(parsedEntry.getSignedBy());
String[] splitCertificates = new String[0];
if (parsedCertificates != null) {
splitCertificates = parsedCertificates.split(",");
}
if (splitCertificates.length > 0 && keystore == null) {
throw new Exception("ER002: Keystore must be defined if signedBy is used");
}
List<Certificate> certList = new ArrayList<Certificate>();
for (int i = 0; i < splitCertificates.length; i++) {
Certificate certificate = keystore.getCertificate(splitCertificates[i]);
if (certificate != null) {
certList.add(certificate);
} else {
// return null to indicate that it never implies any permission
return null;
}
}
Certificate[] certificates;
if (certList.isEmpty()) {
certificates = null;
} else {
certificates = new Certificate[certList.size()];
certList.toArray(certificates);
}
URL url;
if (parsedCodebase == null) {
url = null;
} else {
url = new URL(parsedCodebase);
}
CodeSource cs = new CodeSource(adaptURL(url), certificates);
return cs;
} | java | private CodeSource createCodeSource(ParsedPolicyEntry parsedEntry, KeyStore keystore) throws Exception {
String parsedCodebase = expandStringWithProperty(parsedEntry.getCodebase());
String parsedCertificates = expandStringWithProperty(parsedEntry.getSignedBy());
String[] splitCertificates = new String[0];
if (parsedCertificates != null) {
splitCertificates = parsedCertificates.split(",");
}
if (splitCertificates.length > 0 && keystore == null) {
throw new Exception("ER002: Keystore must be defined if signedBy is used");
}
List<Certificate> certList = new ArrayList<Certificate>();
for (int i = 0; i < splitCertificates.length; i++) {
Certificate certificate = keystore.getCertificate(splitCertificates[i]);
if (certificate != null) {
certList.add(certificate);
} else {
// return null to indicate that it never implies any permission
return null;
}
}
Certificate[] certificates;
if (certList.isEmpty()) {
certificates = null;
} else {
certificates = new Certificate[certList.size()];
certList.toArray(certificates);
}
URL url;
if (parsedCodebase == null) {
url = null;
} else {
url = new URL(parsedCodebase);
}
CodeSource cs = new CodeSource(adaptURL(url), certificates);
return cs;
} | [
"private",
"CodeSource",
"createCodeSource",
"(",
"ParsedPolicyEntry",
"parsedEntry",
",",
"KeyStore",
"keystore",
")",
"throws",
"Exception",
"{",
"String",
"parsedCodebase",
"=",
"expandStringWithProperty",
"(",
"parsedEntry",
".",
"getCodebase",
"(",
")",
")",
";",... | Private method for creating new CodeSource object from ParsedEntry.
@param parsedEntry ParsedEntry with informations about CodeSource
@param keystore KeyStore which is used by this policy file
@return new created CodeSource
@throws Exception when there was any problem during creating CodeSource | [
"Private",
"method",
"for",
"creating",
"new",
"CodeSource",
"object",
"from",
"ParsedEntry",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L558-L596 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.adaptURL | private URL adaptURL(URL url) throws Exception {
if (url != null && url.getProtocol().equals("file")) {
url = new URL(fixEncodedURI(url.toURI().toASCIIString()));
}
return url;
} | java | private URL adaptURL(URL url) throws Exception {
if (url != null && url.getProtocol().equals("file")) {
url = new URL(fixEncodedURI(url.toURI().toASCIIString()));
}
return url;
} | [
"private",
"URL",
"adaptURL",
"(",
"URL",
"url",
")",
"throws",
"Exception",
"{",
"if",
"(",
"url",
"!=",
"null",
"&&",
"url",
".",
"getProtocol",
"(",
")",
".",
"equals",
"(",
"\"file\"",
")",
")",
"{",
"url",
"=",
"new",
"URL",
"(",
"fixEncodedURI"... | Private method for adapting URL for using of this ProgradePolicyFile.
@param url URL for adapting
@return adapted URL
@throws Exception when there was any problem during adapting URL | [
"Private",
"method",
"for",
"adapting",
"URL",
"for",
"using",
"of",
"this",
"ProgradePolicyFile",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L605-L610 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.createKeystore | private KeyStore createKeystore(ParsedKeystoreEntry parsedKeystoreEntry, String keystorePasswordURL, File policyFile)
throws Exception {
if (parsedKeystoreEntry == null) {
return null;
}
KeyStore toReturn;
String keystoreURL = expandStringWithProperty(parsedKeystoreEntry.getKeystoreURL());
String keystoreType = expandStringWithProperty(parsedKeystoreEntry.getKeystoreType());
String keystoreProvider = expandStringWithProperty(parsedKeystoreEntry.getKeystoreProvider());
if (keystoreURL == null) {
throw new Exception("ER003: Null keystore url!");
}
if (keystoreType == null) {
keystoreType = KeyStore.getDefaultType();
}
if (keystoreProvider == null) {
toReturn = KeyStore.getInstance(keystoreType);
} else {
toReturn = KeyStore.getInstance(keystoreType, keystoreProvider);
}
char[] keystorePassword = null;
if (keystorePasswordURL != null) {
keystorePassword = readKeystorePassword(expandStringWithProperty(keystorePasswordURL), policyFile);
}
// try relative path to policy file
String path = getPolicyFileHome(policyFile);
File f = null;
if (path != null) {
f = new File(path, keystoreURL);
}
if (f == null || !f.exists()) {
// try absoluth path
f = new File(keystoreURL);
if (!f.exists()) {
throw new Exception("ER004: KeyStore doesn't exists!");
}
}
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
toReturn.load(fis, keystorePassword);
} finally {
if (fis != null) {
fis.close();
}
}
return toReturn;
} | java | private KeyStore createKeystore(ParsedKeystoreEntry parsedKeystoreEntry, String keystorePasswordURL, File policyFile)
throws Exception {
if (parsedKeystoreEntry == null) {
return null;
}
KeyStore toReturn;
String keystoreURL = expandStringWithProperty(parsedKeystoreEntry.getKeystoreURL());
String keystoreType = expandStringWithProperty(parsedKeystoreEntry.getKeystoreType());
String keystoreProvider = expandStringWithProperty(parsedKeystoreEntry.getKeystoreProvider());
if (keystoreURL == null) {
throw new Exception("ER003: Null keystore url!");
}
if (keystoreType == null) {
keystoreType = KeyStore.getDefaultType();
}
if (keystoreProvider == null) {
toReturn = KeyStore.getInstance(keystoreType);
} else {
toReturn = KeyStore.getInstance(keystoreType, keystoreProvider);
}
char[] keystorePassword = null;
if (keystorePasswordURL != null) {
keystorePassword = readKeystorePassword(expandStringWithProperty(keystorePasswordURL), policyFile);
}
// try relative path to policy file
String path = getPolicyFileHome(policyFile);
File f = null;
if (path != null) {
f = new File(path, keystoreURL);
}
if (f == null || !f.exists()) {
// try absoluth path
f = new File(keystoreURL);
if (!f.exists()) {
throw new Exception("ER004: KeyStore doesn't exists!");
}
}
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
toReturn.load(fis, keystorePassword);
} finally {
if (fis != null) {
fis.close();
}
}
return toReturn;
} | [
"private",
"KeyStore",
"createKeystore",
"(",
"ParsedKeystoreEntry",
"parsedKeystoreEntry",
",",
"String",
"keystorePasswordURL",
",",
"File",
"policyFile",
")",
"throws",
"Exception",
"{",
"if",
"(",
"parsedKeystoreEntry",
"==",
"null",
")",
"{",
"return",
"null",
... | Private method for creating KeyStore object from ParsedKeystoreEntry and other information from policy file.
@param parsedKeystoreEntry parsedKeystoreEntry containing information about keystore
@param keystorePasswordURL URL to file which contain password for given keystore
@param policyFile used policy file
@return new created KeyStore
@throws Exception when there was any problem during creating KeyStore | [
"Private",
"method",
"for",
"creating",
"KeyStore",
"object",
"from",
"ParsedKeystoreEntry",
"and",
"other",
"information",
"from",
"policy",
"file",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L621-L675 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.readKeystorePassword | private char[] readKeystorePassword(String keystorePasswordURL, File policyFile) throws Exception {
// try relative path to policy file
File f = new File(getPolicyFileHome(policyFile), keystorePasswordURL);
if (!f.exists()) {
// try absoluth path
f = new File(keystorePasswordURL);
if (!f.exists()) {
throw new Exception("ER005: File on keystorePasswordURL doesn't exists!");
}
}
Reader reader = new FileReader(f);
StringBuilder sb = new StringBuilder();
char buffer[] = new char[64];
int len;
while ((len = reader.read(buffer)) > 0) {
sb.append(buffer, 0, len);
}
reader.close();
return sb.toString().trim().toCharArray();
} | java | private char[] readKeystorePassword(String keystorePasswordURL, File policyFile) throws Exception {
// try relative path to policy file
File f = new File(getPolicyFileHome(policyFile), keystorePasswordURL);
if (!f.exists()) {
// try absoluth path
f = new File(keystorePasswordURL);
if (!f.exists()) {
throw new Exception("ER005: File on keystorePasswordURL doesn't exists!");
}
}
Reader reader = new FileReader(f);
StringBuilder sb = new StringBuilder();
char buffer[] = new char[64];
int len;
while ((len = reader.read(buffer)) > 0) {
sb.append(buffer, 0, len);
}
reader.close();
return sb.toString().trim().toCharArray();
} | [
"private",
"char",
"[",
"]",
"readKeystorePassword",
"(",
"String",
"keystorePasswordURL",
",",
"File",
"policyFile",
")",
"throws",
"Exception",
"{",
"// try relative path to policy file",
"File",
"f",
"=",
"new",
"File",
"(",
"getPolicyFileHome",
"(",
"policyFile",
... | Private method for reading password for keystore from file.
@param keystorePasswordURL URL to file which contain password for keystore
@param policyFile used policy file
@return password for keystore
@throws Exception when there was any problem during reading keystore password | [
"Private",
"method",
"for",
"reading",
"password",
"for",
"keystore",
"from",
"file",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L685-L704 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.gainPrincipalFromAlias | private String gainPrincipalFromAlias(String alias, KeyStore keystore) throws Exception {
if (keystore == null) {
return null;
}
if (!keystore.containsAlias(alias)) {
return null;
}
Certificate certificate = keystore.getCertificate(alias);
if (certificate == null || !(certificate instanceof X509Certificate)) {
return null;
}
X509Certificate x509Certificate = (X509Certificate) certificate;
X500Principal principal = new X500Principal(x509Certificate.getSubjectX500Principal().toString());
return principal.getName();
} | java | private String gainPrincipalFromAlias(String alias, KeyStore keystore) throws Exception {
if (keystore == null) {
return null;
}
if (!keystore.containsAlias(alias)) {
return null;
}
Certificate certificate = keystore.getCertificate(alias);
if (certificate == null || !(certificate instanceof X509Certificate)) {
return null;
}
X509Certificate x509Certificate = (X509Certificate) certificate;
X500Principal principal = new X500Principal(x509Certificate.getSubjectX500Principal().toString());
return principal.getName();
} | [
"private",
"String",
"gainPrincipalFromAlias",
"(",
"String",
"alias",
",",
"KeyStore",
"keystore",
")",
"throws",
"Exception",
"{",
"if",
"(",
"keystore",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"keystore",
".",
"containsAlias",
... | Private method for gaining X500Principal from keystore according its alias.
@param alias alias of principal
@param keystore KeyStore which is used by this policy file
@return name of gained X500Principal
@throws Exception when there was any problem during gaining Principal | [
"Private",
"method",
"for",
"gaining",
"X500Principal",
"from",
"keystore",
"according",
"its",
"alias",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L714-L730 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.getPolicyFileHome | private String getPolicyFileHome(File file) {
if (file == null || !file.exists()) {
return null;
}
return file.getAbsoluteFile().getParent();
} | java | private String getPolicyFileHome(File file) {
if (file == null || !file.exists()) {
return null;
}
return file.getAbsoluteFile().getParent();
} | [
"private",
"String",
"getPolicyFileHome",
"(",
"File",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"file",
".",
"getAbsoluteFile",
"(",
")",
".",
"getP... | Private method for gaining absolute path of folder with policy file .
@param file file with policy
@return absolute path for folder with policy file or null if file doesn't exist | [
"Private",
"method",
"for",
"gaining",
"absolute",
"path",
"of",
"folder",
"with",
"policy",
"file",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L738-L743 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.getJavaPolicies | private List<ParsedPolicy> getJavaPolicies() {
List<ParsedPolicy> list = new ArrayList<ParsedPolicy>();
int counter = 1;
String policyUrl = null;
while ((policyUrl = SecurityActions.getSecurityProperty("policy.url." + counter)) != null) {
try {
policyUrl = expandStringWithProperty(policyUrl);
} catch (Exception ex) {
System.err.println("Expanding filepath in policy policy.url." + counter + "=" + policyUrl
+ " failed. Exception message: " + ex.getMessage());
counter++;
continue;
}
ParsedPolicy p = null;
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new URL(policyUrl).openStream(), "UTF-8");
p = new Parser(debug).parse(reader);
if (p != null) {
list.add(p);
} else {
System.err.println("Parsed policy policy.url." + counter + "=" + policyUrl + " is null");
}
} catch (Exception ex) {
System.err.println("Policy policy.url." + counter + "=" + policyUrl
+ " wasn't successfully parsed. Exception message: " + ex.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
counter++;
}
return list;
} | java | private List<ParsedPolicy> getJavaPolicies() {
List<ParsedPolicy> list = new ArrayList<ParsedPolicy>();
int counter = 1;
String policyUrl = null;
while ((policyUrl = SecurityActions.getSecurityProperty("policy.url." + counter)) != null) {
try {
policyUrl = expandStringWithProperty(policyUrl);
} catch (Exception ex) {
System.err.println("Expanding filepath in policy policy.url." + counter + "=" + policyUrl
+ " failed. Exception message: " + ex.getMessage());
counter++;
continue;
}
ParsedPolicy p = null;
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new URL(policyUrl).openStream(), "UTF-8");
p = new Parser(debug).parse(reader);
if (p != null) {
list.add(p);
} else {
System.err.println("Parsed policy policy.url." + counter + "=" + policyUrl + " is null");
}
} catch (Exception ex) {
System.err.println("Policy policy.url." + counter + "=" + policyUrl
+ " wasn't successfully parsed. Exception message: " + ex.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
counter++;
}
return list;
} | [
"private",
"List",
"<",
"ParsedPolicy",
">",
"getJavaPolicies",
"(",
")",
"{",
"List",
"<",
"ParsedPolicy",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"ParsedPolicy",
">",
"(",
")",
";",
"int",
"counter",
"=",
"1",
";",
"String",
"policyUrl",
"=",
"null"... | Private method for gaining and parsing all policies defined in java.security file.
@return Parsed policies in list of ParsedPolicy | [
"Private",
"method",
"for",
"gaining",
"and",
"parsing",
"all",
"policies",
"defined",
"in",
"java",
".",
"security",
"file",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L750-L790 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.initializeStaticPolicy | private void initializeStaticPolicy(List<ProGradePolicyEntry> grantEntriesList) throws Exception {
// grant codeBase "file:${{java.ext.dirs}}/*" {
// permission java.security.AllPermission;
// };
ProGradePolicyEntry p1 = new ProGradePolicyEntry(true, debug);
Certificate[] certificates = null;
URL url = new URL(expandStringWithProperty("file:${{java.ext.dirs}}/*"));
CodeSource cs = new CodeSource(adaptURL(url), certificates);
p1.setCodeSource(cs);
p1.addPermission(new AllPermission());
grantEntriesList.add(p1);
// grant {
// permission java.lang.RuntimePermission "stopThread";
// permission java.net.SocketPermission "localhost:1024-", "listen";
// permission java.util.PropertyPermission "java.version", "read";
// permission java.util.PropertyPermission "java.vendor", "read";
// permission java.util.PropertyPermission "java.vendor.url", "read";
// permission java.util.PropertyPermission "java.class.version", "read";
// permission java.util.PropertyPermission "os.name", "read";
// permission java.util.PropertyPermission "os.version", "read";
// permission java.util.PropertyPermission "os.arch", "read";
// permission java.util.PropertyPermission "file.separator", "read";
// permission java.util.PropertyPermission "path.separator", "read";
// permission java.util.PropertyPermission "line.separator", "read";
// permission java.util.PropertyPermission "java.specification.version", "read";
// permission java.util.PropertyPermission "java.specification.vendor", "read";
// permission java.util.PropertyPermission "java.specification.name", "read";
// permission java.util.PropertyPermission "java.vm.specification.version", "read";
// permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
// permission java.util.PropertyPermission "java.vm.specification.name", "read";
// permission java.util.PropertyPermission "java.vm.version", "read";
// permission java.util.PropertyPermission "java.vm.vendor", "read";
// permission java.util.PropertyPermission "java.vm.name", "read";
// };
ProGradePolicyEntry p2 = new ProGradePolicyEntry(true, debug);
p2.addPermission(new RuntimePermission("stopThread"));
p2.addPermission(new SocketPermission("localhost:1024-", "listen"));
p2.addPermission(new PropertyPermission("java.version", "read"));
p2.addPermission(new PropertyPermission("java.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vendor.url", "read"));
p2.addPermission(new PropertyPermission("java.class.version", "read"));
p2.addPermission(new PropertyPermission("os.name", "read"));
p2.addPermission(new PropertyPermission("os.version", "read"));
p2.addPermission(new PropertyPermission("os.arch", "read"));
p2.addPermission(new PropertyPermission("file.separator", "read"));
p2.addPermission(new PropertyPermission("path.separator", "read"));
p2.addPermission(new PropertyPermission("line.separator", "read"));
p2.addPermission(new PropertyPermission("java.specification.version", "read"));
p2.addPermission(new PropertyPermission("java.specification.vendor", "read"));
p2.addPermission(new PropertyPermission("java.specification.name", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.version", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.name", "read"));
p2.addPermission(new PropertyPermission("java.vm.version", "read"));
p2.addPermission(new PropertyPermission("java.vm.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vm.name", "read"));
grantEntriesList.add(p2);
} | java | private void initializeStaticPolicy(List<ProGradePolicyEntry> grantEntriesList) throws Exception {
// grant codeBase "file:${{java.ext.dirs}}/*" {
// permission java.security.AllPermission;
// };
ProGradePolicyEntry p1 = new ProGradePolicyEntry(true, debug);
Certificate[] certificates = null;
URL url = new URL(expandStringWithProperty("file:${{java.ext.dirs}}/*"));
CodeSource cs = new CodeSource(adaptURL(url), certificates);
p1.setCodeSource(cs);
p1.addPermission(new AllPermission());
grantEntriesList.add(p1);
// grant {
// permission java.lang.RuntimePermission "stopThread";
// permission java.net.SocketPermission "localhost:1024-", "listen";
// permission java.util.PropertyPermission "java.version", "read";
// permission java.util.PropertyPermission "java.vendor", "read";
// permission java.util.PropertyPermission "java.vendor.url", "read";
// permission java.util.PropertyPermission "java.class.version", "read";
// permission java.util.PropertyPermission "os.name", "read";
// permission java.util.PropertyPermission "os.version", "read";
// permission java.util.PropertyPermission "os.arch", "read";
// permission java.util.PropertyPermission "file.separator", "read";
// permission java.util.PropertyPermission "path.separator", "read";
// permission java.util.PropertyPermission "line.separator", "read";
// permission java.util.PropertyPermission "java.specification.version", "read";
// permission java.util.PropertyPermission "java.specification.vendor", "read";
// permission java.util.PropertyPermission "java.specification.name", "read";
// permission java.util.PropertyPermission "java.vm.specification.version", "read";
// permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
// permission java.util.PropertyPermission "java.vm.specification.name", "read";
// permission java.util.PropertyPermission "java.vm.version", "read";
// permission java.util.PropertyPermission "java.vm.vendor", "read";
// permission java.util.PropertyPermission "java.vm.name", "read";
// };
ProGradePolicyEntry p2 = new ProGradePolicyEntry(true, debug);
p2.addPermission(new RuntimePermission("stopThread"));
p2.addPermission(new SocketPermission("localhost:1024-", "listen"));
p2.addPermission(new PropertyPermission("java.version", "read"));
p2.addPermission(new PropertyPermission("java.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vendor.url", "read"));
p2.addPermission(new PropertyPermission("java.class.version", "read"));
p2.addPermission(new PropertyPermission("os.name", "read"));
p2.addPermission(new PropertyPermission("os.version", "read"));
p2.addPermission(new PropertyPermission("os.arch", "read"));
p2.addPermission(new PropertyPermission("file.separator", "read"));
p2.addPermission(new PropertyPermission("path.separator", "read"));
p2.addPermission(new PropertyPermission("line.separator", "read"));
p2.addPermission(new PropertyPermission("java.specification.version", "read"));
p2.addPermission(new PropertyPermission("java.specification.vendor", "read"));
p2.addPermission(new PropertyPermission("java.specification.name", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.version", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vm.specification.name", "read"));
p2.addPermission(new PropertyPermission("java.vm.version", "read"));
p2.addPermission(new PropertyPermission("java.vm.vendor", "read"));
p2.addPermission(new PropertyPermission("java.vm.name", "read"));
grantEntriesList.add(p2);
} | [
"private",
"void",
"initializeStaticPolicy",
"(",
"List",
"<",
"ProGradePolicyEntry",
">",
"grantEntriesList",
")",
"throws",
"Exception",
"{",
"// grant codeBase \"file:${{java.ext.dirs}}/*\" {",
"// permission java.security.AllPermission;",
"// };",
"ProGradePolicyEntry",
"p1",
... | Private method for initializing static policy.
@throws Exception when there was any problem during initializing static policy | [
"Private",
"method",
"for",
"initializing",
"static",
"policy",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L797-L857 | train |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.getCertificates | private Certificate[] getCertificates(String parsedCertificates, KeyStore keystore) throws Exception {
String[] splitCertificates = new String[0];
if (parsedCertificates != null) {
splitCertificates = parsedCertificates.split(",");
}
if (splitCertificates.length > 0 && keystore == null) {
throw new Exception("ER006: Keystore must be defined if signedBy is used");
}
List<Certificate> certList = new ArrayList<Certificate>();
for (int i = 0; i < splitCertificates.length; i++) {
Certificate certificate = keystore.getCertificate(splitCertificates[i]);
if (certificate != null) {
certList.add(certificate);
} else {
// return null to indicate that this permission is ignored
return null;
}
}
Certificate[] certificates;
if (certList.isEmpty()) {
certificates = null;
} else {
certificates = new Certificate[certList.size()];
certList.toArray(certificates);
}
return certificates;
} | java | private Certificate[] getCertificates(String parsedCertificates, KeyStore keystore) throws Exception {
String[] splitCertificates = new String[0];
if (parsedCertificates != null) {
splitCertificates = parsedCertificates.split(",");
}
if (splitCertificates.length > 0 && keystore == null) {
throw new Exception("ER006: Keystore must be defined if signedBy is used");
}
List<Certificate> certList = new ArrayList<Certificate>();
for (int i = 0; i < splitCertificates.length; i++) {
Certificate certificate = keystore.getCertificate(splitCertificates[i]);
if (certificate != null) {
certList.add(certificate);
} else {
// return null to indicate that this permission is ignored
return null;
}
}
Certificate[] certificates;
if (certList.isEmpty()) {
certificates = null;
} else {
certificates = new Certificate[certList.size()];
certList.toArray(certificates);
}
return certificates;
} | [
"private",
"Certificate",
"[",
"]",
"getCertificates",
"(",
"String",
"parsedCertificates",
",",
"KeyStore",
"keystore",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"splitCertificates",
"=",
"new",
"String",
"[",
"0",
"]",
";",
"if",
"(",
"parsedCerti... | Private method for getting certificates from KeyStore.
@param parsedCertificates signedBy part of policy file defines certificates
@param keystore KeyStore which is used by this policy file
@return array of Certificates
@throws Exception when there was any problem during getting Certificates | [
"Private",
"method",
"for",
"getting",
"certificates",
"from",
"KeyStore",
"."
] | 371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L892-L918 | train |
bpsm/edn-java | src/main/java/us/bpsm/edn/Symbol.java | Symbol.newSymbol | public static Symbol newSymbol(String prefix, String name) {
checkArguments(prefix, name);
return new Symbol(prefix, name);
} | java | public static Symbol newSymbol(String prefix, String name) {
checkArguments(prefix, name);
return new Symbol(prefix, name);
} | [
"public",
"static",
"Symbol",
"newSymbol",
"(",
"String",
"prefix",
",",
"String",
"name",
")",
"{",
"checkArguments",
"(",
"prefix",
",",
"name",
")",
";",
"return",
"new",
"Symbol",
"(",
"prefix",
",",
"name",
")",
";",
"}"
] | Provide a Symbol with the given prefix and name.
@param prefix
An empty String or a non-empty String obeying the
restrictions specified by edn. Never null.
@param name
A non-empty string obeying the restrictions specified by edn.
Never null.
@return a Symbol, never null. | [
"Provide",
"a",
"Symbol",
"with",
"the",
"given",
"prefix",
"and",
"name",
"."
] | c5dfdb77431da1aca3c257599b237a21575629b2 | https://github.com/bpsm/edn-java/blob/c5dfdb77431da1aca3c257599b237a21575629b2/src/main/java/us/bpsm/edn/Symbol.java#L50-L53 | train |
LachlanMcKee/gsonpath | library/src/main/java/gsonpath/GsonUtil.java | GsonUtil.isValidValue | public static boolean isValidValue(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.skipValue();
return false;
}
return true;
} | java | public static boolean isValidValue(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.skipValue();
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"isValidValue",
"(",
"JsonReader",
"in",
")",
"throws",
"IOException",
"{",
"if",
"(",
"in",
".",
"peek",
"(",
")",
"==",
"JsonToken",
".",
"NULL",
")",
"{",
"in",
".",
"skipValue",
"(",
")",
";",
"return",
"false",
";",
... | Determines whether the next value within the reader is not null.
@param in the json reader used to read the stream
@return true if a valid value exists, or false if the value is null.
@throws IOException see {@link JsonReader#skipValue()} | [
"Determines",
"whether",
"the",
"next",
"value",
"within",
"the",
"reader",
"is",
"not",
"null",
"."
] | 7462869521b163684d66a07feef0ddbadc8949b5 | https://github.com/LachlanMcKee/gsonpath/blob/7462869521b163684d66a07feef0ddbadc8949b5/library/src/main/java/gsonpath/GsonUtil.java#L27-L33 | train |
rnorth/visible-assertions | src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java | VisibleAssertions.assertThat | public static <T> void assertThat(String whatTheObjectIs, T actual, Matcher<? super T> matcher) {
Description description = new StringDescription();
if (matcher.matches(actual)) {
description.appendText(whatTheObjectIs);
description.appendText(" ");
matcher.describeTo(description);
pass(description.toString());
} else {
description.appendText("asserted that it ")
.appendDescriptionOf(matcher)
.appendText(" but ");
matcher.describeMismatch(actual, description);
fail("assertion on " + whatTheObjectIs + " failed", description.toString());
}
} | java | public static <T> void assertThat(String whatTheObjectIs, T actual, Matcher<? super T> matcher) {
Description description = new StringDescription();
if (matcher.matches(actual)) {
description.appendText(whatTheObjectIs);
description.appendText(" ");
matcher.describeTo(description);
pass(description.toString());
} else {
description.appendText("asserted that it ")
.appendDescriptionOf(matcher)
.appendText(" but ");
matcher.describeMismatch(actual, description);
fail("assertion on " + whatTheObjectIs + " failed", description.toString());
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"assertThat",
"(",
"String",
"whatTheObjectIs",
",",
"T",
"actual",
",",
"Matcher",
"<",
"?",
"super",
"T",
">",
"matcher",
")",
"{",
"Description",
"description",
"=",
"new",
"StringDescription",
"(",
")",
";",
... | Assert using a Hamcrest matcher.
@param whatTheObjectIs what is the thing being tested, in a logical sense
@param actual the actual value
@param matcher a matcher to check the actual value against
@param <T> class of the actual value | [
"Assert",
"using",
"a",
"Hamcrest",
"matcher",
"."
] | 6d7a7724db40ac0e9f87279553f814b790310b3b | https://github.com/rnorth/visible-assertions/blob/6d7a7724db40ac0e9f87279553f814b790310b3b/src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java#L345-L359 | train |
rnorth/visible-assertions | src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java | VisibleAssertions.pass | public static void pass(String message) {
if (Boolean.getBoolean("visibleassertions.silence") || Boolean.getBoolean("visibleassertions.silence.passes")) {
return;
}
System.out.println(" " + green(TICK_MARK + " " + message));
} | java | public static void pass(String message) {
if (Boolean.getBoolean("visibleassertions.silence") || Boolean.getBoolean("visibleassertions.silence.passes")) {
return;
}
System.out.println(" " + green(TICK_MARK + " " + message));
} | [
"public",
"static",
"void",
"pass",
"(",
"String",
"message",
")",
"{",
"if",
"(",
"Boolean",
".",
"getBoolean",
"(",
"\"visibleassertions.silence\"",
")",
"||",
"Boolean",
".",
"getBoolean",
"(",
"\"visibleassertions.silence.passes\"",
")",
")",
"{",
"return",
... | Indicate that something passed.
@param message message to display alongside a green tick | [
"Indicate",
"that",
"something",
"passed",
"."
] | 6d7a7724db40ac0e9f87279553f814b790310b3b | https://github.com/rnorth/visible-assertions/blob/6d7a7724db40ac0e9f87279553f814b790310b3b/src/main/java/org/rnorth/visibleassertions/VisibleAssertions.java#L422-L427 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Attribute.java | Attribute.write | protected ByteVector write(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals)
{
ByteVector v = new ByteVector();
v.data = value;
v.length = value.length;
return v;
} | java | protected ByteVector write(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals)
{
ByteVector v = new ByteVector();
v.data = value;
v.length = value.length;
return v;
} | [
"protected",
"ByteVector",
"write",
"(",
"final",
"ClassWriter",
"cw",
",",
"final",
"byte",
"[",
"]",
"code",
",",
"final",
"int",
"len",
",",
"final",
"int",
"maxStack",
",",
"final",
"int",
"maxLocals",
")",
"{",
"ByteVector",
"v",
"=",
"new",
"ByteVe... | Returns the byte array form of this attribute.
@param cw the class to which this attribute must be added. This parameter
can be used to add to the constant pool of this class the items
that corresponds to this attribute.
@param code the bytecode of the method corresponding to this code
attribute, or <tt>null</tt> if this attribute is not a code
attributes.
@param len the length of the bytecode of the method corresponding to this
code attribute, or <tt>null</tt> if this attribute is not a code
attribute.
@param maxStack the maximum stack size of the method corresponding to
this code attribute, or -1 if this attribute is not a code
attribute.
@param maxLocals the maximum number of local variables of the method
corresponding to this code attribute, or -1 if this attribute is
not a code attribute.
@return the byte array form of this attribute. | [
"Returns",
"the",
"byte",
"array",
"form",
"of",
"this",
"attribute",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Attribute.java#L153-L164 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Attribute.java | Attribute.getCount | final int getCount() {
int count = 0;
Attribute attr = this;
while (attr != null) {
count += 1;
attr = attr.next;
}
return count;
} | java | final int getCount() {
int count = 0;
Attribute attr = this;
while (attr != null) {
count += 1;
attr = attr.next;
}
return count;
} | [
"final",
"int",
"getCount",
"(",
")",
"{",
"int",
"count",
"=",
"0",
";",
"Attribute",
"attr",
"=",
"this",
";",
"while",
"(",
"attr",
"!=",
"null",
")",
"{",
"count",
"+=",
"1",
";",
"attr",
"=",
"attr",
".",
"next",
";",
"}",
"return",
"count",... | Returns the length of the attribute list that begins with this attribute.
@return the length of the attribute list that begins with this attribute. | [
"Returns",
"the",
"length",
"of",
"the",
"attribute",
"list",
"that",
"begins",
"with",
"this",
"attribute",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Attribute.java#L171-L179 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Attribute.java | Attribute.getSize | final int getSize(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals)
{
Attribute attr = this;
int size = 0;
while (attr != null) {
cw.newUTF8(attr.type);
size += attr.write(cw, code, len, maxStack, maxLocals).length + 6;
attr = attr.next;
}
return size;
} | java | final int getSize(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals)
{
Attribute attr = this;
int size = 0;
while (attr != null) {
cw.newUTF8(attr.type);
size += attr.write(cw, code, len, maxStack, maxLocals).length + 6;
attr = attr.next;
}
return size;
} | [
"final",
"int",
"getSize",
"(",
"final",
"ClassWriter",
"cw",
",",
"final",
"byte",
"[",
"]",
"code",
",",
"final",
"int",
"len",
",",
"final",
"int",
"maxStack",
",",
"final",
"int",
"maxLocals",
")",
"{",
"Attribute",
"attr",
"=",
"this",
";",
"int",... | Returns the size of all the attributes in this attribute list.
@param cw the class writer to be used to convert the attributes into byte
arrays, with the {@link #write write} method.
@param code the bytecode of the method corresponding to these code
attributes, or <tt>null</tt> if these attributes are not code
attributes.
@param len the length of the bytecode of the method corresponding to
these code attributes, or <tt>null</tt> if these attributes are
not code attributes.
@param maxStack the maximum stack size of the method corresponding to
these code attributes, or -1 if these attributes are not code
attributes.
@param maxLocals the maximum number of local variables of the method
corresponding to these code attributes, or -1 if these attributes
are not code attributes.
@return the size of all the attributes in this attribute list. This size
includes the size of the attribute headers. | [
"Returns",
"the",
"size",
"of",
"all",
"the",
"attributes",
"in",
"this",
"attribute",
"list",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Attribute.java#L201-L216 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Attribute.java | Attribute.put | final void put(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals,
final ByteVector out)
{
Attribute attr = this;
while (attr != null) {
ByteVector b = attr.write(cw, code, len, maxStack, maxLocals);
out.putShort(cw.newUTF8(attr.type)).putInt(b.length);
out.putByteArray(b.data, 0, b.length);
attr = attr.next;
}
} | java | final void put(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals,
final ByteVector out)
{
Attribute attr = this;
while (attr != null) {
ByteVector b = attr.write(cw, code, len, maxStack, maxLocals);
out.putShort(cw.newUTF8(attr.type)).putInt(b.length);
out.putByteArray(b.data, 0, b.length);
attr = attr.next;
}
} | [
"final",
"void",
"put",
"(",
"final",
"ClassWriter",
"cw",
",",
"final",
"byte",
"[",
"]",
"code",
",",
"final",
"int",
"len",
",",
"final",
"int",
"maxStack",
",",
"final",
"int",
"maxLocals",
",",
"final",
"ByteVector",
"out",
")",
"{",
"Attribute",
... | Writes all the attributes of this attribute list in the given byte
vector.
@param cw the class writer to be used to convert the attributes into byte
arrays, with the {@link #write write} method.
@param code the bytecode of the method corresponding to these code
attributes, or <tt>null</tt> if these attributes are not code
attributes.
@param len the length of the bytecode of the method corresponding to
these code attributes, or <tt>null</tt> if these attributes are
not code attributes.
@param maxStack the maximum stack size of the method corresponding to
these code attributes, or -1 if these attributes are not code
attributes.
@param maxLocals the maximum number of local variables of the method
corresponding to these code attributes, or -1 if these attributes
are not code attributes.
@param out where the attributes must be written. | [
"Writes",
"all",
"the",
"attributes",
"of",
"this",
"attribute",
"list",
"in",
"the",
"given",
"byte",
"vector",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Attribute.java#L238-L253 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Label.java | Label.addReference | private void addReference(
final int sourcePosition,
final int referencePosition)
{
if (srcAndRefPositions == null) {
srcAndRefPositions = new int[6];
}
if (referenceCount >= srcAndRefPositions.length) {
int[] a = new int[srcAndRefPositions.length + 6];
System.arraycopy(srcAndRefPositions,
0,
a,
0,
srcAndRefPositions.length);
srcAndRefPositions = a;
}
srcAndRefPositions[referenceCount++] = sourcePosition;
srcAndRefPositions[referenceCount++] = referencePosition;
} | java | private void addReference(
final int sourcePosition,
final int referencePosition)
{
if (srcAndRefPositions == null) {
srcAndRefPositions = new int[6];
}
if (referenceCount >= srcAndRefPositions.length) {
int[] a = new int[srcAndRefPositions.length + 6];
System.arraycopy(srcAndRefPositions,
0,
a,
0,
srcAndRefPositions.length);
srcAndRefPositions = a;
}
srcAndRefPositions[referenceCount++] = sourcePosition;
srcAndRefPositions[referenceCount++] = referencePosition;
} | [
"private",
"void",
"addReference",
"(",
"final",
"int",
"sourcePosition",
",",
"final",
"int",
"referencePosition",
")",
"{",
"if",
"(",
"srcAndRefPositions",
"==",
"null",
")",
"{",
"srcAndRefPositions",
"=",
"new",
"int",
"[",
"6",
"]",
";",
"}",
"if",
"... | Adds a forward reference to this label. This method must be called only
for a true forward reference, i.e. only if this label is not resolved
yet. For backward references, the offset of the reference can be, and
must be, computed and stored directly.
@param sourcePosition the position of the referencing instruction. This
position will be used to compute the offset of this forward
reference.
@param referencePosition the position where the offset for this forward
reference must be stored. | [
"Adds",
"a",
"forward",
"reference",
"to",
"this",
"label",
".",
"This",
"method",
"must",
"be",
"called",
"only",
"for",
"a",
"true",
"forward",
"reference",
"i",
".",
"e",
".",
"only",
"if",
"this",
"label",
"is",
"not",
"resolved",
"yet",
".",
"For"... | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Label.java#L317-L335 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Label.java | Label.inSameSubroutine | boolean inSameSubroutine(final Label block) {
for (int i = 0; i < srcAndRefPositions.length; ++i) {
if ((srcAndRefPositions[i] & block.srcAndRefPositions[i]) != 0) {
return true;
}
}
return false;
} | java | boolean inSameSubroutine(final Label block) {
for (int i = 0; i < srcAndRefPositions.length; ++i) {
if ((srcAndRefPositions[i] & block.srcAndRefPositions[i]) != 0) {
return true;
}
}
return false;
} | [
"boolean",
"inSameSubroutine",
"(",
"final",
"Label",
"block",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"srcAndRefPositions",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"(",
"srcAndRefPositions",
"[",
"i",
"]",
"&",
"block"... | Returns true if this basic block and the given one belong to a common
subroutine.
@param block another basic block.
@return true if this basic block and the given one belong to a common
subroutine. | [
"Returns",
"true",
"if",
"this",
"basic",
"block",
"and",
"the",
"given",
"one",
"belong",
"to",
"a",
"common",
"subroutine",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Label.java#L441-L448 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Label.java | Label.visitSubroutine | void visitSubroutine(final Label JSR, final long id, final int nbSubroutines)
{
if (JSR != null) {
if ((status & VISITED) != 0) {
return;
}
status |= VISITED;
// adds JSR to the successors of this block, if it is a RET block
if ((status & RET) != 0) {
if (!inSameSubroutine(JSR)) {
Edge e = new Edge();
e.info = inputStackTop;
e.successor = JSR.successors.successor;
e.next = successors;
successors = e;
}
}
} else {
// if this block already belongs to subroutine 'id', returns
if (inSubroutine(id)) {
return;
}
// marks this block as belonging to subroutine 'id'
addToSubroutine(id, nbSubroutines);
}
// calls this method recursively on each successor, except JSR targets
Edge e = successors;
while (e != null) {
// if this block is a JSR block, then 'successors.next' leads
// to the JSR target (see {@link #visitJumpInsn}) and must therefore
// not be followed
if ((status & Label.JSR) == 0 || e != successors.next) {
e.successor.visitSubroutine(JSR, id, nbSubroutines);
}
e = e.next;
}
} | java | void visitSubroutine(final Label JSR, final long id, final int nbSubroutines)
{
if (JSR != null) {
if ((status & VISITED) != 0) {
return;
}
status |= VISITED;
// adds JSR to the successors of this block, if it is a RET block
if ((status & RET) != 0) {
if (!inSameSubroutine(JSR)) {
Edge e = new Edge();
e.info = inputStackTop;
e.successor = JSR.successors.successor;
e.next = successors;
successors = e;
}
}
} else {
// if this block already belongs to subroutine 'id', returns
if (inSubroutine(id)) {
return;
}
// marks this block as belonging to subroutine 'id'
addToSubroutine(id, nbSubroutines);
}
// calls this method recursively on each successor, except JSR targets
Edge e = successors;
while (e != null) {
// if this block is a JSR block, then 'successors.next' leads
// to the JSR target (see {@link #visitJumpInsn}) and must therefore
// not be followed
if ((status & Label.JSR) == 0 || e != successors.next) {
e.successor.visitSubroutine(JSR, id, nbSubroutines);
}
e = e.next;
}
} | [
"void",
"visitSubroutine",
"(",
"final",
"Label",
"JSR",
",",
"final",
"long",
"id",
",",
"final",
"int",
"nbSubroutines",
")",
"{",
"if",
"(",
"JSR",
"!=",
"null",
")",
"{",
"if",
"(",
"(",
"status",
"&",
"VISITED",
")",
"!=",
"0",
")",
"{",
"retu... | Finds the basic blocks that belong to a given subroutine, and marks these
blocks as belonging to this subroutine. This recursive method follows the
control flow graph to find all the blocks that are reachable from the
current block WITHOUT following any JSR target.
@param JSR a JSR block that jumps to this subroutine. If this JSR is not
null it is added to the successor of the RET blocks found in the
subroutine.
@param id the id of this subroutine.
@param nbSubroutines the total number of subroutines in the method. | [
"Finds",
"the",
"basic",
"blocks",
"that",
"belong",
"to",
"a",
"given",
"subroutine",
"and",
"marks",
"these",
"blocks",
"as",
"belonging",
"to",
"this",
"subroutine",
".",
"This",
"recursive",
"method",
"follows",
"the",
"control",
"flow",
"graph",
"to",
"... | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Label.java#L476-L512 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/MethodWriter.java | MethodWriter.noSuccessor | private void noSuccessor() {
if (compute == FRAMES) {
Label l = new Label();
l.frame = new Frame();
l.frame.owner = l;
l.resolve(this, code.length, code.data);
previousBlock.successor = l;
previousBlock = l;
} else {
currentBlock.outputStackMax = maxStackSize;
}
currentBlock = null;
} | java | private void noSuccessor() {
if (compute == FRAMES) {
Label l = new Label();
l.frame = new Frame();
l.frame.owner = l;
l.resolve(this, code.length, code.data);
previousBlock.successor = l;
previousBlock = l;
} else {
currentBlock.outputStackMax = maxStackSize;
}
currentBlock = null;
} | [
"private",
"void",
"noSuccessor",
"(",
")",
"{",
"if",
"(",
"compute",
"==",
"FRAMES",
")",
"{",
"Label",
"l",
"=",
"new",
"Label",
"(",
")",
";",
"l",
".",
"frame",
"=",
"new",
"Frame",
"(",
")",
";",
"l",
".",
"frame",
".",
"owner",
"=",
"l",... | Ends the current basic block. This method must be used in the case where
the current basic block does not have any successor. | [
"Ends",
"the",
"current",
"basic",
"block",
".",
"This",
"method",
"must",
"be",
"used",
"in",
"the",
"case",
"where",
"the",
"current",
"basic",
"block",
"does",
"not",
"have",
"any",
"successor",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/MethodWriter.java#L1498-L1510 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/MethodWriter.java | MethodWriter.visitFrame | private void visitFrame(final Frame f) {
int i, t;
int nTop = 0;
int nLocal = 0;
int nStack = 0;
int[] locals = f.inputLocals;
int[] stacks = f.inputStack;
// computes the number of locals (ignores TOP types that are just after
// a LONG or a DOUBLE, and all trailing TOP types)
for (i = 0; i < locals.length; ++i) {
t = locals[i];
if (t == Frame.TOP) {
++nTop;
} else {
nLocal += nTop + 1;
nTop = 0;
}
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
// computes the stack size (ignores TOP types that are just after
// a LONG or a DOUBLE)
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
++nStack;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
// visits the frame and its content
startFrame(f.owner.position, nLocal, nStack);
for (i = 0; nLocal > 0; ++i, --nLocal) {
t = locals[i];
frame[frameIndex++] = t;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
frame[frameIndex++] = t;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
endFrame();
} | java | private void visitFrame(final Frame f) {
int i, t;
int nTop = 0;
int nLocal = 0;
int nStack = 0;
int[] locals = f.inputLocals;
int[] stacks = f.inputStack;
// computes the number of locals (ignores TOP types that are just after
// a LONG or a DOUBLE, and all trailing TOP types)
for (i = 0; i < locals.length; ++i) {
t = locals[i];
if (t == Frame.TOP) {
++nTop;
} else {
nLocal += nTop + 1;
nTop = 0;
}
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
// computes the stack size (ignores TOP types that are just after
// a LONG or a DOUBLE)
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
++nStack;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
// visits the frame and its content
startFrame(f.owner.position, nLocal, nStack);
for (i = 0; nLocal > 0; ++i, --nLocal) {
t = locals[i];
frame[frameIndex++] = t;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
for (i = 0; i < stacks.length; ++i) {
t = stacks[i];
frame[frameIndex++] = t;
if (t == Frame.LONG || t == Frame.DOUBLE) {
++i;
}
}
endFrame();
} | [
"private",
"void",
"visitFrame",
"(",
"final",
"Frame",
"f",
")",
"{",
"int",
"i",
",",
"t",
";",
"int",
"nTop",
"=",
"0",
";",
"int",
"nLocal",
"=",
"0",
";",
"int",
"nStack",
"=",
"0",
";",
"int",
"[",
"]",
"locals",
"=",
"f",
".",
"inputLoca... | Visits a frame that has been computed from scratch.
@param f the frame that must be visited. | [
"Visits",
"a",
"frame",
"that",
"has",
"been",
"computed",
"from",
"scratch",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/MethodWriter.java#L1521-L1568 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/MethodWriter.java | MethodWriter.readInt | static int readInt(final byte[] b, final int index) {
return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
} | java | static int readInt(final byte[] b, final int index) {
return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
} | [
"static",
"int",
"readInt",
"(",
"final",
"byte",
"[",
"]",
"b",
",",
"final",
"int",
"index",
")",
"{",
"return",
"(",
"(",
"b",
"[",
"index",
"]",
"&",
"0xFF",
")",
"<<",
"24",
")",
"|",
"(",
"(",
"b",
"[",
"index",
"+",
"1",
"]",
"&",
"0... | Reads a signed int value in the given byte array.
@param b a byte array.
@param index the start index of the value to be read.
@return the read value. | [
"Reads",
"a",
"signed",
"int",
"value",
"in",
"the",
"given",
"byte",
"array",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/MethodWriter.java#L2518-L2521 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/MethodWriter.java | MethodWriter.writeShort | static void writeShort(final byte[] b, final int index, final int s) {
b[index] = (byte) (s >>> 8);
b[index + 1] = (byte) s;
} | java | static void writeShort(final byte[] b, final int index, final int s) {
b[index] = (byte) (s >>> 8);
b[index + 1] = (byte) s;
} | [
"static",
"void",
"writeShort",
"(",
"final",
"byte",
"[",
"]",
"b",
",",
"final",
"int",
"index",
",",
"final",
"int",
"s",
")",
"{",
"b",
"[",
"index",
"]",
"=",
"(",
"byte",
")",
"(",
"s",
">>>",
"8",
")",
";",
"b",
"[",
"index",
"+",
"1",... | Writes a short value in the given byte array.
@param b a byte array.
@param index where the first byte of the short value must be written.
@param s the value to be written in the given byte array. | [
"Writes",
"a",
"short",
"value",
"in",
"the",
"given",
"byte",
"array",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/MethodWriter.java#L2530-L2533 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/MethodWriter.java | MethodWriter.getNewOffset | static void getNewOffset(
final int[] indexes,
final int[] sizes,
final Label label)
{
if ((label.status & Label.RESIZED) == 0) {
label.position = getNewOffset(indexes, sizes, 0, label.position);
label.status |= Label.RESIZED;
}
} | java | static void getNewOffset(
final int[] indexes,
final int[] sizes,
final Label label)
{
if ((label.status & Label.RESIZED) == 0) {
label.position = getNewOffset(indexes, sizes, 0, label.position);
label.status |= Label.RESIZED;
}
} | [
"static",
"void",
"getNewOffset",
"(",
"final",
"int",
"[",
"]",
"indexes",
",",
"final",
"int",
"[",
"]",
"sizes",
",",
"final",
"Label",
"label",
")",
"{",
"if",
"(",
"(",
"label",
".",
"status",
"&",
"Label",
".",
"RESIZED",
")",
"==",
"0",
")",... | Updates the offset of the given label.
@param indexes current positions of the instructions to be resized. Each
instruction must be designated by the index of its <i>last</i>
byte, plus one (or, in other words, by the index of the <i>first</i>
byte of the <i>next</i> instruction).
@param sizes the number of bytes to be <i>added</i> to the above
instructions. More precisely, for each i < <tt>len</tt>,
<tt>sizes</tt>[i] bytes will be added at the end of the
instruction designated by <tt>indexes</tt>[i] or, if
<tt>sizes</tt>[i] is negative, the <i>last</i> |<tt>sizes[i]</tt>|
bytes of the instruction will be removed (the instruction size
<i>must not</i> become negative or null).
@param label the label whose offset must be updated. | [
"Updates",
"the",
"offset",
"of",
"the",
"given",
"label",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/MethodWriter.java#L2591-L2600 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/ClassReader.java | ClassReader.readClass | private static byte[] readClass(final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
}
len += n;
if (len == b.length) {
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
}
} | java | private static byte[] readClass(final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
}
len += n;
if (len == b.length) {
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
}
} | [
"private",
"static",
"byte",
"[",
"]",
"readClass",
"(",
"final",
"InputStream",
"is",
")",
"throws",
"IOException",
"{",
"if",
"(",
"is",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Class not found\"",
")",
";",
"}",
"byte",
"[",
"]",... | Reads the bytecode of a class.
@param is an input stream from which to read the class.
@return the bytecode read from the given input stream.
@throws IOException if a problem occurs during reading. | [
"Reads",
"the",
"bytecode",
"of",
"a",
"class",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassReader.java#L380-L403 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/ClassReader.java | ClassReader.readParameterAnnotations | private void readParameterAnnotations(
int v,
final String desc,
final char[] buf,
final boolean visible,
final MethodVisitor mv)
{
int i;
int n = b[v++] & 0xFF;
// workaround for a bug in javac (javac compiler generates a parameter
// annotation array whose size is equal to the number of parameters in
// the Java source file, while it should generate an array whose size is
// equal to the number of parameters in the method descriptor - which
// includes the synthetic parameters added by the compiler). This work-
// around supposes that the synthetic parameters are the first ones.
int synthetics = Type.getArgumentTypes(desc).length - n;
AnnotationVisitor av;
for (i = 0; i < synthetics; ++i) {
// virtual annotation to detect synthetic parameters in MethodWriter
av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false);
if (av != null) {
av.visitEnd();
}
}
for (; i < n + synthetics; ++i) {
int j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible);
v = readAnnotationValues(v + 2, buf, true, av);
}
}
} | java | private void readParameterAnnotations(
int v,
final String desc,
final char[] buf,
final boolean visible,
final MethodVisitor mv)
{
int i;
int n = b[v++] & 0xFF;
// workaround for a bug in javac (javac compiler generates a parameter
// annotation array whose size is equal to the number of parameters in
// the Java source file, while it should generate an array whose size is
// equal to the number of parameters in the method descriptor - which
// includes the synthetic parameters added by the compiler). This work-
// around supposes that the synthetic parameters are the first ones.
int synthetics = Type.getArgumentTypes(desc).length - n;
AnnotationVisitor av;
for (i = 0; i < synthetics; ++i) {
// virtual annotation to detect synthetic parameters in MethodWriter
av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false);
if (av != null) {
av.visitEnd();
}
}
for (; i < n + synthetics; ++i) {
int j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
av = mv.visitParameterAnnotation(i, readUTF8(v, buf), visible);
v = readAnnotationValues(v + 2, buf, true, av);
}
}
} | [
"private",
"void",
"readParameterAnnotations",
"(",
"int",
"v",
",",
"final",
"String",
"desc",
",",
"final",
"char",
"[",
"]",
"buf",
",",
"final",
"boolean",
"visible",
",",
"final",
"MethodVisitor",
"mv",
")",
"{",
"int",
"i",
";",
"int",
"n",
"=",
... | Reads parameter annotations and makes the given visitor visit them.
@param v start offset in {@link #b b} of the annotations to be read.
@param desc the method descriptor.
@param buf buffer to be used to call {@link #readUTF8 readUTF8},
{@link #readClass(int,char[]) readClass} or
{@link #readConst readConst}.
@param visible <tt>true</tt> if the annotations to be read are visible
at runtime.
@param mv the visitor that must visit the annotations. | [
"Reads",
"parameter",
"annotations",
"and",
"makes",
"the",
"given",
"visitor",
"visit",
"them",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassReader.java#L1471-L1503 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Frame.java | Frame.push | private void push(final int type) {
// creates and/or resizes the output stack array if necessary
if (outputStack == null) {
outputStack = new int[10];
}
int n = outputStack.length;
if (outputStackTop >= n) {
int[] t = new int[Math.max(outputStackTop + 1, 2 * n)];
System.arraycopy(outputStack, 0, t, 0, n);
outputStack = t;
}
// pushes the type on the output stack
outputStack[outputStackTop++] = type;
// updates the maximun height reached by the output stack, if needed
int top = owner.inputStackTop + outputStackTop;
if (top > owner.outputStackMax) {
owner.outputStackMax = top;
}
} | java | private void push(final int type) {
// creates and/or resizes the output stack array if necessary
if (outputStack == null) {
outputStack = new int[10];
}
int n = outputStack.length;
if (outputStackTop >= n) {
int[] t = new int[Math.max(outputStackTop + 1, 2 * n)];
System.arraycopy(outputStack, 0, t, 0, n);
outputStack = t;
}
// pushes the type on the output stack
outputStack[outputStackTop++] = type;
// updates the maximun height reached by the output stack, if needed
int top = owner.inputStackTop + outputStackTop;
if (top > owner.outputStackMax) {
owner.outputStackMax = top;
}
} | [
"private",
"void",
"push",
"(",
"final",
"int",
"type",
")",
"{",
"// creates and/or resizes the output stack array if necessary",
"if",
"(",
"outputStack",
"==",
"null",
")",
"{",
"outputStack",
"=",
"new",
"int",
"[",
"10",
"]",
";",
"}",
"int",
"n",
"=",
... | Pushes a new type onto the output frame stack.
@param type the type that must be pushed. | [
"Pushes",
"a",
"new",
"type",
"onto",
"the",
"output",
"frame",
"stack",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Frame.java#L562-L580 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Frame.java | Frame.pop | private void pop(final String desc) {
char c = desc.charAt(0);
if (c == '(') {
pop((MethodWriter.getArgumentsAndReturnSizes(desc) >> 2) - 1);
} else if (c == 'J' || c == 'D') {
pop(2);
} else {
pop(1);
}
} | java | private void pop(final String desc) {
char c = desc.charAt(0);
if (c == '(') {
pop((MethodWriter.getArgumentsAndReturnSizes(desc) >> 2) - 1);
} else if (c == 'J' || c == 'D') {
pop(2);
} else {
pop(1);
}
} | [
"private",
"void",
"pop",
"(",
"final",
"String",
"desc",
")",
"{",
"char",
"c",
"=",
"desc",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"pop",
"(",
"(",
"MethodWriter",
".",
"getArgumentsAndReturnSizes",
"(",
"des... | Pops a type from the output frame stack.
@param desc the descriptor of the type to be popped. Can also be a method
descriptor (in this case this method pops the types corresponding
to the method arguments). | [
"Pops",
"a",
"type",
"from",
"the",
"output",
"frame",
"stack",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Frame.java#L710-L719 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Frame.java | Frame.initInputFrame | void initInputFrame(
final ClassWriter cw,
final int access,
final Type[] args,
final int maxLocals)
{
inputLocals = new int[maxLocals];
inputStack = new int[0];
int i = 0;
if ((access & Opcodes.ACC_STATIC) == 0) {
if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) {
inputLocals[i++] = OBJECT | cw.addType(cw.thisName);
} else {
inputLocals[i++] = UNINITIALIZED_THIS;
}
}
for (int j = 0; j < args.length; ++j) {
int t = type(cw, args[j].getDescriptor());
inputLocals[i++] = t;
if (t == LONG || t == DOUBLE) {
inputLocals[i++] = TOP;
}
}
while (i < maxLocals) {
inputLocals[i++] = TOP;
}
} | java | void initInputFrame(
final ClassWriter cw,
final int access,
final Type[] args,
final int maxLocals)
{
inputLocals = new int[maxLocals];
inputStack = new int[0];
int i = 0;
if ((access & Opcodes.ACC_STATIC) == 0) {
if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) {
inputLocals[i++] = OBJECT | cw.addType(cw.thisName);
} else {
inputLocals[i++] = UNINITIALIZED_THIS;
}
}
for (int j = 0; j < args.length; ++j) {
int t = type(cw, args[j].getDescriptor());
inputLocals[i++] = t;
if (t == LONG || t == DOUBLE) {
inputLocals[i++] = TOP;
}
}
while (i < maxLocals) {
inputLocals[i++] = TOP;
}
} | [
"void",
"initInputFrame",
"(",
"final",
"ClassWriter",
"cw",
",",
"final",
"int",
"access",
",",
"final",
"Type",
"[",
"]",
"args",
",",
"final",
"int",
"maxLocals",
")",
"{",
"inputLocals",
"=",
"new",
"int",
"[",
"maxLocals",
"]",
";",
"inputStack",
"=... | Initializes the input frame of the first basic block from the method
descriptor.
@param cw the ClassWriter to which this label belongs.
@param access the access flags of the method to which this label belongs.
@param args the formal parameter types of this method.
@param maxLocals the maximum number of local variables of this method. | [
"Initializes",
"the",
"input",
"frame",
"of",
"the",
"first",
"basic",
"block",
"from",
"the",
"method",
"descriptor",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Frame.java#L786-L812 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/AnnotationWriter.java | AnnotationWriter.getSize | int getSize() {
int size = 0;
AnnotationWriter aw = this;
while (aw != null) {
size += aw.bv.length;
aw = aw.next;
}
return size;
} | java | int getSize() {
int size = 0;
AnnotationWriter aw = this;
while (aw != null) {
size += aw.bv.length;
aw = aw.next;
}
return size;
} | [
"int",
"getSize",
"(",
")",
"{",
"int",
"size",
"=",
"0",
";",
"AnnotationWriter",
"aw",
"=",
"this",
";",
"while",
"(",
"aw",
"!=",
"null",
")",
"{",
"size",
"+=",
"aw",
".",
"bv",
".",
"length",
";",
"aw",
"=",
"aw",
".",
"next",
";",
"}",
... | Returns the size of this annotation writer list.
@return the size of this annotation writer list. | [
"Returns",
"the",
"size",
"of",
"this",
"annotation",
"writer",
"list",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/AnnotationWriter.java#L242-L250 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/AnnotationWriter.java | AnnotationWriter.put | void put(final ByteVector out) {
int n = 0;
int size = 2;
AnnotationWriter aw = this;
AnnotationWriter last = null;
while (aw != null) {
++n;
size += aw.bv.length;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putInt(size);
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
} | java | void put(final ByteVector out) {
int n = 0;
int size = 2;
AnnotationWriter aw = this;
AnnotationWriter last = null;
while (aw != null) {
++n;
size += aw.bv.length;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putInt(size);
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
} | [
"void",
"put",
"(",
"final",
"ByteVector",
"out",
")",
"{",
"int",
"n",
"=",
"0",
";",
"int",
"size",
"=",
"2",
";",
"AnnotationWriter",
"aw",
"=",
"this",
";",
"AnnotationWriter",
"last",
"=",
"null",
";",
"while",
"(",
"aw",
"!=",
"null",
")",
"{... | Puts the annotations of this annotation writer list into the given byte
vector.
@param out where the annotations must be put. | [
"Puts",
"the",
"annotations",
"of",
"this",
"annotation",
"writer",
"list",
"into",
"the",
"given",
"byte",
"vector",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/AnnotationWriter.java#L258-L278 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/AnnotationWriter.java | AnnotationWriter.put | static void put(
final AnnotationWriter[] panns,
final int off,
final ByteVector out)
{
int size = 1 + 2 * (panns.length - off);
for (int i = off; i < panns.length; ++i) {
size += panns[i] == null ? 0 : panns[i].getSize();
}
out.putInt(size).putByte(panns.length - off);
for (int i = off; i < panns.length; ++i) {
AnnotationWriter aw = panns[i];
AnnotationWriter last = null;
int n = 0;
while (aw != null) {
++n;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
}
} | java | static void put(
final AnnotationWriter[] panns,
final int off,
final ByteVector out)
{
int size = 1 + 2 * (panns.length - off);
for (int i = off; i < panns.length; ++i) {
size += panns[i] == null ? 0 : panns[i].getSize();
}
out.putInt(size).putByte(panns.length - off);
for (int i = off; i < panns.length; ++i) {
AnnotationWriter aw = panns[i];
AnnotationWriter last = null;
int n = 0;
while (aw != null) {
++n;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
}
} | [
"static",
"void",
"put",
"(",
"final",
"AnnotationWriter",
"[",
"]",
"panns",
",",
"final",
"int",
"off",
",",
"final",
"ByteVector",
"out",
")",
"{",
"int",
"size",
"=",
"1",
"+",
"2",
"*",
"(",
"panns",
".",
"length",
"-",
"off",
")",
";",
"for",... | Puts the given annotation lists into the given byte vector.
@param panns an array of annotation writer lists.
@param off index of the first annotation to be written.
@param out where the annotations must be put. | [
"Puts",
"the",
"given",
"annotation",
"lists",
"into",
"the",
"given",
"byte",
"vector",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/AnnotationWriter.java#L287-L315 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getType | public static Type getType(final Class c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /* if (c == Long.TYPE) */{
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
} | java | public static Type getType(final Class c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /* if (c == Long.TYPE) */{
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
} | [
"public",
"static",
"Type",
"getType",
"(",
"final",
"Class",
"c",
")",
"{",
"if",
"(",
"c",
".",
"isPrimitive",
"(",
")",
")",
"{",
"if",
"(",
"c",
"==",
"Integer",
".",
"TYPE",
")",
"{",
"return",
"INT_TYPE",
";",
"}",
"else",
"if",
"(",
"c",
... | Returns the Java type corresponding to the given class.
@param c a class.
@return the Java type corresponding to the given class. | [
"Returns",
"the",
"Java",
"type",
"corresponding",
"to",
"the",
"given",
"class",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L227-L251 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getArgumentTypes | public static Type[] getArgumentTypes(final Method method) {
Class[] classes = method.getParameterTypes();
Type[] types = new Type[classes.length];
for (int i = classes.length - 1; i >= 0; --i) {
types[i] = getType(classes[i]);
}
return types;
} | java | public static Type[] getArgumentTypes(final Method method) {
Class[] classes = method.getParameterTypes();
Type[] types = new Type[classes.length];
for (int i = classes.length - 1; i >= 0; --i) {
types[i] = getType(classes[i]);
}
return types;
} | [
"public",
"static",
"Type",
"[",
"]",
"getArgumentTypes",
"(",
"final",
"Method",
"method",
")",
"{",
"Class",
"[",
"]",
"classes",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"Type",
"[",
"]",
"types",
"=",
"new",
"Type",
"[",
"classes",
"... | Returns the Java types corresponding to the argument types of the given
method.
@param method a method.
@return the Java types corresponding to the argument types of the given
method. | [
"Returns",
"the",
"Java",
"types",
"corresponding",
"to",
"the",
"argument",
"types",
"of",
"the",
"given",
"method",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L296-L303 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getReturnType | public static Type getReturnType(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
} | java | public static Type getReturnType(final String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
} | [
"public",
"static",
"Type",
"getReturnType",
"(",
"final",
"String",
"methodDescriptor",
")",
"{",
"char",
"[",
"]",
"buf",
"=",
"methodDescriptor",
".",
"toCharArray",
"(",
")",
";",
"return",
"getType",
"(",
"buf",
",",
"methodDescriptor",
".",
"indexOf",
... | Returns the Java type corresponding to the return type of the given
method descriptor.
@param methodDescriptor a method descriptor.
@return the Java type corresponding to the return type of the given
method descriptor. | [
"Returns",
"the",
"Java",
"type",
"corresponding",
"to",
"the",
"return",
"type",
"of",
"the",
"given",
"method",
"descriptor",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L313-L316 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getClassName | public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
// case OBJECT:
default:
return new String(buf, off, len).replace('/', '.');
}
} | java | public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
// case OBJECT:
default:
return new String(buf, off, len).replace('/', '.');
}
} | [
"public",
"String",
"getClassName",
"(",
")",
"{",
"switch",
"(",
"sort",
")",
"{",
"case",
"VOID",
":",
"return",
"\"void\"",
";",
"case",
"BOOLEAN",
":",
"return",
"\"boolean\"",
";",
"case",
"CHAR",
":",
"return",
"\"char\"",
";",
"case",
"BYTE",
":",... | Returns the name of the class corresponding to this type.
@return the fully qualified name of the class corresponding to this type. | [
"Returns",
"the",
"name",
"of",
"the",
"class",
"corresponding",
"to",
"this",
"type",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L426-L456 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getDescriptor | private void getDescriptor(final StringBuffer buf) {
switch (sort) {
case VOID:
buf.append('V');
return;
case BOOLEAN:
buf.append('Z');
return;
case CHAR:
buf.append('C');
return;
case BYTE:
buf.append('B');
return;
case SHORT:
buf.append('S');
return;
case INT:
buf.append('I');
return;
case FLOAT:
buf.append('F');
return;
case LONG:
buf.append('J');
return;
case DOUBLE:
buf.append('D');
return;
case ARRAY:
buf.append(this.buf, off, len);
return;
// case OBJECT:
default:
buf.append('L');
buf.append(this.buf, off, len);
buf.append(';');
}
} | java | private void getDescriptor(final StringBuffer buf) {
switch (sort) {
case VOID:
buf.append('V');
return;
case BOOLEAN:
buf.append('Z');
return;
case CHAR:
buf.append('C');
return;
case BYTE:
buf.append('B');
return;
case SHORT:
buf.append('S');
return;
case INT:
buf.append('I');
return;
case FLOAT:
buf.append('F');
return;
case LONG:
buf.append('J');
return;
case DOUBLE:
buf.append('D');
return;
case ARRAY:
buf.append(this.buf, off, len);
return;
// case OBJECT:
default:
buf.append('L');
buf.append(this.buf, off, len);
buf.append(';');
}
} | [
"private",
"void",
"getDescriptor",
"(",
"final",
"StringBuffer",
"buf",
")",
"{",
"switch",
"(",
"sort",
")",
"{",
"case",
"VOID",
":",
"buf",
".",
"append",
"(",
"'",
"'",
")",
";",
"return",
";",
"case",
"BOOLEAN",
":",
"buf",
".",
"append",
"(",
... | Appends the descriptor corresponding to this Java type to the given
string buffer.
@param buf the string buffer to which the descriptor must be appended. | [
"Appends",
"the",
"descriptor",
"corresponding",
"to",
"this",
"Java",
"type",
"to",
"the",
"given",
"string",
"buffer",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L514-L552 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/Type.java | Type.getOpcode | public int getOpcode(final int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
switch (sort) {
case BOOLEAN:
case BYTE:
return opcode + 5;
case CHAR:
return opcode + 6;
case SHORT:
return opcode + 7;
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
} else {
switch (sort) {
case VOID:
return opcode + 5;
case BOOLEAN:
case CHAR:
case BYTE:
case SHORT:
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
}
} | java | public int getOpcode(final int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
switch (sort) {
case BOOLEAN:
case BYTE:
return opcode + 5;
case CHAR:
return opcode + 6;
case SHORT:
return opcode + 7;
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
} else {
switch (sort) {
case VOID:
return opcode + 5;
case BOOLEAN:
case CHAR:
case BYTE:
case SHORT:
case INT:
return opcode;
case FLOAT:
return opcode + 2;
case LONG:
return opcode + 1;
case DOUBLE:
return opcode + 3;
// case ARRAY:
// case OBJECT:
default:
return opcode + 4;
}
}
} | [
"public",
"int",
"getOpcode",
"(",
"final",
"int",
"opcode",
")",
"{",
"if",
"(",
"opcode",
"==",
"Opcodes",
".",
"IALOAD",
"||",
"opcode",
"==",
"Opcodes",
".",
"IASTORE",
")",
"{",
"switch",
"(",
"sort",
")",
"{",
"case",
"BOOLEAN",
":",
"case",
"B... | Returns a JVM instruction opcode adapted to this Java type.
@param opcode a JVM instruction opcode. This opcode must be one of ILOAD,
ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL,
ISHR, IUSHR, IAND, IOR, IXOR and IRETURN.
@return an opcode that is similar to the given opcode, but adapted to
this Java type. For example, if this type is <tt>float</tt> and
<tt>opcode</tt> is IRETURN, this method returns FRETURN. | [
"Returns",
"a",
"JVM",
"instruction",
"opcode",
"adapted",
"to",
"this",
"Java",
"type",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/Type.java#L690-L735 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/FieldWriter.java | FieldWriter.getSize | int getSize() {
int size = 8;
if (value != 0) {
cw.newUTF8("ConstantValue");
size += 8;
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
cw.newUTF8("Synthetic");
size += 6;
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
cw.newUTF8("Deprecated");
size += 6;
}
if (ClassReader.SIGNATURES && signature != 0) {
cw.newUTF8("Signature");
size += 8;
}
if (ClassReader.ANNOTATIONS && anns != null) {
cw.newUTF8("RuntimeVisibleAnnotations");
size += 8 + anns.getSize();
}
if (ClassReader.ANNOTATIONS && ianns != null) {
cw.newUTF8("RuntimeInvisibleAnnotations");
size += 8 + ianns.getSize();
}
if (attrs != null) {
size += attrs.getSize(cw, null, 0, -1, -1);
}
return size;
} | java | int getSize() {
int size = 8;
if (value != 0) {
cw.newUTF8("ConstantValue");
size += 8;
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
cw.newUTF8("Synthetic");
size += 6;
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
cw.newUTF8("Deprecated");
size += 6;
}
if (ClassReader.SIGNATURES && signature != 0) {
cw.newUTF8("Signature");
size += 8;
}
if (ClassReader.ANNOTATIONS && anns != null) {
cw.newUTF8("RuntimeVisibleAnnotations");
size += 8 + anns.getSize();
}
if (ClassReader.ANNOTATIONS && ianns != null) {
cw.newUTF8("RuntimeInvisibleAnnotations");
size += 8 + ianns.getSize();
}
if (attrs != null) {
size += attrs.getSize(cw, null, 0, -1, -1);
}
return size;
} | [
"int",
"getSize",
"(",
")",
"{",
"int",
"size",
"=",
"8",
";",
"if",
"(",
"value",
"!=",
"0",
")",
"{",
"cw",
".",
"newUTF8",
"(",
"\"ConstantValue\"",
")",
";",
"size",
"+=",
"8",
";",
"}",
"if",
"(",
"(",
"access",
"&",
"Opcodes",
".",
"ACC_S... | Returns the size of this field.
@return the size of this field. | [
"Returns",
"the",
"size",
"of",
"this",
"field",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/FieldWriter.java#L175-L207 | train |
xsonorg/xson | src/main/java/org/xson/core/asm/FieldWriter.java | FieldWriter.put | void put(final ByteVector out) {
out.putShort(access).putShort(name).putShort(desc);
int attributeCount = 0;
if (value != 0) {
++attributeCount;
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
++attributeCount;
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
}
if (ClassReader.SIGNATURES && signature != 0) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && anns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && ianns != null) {
++attributeCount;
}
if (attrs != null) {
attributeCount += attrs.getCount();
}
out.putShort(attributeCount);
if (value != 0) {
out.putShort(cw.newUTF8("ConstantValue"));
out.putInt(2).putShort(value);
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
out.putShort(cw.newUTF8("Synthetic")).putInt(0);
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
out.putShort(cw.newUTF8("Deprecated")).putInt(0);
}
if (ClassReader.SIGNATURES && signature != 0) {
out.putShort(cw.newUTF8("Signature"));
out.putInt(2).putShort(signature);
}
if (ClassReader.ANNOTATIONS && anns != null) {
out.putShort(cw.newUTF8("RuntimeVisibleAnnotations"));
anns.put(out);
}
if (ClassReader.ANNOTATIONS && ianns != null) {
out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations"));
ianns.put(out);
}
if (attrs != null) {
attrs.put(cw, null, 0, -1, -1, out);
}
} | java | void put(final ByteVector out) {
out.putShort(access).putShort(name).putShort(desc);
int attributeCount = 0;
if (value != 0) {
++attributeCount;
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
++attributeCount;
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
}
if (ClassReader.SIGNATURES && signature != 0) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && anns != null) {
++attributeCount;
}
if (ClassReader.ANNOTATIONS && ianns != null) {
++attributeCount;
}
if (attrs != null) {
attributeCount += attrs.getCount();
}
out.putShort(attributeCount);
if (value != 0) {
out.putShort(cw.newUTF8("ConstantValue"));
out.putInt(2).putShort(value);
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& (cw.version & 0xffff) < Opcodes.V1_5)
{
out.putShort(cw.newUTF8("Synthetic")).putInt(0);
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
out.putShort(cw.newUTF8("Deprecated")).putInt(0);
}
if (ClassReader.SIGNATURES && signature != 0) {
out.putShort(cw.newUTF8("Signature"));
out.putInt(2).putShort(signature);
}
if (ClassReader.ANNOTATIONS && anns != null) {
out.putShort(cw.newUTF8("RuntimeVisibleAnnotations"));
anns.put(out);
}
if (ClassReader.ANNOTATIONS && ianns != null) {
out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations"));
ianns.put(out);
}
if (attrs != null) {
attrs.put(cw, null, 0, -1, -1, out);
}
} | [
"void",
"put",
"(",
"final",
"ByteVector",
"out",
")",
"{",
"out",
".",
"putShort",
"(",
"access",
")",
".",
"putShort",
"(",
"name",
")",
".",
"putShort",
"(",
"desc",
")",
";",
"int",
"attributeCount",
"=",
"0",
";",
"if",
"(",
"value",
"!=",
"0"... | Puts the content of this field into the given byte vector.
@param out where the content of this field must be put. | [
"Puts",
"the",
"content",
"of",
"this",
"field",
"into",
"the",
"given",
"byte",
"vector",
"."
] | ce1e197ec4ef9be448ed6ca96513e886151f83a9 | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/FieldWriter.java#L214-L268 | train |
lucasr/probe | library/src/main/java/org/lucasr/probe/ViewClassUtil.java | ViewClassUtil.loadViewClass | static Class<?> loadViewClass(Context context, String name)
throws ClassNotFoundException {
return context.getClassLoader().loadClass(name).asSubclass(View.class);
} | java | static Class<?> loadViewClass(Context context, String name)
throws ClassNotFoundException {
return context.getClassLoader().loadClass(name).asSubclass(View.class);
} | [
"static",
"Class",
"<",
"?",
">",
"loadViewClass",
"(",
"Context",
"context",
",",
"String",
"name",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"context",
".",
"getClassLoader",
"(",
")",
".",
"loadClass",
"(",
"name",
")",
".",
"asSubclass",
"(... | Loads class for the given class name. | [
"Loads",
"class",
"for",
"the",
"given",
"class",
"name",
"."
] | cd15cc04383a1bf85de2f4c345d2018415b9ddc9 | https://github.com/lucasr/probe/blob/cd15cc04383a1bf85de2f4c345d2018415b9ddc9/library/src/main/java/org/lucasr/probe/ViewClassUtil.java#L41-L44 | train |
lucasr/probe | library/src/main/java/org/lucasr/probe/ViewClassUtil.java | ViewClassUtil.findViewClass | static Class<?> findViewClass(Context context, String name)
throws ClassNotFoundException {
if (name.indexOf('.') >= 0) {
return loadViewClass(context, name);
}
for (String prefix : VIEW_CLASS_PREFIX_LIST) {
try {
return loadViewClass(context, prefix + name);
} catch (ClassNotFoundException e) {
continue;
}
}
throw new ClassNotFoundException("Couldn't load View class for " + name);
} | java | static Class<?> findViewClass(Context context, String name)
throws ClassNotFoundException {
if (name.indexOf('.') >= 0) {
return loadViewClass(context, name);
}
for (String prefix : VIEW_CLASS_PREFIX_LIST) {
try {
return loadViewClass(context, prefix + name);
} catch (ClassNotFoundException e) {
continue;
}
}
throw new ClassNotFoundException("Couldn't load View class for " + name);
} | [
"static",
"Class",
"<",
"?",
">",
"findViewClass",
"(",
"Context",
"context",
",",
"String",
"name",
")",
"throws",
"ClassNotFoundException",
"{",
"if",
"(",
"name",
".",
"indexOf",
"(",
"'",
"'",
")",
">=",
"0",
")",
"{",
"return",
"loadViewClass",
"(",... | Tries to load class using a predefined list of class prefixes for
Android views. | [
"Tries",
"to",
"load",
"class",
"using",
"a",
"predefined",
"list",
"of",
"class",
"prefixes",
"for",
"Android",
"views",
"."
] | cd15cc04383a1bf85de2f4c345d2018415b9ddc9 | https://github.com/lucasr/probe/blob/cd15cc04383a1bf85de2f4c345d2018415b9ddc9/library/src/main/java/org/lucasr/probe/ViewClassUtil.java#L63-L78 | train |
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsAuthenticator.java | CallStatsAuthenticator.scheduleAuthentication | private void scheduleAuthentication(final int appId, final String bridgeId,
final CallStatsHttp2Client httpClient) {
scheduler.schedule(new Runnable() {
public void run() {
sendAsyncAuthenticationRequest(appId, bridgeId, httpClient);
}
}, authenticationRetryTimeout, TimeUnit.MILLISECONDS);
} | java | private void scheduleAuthentication(final int appId, final String bridgeId,
final CallStatsHttp2Client httpClient) {
scheduler.schedule(new Runnable() {
public void run() {
sendAsyncAuthenticationRequest(appId, bridgeId, httpClient);
}
}, authenticationRetryTimeout, TimeUnit.MILLISECONDS);
} | [
"private",
"void",
"scheduleAuthentication",
"(",
"final",
"int",
"appId",
",",
"final",
"String",
"bridgeId",
",",
"final",
"CallStatsHttp2Client",
"httpClient",
")",
"{",
"scheduler",
".",
"schedule",
"(",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
... | Schedule authentication.
@param appId the app id
@param appSecret the app secret
@param bridgeId the bridge id
@param httpClient the http client | [
"Schedule",
"authentication",
"."
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsAuthenticator.java#L166-L173 | train |
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java | CallStatsBridgeKeepAliveManager.startKeepAliveSender | public void startKeepAliveSender(String authToken) {
this.token = authToken;
stopKeepAliveSender();
logger.info("Starting keepAlive Sender");
future = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
sendKeepAliveBridgeMessage(appId, bridgeId, token, httpClient);
}
}, 0, keepAliveInterval, TimeUnit.MILLISECONDS);
} | java | public void startKeepAliveSender(String authToken) {
this.token = authToken;
stopKeepAliveSender();
logger.info("Starting keepAlive Sender");
future = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
sendKeepAliveBridgeMessage(appId, bridgeId, token, httpClient);
}
}, 0, keepAliveInterval, TimeUnit.MILLISECONDS);
} | [
"public",
"void",
"startKeepAliveSender",
"(",
"String",
"authToken",
")",
"{",
"this",
".",
"token",
"=",
"authToken",
";",
"stopKeepAliveSender",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"Starting keepAlive Sender\"",
")",
";",
"future",
"=",
"scheduler",
... | Start keep alive sender.
@param authToken authentication token | [
"Start",
"keep",
"alive",
"sender",
"."
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java#L103-L113 | train |
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java | CallStatsBridgeKeepAliveManager.sendKeepAliveBridgeMessage | private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token,
final CallStatsHttp2Client httpClient) {
long apiTS = System.currentTimeMillis();
BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS);
String requestMessageString = gson.toJson(message);
httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeKeepAliveResponse keepAliveResponse;
try {
String responseString = response.body().string();
keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
keepAliveStatusListener.onSuccess();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
stopKeepAliveSender();
keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR,
keepAliveResponse.getMsg());
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.info("Response exception " + e.toString());
httpClient.setDisrupted(true);
}
});
} | java | private void sendKeepAliveBridgeMessage(int appId, String bridgeId, String token,
final CallStatsHttp2Client httpClient) {
long apiTS = System.currentTimeMillis();
BridgeKeepAliveMessage message = new BridgeKeepAliveMessage(bridgeId, apiTS);
String requestMessageString = gson.toJson(message);
httpClient.sendBridgeAlive(keepAliveEventUrl, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeKeepAliveResponse keepAliveResponse;
try {
String responseString = response.body().string();
keepAliveResponse = gson.fromJson(responseString, BridgeKeepAliveResponse.class);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
keepAliveStatusListener.onSuccess();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
stopKeepAliveSender();
keepAliveStatusListener.onKeepAliveError(CallStatsErrors.AUTH_ERROR,
keepAliveResponse.getMsg());
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.info("Response exception " + e.toString());
httpClient.setDisrupted(true);
}
});
} | [
"private",
"void",
"sendKeepAliveBridgeMessage",
"(",
"int",
"appId",
",",
"String",
"bridgeId",
",",
"String",
"token",
",",
"final",
"CallStatsHttp2Client",
"httpClient",
")",
"{",
"long",
"apiTS",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"Bridg... | Send keep alive bridge message.
@param appId the app id
@param bridgeId the bridge id
@param token the token
@param httpClient the http client | [
"Send",
"keep",
"alive",
"bridge",
"message",
"."
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/internal/CallStatsBridgeKeepAliveManager.java#L124-L164 | train |
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/CallStats.java | CallStats.sendCallStatsBridgeStatusUpdate | public void sendCallStatsBridgeStatusUpdate(BridgeStatusInfo bridgeStatusInfo) {
if (!isInitialized()) {
bridgeStatusInfoQueue.push(bridgeStatusInfo);
return;
}
long epoch = System.currentTimeMillis();
String token = getToken();
BridgeStatusUpdateMessage eventMessage =
new BridgeStatusUpdateMessage(bridgeId, epoch, bridgeStatusInfo);
String requestMessageString = gson.toJson(eventMessage);
String url = "/" + appId + "/stats/bridge/status";
httpClient.sendBridgeStatistics(url, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeStatusUpdateResponse eventResponseMessage;
try {
String responseString = response.body().string();
eventResponseMessage =
gson.fromJson(responseString, BridgeStatusUpdateResponse.class);
} catch (IOException e) {
logger.error("IO Exception " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
logger.debug("BridgeStatusUpdate Response " + eventResponseMessage.getStatus() + ":"
+ eventResponseMessage.getMsg());
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
sendCallStatsBridgeStatusUpdateFromQueue();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
bridgeKeepAliveManager.stopKeepAliveSender();
authenticator.doAuthentication();
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.error("Response exception" + e.getMessage(), e);
httpClient.setDisrupted(true);
}
});
} | java | public void sendCallStatsBridgeStatusUpdate(BridgeStatusInfo bridgeStatusInfo) {
if (!isInitialized()) {
bridgeStatusInfoQueue.push(bridgeStatusInfo);
return;
}
long epoch = System.currentTimeMillis();
String token = getToken();
BridgeStatusUpdateMessage eventMessage =
new BridgeStatusUpdateMessage(bridgeId, epoch, bridgeStatusInfo);
String requestMessageString = gson.toJson(eventMessage);
String url = "/" + appId + "/stats/bridge/status";
httpClient.sendBridgeStatistics(url, token, requestMessageString,
new CallStatsHttp2ResponseListener() {
public void onResponse(Response response) {
int responseStatus = response.code();
BridgeStatusUpdateResponse eventResponseMessage;
try {
String responseString = response.body().string();
eventResponseMessage =
gson.fromJson(responseString, BridgeStatusUpdateResponse.class);
} catch (IOException e) {
logger.error("IO Exception " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (JsonSyntaxException e) {
logger.error("Json Syntax Exception " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
}
logger.debug("BridgeStatusUpdate Response " + eventResponseMessage.getStatus() + ":"
+ eventResponseMessage.getMsg());
httpClient.setDisrupted(false);
if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
sendCallStatsBridgeStatusUpdateFromQueue();
} else if (responseStatus == CallStatsResponseStatus.INVALID_AUTHENTICATION_TOKEN) {
bridgeKeepAliveManager.stopKeepAliveSender();
authenticator.doAuthentication();
} else {
httpClient.setDisrupted(true);
}
}
public void onFailure(Exception e) {
logger.error("Response exception" + e.getMessage(), e);
httpClient.setDisrupted(true);
}
});
} | [
"public",
"void",
"sendCallStatsBridgeStatusUpdate",
"(",
"BridgeStatusInfo",
"bridgeStatusInfo",
")",
"{",
"if",
"(",
"!",
"isInitialized",
"(",
")",
")",
"{",
"bridgeStatusInfoQueue",
".",
"push",
"(",
"bridgeStatusInfo",
")",
";",
"return",
";",
"}",
"long",
... | Send call stats bridge status update.
@param bridgeStatusInfo the bridge status info | [
"Send",
"call",
"stats",
"bridge",
"status",
"update",
"."
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/CallStats.java#L194-L242 | train |
callstats-io/callstats.java | callstats-java-sample-maven/sample.sdk/src/main/java/io/callstats/sample/sdk/LocalTokenGenerator.java | LocalTokenGenerator.readEcPrivateKey | private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
{
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
char[] cbuf = new char[1024];
for (int i=0; i <= 10*1024; i++) {
if (!br.ready())
break;
int len = br.read(cbuf, i*1024, 1024);
sb.append(cbuf, 0, len);
}
if (br.ready()) {
throw new IndexOutOfBoundsException("JWK file larger than 10MB");
}
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
try {
@SuppressWarnings({ "unchecked", "rawtypes" })
EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
Base64Encoder enc = new Base64Encoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
return jwk.getPrivateKey();
} catch (JoseException e1) {
e1.printStackTrace();
}
return null;
} finally {
br.close();
}
} | java | private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
{
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
char[] cbuf = new char[1024];
for (int i=0; i <= 10*1024; i++) {
if (!br.ready())
break;
int len = br.read(cbuf, i*1024, 1024);
sb.append(cbuf, 0, len);
}
if (br.ready()) {
throw new IndexOutOfBoundsException("JWK file larger than 10MB");
}
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
try {
@SuppressWarnings({ "unchecked", "rawtypes" })
EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
Base64Encoder enc = new Base64Encoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
return jwk.getPrivateKey();
} catch (JoseException e1) {
e1.printStackTrace();
}
return null;
} finally {
br.close();
}
} | [
"private",
"PrivateKey",
"readEcPrivateKey",
"(",
"String",
"fileName",
")",
"throws",
"InvalidKeySpecException",
",",
"NoSuchAlgorithmException",
",",
"IOException",
",",
"NoSuchProviderException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",... | Reads JWK into PrivateKEy instance
@param fileName Path to the JWK file
@return java.security.PrivateKey instance of JWK
@throws InvalidKeySpecException
@throws NoSuchAlgorithmException
@throws IOException
@throws NoSuchProviderException | [
"Reads",
"JWK",
"into",
"PrivateKEy",
"instance"
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sample-maven/sample.sdk/src/main/java/io/callstats/sample/sdk/LocalTokenGenerator.java#L182-L213 | train |
callstats-io/callstats.java | callstats-java-sdk/src/main/java/io/callstats/sdk/messages/BridgeStatusUpdateMessage.java | BridgeStatusUpdateMessage.setLocalID | public void setLocalID(String userID) {
try {
this.localID = URLEncoder.encode(userID, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
} ;
} | java | public void setLocalID(String userID) {
try {
this.localID = URLEncoder.encode(userID, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException " + e.getMessage(), e);
e.printStackTrace();
throw new RuntimeException(e);
} ;
} | [
"public",
"void",
"setLocalID",
"(",
"String",
"userID",
")",
"{",
"try",
"{",
"this",
".",
"localID",
"=",
"URLEncoder",
".",
"encode",
"(",
"userID",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"logger",
... | Sets the bridge id.
@param userID the new bridge id | [
"Sets",
"the",
"bridge",
"id",
"."
] | 04ec34f1490b75952ed90da706d59e311e2b44f1 | https://github.com/callstats-io/callstats.java/blob/04ec34f1490b75952ed90da706d59e311e2b44f1/callstats-java-sdk/src/main/java/io/callstats/sdk/messages/BridgeStatusUpdateMessage.java#L154-L162 | train |
FaritorKang/unmz-common-util | src/main/java/net/unmz/java/util/date/DateUtils.java | DateUtils.daysBetween | public static final int daysBetween(Date early, Date late) {
java.util.GregorianCalendar calst = new java.util.GregorianCalendar();
java.util.GregorianCalendar caled = new java.util.GregorianCalendar();
calst.setTime(early);
caled.setTime(late);
// 设置时间为0时
calst.set(java.util.GregorianCalendar.HOUR_OF_DAY, 0);
calst.set(java.util.GregorianCalendar.MINUTE, 0);
calst.set(java.util.GregorianCalendar.SECOND, 0);
caled.set(java.util.GregorianCalendar.HOUR_OF_DAY, 0);
caled.set(java.util.GregorianCalendar.MINUTE, 0);
caled.set(java.util.GregorianCalendar.SECOND, 0);
// 得到两个日期相差的天数
int days = ((int) (caled.getTime().getTime() / 1000 / 3600 / 24) - (int) (calst
.getTime().getTime() / 1000 / 3600 / 24));
return days;
} | java | public static final int daysBetween(Date early, Date late) {
java.util.GregorianCalendar calst = new java.util.GregorianCalendar();
java.util.GregorianCalendar caled = new java.util.GregorianCalendar();
calst.setTime(early);
caled.setTime(late);
// 设置时间为0时
calst.set(java.util.GregorianCalendar.HOUR_OF_DAY, 0);
calst.set(java.util.GregorianCalendar.MINUTE, 0);
calst.set(java.util.GregorianCalendar.SECOND, 0);
caled.set(java.util.GregorianCalendar.HOUR_OF_DAY, 0);
caled.set(java.util.GregorianCalendar.MINUTE, 0);
caled.set(java.util.GregorianCalendar.SECOND, 0);
// 得到两个日期相差的天数
int days = ((int) (caled.getTime().getTime() / 1000 / 3600 / 24) - (int) (calst
.getTime().getTime() / 1000 / 3600 / 24));
return days;
} | [
"public",
"static",
"final",
"int",
"daysBetween",
"(",
"Date",
"early",
",",
"Date",
"late",
")",
"{",
"java",
".",
"util",
".",
"GregorianCalendar",
"calst",
"=",
"new",
"java",
".",
"util",
".",
"GregorianCalendar",
"(",
")",
";",
"java",
".",
"util",... | Returns the days between two dates. Positive values indicate that the
second date is after the first, and negative values indicate, well, the
opposite. Relying on specific times is problematic.
@param early
the "first date"
@param late
the "second date"
@return the days between the two dates | [
"Returns",
"the",
"days",
"between",
"two",
"dates",
".",
"Positive",
"values",
"indicate",
"that",
"the",
"second",
"date",
"is",
"after",
"the",
"first",
"and",
"negative",
"values",
"indicate",
"well",
"the",
"opposite",
".",
"Relying",
"on",
"specific",
... | 2912b8889b85ed910d536f85b24b6fa68035814a | https://github.com/FaritorKang/unmz-common-util/blob/2912b8889b85ed910d536f85b24b6fa68035814a/src/main/java/net/unmz/java/util/date/DateUtils.java#L181-L198 | train |
FaritorKang/unmz-common-util | src/main/java/net/unmz/java/util/xml/JaxbUtils.java | JaxbUtils.toXml | public String toXml(Object root, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
} | java | public String toXml(Object root, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
} | [
"public",
"String",
"toXml",
"(",
"Object",
"root",
",",
"String",
"encoding",
")",
"{",
"try",
"{",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"createMarshaller",
"(",
"encoding",
")",
".",
"marshal",
"(",
"root",
",",
"writer",
... | Java Object->Xml. | [
"Java",
"Object",
"-",
">",
"Xml",
"."
] | 2912b8889b85ed910d536f85b24b6fa68035814a | https://github.com/FaritorKang/unmz-common-util/blob/2912b8889b85ed910d536f85b24b6fa68035814a/src/main/java/net/unmz/java/util/xml/JaxbUtils.java#L42-L50 | train |
google/gwtmockito | gwtmockito/src/main/java/com/google/gwtmockito/fakes/FakeUiBinderProvider.java | FakeUiBinderProvider.getFake | @Override
public UiBinder<?, ?> getFake(final Class<?> type) {
return (UiBinder<?, ?>) Proxy.newProxyInstance(
FakeUiBinderProvider.class.getClassLoader(),
new Class<?>[] {type},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
// createAndBindUi is the only method defined by UiBinder
for (Field field : getAllFields(args[0].getClass())) {
if (field.isAnnotationPresent(UiField.class)
&& !field.getAnnotation(UiField.class).provided()) {
field.setAccessible(true);
field.set(args[0], GWT.create(field.getType()));
}
}
return GWT.create(getUiRootType(type));
}
});
} | java | @Override
public UiBinder<?, ?> getFake(final Class<?> type) {
return (UiBinder<?, ?>) Proxy.newProxyInstance(
FakeUiBinderProvider.class.getClassLoader(),
new Class<?>[] {type},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
// createAndBindUi is the only method defined by UiBinder
for (Field field : getAllFields(args[0].getClass())) {
if (field.isAnnotationPresent(UiField.class)
&& !field.getAnnotation(UiField.class).provided()) {
field.setAccessible(true);
field.set(args[0], GWT.create(field.getType()));
}
}
return GWT.create(getUiRootType(type));
}
});
} | [
"@",
"Override",
"public",
"UiBinder",
"<",
"?",
",",
"?",
">",
"getFake",
"(",
"final",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"return",
"(",
"UiBinder",
"<",
"?",
",",
"?",
">",
")",
"Proxy",
".",
"newProxyInstance",
"(",
"FakeUiBinderProvider",
... | Returns a new instance of FakeUiBinder that implements the given interface.
This is accomplished by returning a dynamic proxy object that delegates
calls to a backing FakeUiBinder.
@param type interface to be implemented by the returned type. This must
represent an interface that directly extends {@link UiBinder}. | [
"Returns",
"a",
"new",
"instance",
"of",
"FakeUiBinder",
"that",
"implements",
"the",
"given",
"interface",
".",
"This",
"is",
"accomplished",
"by",
"returning",
"a",
"dynamic",
"proxy",
"object",
"that",
"delegates",
"calls",
"to",
"a",
"backing",
"FakeUiBinder... | e886a9b9d290169b5f83582dd89b7545c5f198a2 | https://github.com/google/gwtmockito/blob/e886a9b9d290169b5f83582dd89b7545c5f198a2/gwtmockito/src/main/java/com/google/gwtmockito/fakes/FakeUiBinderProvider.java#L51-L70 | train |
google/gwtmockito | gwtmockito/src/main/java/com/google/gwtmockito/fakes/FakeClientBundleProvider.java | FakeClientBundleProvider.createFakeResource | @SuppressWarnings("unchecked") // safe since the proxy implements type
private <T> T createFakeResource(Class<T> type, final String name) {
return (T) Proxy.newProxyInstance(
FakeClientBundleProvider.class.getClassLoader(),
new Class<?>[] {type},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
Class<?> returnType = method.getReturnType();
if (returnType == String.class) {
return name;
} else if (returnType == SafeHtml.class) {
return SafeHtmlUtils.fromTrustedString(name);
} else if (returnType == SafeUri.class) {
return UriUtils.fromTrustedString(name);
} else if (returnType == boolean.class) {
return false;
} else if (returnType == int.class) {
return 0;
} else if (method.getParameterTypes()[0] == ResourceCallback.class) {
// Read the underlying resource type out of the generic parameter
// in the method's argument
Class<?> resourceType =
(Class<?>)
((ParameterizedType) args[0].getClass().getGenericInterfaces()[0])
.getActualTypeArguments()[0];
((ResourceCallback<ResourcePrototype>) args[0]).onSuccess(
(ResourcePrototype) createFakeResource(resourceType, name));
return null;
} else {
throw new IllegalArgumentException(
"Unexpected return type for method " + method.getName());
}
}
});
} | java | @SuppressWarnings("unchecked") // safe since the proxy implements type
private <T> T createFakeResource(Class<T> type, final String name) {
return (T) Proxy.newProxyInstance(
FakeClientBundleProvider.class.getClassLoader(),
new Class<?>[] {type},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
Class<?> returnType = method.getReturnType();
if (returnType == String.class) {
return name;
} else if (returnType == SafeHtml.class) {
return SafeHtmlUtils.fromTrustedString(name);
} else if (returnType == SafeUri.class) {
return UriUtils.fromTrustedString(name);
} else if (returnType == boolean.class) {
return false;
} else if (returnType == int.class) {
return 0;
} else if (method.getParameterTypes()[0] == ResourceCallback.class) {
// Read the underlying resource type out of the generic parameter
// in the method's argument
Class<?> resourceType =
(Class<?>)
((ParameterizedType) args[0].getClass().getGenericInterfaces()[0])
.getActualTypeArguments()[0];
((ResourceCallback<ResourcePrototype>) args[0]).onSuccess(
(ResourcePrototype) createFakeResource(resourceType, name));
return null;
} else {
throw new IllegalArgumentException(
"Unexpected return type for method " + method.getName());
}
}
});
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// safe since the proxy implements type",
"private",
"<",
"T",
">",
"T",
"createFakeResource",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"final",
"String",
"name",
")",
"{",
"return",
"(",
"T",
")",
"Proxy",... | Creates a fake resource class that returns its own name where possible. | [
"Creates",
"a",
"fake",
"resource",
"class",
"that",
"returns",
"its",
"own",
"name",
"where",
"possible",
"."
] | e886a9b9d290169b5f83582dd89b7545c5f198a2 | https://github.com/google/gwtmockito/blob/e886a9b9d290169b5f83582dd89b7545c5f198a2/gwtmockito/src/main/java/com/google/gwtmockito/fakes/FakeClientBundleProvider.java#L71-L106 | train |
google/gwtmockito | gwtmockito/src/main/java/com/google/gwtmockito/impl/StubGenerator.java | StubGenerator.shouldStub | public static boolean shouldStub(CtMethod method, Collection<Class<?>> classesToStub) {
// Stub any methods for which we have given explicit implementations
if (STUB_METHODS.containsKey(new ClassAndMethod(
method.getDeclaringClass().getName(), method.getName()))) {
return true;
}
// Stub all non-abstract methods of classes for which stubbing has been requested
for (Class<?> clazz : classesToStub) {
if (declaringClassIs(method, clazz) && (method.getModifiers() & Modifier.ABSTRACT) == 0) {
return true;
}
}
// Stub all native methods
if ((method.getModifiers() & Modifier.NATIVE) != 0) {
return true;
}
return false;
} | java | public static boolean shouldStub(CtMethod method, Collection<Class<?>> classesToStub) {
// Stub any methods for which we have given explicit implementations
if (STUB_METHODS.containsKey(new ClassAndMethod(
method.getDeclaringClass().getName(), method.getName()))) {
return true;
}
// Stub all non-abstract methods of classes for which stubbing has been requested
for (Class<?> clazz : classesToStub) {
if (declaringClassIs(method, clazz) && (method.getModifiers() & Modifier.ABSTRACT) == 0) {
return true;
}
}
// Stub all native methods
if ((method.getModifiers() & Modifier.NATIVE) != 0) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"shouldStub",
"(",
"CtMethod",
"method",
",",
"Collection",
"<",
"Class",
"<",
"?",
">",
">",
"classesToStub",
")",
"{",
"// Stub any methods for which we have given explicit implementations",
"if",
"(",
"STUB_METHODS",
".",
"containsKey",... | Returns whether the behavior of the given method should be replaced. | [
"Returns",
"whether",
"the",
"behavior",
"of",
"the",
"given",
"method",
"should",
"be",
"replaced",
"."
] | e886a9b9d290169b5f83582dd89b7545c5f198a2 | https://github.com/google/gwtmockito/blob/e886a9b9d290169b5f83582dd89b7545c5f198a2/gwtmockito/src/main/java/com/google/gwtmockito/impl/StubGenerator.java#L76-L96 | train |
google/gwtmockito | gwtmockito/src/main/java/com/google/gwtmockito/impl/StubGenerator.java | StubGenerator.invoke | public static Object invoke(Class<?> returnType, String className, String methodName) {
// If we have an explicit implementation for this method, invoke it
if (STUB_METHODS.containsKey(new ClassAndMethod(className, methodName))) {
return STUB_METHODS.get(new ClassAndMethod(className, methodName)).invoke();
}
// Otherwise return an appropriate basic type
if (returnType == String.class) {
return "";
} else if (returnType == Boolean.class) {
return false;
} else if (returnType == Byte.class) {
return (byte) 0;
} else if (returnType == Character.class) {
return (char) 0;
} else if (returnType == Double.class) {
return (double) 0;
} else if (returnType == Integer.class) {
return (int) 0;
} else if (returnType == Float.class) {
return (float) 0;
} else if (returnType == Long.class) {
return (long) 0;
} else if (returnType == Short.class) {
return (short) 0;
} else {
return Mockito.mock(returnType, new ReturnsCustomMocks());
}
} | java | public static Object invoke(Class<?> returnType, String className, String methodName) {
// If we have an explicit implementation for this method, invoke it
if (STUB_METHODS.containsKey(new ClassAndMethod(className, methodName))) {
return STUB_METHODS.get(new ClassAndMethod(className, methodName)).invoke();
}
// Otherwise return an appropriate basic type
if (returnType == String.class) {
return "";
} else if (returnType == Boolean.class) {
return false;
} else if (returnType == Byte.class) {
return (byte) 0;
} else if (returnType == Character.class) {
return (char) 0;
} else if (returnType == Double.class) {
return (double) 0;
} else if (returnType == Integer.class) {
return (int) 0;
} else if (returnType == Float.class) {
return (float) 0;
} else if (returnType == Long.class) {
return (long) 0;
} else if (returnType == Short.class) {
return (short) 0;
} else {
return Mockito.mock(returnType, new ReturnsCustomMocks());
}
} | [
"public",
"static",
"Object",
"invoke",
"(",
"Class",
"<",
"?",
">",
"returnType",
",",
"String",
"className",
",",
"String",
"methodName",
")",
"{",
"// If we have an explicit implementation for this method, invoke it",
"if",
"(",
"STUB_METHODS",
".",
"containsKey",
... | Invokes the stubbed behavior of the given method. | [
"Invokes",
"the",
"stubbed",
"behavior",
"of",
"the",
"given",
"method",
"."
] | e886a9b9d290169b5f83582dd89b7545c5f198a2 | https://github.com/google/gwtmockito/blob/e886a9b9d290169b5f83582dd89b7545c5f198a2/gwtmockito/src/main/java/com/google/gwtmockito/impl/StubGenerator.java#L99-L127 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/CompilationFailedException.java | CompilationFailedException.create | public static CompilationFailedException create(final IMessage[] errors) {
final StringBuilder sb = new StringBuilder();
sb.append("AJC compiler errors:").append(LINE_SEPARATOR);
for (final IMessage error : errors) {
sb.append(error.toString()).append(LINE_SEPARATOR);
}
return new CompilationFailedException(sb.toString());
} | java | public static CompilationFailedException create(final IMessage[] errors) {
final StringBuilder sb = new StringBuilder();
sb.append("AJC compiler errors:").append(LINE_SEPARATOR);
for (final IMessage error : errors) {
sb.append(error.toString()).append(LINE_SEPARATOR);
}
return new CompilationFailedException(sb.toString());
} | [
"public",
"static",
"CompilationFailedException",
"create",
"(",
"final",
"IMessage",
"[",
"]",
"errors",
")",
"{",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"AJC compiler errors:\"",
")",
".",
"app... | Factory method which creates a CompilationFailedException from the supplied AJC IMessages.
@param errors A non-empty array of IMessage objects which
@return A CompilationFailedException containing a string representation of the supplied errors. | [
"Factory",
"method",
"which",
"creates",
"a",
"CompilationFailedException",
"from",
"the",
"supplied",
"AJC",
"IMessages",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/CompilationFailedException.java#L27-L36 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/EclipseAjcMojo.java | EclipseAjcMojo.writeDocument | private void writeDocument( Document document, File file )
throws TransformerException, FileNotFoundException
{
document.normalize();
DOMSource source = new DOMSource( document );
StreamResult result = new StreamResult( new FileOutputStream( file ) );
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.transform( source, result );
} | java | private void writeDocument( Document document, File file )
throws TransformerException, FileNotFoundException
{
document.normalize();
DOMSource source = new DOMSource( document );
StreamResult result = new StreamResult( new FileOutputStream( file ) );
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.transform( source, result );
} | [
"private",
"void",
"writeDocument",
"(",
"Document",
"document",
",",
"File",
"file",
")",
"throws",
"TransformerException",
",",
"FileNotFoundException",
"{",
"document",
".",
"normalize",
"(",
")",
";",
"DOMSource",
"source",
"=",
"new",
"DOMSource",
"(",
"doc... | write document to the file
@param document
@param file
@throws TransformerException
@throws FileNotFoundException | [
"write",
"document",
"to",
"the",
"file"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/EclipseAjcMojo.java#L319-L328 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.createClassPath | @SuppressWarnings( "unchecked" )
public static String createClassPath( MavenProject project, List<Artifact> pluginArtifacts, List<String> outDirs )
{
String cp = new String();
Set<Artifact> classPathElements = Collections.synchronizedSet( new LinkedHashSet<Artifact>() );
Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
classPathElements.addAll( dependencyArtifacts == null ? Collections.<Artifact>emptySet() : dependencyArtifacts );
classPathElements.addAll( project.getArtifacts() );
classPathElements.addAll( pluginArtifacts == null ? Collections.<Artifact>emptySet() : pluginArtifacts );
for ( Artifact classPathElement : classPathElements )
{
File artifact = classPathElement.getFile();
if ( null != artifact )
{
String type = classPathElement.getType();
if (!type.equals("pom")){
cp += classPathElement.getFile().getAbsolutePath();
cp += File.pathSeparatorChar;
}
}
}
Iterator<String> outIter = outDirs.iterator();
while ( outIter.hasNext() )
{
cp += outIter.next();
cp += File.pathSeparatorChar;
}
if ( cp.endsWith( "" + File.pathSeparatorChar ) )
{
cp = cp.substring( 0, cp.length() - 1 );
}
cp = StringUtils.replace( cp, "//", "/" );
return cp;
} | java | @SuppressWarnings( "unchecked" )
public static String createClassPath( MavenProject project, List<Artifact> pluginArtifacts, List<String> outDirs )
{
String cp = new String();
Set<Artifact> classPathElements = Collections.synchronizedSet( new LinkedHashSet<Artifact>() );
Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
classPathElements.addAll( dependencyArtifacts == null ? Collections.<Artifact>emptySet() : dependencyArtifacts );
classPathElements.addAll( project.getArtifacts() );
classPathElements.addAll( pluginArtifacts == null ? Collections.<Artifact>emptySet() : pluginArtifacts );
for ( Artifact classPathElement : classPathElements )
{
File artifact = classPathElement.getFile();
if ( null != artifact )
{
String type = classPathElement.getType();
if (!type.equals("pom")){
cp += classPathElement.getFile().getAbsolutePath();
cp += File.pathSeparatorChar;
}
}
}
Iterator<String> outIter = outDirs.iterator();
while ( outIter.hasNext() )
{
cp += outIter.next();
cp += File.pathSeparatorChar;
}
if ( cp.endsWith( "" + File.pathSeparatorChar ) )
{
cp = cp.substring( 0, cp.length() - 1 );
}
cp = StringUtils.replace( cp, "//", "/" );
return cp;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"String",
"createClassPath",
"(",
"MavenProject",
"project",
",",
"List",
"<",
"Artifact",
">",
"pluginArtifacts",
",",
"List",
"<",
"String",
">",
"outDirs",
")",
"{",
"String",
"cp",
"="... | Constructs AspectJ compiler classpath string
@param project the Maven Project
@param pluginArtifacts the plugin Artifacts
@param outDirs the outputDirectories
@return a os spesific classpath string | [
"Constructs",
"AspectJ",
"compiler",
"classpath",
"string"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L89-L124 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.getBuildFilesForAjdtFile | public static Set<String> getBuildFilesForAjdtFile( String ajdtBuildDefFile, File basedir )
throws MojoExecutionException
{
Set<String> result = new LinkedHashSet<String>();
Properties ajdtBuildProperties = new Properties();
try
{
ajdtBuildProperties.load( new FileInputStream( new File( basedir, ajdtBuildDefFile ) ) );
}
catch ( FileNotFoundException e )
{
throw new MojoExecutionException( "Build properties file specified not found", e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error reading build properties file specified", e );
}
result.addAll( resolveIncludeExcludeString( ajdtBuildProperties.getProperty( "src.includes" ), basedir ) );
Set<String> exludes = resolveIncludeExcludeString( ajdtBuildProperties.getProperty( "src.excludes" ), basedir );
result.removeAll( exludes );
return result;
} | java | public static Set<String> getBuildFilesForAjdtFile( String ajdtBuildDefFile, File basedir )
throws MojoExecutionException
{
Set<String> result = new LinkedHashSet<String>();
Properties ajdtBuildProperties = new Properties();
try
{
ajdtBuildProperties.load( new FileInputStream( new File( basedir, ajdtBuildDefFile ) ) );
}
catch ( FileNotFoundException e )
{
throw new MojoExecutionException( "Build properties file specified not found", e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error reading build properties file specified", e );
}
result.addAll( resolveIncludeExcludeString( ajdtBuildProperties.getProperty( "src.includes" ), basedir ) );
Set<String> exludes = resolveIncludeExcludeString( ajdtBuildProperties.getProperty( "src.excludes" ), basedir );
result.removeAll( exludes );
return result;
} | [
"public",
"static",
"Set",
"<",
"String",
">",
"getBuildFilesForAjdtFile",
"(",
"String",
"ajdtBuildDefFile",
",",
"File",
"basedir",
")",
"throws",
"MojoExecutionException",
"{",
"Set",
"<",
"String",
">",
"result",
"=",
"new",
"LinkedHashSet",
"<",
"String",
"... | Based on a AJDT build properties file resolves the combination of all
include and exclude statements and returns a set of all the files to be
compiled and weaved.
@param ajdtBuildDefFile the ajdtBuildDefFile
@param basedir the baseDirectory
@return
@throws MojoExecutionException | [
"Based",
"on",
"a",
"AJDT",
"build",
"properties",
"file",
"resolves",
"the",
"combination",
"of",
"all",
"include",
"and",
"exclude",
"statements",
"and",
"returns",
"a",
"set",
"of",
"all",
"the",
"files",
"to",
"be",
"compiled",
"and",
"weaved",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L136-L159 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.getBuildFilesForSourceDirs | public static Set<String> getBuildFilesForSourceDirs( List<String> sourceDirs, String[] includes, String[] excludes )
throws MojoExecutionException
{
Set<String> result = new LinkedHashSet<String>();
for ( String sourceDir : sourceDirs )
{
try
{
if ( FileUtils.fileExists( sourceDir ) )
{
result.addAll( FileUtils
.getFileNames( new File( sourceDir ),
( null == includes || 0 == includes.length ) ? DEFAULT_INCLUDES
: getAsCsv( includes ),
( null == excludes || 0 == excludes.length ) ? DEFAULT_EXCLUDES
: getAsCsv( excludes ), true ) );
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error resolving sourcedirs", e );
}
}
// We might need to check if some of these files are already included through the weaveDirectories.
return result;
} | java | public static Set<String> getBuildFilesForSourceDirs( List<String> sourceDirs, String[] includes, String[] excludes )
throws MojoExecutionException
{
Set<String> result = new LinkedHashSet<String>();
for ( String sourceDir : sourceDirs )
{
try
{
if ( FileUtils.fileExists( sourceDir ) )
{
result.addAll( FileUtils
.getFileNames( new File( sourceDir ),
( null == includes || 0 == includes.length ) ? DEFAULT_INCLUDES
: getAsCsv( includes ),
( null == excludes || 0 == excludes.length ) ? DEFAULT_EXCLUDES
: getAsCsv( excludes ), true ) );
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error resolving sourcedirs", e );
}
}
// We might need to check if some of these files are already included through the weaveDirectories.
return result;
} | [
"public",
"static",
"Set",
"<",
"String",
">",
"getBuildFilesForSourceDirs",
"(",
"List",
"<",
"String",
">",
"sourceDirs",
",",
"String",
"[",
"]",
"includes",
",",
"String",
"[",
"]",
"excludes",
")",
"throws",
"MojoExecutionException",
"{",
"Set",
"<",
"S... | Based on a set of sourcedirs, apply include and exclude statements and
returns a set of all the files to be compiled and weaved.
@param sourceDirs
@param includes
@param excludes
@return
@throws MojoExecutionException | [
"Based",
"on",
"a",
"set",
"of",
"sourcedirs",
"apply",
"include",
"and",
"exclude",
"statements",
"and",
"returns",
"a",
"set",
"of",
"all",
"the",
"files",
"to",
"be",
"compiled",
"and",
"weaved",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L171-L198 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.getWeaveSourceFiles | public static Set<String> getWeaveSourceFiles( String[] weaveDirs )
throws MojoExecutionException
{
Set<String> result = new HashSet<String>();
for ( int i = 0; i < weaveDirs.length; i++ )
{
String weaveDir = weaveDirs[i];
if ( FileUtils.fileExists( weaveDir ) )
{
try
{
result.addAll( FileUtils.getFileNames( new File( weaveDir ), "**/*.class", DEFAULT_EXCLUDES, true ) );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error resolving weavedirs", e );
}
}
}
return result;
} | java | public static Set<String> getWeaveSourceFiles( String[] weaveDirs )
throws MojoExecutionException
{
Set<String> result = new HashSet<String>();
for ( int i = 0; i < weaveDirs.length; i++ )
{
String weaveDir = weaveDirs[i];
if ( FileUtils.fileExists( weaveDir ) )
{
try
{
result.addAll( FileUtils.getFileNames( new File( weaveDir ), "**/*.class", DEFAULT_EXCLUDES, true ) );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IO Error resolving weavedirs", e );
}
}
}
return result;
} | [
"public",
"static",
"Set",
"<",
"String",
">",
"getWeaveSourceFiles",
"(",
"String",
"[",
"]",
"weaveDirs",
")",
"throws",
"MojoExecutionException",
"{",
"Set",
"<",
"String",
">",
"result",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"for",
... | Based on a set of weavedirs returns a set of all the files to be weaved.
@return
@throws MojoExecutionException | [
"Based",
"on",
"a",
"set",
"of",
"weavedirs",
"returns",
"a",
"set",
"of",
"all",
"the",
"files",
"to",
"be",
"weaved",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L206-L227 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.readBuildConfigFile | public static List<String> readBuildConfigFile( String fileName, File outputDir )
throws IOException
{
List<String> arguments = new ArrayList<String>();
File argFile = new File( outputDir, fileName );
if ( FileUtils.fileExists( argFile.getAbsolutePath() ) )
{
FileReader reader = new FileReader( argFile );
BufferedReader bufRead = new BufferedReader( reader );
String line = null;
do
{
line = bufRead.readLine();
if ( null != line )
{
arguments.add( line );
}
}
while ( null != line );
}
return arguments;
} | java | public static List<String> readBuildConfigFile( String fileName, File outputDir )
throws IOException
{
List<String> arguments = new ArrayList<String>();
File argFile = new File( outputDir, fileName );
if ( FileUtils.fileExists( argFile.getAbsolutePath() ) )
{
FileReader reader = new FileReader( argFile );
BufferedReader bufRead = new BufferedReader( reader );
String line = null;
do
{
line = bufRead.readLine();
if ( null != line )
{
arguments.add( line );
}
}
while ( null != line );
}
return arguments;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"readBuildConfigFile",
"(",
"String",
"fileName",
",",
"File",
"outputDir",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"arguments",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
"... | Reads a build config file, and returns the List of all compiler arguments.
@param fileName the filename of the argfile
@param outputDir the build output area
@return
@throws IOException | [
"Reads",
"a",
"build",
"config",
"file",
"and",
"returns",
"the",
"List",
"of",
"all",
"compiler",
"arguments",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L264-L285 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.getAsCsv | protected static String getAsCsv( String[] strings )
{
String csv = "";
if ( null != strings )
{
for ( int i = 0; i < strings.length; i++ )
{
csv += strings[i];
if ( i < ( strings.length - 1 ) )
{
csv += ",";
}
}
}
return csv;
} | java | protected static String getAsCsv( String[] strings )
{
String csv = "";
if ( null != strings )
{
for ( int i = 0; i < strings.length; i++ )
{
csv += strings[i];
if ( i < ( strings.length - 1 ) )
{
csv += ",";
}
}
}
return csv;
} | [
"protected",
"static",
"String",
"getAsCsv",
"(",
"String",
"[",
"]",
"strings",
")",
"{",
"String",
"csv",
"=",
"\"\"",
";",
"if",
"(",
"null",
"!=",
"strings",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"strings",
".",
"length",
... | Convert a string array to a comma separated list
@param strings
@return | [
"Convert",
"a",
"string",
"array",
"to",
"a",
"comma",
"separated",
"list"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L293-L308 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.resolveIncludeExcludeString | protected static Set<String> resolveIncludeExcludeString( String input, File basedir )
throws MojoExecutionException
{
Set<String> inclExlSet = new LinkedHashSet<String>();
try
{
if ( null == input || input.trim().equals( "" ) )
{
return inclExlSet;
}
String[] elements = input.split( "," );
if ( null != elements )
{
for ( int i = 0; i < elements.length; i++ )
{
String element = elements[i];
if ( element.endsWith( ".java" ) || element.endsWith( ".aj" ) )
{
inclExlSet.addAll( FileUtils.getFileNames( basedir, element, "", true ) );
}
else
{
File lookupBaseDir = new File( basedir, element );
if ( FileUtils.fileExists( lookupBaseDir.getAbsolutePath() ) )
{
inclExlSet.addAll( FileUtils.getFileNames( lookupBaseDir, DEFAULT_INCLUDES, "",
true ) );
}
}
}
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not resolve java or aspect sources to compile", e );
}
return inclExlSet;
} | java | protected static Set<String> resolveIncludeExcludeString( String input, File basedir )
throws MojoExecutionException
{
Set<String> inclExlSet = new LinkedHashSet<String>();
try
{
if ( null == input || input.trim().equals( "" ) )
{
return inclExlSet;
}
String[] elements = input.split( "," );
if ( null != elements )
{
for ( int i = 0; i < elements.length; i++ )
{
String element = elements[i];
if ( element.endsWith( ".java" ) || element.endsWith( ".aj" ) )
{
inclExlSet.addAll( FileUtils.getFileNames( basedir, element, "", true ) );
}
else
{
File lookupBaseDir = new File( basedir, element );
if ( FileUtils.fileExists( lookupBaseDir.getAbsolutePath() ) )
{
inclExlSet.addAll( FileUtils.getFileNames( lookupBaseDir, DEFAULT_INCLUDES, "",
true ) );
}
}
}
}
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not resolve java or aspect sources to compile", e );
}
return inclExlSet;
} | [
"protected",
"static",
"Set",
"<",
"String",
">",
"resolveIncludeExcludeString",
"(",
"String",
"input",
",",
"File",
"basedir",
")",
"throws",
"MojoExecutionException",
"{",
"Set",
"<",
"String",
">",
"inclExlSet",
"=",
"new",
"LinkedHashSet",
"<",
"String",
">... | Helper method to find all .java or .aj files specified by the
includeString. The includeString is a comma separated list over files, or
directories relative to the specified basedir. Examples of correct
listings
<pre>
src/main/java/
src/main/java
src/main/java/com/project/AClass.java
src/main/java/com/project/AnAspect.aj
src/main/java/com/project/AnAspect.java
</pre>
@param input
@param basedir the baseDirectory
@return a list over all files inn the include string
@throws IOException | [
"Helper",
"method",
"to",
"find",
"all",
".",
"java",
"or",
".",
"aj",
"files",
"specified",
"by",
"the",
"includeString",
".",
"The",
"includeString",
"is",
"a",
"comma",
"separated",
"list",
"over",
"files",
"or",
"directories",
"relative",
"to",
"the",
... | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L329-L367 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java | AjcReportMojo.executeReport | @SuppressWarnings( "unchecked" )
protected void executeReport( Locale locale )
throws MavenReportException
{
getLog().info( "Starting generating ajdoc" );
project.getCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + aspectDirectory );
project.getTestCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + testAspectDirectory );
List<String> arguments = new ArrayList<String>();
// Add classpath
arguments.add( "-classpath" );
arguments.add( AjcHelper.createClassPath( project, pluginArtifacts, getClasspathDirectories() ) );
arguments.addAll( ajcOptions );
Set<String> includes;
try
{
if ( null != ajdtBuildDefFile )
{
includes = AjcHelper.getBuildFilesForAjdtFile( ajdtBuildDefFile, basedir );
}
else
{
includes = AjcHelper.getBuildFilesForSourceDirs( getSourceDirectories(), this.includes, this.excludes );
}
}
catch ( MojoExecutionException e )
{
throw new MavenReportException( "AspectJ Report failed", e );
}
// add target dir argument
arguments.add( "-d" );
arguments.add( StringUtils.replace( getOutputDirectory(), "//", "/" ) );
arguments.addAll( includes );
if ( getLog().isDebugEnabled() )
{
StringBuilder command = new StringBuilder( "Running : ajdoc " );
for ( String argument : arguments )
{
command.append( ' ' ).append( argument );
}
getLog().debug( command );
}
// There seems to be a difference in classloading when calling 'mvn site' or 'mvn aspectj:aspectj-report'.
// When calling mvn site, without the contextClassLoader set, you might see the next message:
// javadoc: error - Cannot find doclet class com.sun.tools.doclets.standard.Standard
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
// MASPECTJ-11: Make the ajdoc use the ${project.build.directory} directory for its intermediate folder.
// The argument should be the absolute path to the parent directory of the "ajdocworkingdir" folder.
Main.setOutputWorkingDir( buildDirectory.getAbsolutePath() );
// Now produce the JavaDoc.
Main.main( (String[]) arguments.toArray( new String[0] ) );
}
finally
{
Thread.currentThread().setContextClassLoader( oldContextClassLoader );
}
} | java | @SuppressWarnings( "unchecked" )
protected void executeReport( Locale locale )
throws MavenReportException
{
getLog().info( "Starting generating ajdoc" );
project.getCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + aspectDirectory );
project.getTestCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + testAspectDirectory );
List<String> arguments = new ArrayList<String>();
// Add classpath
arguments.add( "-classpath" );
arguments.add( AjcHelper.createClassPath( project, pluginArtifacts, getClasspathDirectories() ) );
arguments.addAll( ajcOptions );
Set<String> includes;
try
{
if ( null != ajdtBuildDefFile )
{
includes = AjcHelper.getBuildFilesForAjdtFile( ajdtBuildDefFile, basedir );
}
else
{
includes = AjcHelper.getBuildFilesForSourceDirs( getSourceDirectories(), this.includes, this.excludes );
}
}
catch ( MojoExecutionException e )
{
throw new MavenReportException( "AspectJ Report failed", e );
}
// add target dir argument
arguments.add( "-d" );
arguments.add( StringUtils.replace( getOutputDirectory(), "//", "/" ) );
arguments.addAll( includes );
if ( getLog().isDebugEnabled() )
{
StringBuilder command = new StringBuilder( "Running : ajdoc " );
for ( String argument : arguments )
{
command.append( ' ' ).append( argument );
}
getLog().debug( command );
}
// There seems to be a difference in classloading when calling 'mvn site' or 'mvn aspectj:aspectj-report'.
// When calling mvn site, without the contextClassLoader set, you might see the next message:
// javadoc: error - Cannot find doclet class com.sun.tools.doclets.standard.Standard
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
// MASPECTJ-11: Make the ajdoc use the ${project.build.directory} directory for its intermediate folder.
// The argument should be the absolute path to the parent directory of the "ajdocworkingdir" folder.
Main.setOutputWorkingDir( buildDirectory.getAbsolutePath() );
// Now produce the JavaDoc.
Main.main( (String[]) arguments.toArray( new String[0] ) );
}
finally
{
Thread.currentThread().setContextClassLoader( oldContextClassLoader );
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"void",
"executeReport",
"(",
"Locale",
"locale",
")",
"throws",
"MavenReportException",
"{",
"getLog",
"(",
")",
".",
"info",
"(",
"\"Starting generating ajdoc\"",
")",
";",
"project",
".",
"getComp... | Executes this ajdoc-report generation. | [
"Executes",
"this",
"ajdoc",
"-",
"report",
"generation",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java#L212-L281 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java | AjcReportMojo.getSourceDirectories | @SuppressWarnings( "unchecked" )
protected List<String> getSourceDirectories()
{
List<String> sourceDirectories = new ArrayList<String>();
sourceDirectories.addAll( project.getCompileSourceRoots() );
sourceDirectories.addAll( project.getTestCompileSourceRoots() );
return sourceDirectories;
} | java | @SuppressWarnings( "unchecked" )
protected List<String> getSourceDirectories()
{
List<String> sourceDirectories = new ArrayList<String>();
sourceDirectories.addAll( project.getCompileSourceRoots() );
sourceDirectories.addAll( project.getTestCompileSourceRoots() );
return sourceDirectories;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"List",
"<",
"String",
">",
"getSourceDirectories",
"(",
")",
"{",
"List",
"<",
"String",
">",
"sourceDirectories",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"sourceDirectories"... | Get the directories containg sources | [
"Get",
"the",
"directories",
"containg",
"sources"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java#L286-L293 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java | AjcReportMojo.getClasspathDirectories | protected List<String> getClasspathDirectories()
{
return Arrays.asList( project.getBuild().getOutputDirectory(),
project.getBuild().getTestOutputDirectory() );
} | java | protected List<String> getClasspathDirectories()
{
return Arrays.asList( project.getBuild().getOutputDirectory(),
project.getBuild().getTestOutputDirectory() );
} | [
"protected",
"List",
"<",
"String",
">",
"getClasspathDirectories",
"(",
")",
"{",
"return",
"Arrays",
".",
"asList",
"(",
"project",
".",
"getBuild",
"(",
")",
".",
"getOutputDirectory",
"(",
")",
",",
"project",
".",
"getBuild",
"(",
")",
".",
"getTestOu... | get compileroutput directory. | [
"get",
"compileroutput",
"directory",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java#L306-L310 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java | AjcReportMojo.setComplianceLevel | public void setComplianceLevel( String complianceLevel )
{
if ( AjcHelper.isValidComplianceLevel( complianceLevel ) )
{
ajcOptions.add( "-source" );
ajcOptions.add( complianceLevel );
}
} | java | public void setComplianceLevel( String complianceLevel )
{
if ( AjcHelper.isValidComplianceLevel( complianceLevel ) )
{
ajcOptions.add( "-source" );
ajcOptions.add( complianceLevel );
}
} | [
"public",
"void",
"setComplianceLevel",
"(",
"String",
"complianceLevel",
")",
"{",
"if",
"(",
"AjcHelper",
".",
"isValidComplianceLevel",
"(",
"complianceLevel",
")",
")",
"{",
"ajcOptions",
".",
"add",
"(",
"\"-source\"",
")",
";",
"ajcOptions",
".",
"add",
... | Setters which when called sets compiler arguments | [
"Setters",
"which",
"when",
"called",
"sets",
"compiler",
"arguments"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcReportMojo.java#L425-L432 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java | AbstractAjcCompiler.assembleArguments | protected void assembleArguments()
throws MojoExecutionException {
if (XhasMember) {
ajcOptions.add("-XhasMember");
}
// Add classpath
ajcOptions.add("-classpath");
ajcOptions.add(AjcHelper.createClassPath(project, null, getClasspathDirectories()));
// Add boot classpath
if (null != bootclasspath) {
ajcOptions.add("-bootclasspath");
ajcOptions.add(bootclasspath);
}
if (null != Xjoinpoints) {
ajcOptions.add("-Xjoinpoints:" + Xjoinpoints);
}
// Add warn option
if (null != warn) {
ajcOptions.add("-warn:" + warn);
}
if (null != proc) {
ajcOptions.add("-proc:" + proc);
}
if (Xset != null && !Xset.isEmpty()) {
StringBuilder sb = new StringBuilder("-Xset:");
for (Map.Entry<String, String> param : Xset.entrySet()) {
sb.append(param.getKey());
sb.append("=");
sb.append(param.getValue());
sb.append(',');
}
ajcOptions.add(sb.substring(0, sb.length() - 1));
}
// Add artifacts or directories to weave
String joinedWeaveDirectories = null;
if (weaveDirectories != null) {
joinedWeaveDirectories = StringUtils.join(weaveDirectories, File.pathSeparator);
}
addModulesArgument("-inpath", ajcOptions, weaveDependencies, joinedWeaveDirectories,
"dependencies and/or directories to weave");
// Add library artifacts
addModulesArgument("-aspectpath", ajcOptions, aspectLibraries, getAdditionalAspectPaths(),
"an aspect library");
// Add xmlConfigured option and argument
if (null != xmlConfigured) {
ajcOptions.add("-xmlConfigured");
ajcOptions.add(xmlConfigured.getAbsolutePath());
}
// add target dir argument
ajcOptions.add("-d");
ajcOptions.add(getOutputDirectory().getAbsolutePath());
ajcOptions.add("-s");
ajcOptions.add(getGeneratedSourcesDirectory().getAbsolutePath());
// Add all the files to be included in the build,
if (null != ajdtBuildDefFile) {
resolvedIncludes = AjcHelper.getBuildFilesForAjdtFile(ajdtBuildDefFile, basedir);
} else {
resolvedIncludes = getIncludedSources();
}
ajcOptions.addAll(resolvedIncludes);
} | java | protected void assembleArguments()
throws MojoExecutionException {
if (XhasMember) {
ajcOptions.add("-XhasMember");
}
// Add classpath
ajcOptions.add("-classpath");
ajcOptions.add(AjcHelper.createClassPath(project, null, getClasspathDirectories()));
// Add boot classpath
if (null != bootclasspath) {
ajcOptions.add("-bootclasspath");
ajcOptions.add(bootclasspath);
}
if (null != Xjoinpoints) {
ajcOptions.add("-Xjoinpoints:" + Xjoinpoints);
}
// Add warn option
if (null != warn) {
ajcOptions.add("-warn:" + warn);
}
if (null != proc) {
ajcOptions.add("-proc:" + proc);
}
if (Xset != null && !Xset.isEmpty()) {
StringBuilder sb = new StringBuilder("-Xset:");
for (Map.Entry<String, String> param : Xset.entrySet()) {
sb.append(param.getKey());
sb.append("=");
sb.append(param.getValue());
sb.append(',');
}
ajcOptions.add(sb.substring(0, sb.length() - 1));
}
// Add artifacts or directories to weave
String joinedWeaveDirectories = null;
if (weaveDirectories != null) {
joinedWeaveDirectories = StringUtils.join(weaveDirectories, File.pathSeparator);
}
addModulesArgument("-inpath", ajcOptions, weaveDependencies, joinedWeaveDirectories,
"dependencies and/or directories to weave");
// Add library artifacts
addModulesArgument("-aspectpath", ajcOptions, aspectLibraries, getAdditionalAspectPaths(),
"an aspect library");
// Add xmlConfigured option and argument
if (null != xmlConfigured) {
ajcOptions.add("-xmlConfigured");
ajcOptions.add(xmlConfigured.getAbsolutePath());
}
// add target dir argument
ajcOptions.add("-d");
ajcOptions.add(getOutputDirectory().getAbsolutePath());
ajcOptions.add("-s");
ajcOptions.add(getGeneratedSourcesDirectory().getAbsolutePath());
// Add all the files to be included in the build,
if (null != ajdtBuildDefFile) {
resolvedIncludes = AjcHelper.getBuildFilesForAjdtFile(ajdtBuildDefFile, basedir);
} else {
resolvedIncludes = getIncludedSources();
}
ajcOptions.addAll(resolvedIncludes);
} | [
"protected",
"void",
"assembleArguments",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"if",
"(",
"XhasMember",
")",
"{",
"ajcOptions",
".",
"add",
"(",
"\"-XhasMember\"",
")",
";",
"}",
"// Add classpath",
"ajcOptions",
".",
"add",
"(",
"\"-classpath\"",
... | Assembles a complete ajc compiler arguments list.
@throws MojoExecutionException error in configuration | [
"Assembles",
"a",
"complete",
"ajc",
"compiler",
"arguments",
"list",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java#L565-L637 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java | AbstractAjcCompiler.addModulesArgument | private void addModulesArgument(final String argument, final List<String> arguments, final Module[] modules,
final String aditionalpath, final String role)
throws MojoExecutionException {
StringBuilder buf = new StringBuilder();
if (null != aditionalpath) {
arguments.add(argument);
buf.append(aditionalpath);
}
if (modules != null && modules.length > 0) {
if (!arguments.contains(argument)) {
arguments.add(argument);
}
for (int i = 0; i < modules.length; ++i) {
Module module = modules[i];
// String key = ArtifactUtils.versionlessKey( module.getGroupId(), module.getArtifactId() );
// Artifact artifact = (Artifact) project.getArtifactMap().get( key );
Artifact artifact = null;
@SuppressWarnings("unchecked") Set<Artifact> allArtifacts = project.getArtifacts();
for (Artifact art : allArtifacts) {
if (art.getGroupId().equals(module.getGroupId()) && art.getArtifactId().equals(
module.getArtifactId()) && StringUtils.defaultString(module.getClassifier()).equals(
StringUtils.defaultString(art.getClassifier())) && StringUtils.defaultString(
module.getType(), "jar").equals(StringUtils.defaultString(art.getType()))) {
artifact = art;
break;
}
}
if (artifact == null) {
throw new MojoExecutionException(
"The artifact " + module.toString() + " referenced in aspectj plugin as " + role
+ ", is not found the project dependencies");
}
if (buf.length() != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(artifact.getFile().getPath());
}
}
if (buf.length() > 0) {
String pathString = buf.toString();
arguments.add(pathString);
getLog().debug("Adding " + argument + ": " + pathString);
}
} | java | private void addModulesArgument(final String argument, final List<String> arguments, final Module[] modules,
final String aditionalpath, final String role)
throws MojoExecutionException {
StringBuilder buf = new StringBuilder();
if (null != aditionalpath) {
arguments.add(argument);
buf.append(aditionalpath);
}
if (modules != null && modules.length > 0) {
if (!arguments.contains(argument)) {
arguments.add(argument);
}
for (int i = 0; i < modules.length; ++i) {
Module module = modules[i];
// String key = ArtifactUtils.versionlessKey( module.getGroupId(), module.getArtifactId() );
// Artifact artifact = (Artifact) project.getArtifactMap().get( key );
Artifact artifact = null;
@SuppressWarnings("unchecked") Set<Artifact> allArtifacts = project.getArtifacts();
for (Artifact art : allArtifacts) {
if (art.getGroupId().equals(module.getGroupId()) && art.getArtifactId().equals(
module.getArtifactId()) && StringUtils.defaultString(module.getClassifier()).equals(
StringUtils.defaultString(art.getClassifier())) && StringUtils.defaultString(
module.getType(), "jar").equals(StringUtils.defaultString(art.getType()))) {
artifact = art;
break;
}
}
if (artifact == null) {
throw new MojoExecutionException(
"The artifact " + module.toString() + " referenced in aspectj plugin as " + role
+ ", is not found the project dependencies");
}
if (buf.length() != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(artifact.getFile().getPath());
}
}
if (buf.length() > 0) {
String pathString = buf.toString();
arguments.add(pathString);
getLog().debug("Adding " + argument + ": " + pathString);
}
} | [
"private",
"void",
"addModulesArgument",
"(",
"final",
"String",
"argument",
",",
"final",
"List",
"<",
"String",
">",
"arguments",
",",
"final",
"Module",
"[",
"]",
"modules",
",",
"final",
"String",
"aditionalpath",
",",
"final",
"String",
"role",
")",
"th... | Finds all artifacts in the weavemodule property, and adds them to the ajc options.
@param argument
@param arguments
@param modules
@param aditionalpath
@param role
@throws MojoExecutionException | [
"Finds",
"all",
"artifacts",
"in",
"the",
"weavemodule",
"property",
"and",
"adds",
"them",
"to",
"the",
"ajc",
"options",
"."
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java#L671-L716 | train |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java | AbstractAjcCompiler.isBuildNeeded | protected boolean isBuildNeeded()
throws MojoExecutionException {
File outDir = getOutputDirectory();
return hasNoPreviousBuild(outDir) || hasArgumentsChanged(outDir) ||
hasSourcesChanged(outDir) || hasNonWeavedClassesChanged(outDir);
} | java | protected boolean isBuildNeeded()
throws MojoExecutionException {
File outDir = getOutputDirectory();
return hasNoPreviousBuild(outDir) || hasArgumentsChanged(outDir) ||
hasSourcesChanged(outDir) || hasNonWeavedClassesChanged(outDir);
} | [
"protected",
"boolean",
"isBuildNeeded",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"File",
"outDir",
"=",
"getOutputDirectory",
"(",
")",
";",
"return",
"hasNoPreviousBuild",
"(",
"outDir",
")",
"||",
"hasArgumentsChanged",
"(",
"outDir",
")",
"||",
"hasS... | Checks modifications that would make us need a build
@return <code>true</code> if build is needed, otherwise <code>false</code>
@throws MojoExecutionException | [
"Checks",
"modifications",
"that",
"would",
"make",
"us",
"need",
"a",
"build"
] | 120ee1ce08b93873931035ed98cd70e3ccceeefb | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AbstractAjcCompiler.java#L724-L730 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LogInputReader.java | LogInputReader.next | @Override
public RequestLogs next() throws NoSuchElementException {
Preconditions.checkNotNull(logIterator, "Reader was not initialized via beginSlice()");
if (logIterator.hasNext()) {
lastLog = logIterator.next();
return lastLog;
} else {
log.fine("Shard completed: " + shardLogQuery.getStartTimeUsec() + "-"
+ shardLogQuery.getEndTimeUsec());
throw new NoSuchElementException();
}
} | java | @Override
public RequestLogs next() throws NoSuchElementException {
Preconditions.checkNotNull(logIterator, "Reader was not initialized via beginSlice()");
if (logIterator.hasNext()) {
lastLog = logIterator.next();
return lastLog;
} else {
log.fine("Shard completed: " + shardLogQuery.getStartTimeUsec() + "-"
+ shardLogQuery.getEndTimeUsec());
throw new NoSuchElementException();
}
} | [
"@",
"Override",
"public",
"RequestLogs",
"next",
"(",
")",
"throws",
"NoSuchElementException",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"logIterator",
",",
"\"Reader was not initialized via beginSlice()\"",
")",
";",
"if",
"(",
"logIterator",
".",
"hasNext",
"... | Retrieve the next RequestLog | [
"Retrieve",
"the",
"next",
"RequestLog"
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LogInputReader.java#L76-L87 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LogInputReader.java | LogInputReader.getProgress | @Override
public Double getProgress() {
if ((shardLogQuery.getStartTimeUsec() == null) || (shardLogQuery.getEndTimeUsec() == null)) {
return null;
} else if (lastLog == null) {
return 0.0;
} else {
long processedTimeUsec = shardLogQuery.getEndTimeUsec() - lastLog.getEndTimeUsec();
long totalTimeUsec = shardLogQuery.getEndTimeUsec() - shardLogQuery.getStartTimeUsec();
return ((double) processedTimeUsec / totalTimeUsec);
}
} | java | @Override
public Double getProgress() {
if ((shardLogQuery.getStartTimeUsec() == null) || (shardLogQuery.getEndTimeUsec() == null)) {
return null;
} else if (lastLog == null) {
return 0.0;
} else {
long processedTimeUsec = shardLogQuery.getEndTimeUsec() - lastLog.getEndTimeUsec();
long totalTimeUsec = shardLogQuery.getEndTimeUsec() - shardLogQuery.getStartTimeUsec();
return ((double) processedTimeUsec / totalTimeUsec);
}
} | [
"@",
"Override",
"public",
"Double",
"getProgress",
"(",
")",
"{",
"if",
"(",
"(",
"shardLogQuery",
".",
"getStartTimeUsec",
"(",
")",
"==",
"null",
")",
"||",
"(",
"shardLogQuery",
".",
"getEndTimeUsec",
"(",
")",
"==",
"null",
")",
")",
"{",
"return",
... | Determine the approximate progress for this shard assuming the RequestLogs are uniformly
distributed across the entire time range. | [
"Determine",
"the",
"approximate",
"progress",
"for",
"this",
"shard",
"assuming",
"the",
"RequestLogs",
"are",
"uniformly",
"distributed",
"across",
"the",
"entire",
"time",
"range",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LogInputReader.java#L93-L104 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/servlets/ShufflerServlet.java | ShufflerServlet.enqueueCallbackTask | private static void enqueueCallbackTask(final ShufflerParams shufflerParams, final String url,
final String taskName) {
RetryHelper.runWithRetries(callable(new Runnable() {
@Override
public void run() {
String hostname = ModulesServiceFactory.getModulesService().getVersionHostname(
shufflerParams.getCallbackModule(), shufflerParams.getCallbackVersion());
Queue queue = QueueFactory.getQueue(shufflerParams.getCallbackQueue());
String separater = shufflerParams.getCallbackPath().contains("?") ? "&" : "?";
try {
queue.add(TaskOptions.Builder.withUrl(shufflerParams.getCallbackPath() + separater + url)
.method(TaskOptions.Method.GET).header("Host", hostname).taskName(taskName));
} catch (TaskAlreadyExistsException e) {
// harmless dup.
}
}
}), RETRY_PARAMS, EXCEPTION_HANDLER);
} | java | private static void enqueueCallbackTask(final ShufflerParams shufflerParams, final String url,
final String taskName) {
RetryHelper.runWithRetries(callable(new Runnable() {
@Override
public void run() {
String hostname = ModulesServiceFactory.getModulesService().getVersionHostname(
shufflerParams.getCallbackModule(), shufflerParams.getCallbackVersion());
Queue queue = QueueFactory.getQueue(shufflerParams.getCallbackQueue());
String separater = shufflerParams.getCallbackPath().contains("?") ? "&" : "?";
try {
queue.add(TaskOptions.Builder.withUrl(shufflerParams.getCallbackPath() + separater + url)
.method(TaskOptions.Method.GET).header("Host", hostname).taskName(taskName));
} catch (TaskAlreadyExistsException e) {
// harmless dup.
}
}
}), RETRY_PARAMS, EXCEPTION_HANDLER);
} | [
"private",
"static",
"void",
"enqueueCallbackTask",
"(",
"final",
"ShufflerParams",
"shufflerParams",
",",
"final",
"String",
"url",
",",
"final",
"String",
"taskName",
")",
"{",
"RetryHelper",
".",
"runWithRetries",
"(",
"callable",
"(",
"new",
"Runnable",
"(",
... | Notifies the caller that the job has completed. | [
"Notifies",
"the",
"caller",
"that",
"the",
"job",
"has",
"completed",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/servlets/ShufflerServlet.java#L222-L239 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.