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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/RemoveFieldRunnable.java | RemoveFieldRunnable.run | public void run() {
if (maxTime < 0) {
return;
}
long timeMillis = (long)maxTime * 60 * 1000;
endTime = new Date((new Date()).getTime() + timeMillis);
while (!cancel && endTime.after(new Date())) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
cancel = true;
}
}
if (!cancel && !endTime.after(new Date())) {
session.removeAttribute(key);
}
} | java | public void run() {
if (maxTime < 0) {
return;
}
long timeMillis = (long)maxTime * 60 * 1000;
endTime = new Date((new Date()).getTime() + timeMillis);
while (!cancel && endTime.after(new Date())) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
cancel = true;
}
}
if (!cancel && !endTime.after(new Date())) {
session.removeAttribute(key);
}
} | [
"public",
"void",
"run",
"(",
")",
"{",
"if",
"(",
"maxTime",
"<",
"0",
")",
"{",
"return",
";",
"}",
"long",
"timeMillis",
"=",
"(",
"long",
")",
"maxTime",
"*",
"60",
"*",
"1000",
";",
"endTime",
"=",
"new",
"Date",
"(",
"(",
"new",
"Date",
"... | Remove field from session after maxTime is elapsed. | [
"Remove",
"field",
"from",
"session",
"after",
"maxTime",
"is",
"elapsed",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/RemoveFieldRunnable.java#L42-L59 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/InstructionList.java | InstructionList.getInstructions | public Collection<Instruction> getInstructions() {
return new AbstractCollection<Instruction>() {
public Iterator<Instruction> iterator() {
return new Iterator<Instruction>() {
private Instruction mNext = mFirst;
public boolean hasNext() {
return mNext != null;
}
public Instruction next() {
if (mNext == null) {
throw new NoSuchElementException();
}
Instruction current = mNext;
mNext = mNext.mNext;
return current;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
int count = 0;
for (Instruction i = mFirst; i != null; i = i.mNext) {
count++;
}
return count;
}
};
} | java | public Collection<Instruction> getInstructions() {
return new AbstractCollection<Instruction>() {
public Iterator<Instruction> iterator() {
return new Iterator<Instruction>() {
private Instruction mNext = mFirst;
public boolean hasNext() {
return mNext != null;
}
public Instruction next() {
if (mNext == null) {
throw new NoSuchElementException();
}
Instruction current = mNext;
mNext = mNext.mNext;
return current;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
int count = 0;
for (Instruction i = mFirst; i != null; i = i.mNext) {
count++;
}
return count;
}
};
} | [
"public",
"Collection",
"<",
"Instruction",
">",
"getInstructions",
"(",
")",
"{",
"return",
"new",
"AbstractCollection",
"<",
"Instruction",
">",
"(",
")",
"{",
"public",
"Iterator",
"<",
"Instruction",
">",
"iterator",
"(",
")",
"{",
"return",
"new",
"Iter... | Returns an immutable collection of all the instructions in this
InstructionList. | [
"Returns",
"an",
"immutable",
"collection",
"of",
"all",
"the",
"instructions",
"in",
"this",
"InstructionList",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/InstructionList.java#L101-L135 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/InstructionList.java | InstructionList.createLocalParameter | public LocalVariable createLocalParameter(String name, TypeDesc type) {
LocalVariable var = new LocalVariableImpl
(mLocalVariables.size(), name, type, mNextFixedVariableNumber);
mLocalVariables.add(var);
mNextFixedVariableNumber += type.isDoubleWord() ? 2 : 1;
return var;
} | java | public LocalVariable createLocalParameter(String name, TypeDesc type) {
LocalVariable var = new LocalVariableImpl
(mLocalVariables.size(), name, type, mNextFixedVariableNumber);
mLocalVariables.add(var);
mNextFixedVariableNumber += type.isDoubleWord() ? 2 : 1;
return var;
} | [
"public",
"LocalVariable",
"createLocalParameter",
"(",
"String",
"name",
",",
"TypeDesc",
"type",
")",
"{",
"LocalVariable",
"var",
"=",
"new",
"LocalVariableImpl",
"(",
"mLocalVariables",
".",
"size",
"(",
")",
",",
"name",
",",
"type",
",",
"mNextFixedVariabl... | All parameters must be defined before adding instructions. | [
"All",
"parameters",
"must",
"be",
"defined",
"before",
"adding",
"instructions",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/InstructionList.java#L172-L178 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/localization/AbstractBundleInterceptor.java | AbstractBundleInterceptor.intercept | public Resolution intercept(ExecutionContext context)
throws Exception
{
HttpServletRequest request = context.getActionBeanContext().getRequest();
if (resourceBundleFactory != null)
{
ResourceBundle bundle = resourceBundleFactory.getDefaultBundle(request.getLocale());
setMessageResourceBundle(request, bundle);
}
setOtherResourceBundles(request);
return context.proceed();
} | java | public Resolution intercept(ExecutionContext context)
throws Exception
{
HttpServletRequest request = context.getActionBeanContext().getRequest();
if (resourceBundleFactory != null)
{
ResourceBundle bundle = resourceBundleFactory.getDefaultBundle(request.getLocale());
setMessageResourceBundle(request, bundle);
}
setOtherResourceBundles(request);
return context.proceed();
} | [
"public",
"Resolution",
"intercept",
"(",
"ExecutionContext",
"context",
")",
"throws",
"Exception",
"{",
"HttpServletRequest",
"request",
"=",
"context",
".",
"getActionBeanContext",
"(",
")",
".",
"getRequest",
"(",
")",
";",
"if",
"(",
"resourceBundleFactory",
... | Invoked when intercepting the flow of execution.
@param context the ExecutionContext of the request currently being processed
@return the result of calling context.proceed(), or if the interceptor wishes to change
the flow of execution, a Resolution
@throws Exception if any non-recoverable errors occur | [
"Invoked",
"when",
"intercepting",
"the",
"flow",
"of",
"execution",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/localization/AbstractBundleInterceptor.java#L146-L160 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/SecurityInterceptor.java | SecurityInterceptor.intercept | public Resolution intercept(ExecutionContext executionContext)
throws Exception
{
Resolution resolution;
if (securityManager != null)
{
// Add the security manager to the request.
// This is used (for example) by the security tag.
executionContext.getActionBeanContext().getRequest().setAttribute(SecurityInterceptor.SECURITY_MANAGER,
securityManager);
switch (executionContext.getLifecycleStage())
{
case BindingAndValidation:
case CustomValidation:
resolution = interceptBindingAndValidation(executionContext);
break;
case EventHandling:
resolution = interceptEventHandling(executionContext);
break;
case ResolutionExecution:
resolution = interceptResolutionExecution(executionContext);
break;
default: // Should not happen (see @Intercepts annotation on class)
resolution = executionContext.proceed();
break;
}
}
else
{
// There is no security manager, so everything is allowed.
resolution = executionContext.proceed();
}
return resolution;
} | java | public Resolution intercept(ExecutionContext executionContext)
throws Exception
{
Resolution resolution;
if (securityManager != null)
{
// Add the security manager to the request.
// This is used (for example) by the security tag.
executionContext.getActionBeanContext().getRequest().setAttribute(SecurityInterceptor.SECURITY_MANAGER,
securityManager);
switch (executionContext.getLifecycleStage())
{
case BindingAndValidation:
case CustomValidation:
resolution = interceptBindingAndValidation(executionContext);
break;
case EventHandling:
resolution = interceptEventHandling(executionContext);
break;
case ResolutionExecution:
resolution = interceptResolutionExecution(executionContext);
break;
default: // Should not happen (see @Intercepts annotation on class)
resolution = executionContext.proceed();
break;
}
}
else
{
// There is no security manager, so everything is allowed.
resolution = executionContext.proceed();
}
return resolution;
} | [
"public",
"Resolution",
"intercept",
"(",
"ExecutionContext",
"executionContext",
")",
"throws",
"Exception",
"{",
"Resolution",
"resolution",
";",
"if",
"(",
"securityManager",
"!=",
"null",
")",
"{",
"// Add the security manager to the request.",
"// This is used (for exa... | Intercept execution.
@param executionContext the context of the execution being intercepted
@return the resulting {@link Resolution}; returns {@link ExecutionContext#proceed()} if all is well
@throws Exception on error | [
"Intercept",
"execution",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/SecurityInterceptor.java#L112-L149 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/SecurityInterceptor.java | SecurityInterceptor.interceptEventHandling | protected Resolution interceptEventHandling(ExecutionContext executionContext)
throws Exception
{
// Before handling the event, check if access is allowed.
// If not explicitly allowed, access is denied.
Resolution resolution;
if (Boolean.TRUE.equals(getAccessAllowed(executionContext)))
{
resolution = executionContext.proceed();
}
else
{
LOG.debug("The security manager has denied access.");
resolution = handleAccessDenied(executionContext.getActionBean(), executionContext.getHandler());
}
return resolution;
} | java | protected Resolution interceptEventHandling(ExecutionContext executionContext)
throws Exception
{
// Before handling the event, check if access is allowed.
// If not explicitly allowed, access is denied.
Resolution resolution;
if (Boolean.TRUE.equals(getAccessAllowed(executionContext)))
{
resolution = executionContext.proceed();
}
else
{
LOG.debug("The security manager has denied access.");
resolution = handleAccessDenied(executionContext.getActionBean(), executionContext.getHandler());
}
return resolution;
} | [
"protected",
"Resolution",
"interceptEventHandling",
"(",
"ExecutionContext",
"executionContext",
")",
"throws",
"Exception",
"{",
"// Before handling the event, check if access is allowed.",
"// If not explicitly allowed, access is denied.",
"Resolution",
"resolution",
";",
"if",
"(... | Intercept execution for event handling. Checks if the security manager allows access before allowing the event.
@param executionContext the context of the execution being intercepted
@return the resulting {@link net.sourceforge.stripes.action.Resolution}; returns {@link ExecutionContext#proceed()} if all is well
@throws Exception on error | [
"Intercept",
"execution",
"for",
"event",
"handling",
".",
"Checks",
"if",
"the",
"security",
"manager",
"allows",
"access",
"before",
"allowing",
"the",
"event",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/SecurityInterceptor.java#L191-L210 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/TypeDesc.java | TypeDesc.forDescriptor | public static TypeDesc forDescriptor(final String desc) throws IllegalArgumentException {
TypeDesc type = cDescriptorsToInstances.get(desc);
if (type != null) {
return type;
}
// TODO: Support generics in descriptor.
String rootDesc = desc;
int cursor = 0;
int dim = 0;
try {
char c;
while ((c = rootDesc.charAt(cursor++)) == '[') {
dim++;
}
switch (c) {
case 'V':
type = VOID;
break;
case 'Z':
type = BOOLEAN;
break;
case 'C':
type = CHAR;
break;
case 'B':
type = BYTE;
break;
case 'S':
type = SHORT;
break;
case 'I':
type = INT;
break;
case 'J':
type = LONG;
break;
case 'F':
type = FLOAT;
break;
case 'D':
type = DOUBLE;
break;
case 'L':
if (dim > 0) {
rootDesc = rootDesc.substring(dim);
cursor = 1;
}
StringBuffer name = new StringBuffer(rootDesc.length() - 2);
while ((c = rootDesc.charAt(cursor++)) != ';') {
if (c == '/') {
c = '.';
}
name.append(c);
}
type = intern(new ObjectType(rootDesc, name.toString()));
break;
default:
throw invalidDescriptor(desc);
}
} catch (NullPointerException e) {
throw invalidDescriptor(desc);
} catch (IndexOutOfBoundsException e) {
throw invalidDescriptor(desc);
}
if (cursor != rootDesc.length()) {
throw invalidDescriptor(desc);
}
while (--dim >= 0) {
type = type.toArrayType();
}
cDescriptorsToInstances.put(desc, type);
return type;
} | java | public static TypeDesc forDescriptor(final String desc) throws IllegalArgumentException {
TypeDesc type = cDescriptorsToInstances.get(desc);
if (type != null) {
return type;
}
// TODO: Support generics in descriptor.
String rootDesc = desc;
int cursor = 0;
int dim = 0;
try {
char c;
while ((c = rootDesc.charAt(cursor++)) == '[') {
dim++;
}
switch (c) {
case 'V':
type = VOID;
break;
case 'Z':
type = BOOLEAN;
break;
case 'C':
type = CHAR;
break;
case 'B':
type = BYTE;
break;
case 'S':
type = SHORT;
break;
case 'I':
type = INT;
break;
case 'J':
type = LONG;
break;
case 'F':
type = FLOAT;
break;
case 'D':
type = DOUBLE;
break;
case 'L':
if (dim > 0) {
rootDesc = rootDesc.substring(dim);
cursor = 1;
}
StringBuffer name = new StringBuffer(rootDesc.length() - 2);
while ((c = rootDesc.charAt(cursor++)) != ';') {
if (c == '/') {
c = '.';
}
name.append(c);
}
type = intern(new ObjectType(rootDesc, name.toString()));
break;
default:
throw invalidDescriptor(desc);
}
} catch (NullPointerException e) {
throw invalidDescriptor(desc);
} catch (IndexOutOfBoundsException e) {
throw invalidDescriptor(desc);
}
if (cursor != rootDesc.length()) {
throw invalidDescriptor(desc);
}
while (--dim >= 0) {
type = type.toArrayType();
}
cDescriptorsToInstances.put(desc, type);
return type;
} | [
"public",
"static",
"TypeDesc",
"forDescriptor",
"(",
"final",
"String",
"desc",
")",
"throws",
"IllegalArgumentException",
"{",
"TypeDesc",
"type",
"=",
"cDescriptorsToInstances",
".",
"get",
"(",
"desc",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
... | Acquire a TypeDesc from a type descriptor. | [
"Acquire",
"a",
"TypeDesc",
"from",
"a",
"type",
"descriptor",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/TypeDesc.java#L277-L355 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionMapper.java | SessionMapper.valueUnbound | public void valueUnbound(HttpSessionBindingEvent event) {
for (SessionFieldMapper fieldMapper : this.values()) {
if (fieldMapper.runnable != null) fieldMapper.runnable.cancel();
}
} | java | public void valueUnbound(HttpSessionBindingEvent event) {
for (SessionFieldMapper fieldMapper : this.values()) {
if (fieldMapper.runnable != null) fieldMapper.runnable.cancel();
}
} | [
"public",
"void",
"valueUnbound",
"(",
"HttpSessionBindingEvent",
"event",
")",
"{",
"for",
"(",
"SessionFieldMapper",
"fieldMapper",
":",
"this",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"fieldMapper",
".",
"runnable",
"!=",
"null",
")",
"fieldMapper",
... | Cancel all threads from field mappers. | [
"Cancel",
"all",
"threads",
"from",
"field",
"mappers",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionMapper.java#L23-L27 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionMapper.java | SessionMapper.sessionWillPassivate | public void sessionWillPassivate(HttpSessionEvent event) {
for (Entry<String, SessionFieldMapper> entry : this.entrySet()) {
if (!entry.getValue().serializable) {
event.getSession().removeAttribute(entry.getKey());
}
}
} | java | public void sessionWillPassivate(HttpSessionEvent event) {
for (Entry<String, SessionFieldMapper> entry : this.entrySet()) {
if (!entry.getValue().serializable) {
event.getSession().removeAttribute(entry.getKey());
}
}
} | [
"public",
"void",
"sessionWillPassivate",
"(",
"HttpSessionEvent",
"event",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"SessionFieldMapper",
">",
"entry",
":",
"this",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"!",
"entry",
".",
"getValue",
... | Remove all non-serializable fields from session. | [
"Remove",
"all",
"non",
"-",
"serializable",
"fields",
"from",
"session",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionMapper.java#L35-L41 | train |
cojen/Cojen | src/main/java/org/cojen/util/ReferencedValueHashMap.java | ReferencedValueHashMap.cleanup | private void cleanup() {
Entry<K, V>[] tab = this.table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<K, V> e = tab[i], prev = null; e != null; e = e.next) {
if (e.get() == null) {
// Clean up after a cleared Reference.
this.modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[i] = e.next;
}
this.count--;
} else {
prev = e;
}
}
}
} | java | private void cleanup() {
Entry<K, V>[] tab = this.table;
for (int i = tab.length ; i-- > 0 ;) {
for (Entry<K, V> e = tab[i], prev = null; e != null; e = e.next) {
if (e.get() == null) {
// Clean up after a cleared Reference.
this.modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[i] = e.next;
}
this.count--;
} else {
prev = e;
}
}
}
} | [
"private",
"void",
"cleanup",
"(",
")",
"{",
"Entry",
"<",
"K",
",",
"V",
">",
"[",
"]",
"tab",
"=",
"this",
".",
"table",
";",
"for",
"(",
"int",
"i",
"=",
"tab",
".",
"length",
";",
"i",
"--",
">",
"0",
";",
")",
"{",
"for",
"(",
"Entry",... | Scans the contents of this map, removing all entries that have a
cleared soft value. | [
"Scans",
"the",
"contents",
"of",
"this",
"map",
"removing",
"all",
"entries",
"that",
"have",
"a",
"cleared",
"soft",
"value",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ReferencedValueHashMap.java#L257-L276 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/localization/GenericBundleInterceptor.java | GenericBundleInterceptor.setMessageResourceBundle | @Override
protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle) {
request.setAttribute(REQ_ATTR_MESSAGE_RESOURCE_BUNDLE, bundle);
} | java | @Override
protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle) {
request.setAttribute(REQ_ATTR_MESSAGE_RESOURCE_BUNDLE, bundle);
} | [
"@",
"Override",
"protected",
"void",
"setMessageResourceBundle",
"(",
"HttpServletRequest",
"request",
",",
"ResourceBundle",
"bundle",
")",
"{",
"request",
".",
"setAttribute",
"(",
"REQ_ATTR_MESSAGE_RESOURCE_BUNDLE",
",",
"bundle",
")",
";",
"}"
] | Puts the resource bundle as a request-scope attribute. | [
"Puts",
"the",
"resource",
"bundle",
"as",
"a",
"request",
"-",
"scope",
"attribute",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/localization/GenericBundleInterceptor.java#L26-L29 | train |
Faylixe/googlecodejam-client | src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java | Problem.getProblemInputs | public List<ProblemInput> getProblemInputs() {
return (inputs == null ? Collections.emptyList() : Arrays.asList(inputs));
} | java | public List<ProblemInput> getProblemInputs() {
return (inputs == null ? Collections.emptyList() : Arrays.asList(inputs));
} | [
"public",
"List",
"<",
"ProblemInput",
">",
"getProblemInputs",
"(",
")",
"{",
"return",
"(",
"inputs",
"==",
"null",
"?",
"Collections",
".",
"emptyList",
"(",
")",
":",
"Arrays",
".",
"asList",
"(",
"inputs",
")",
")",
";",
"}"
] | Getter for the problem inputs.
@return List of inputs that are available for solving in this problem.
@see #inputs | [
"Getter",
"for",
"the",
"problem",
"inputs",
"."
] | 84a5fed4e049dca48994dc3f70213976aaff4bd3 | https://github.com/Faylixe/googlecodejam-client/blob/84a5fed4e049dca48994dc3f70213976aaff4bd3/src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java#L211-L213 | train |
Faylixe/googlecodejam-client | src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java | Problem.getProblemInput | public ProblemInput getProblemInput(final int index) {
final List<ProblemInput> inputs = getProblemInputs();
if (index < 0 || inputs.size() <= index) {
throw new ArrayIndexOutOfBoundsException();
}
return inputs.get(index);
} | java | public ProblemInput getProblemInput(final int index) {
final List<ProblemInput> inputs = getProblemInputs();
if (index < 0 || inputs.size() <= index) {
throw new ArrayIndexOutOfBoundsException();
}
return inputs.get(index);
} | [
"public",
"ProblemInput",
"getProblemInput",
"(",
"final",
"int",
"index",
")",
"{",
"final",
"List",
"<",
"ProblemInput",
">",
"inputs",
"=",
"getProblemInputs",
"(",
")",
";",
"if",
"(",
"index",
"<",
"0",
"||",
"inputs",
".",
"size",
"(",
")",
"<=",
... | Shortcut method for reducing law of Demeters issues.
@param index Index of the problem input to retrieve.
@return Problem input instance required.
@throws ArrayIndexOutOfBoundsException If the given index is not valid. | [
"Shortcut",
"method",
"for",
"reducing",
"law",
"of",
"Demeters",
"issues",
"."
] | 84a5fed4e049dca48994dc3f70213976aaff4bd3 | https://github.com/Faylixe/googlecodejam-client/blob/84a5fed4e049dca48994dc3f70213976aaff4bd3/src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java#L222-L228 | train |
Faylixe/googlecodejam-client | src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java | Problem.readObject | private void readObject(final ObjectInputStream stream) throws OptionalDataException, ClassNotFoundException, IOException {
stream.registerValidation(this, 0);
stream.defaultReadObject();
} | java | private void readObject(final ObjectInputStream stream) throws OptionalDataException, ClassNotFoundException, IOException {
stream.registerValidation(this, 0);
stream.defaultReadObject();
} | [
"private",
"void",
"readObject",
"(",
"final",
"ObjectInputStream",
"stream",
")",
"throws",
"OptionalDataException",
",",
"ClassNotFoundException",
",",
"IOException",
"{",
"stream",
".",
"registerValidation",
"(",
"this",
",",
"0",
")",
";",
"stream",
".",
"defa... | Custom readObject method that registers this object as a deserialization validator.
@param stream {@link ObjectInputStream} to register this validator to.
@throws OptionalDataException If any error occurs while reading the object.
@throws ClassNotFoundException If the default readObject call can not find a required class.
@throws IOException If any error occurs while reading the object. | [
"Custom",
"readObject",
"method",
"that",
"registers",
"this",
"object",
"as",
"a",
"deserialization",
"validator",
"."
] | 84a5fed4e049dca48994dc3f70213976aaff4bd3 | https://github.com/Faylixe/googlecodejam-client/blob/84a5fed4e049dca48994dc3f70213976aaff4bd3/src/main/java/fr/faylixe/googlecodejam/client/webservice/Problem.java#L263-L266 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/Opcode.java | Opcode.canThrowException | public final static boolean canThrowException(byte opcode) {
switch (opcode) {
default:
return false;
case IALOAD:
case LALOAD:
case FALOAD:
case DALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
case IASTORE:
case LASTORE:
case FASTORE:
case DASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
case IDIV:
case LDIV:
case IREM:
case LREM:
case GETFIELD:
case PUTFIELD:
case INVOKEVIRTUAL:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEINTERFACE:
case NEWARRAY:
case ANEWARRAY:
case ARRAYLENGTH:
case ATHROW:
case CHECKCAST:
case MONITORENTER:
case MONITOREXIT:
case MULTIANEWARRAY:
return true;
}
} | java | public final static boolean canThrowException(byte opcode) {
switch (opcode) {
default:
return false;
case IALOAD:
case LALOAD:
case FALOAD:
case DALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
case IASTORE:
case LASTORE:
case FASTORE:
case DASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
case IDIV:
case LDIV:
case IREM:
case LREM:
case GETFIELD:
case PUTFIELD:
case INVOKEVIRTUAL:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEINTERFACE:
case NEWARRAY:
case ANEWARRAY:
case ARRAYLENGTH:
case ATHROW:
case CHECKCAST:
case MONITORENTER:
case MONITOREXIT:
case MULTIANEWARRAY:
return true;
}
} | [
"public",
"final",
"static",
"boolean",
"canThrowException",
"(",
"byte",
"opcode",
")",
"{",
"switch",
"(",
"opcode",
")",
"{",
"default",
":",
"return",
"false",
";",
"case",
"IALOAD",
":",
"case",
"LALOAD",
":",
"case",
"FALOAD",
":",
"case",
"DALOAD",
... | Returns true if the given opcode can throw an exception at runtime. | [
"Returns",
"true",
"if",
"the",
"given",
"opcode",
"can",
"throw",
"an",
"exception",
"at",
"runtime",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/Opcode.java#L296-L336 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanIntrospector.java | BeanIntrospector.getAllProperties | public static Map<String, BeanProperty> getAllProperties(Class clazz) {
synchronized (cPropertiesCache) {
Map<String, BeanProperty> properties;
SoftReference<Map<String, BeanProperty>> ref = cPropertiesCache.get(clazz);
if (ref != null) {
properties = ref.get();
if (properties != null) {
return properties;
}
}
properties = createProperties(clazz);
cPropertiesCache.put(clazz, new SoftReference<Map<String, BeanProperty>>(properties));
return properties;
}
} | java | public static Map<String, BeanProperty> getAllProperties(Class clazz) {
synchronized (cPropertiesCache) {
Map<String, BeanProperty> properties;
SoftReference<Map<String, BeanProperty>> ref = cPropertiesCache.get(clazz);
if (ref != null) {
properties = ref.get();
if (properties != null) {
return properties;
}
}
properties = createProperties(clazz);
cPropertiesCache.put(clazz, new SoftReference<Map<String, BeanProperty>>(properties));
return properties;
}
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"BeanProperty",
">",
"getAllProperties",
"(",
"Class",
"clazz",
")",
"{",
"synchronized",
"(",
"cPropertiesCache",
")",
"{",
"Map",
"<",
"String",
",",
"BeanProperty",
">",
"properties",
";",
"SoftReference",
"<",... | Returns a Map of all the available properties on a given class including
write-only and indexed properties.
@return Map<String, BeanProperty> an unmodifiable mapping of property
names (Strings) to BeanProperty objects. | [
"Returns",
"a",
"Map",
"of",
"all",
"the",
"available",
"properties",
"on",
"a",
"given",
"class",
"including",
"write",
"-",
"only",
"and",
"indexed",
"properties",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanIntrospector.java#L51-L65 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanIntrospector.java | BeanIntrospector.extractPropertyName | private static String extractPropertyName(Method method, String prefix) {
String name = method.getName();
if (!name.startsWith(prefix)) {
return null;
}
if (name.length() == prefix.length()) {
return "";
}
name = name.substring(prefix.length());
if (!Character.isUpperCase(name.charAt(0)) || name.indexOf('$') >= 0) {
return null;
}
// Decapitalize the name only if it doesn't begin with two uppercase
// letters.
if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) {
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
name = new String(chars);
}
return name.intern();
} | java | private static String extractPropertyName(Method method, String prefix) {
String name = method.getName();
if (!name.startsWith(prefix)) {
return null;
}
if (name.length() == prefix.length()) {
return "";
}
name = name.substring(prefix.length());
if (!Character.isUpperCase(name.charAt(0)) || name.indexOf('$') >= 0) {
return null;
}
// Decapitalize the name only if it doesn't begin with two uppercase
// letters.
if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) {
char chars[] = name.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
name = new String(chars);
}
return name.intern();
} | [
"private",
"static",
"String",
"extractPropertyName",
"(",
"Method",
"method",
",",
"String",
"prefix",
")",
"{",
"String",
"name",
"=",
"method",
".",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"name",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"... | Returns null if prefix pattern doesn't match | [
"Returns",
"null",
"if",
"prefix",
"pattern",
"doesn",
"t",
"match"
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanIntrospector.java#L244-L267 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.saveFields | protected void saveFields(Collection<Field> fields, ActionBean actionBean, HttpSession session) throws IllegalAccessException {
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
setAttribute(session, getFieldKey(field, actionBean.getClass()), field.get(actionBean), ((Session)field.getAnnotation(Session.class)).serializable(), ((Session)field.getAnnotation(Session.class)).maxTime());
}
} | java | protected void saveFields(Collection<Field> fields, ActionBean actionBean, HttpSession session) throws IllegalAccessException {
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
setAttribute(session, getFieldKey(field, actionBean.getClass()), field.get(actionBean), ((Session)field.getAnnotation(Session.class)).serializable(), ((Session)field.getAnnotation(Session.class)).maxTime());
}
} | [
"protected",
"void",
"saveFields",
"(",
"Collection",
"<",
"Field",
">",
"fields",
",",
"ActionBean",
"actionBean",
",",
"HttpSession",
"session",
")",
"throws",
"IllegalAccessException",
"{",
"for",
"(",
"Field",
"field",
":",
"fields",
")",
"{",
"if",
"(",
... | Saves all fields in session.
@param fields Fields to save in session.
@param actionBean ActionBean.
@param session HttpSession.
@throws IllegalAccessException Cannot get access to some fields. | [
"Saves",
"all",
"fields",
"in",
"session",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L76-L83 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.restoreFields | protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException {
HttpSession session = context.getRequest().getSession(false);
if (session != null) {
Set<String> parameters = this.getParameters(context.getRequest());
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (!parameters.contains(field.getName())) {
// Replace value.
Object value = session.getAttribute(getFieldKey(field, actionBean.getClass()));
// If value is null and field is primitive, don't set value.
if (!(value == null && field.getType().isPrimitive())) {
field.set(actionBean, value);
}
}
}
}
} | java | protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException {
HttpSession session = context.getRequest().getSession(false);
if (session != null) {
Set<String> parameters = this.getParameters(context.getRequest());
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (!parameters.contains(field.getName())) {
// Replace value.
Object value = session.getAttribute(getFieldKey(field, actionBean.getClass()));
// If value is null and field is primitive, don't set value.
if (!(value == null && field.getType().isPrimitive())) {
field.set(actionBean, value);
}
}
}
}
} | [
"protected",
"void",
"restoreFields",
"(",
"Collection",
"<",
"Field",
">",
"fields",
",",
"ActionBean",
"actionBean",
",",
"ActionBeanContext",
"context",
")",
"throws",
"IllegalAccessException",
"{",
"HttpSession",
"session",
"=",
"context",
".",
"getRequest",
"("... | Restore all fields from value stored in session except if they.
@param fields Fields to restore from session.
@param actionBean ActionBean.
@param context ActionBeanContext.
@throws IllegalAccessException Cannot get access to some fields. | [
"Restore",
"all",
"fields",
"from",
"value",
"stored",
"in",
"session",
"except",
"if",
"they",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L91-L109 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.getParameters | protected Set<String> getParameters(HttpServletRequest request) {
Set<String> parameters = new HashSet<String>();
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String parameter = (String) paramNames.nextElement();
// Keep only first property.
while (parameter.contains(".") || parameter.contains("[")) {
if (parameter.contains(".")) {
parameter = parameter.substring(0, parameter.indexOf("."));
}
if (parameter.contains("[")) {
parameter = parameter.substring(0, parameter.indexOf("["));
}
}
parameters.add(parameter);
}
return parameters;
} | java | protected Set<String> getParameters(HttpServletRequest request) {
Set<String> parameters = new HashSet<String>();
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String parameter = (String) paramNames.nextElement();
// Keep only first property.
while (parameter.contains(".") || parameter.contains("[")) {
if (parameter.contains(".")) {
parameter = parameter.substring(0, parameter.indexOf("."));
}
if (parameter.contains("[")) {
parameter = parameter.substring(0, parameter.indexOf("["));
}
}
parameters.add(parameter);
}
return parameters;
} | [
"protected",
"Set",
"<",
"String",
">",
"getParameters",
"(",
"HttpServletRequest",
"request",
")",
"{",
"Set",
"<",
"String",
">",
"parameters",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"Enumeration",
"<",
"?",
">",
"paramNames",
"=",
"... | Returns all property that stripes will replace for request.
@param request Request.
@return All property that stripes will replace for request. | [
"Returns",
"all",
"property",
"that",
"stripes",
"will",
"replace",
"for",
"request",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L115-L132 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.getFieldKey | protected String getFieldKey(Field field, Class<? extends ActionBean> actionBeanClass) {
// Use key attribute if it is defined.
String sessionKey = ((Session)field.getAnnotation(Session.class)).key();
if (sessionKey != null && !"".equals(sessionKey)) {
return sessionKey;
}
else {
// Use default key since no custom key is defined.
return actionBeanClass + "#" + field.getName();
}
} | java | protected String getFieldKey(Field field, Class<? extends ActionBean> actionBeanClass) {
// Use key attribute if it is defined.
String sessionKey = ((Session)field.getAnnotation(Session.class)).key();
if (sessionKey != null && !"".equals(sessionKey)) {
return sessionKey;
}
else {
// Use default key since no custom key is defined.
return actionBeanClass + "#" + field.getName();
}
} | [
"protected",
"String",
"getFieldKey",
"(",
"Field",
"field",
",",
"Class",
"<",
"?",
"extends",
"ActionBean",
">",
"actionBeanClass",
")",
"{",
"// Use key attribute if it is defined.\r",
"String",
"sessionKey",
"=",
"(",
"(",
"Session",
")",
"field",
".",
"getAnn... | Returns session key under which field should be saved or read.
@param field Field.
@param actionBeanClass Action bean class.
@return Session key under which field should be saved or read. | [
"Returns",
"session",
"key",
"under",
"which",
"field",
"should",
"be",
"saved",
"or",
"read",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L139-L149 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.getSessionFields | protected Collection<Field> getSessionFields(Class<?> clazz) {
Collection<Field> fields = fieldMap.get(clazz);
if (fields == null) {
fields = ReflectUtil.getFields(clazz);
Iterator<Field> iterator = fields.iterator();
while (iterator.hasNext()) {
Field field = iterator.next();
if (!field.isAnnotationPresent(Session.class)) {
iterator.remove();
}
}
fieldMap.put(clazz, fields);
}
return fields;
} | java | protected Collection<Field> getSessionFields(Class<?> clazz) {
Collection<Field> fields = fieldMap.get(clazz);
if (fields == null) {
fields = ReflectUtil.getFields(clazz);
Iterator<Field> iterator = fields.iterator();
while (iterator.hasNext()) {
Field field = iterator.next();
if (!field.isAnnotationPresent(Session.class)) {
iterator.remove();
}
}
fieldMap.put(clazz, fields);
}
return fields;
} | [
"protected",
"Collection",
"<",
"Field",
">",
"getSessionFields",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"Collection",
"<",
"Field",
">",
"fields",
"=",
"fieldMap",
".",
"get",
"(",
"clazz",
")",
";",
"if",
"(",
"fields",
"==",
"null",
")",
... | Returns all fields with Session annotation for a class.
@param clazz Class.
@return All fields with Session annotation for a class. | [
"Returns",
"all",
"fields",
"with",
"Session",
"annotation",
"for",
"a",
"class",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L155-L169 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.getAttribute | @Deprecated
public static Object getAttribute(HttpSession session, String key) {
return session.getAttribute(key);
} | java | @Deprecated
public static Object getAttribute(HttpSession session, String key) {
return session.getAttribute(key);
} | [
"@",
"Deprecated",
"public",
"static",
"Object",
"getAttribute",
"(",
"HttpSession",
"session",
",",
"String",
"key",
")",
"{",
"return",
"session",
".",
"getAttribute",
"(",
"key",
")",
";",
"}"
] | Returns an object in session.
@param session session.
@param key Key under which object is saved.
@return Object.
@deprecated Use {@link HttpSession#getAttribute(String)} instead. | [
"Returns",
"an",
"object",
"in",
"session",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L179-L182 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java | SessionStoreInterceptor.setAttribute | protected Object setAttribute(HttpSession session, String key, Object object, boolean serializable, int maxTime) {
if (object == null) {
// If object is null, remove attribute.
Object ret;
synchronized (session) {
ret = session.getAttribute(key);
session.removeAttribute(key);
}
return ret;
}
else {
// Set object in session.
Object ret;
synchronized (session) {
ret = session.getAttribute(key);
session.setAttribute(key, object);
}
SessionMapper mapper = (SessionMapper) session.getAttribute(MAPPER_ATTRIBUTE);
if (mapper == null) {
// Register mapper for session.
mapper = new SessionMapper();
session.setAttribute(MAPPER_ATTRIBUTE, mapper);
}
synchronized (mapper) {
// Update field mapper.
SessionFieldMapper fieldMapper = mapper.get(key);
if (fieldMapper == null) {
fieldMapper = new SessionFieldMapper(serializable && object instanceof Serializable);
mapper.put(key, fieldMapper);
}
if (maxTime > 0) {
// Register runnable to remove attribute.
if (fieldMapper.runnable != null) {
// Cancel old runnable because a new one will be created.
fieldMapper.runnable.cancel();
}
// Register runnable.
RemoveFieldRunnable runnable = new RemoveFieldRunnable(key, maxTime, session);
fieldMapper.runnable = runnable;
(new Thread(runnable)).start();
}
}
return ret;
}
} | java | protected Object setAttribute(HttpSession session, String key, Object object, boolean serializable, int maxTime) {
if (object == null) {
// If object is null, remove attribute.
Object ret;
synchronized (session) {
ret = session.getAttribute(key);
session.removeAttribute(key);
}
return ret;
}
else {
// Set object in session.
Object ret;
synchronized (session) {
ret = session.getAttribute(key);
session.setAttribute(key, object);
}
SessionMapper mapper = (SessionMapper) session.getAttribute(MAPPER_ATTRIBUTE);
if (mapper == null) {
// Register mapper for session.
mapper = new SessionMapper();
session.setAttribute(MAPPER_ATTRIBUTE, mapper);
}
synchronized (mapper) {
// Update field mapper.
SessionFieldMapper fieldMapper = mapper.get(key);
if (fieldMapper == null) {
fieldMapper = new SessionFieldMapper(serializable && object instanceof Serializable);
mapper.put(key, fieldMapper);
}
if (maxTime > 0) {
// Register runnable to remove attribute.
if (fieldMapper.runnable != null) {
// Cancel old runnable because a new one will be created.
fieldMapper.runnable.cancel();
}
// Register runnable.
RemoveFieldRunnable runnable = new RemoveFieldRunnable(key, maxTime, session);
fieldMapper.runnable = runnable;
(new Thread(runnable)).start();
}
}
return ret;
}
} | [
"protected",
"Object",
"setAttribute",
"(",
"HttpSession",
"session",
",",
"String",
"key",
",",
"Object",
"object",
",",
"boolean",
"serializable",
",",
"int",
"maxTime",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"// If object is null, remove attri... | Saves an object in session for latter use.
@param session Session in which to store object.
@param key Key under which object is saved.
@param object Object to save.
@param serializable True if object is serializable.
@param maxTime Maximum time to keep object in session.
@return Object previously saved under key. | [
"Saves",
"an",
"object",
"in",
"session",
"for",
"latter",
"use",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/session/SessionStoreInterceptor.java#L192-L236 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/jstl/JstlBundleInterceptor.java | JstlBundleInterceptor.setMessageResourceBundle | @Override
protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle)
{
Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, request.getLocale()));
LOGGER.debug("Enabled JSTL localization using: ", bundle);
LOGGER.debug("Loaded resource bundle ", bundle, " as default bundle");
} | java | @Override
protected void setMessageResourceBundle(HttpServletRequest request, ResourceBundle bundle)
{
Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, request.getLocale()));
LOGGER.debug("Enabled JSTL localization using: ", bundle);
LOGGER.debug("Loaded resource bundle ", bundle, " as default bundle");
} | [
"@",
"Override",
"protected",
"void",
"setMessageResourceBundle",
"(",
"HttpServletRequest",
"request",
",",
"ResourceBundle",
"bundle",
")",
"{",
"Config",
".",
"set",
"(",
"request",
",",
"Config",
".",
"FMT_LOCALIZATION_CONTEXT",
",",
"new",
"LocalizationContext",
... | Sets the message resource bundle in the request using the JSTL's mechanism. | [
"Sets",
"the",
"message",
"resource",
"bundle",
"in",
"the",
"request",
"using",
"the",
"JSTL",
"s",
"mechanism",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/jstl/JstlBundleInterceptor.java#L104-L110 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/jstl/JstlBundleInterceptor.java | JstlBundleInterceptor.setOtherResourceBundles | @Override
protected void setOtherResourceBundles(HttpServletRequest request)
{
Locale locale = request.getLocale();
if (errorBundleName != null)
{
ResourceBundle errorBundle = getLocalizationBundleFactory().getErrorMessageBundle(locale);
Config.set(request, errorBundleName, new LocalizationContext(errorBundle, locale));
LOGGER.debug("Loaded Stripes error message bundle ", errorBundle, " as ", errorBundleName);
}
if (fieldBundleName != null)
{
ResourceBundle fieldBundle = getLocalizationBundleFactory().getFormFieldBundle(locale);
Config.set(request, fieldBundleName, new LocalizationContext(fieldBundle, locale));
LOGGER.debug("Loaded Stripes field name bundle ", fieldBundle, " as ", fieldBundleName);
}
} | java | @Override
protected void setOtherResourceBundles(HttpServletRequest request)
{
Locale locale = request.getLocale();
if (errorBundleName != null)
{
ResourceBundle errorBundle = getLocalizationBundleFactory().getErrorMessageBundle(locale);
Config.set(request, errorBundleName, new LocalizationContext(errorBundle, locale));
LOGGER.debug("Loaded Stripes error message bundle ", errorBundle, " as ", errorBundleName);
}
if (fieldBundleName != null)
{
ResourceBundle fieldBundle = getLocalizationBundleFactory().getFormFieldBundle(locale);
Config.set(request, fieldBundleName, new LocalizationContext(fieldBundle, locale));
LOGGER.debug("Loaded Stripes field name bundle ", fieldBundle, " as ", fieldBundleName);
}
} | [
"@",
"Override",
"protected",
"void",
"setOtherResourceBundles",
"(",
"HttpServletRequest",
"request",
")",
"{",
"Locale",
"locale",
"=",
"request",
".",
"getLocale",
"(",
")",
";",
"if",
"(",
"errorBundleName",
"!=",
"null",
")",
"{",
"ResourceBundle",
"errorBu... | Sets the Stripes error and field resource bundles in the request, if their names have been configured. | [
"Sets",
"the",
"Stripes",
"error",
"and",
"field",
"resource",
"bundles",
"in",
"the",
"request",
"if",
"their",
"names",
"have",
"been",
"configured",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/jstl/JstlBundleInterceptor.java#L115-L133 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/InstanceBasedSecurityManager.java | InstanceBasedSecurityManager.evaluateRoleExpression | private Object evaluateRoleExpression(ActionBean bean, String expression)
{
try
{
LOG.debug("Evaluating expression: '" + expression + '\'');
// This is somewhat of a hack until the ExpressionEvaluator becomes more accessible.
ParameterName name = new ParameterName("security");
List<Object> values = new ArrayList<Object>();
values.add(null);
ValidationMetadata metadata = new ValidationMetadata("security").expression(expression);
ValidationErrors errors = new ValidationErrors();
ExpressionValidator.evaluate(bean, name, values, metadata, errors);
return errors.isEmpty();
}
catch (Exception exc)
{
throw new StripesRuntimeException(exc);
}
} | java | private Object evaluateRoleExpression(ActionBean bean, String expression)
{
try
{
LOG.debug("Evaluating expression: '" + expression + '\'');
// This is somewhat of a hack until the ExpressionEvaluator becomes more accessible.
ParameterName name = new ParameterName("security");
List<Object> values = new ArrayList<Object>();
values.add(null);
ValidationMetadata metadata = new ValidationMetadata("security").expression(expression);
ValidationErrors errors = new ValidationErrors();
ExpressionValidator.evaluate(bean, name, values, metadata, errors);
return errors.isEmpty();
}
catch (Exception exc)
{
throw new StripesRuntimeException(exc);
}
} | [
"private",
"Object",
"evaluateRoleExpression",
"(",
"ActionBean",
"bean",
",",
"String",
"expression",
")",
"{",
"try",
"{",
"LOG",
".",
"debug",
"(",
"\"Evaluating expression: '\"",
"+",
"expression",
"+",
"'",
"'",
")",
";",
"// This is somewhat of a hack until th... | Evaluate the given EL expression using the current action bean to resolve variables.
@param bean the bean to evaluate the expression on
@param expression the EL expression to evaluate
@return the result of the EL expression | [
"Evaluate",
"the",
"given",
"EL",
"expression",
"using",
"the",
"current",
"action",
"bean",
"to",
"resolve",
"variables",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/InstanceBasedSecurityManager.java#L120-L141 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/MethodDesc.java | MethodDesc.forDescriptor | public static MethodDesc forDescriptor(String desc)
throws IllegalArgumentException
{
try {
int cursor = 0;
char c;
if ((c = desc.charAt(cursor++)) != '(') {
throw invalidDescriptor(desc);
}
StringBuffer buf = new StringBuffer();
List<TypeDesc> list = new ArrayList<TypeDesc>();
while ((c = desc.charAt(cursor++)) != ')') {
switch (c) {
case 'V':
case 'I':
case 'C':
case 'Z':
case 'D':
case 'F':
case 'J':
case 'B':
case 'S':
buf.append(c);
break;
case '[':
buf.append(c);
continue;
case 'L':
while (true) {
buf.append(c);
if (c == ';') {
break;
}
c = desc.charAt(cursor++);
}
break;
default:
throw invalidDescriptor(desc);
}
list.add(TypeDesc.forDescriptor(buf.toString()));
buf.setLength(0);
}
TypeDesc ret = TypeDesc.forDescriptor(desc.substring(cursor));
TypeDesc[] tds = list.toArray(new TypeDesc[list.size()]);
return intern(new MethodDesc(desc, ret, tds));
} catch (NullPointerException e) {
throw invalidDescriptor(desc);
} catch (IndexOutOfBoundsException e) {
throw invalidDescriptor(desc);
}
} | java | public static MethodDesc forDescriptor(String desc)
throws IllegalArgumentException
{
try {
int cursor = 0;
char c;
if ((c = desc.charAt(cursor++)) != '(') {
throw invalidDescriptor(desc);
}
StringBuffer buf = new StringBuffer();
List<TypeDesc> list = new ArrayList<TypeDesc>();
while ((c = desc.charAt(cursor++)) != ')') {
switch (c) {
case 'V':
case 'I':
case 'C':
case 'Z':
case 'D':
case 'F':
case 'J':
case 'B':
case 'S':
buf.append(c);
break;
case '[':
buf.append(c);
continue;
case 'L':
while (true) {
buf.append(c);
if (c == ';') {
break;
}
c = desc.charAt(cursor++);
}
break;
default:
throw invalidDescriptor(desc);
}
list.add(TypeDesc.forDescriptor(buf.toString()));
buf.setLength(0);
}
TypeDesc ret = TypeDesc.forDescriptor(desc.substring(cursor));
TypeDesc[] tds = list.toArray(new TypeDesc[list.size()]);
return intern(new MethodDesc(desc, ret, tds));
} catch (NullPointerException e) {
throw invalidDescriptor(desc);
} catch (IndexOutOfBoundsException e) {
throw invalidDescriptor(desc);
}
} | [
"public",
"static",
"MethodDesc",
"forDescriptor",
"(",
"String",
"desc",
")",
"throws",
"IllegalArgumentException",
"{",
"try",
"{",
"int",
"cursor",
"=",
"0",
";",
"char",
"c",
";",
"if",
"(",
"(",
"c",
"=",
"desc",
".",
"charAt",
"(",
"cursor",
"++",
... | Acquire a MethodDesc from a type descriptor. | [
"Acquire",
"a",
"MethodDesc",
"from",
"a",
"type",
"descriptor",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/MethodDesc.java#L65-L122 | train |
cojen/Cojen | src/main/java/org/cojen/util/BelatedCreator.java | BelatedCreator.get | public synchronized T get(final int timeoutMillis) throws E {
if (mReal != null) {
return mReal;
}
if (mBogus != null && mMinRetryDelayMillis < 0) {
return mBogus;
}
if (mCreateThread == null) {
mCreateThread = new CreateThread();
cThreadPool.submit(mCreateThread);
}
if (timeoutMillis != 0) {
final long start = System.nanoTime();
try {
if (timeoutMillis < 0) {
while (mReal == null && mCreateThread != null) {
if (timeoutMillis < 0) {
wait();
}
}
} else {
long remaining = timeoutMillis;
while (mReal == null && mCreateThread != null && !mFailed) {
wait(remaining);
long elapsed = (System.nanoTime() - start) / 1000000L;
if ((remaining -= elapsed) <= 0) {
break;
}
}
}
} catch (InterruptedException e) {
}
if (mReal != null) {
return mReal;
}
long elapsed = (System.nanoTime() - start) / 1000000L;
if (elapsed >= timeoutMillis) {
timedOutNotification(elapsed);
}
}
if (mFailedError != null) {
// Take ownership of error. Also stitch traces together for
// context. This gives the illusion that the creation attempt
// occurred in this thread.
Throwable error = mFailedError;
mFailedError = null;
StackTraceElement[] trace = error.getStackTrace();
error.fillInStackTrace();
StackTraceElement[] localTrace = error.getStackTrace();
StackTraceElement[] completeTrace =
new StackTraceElement[trace.length + localTrace.length];
System.arraycopy(trace, 0, completeTrace, 0, trace.length);
System.arraycopy(localTrace, 0, completeTrace, trace.length, localTrace.length);
error.setStackTrace(completeTrace);
ThrowUnchecked.fire(error);
}
if (mBogus == null) {
mRef = new AtomicReference<T>(createBogus());
mBogus = AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
try {
return getWrapper().newInstance(mRef);
} catch (Exception e) {
ThrowUnchecked.fire(e);
return null;
}
}
});
}
return mBogus;
} | java | public synchronized T get(final int timeoutMillis) throws E {
if (mReal != null) {
return mReal;
}
if (mBogus != null && mMinRetryDelayMillis < 0) {
return mBogus;
}
if (mCreateThread == null) {
mCreateThread = new CreateThread();
cThreadPool.submit(mCreateThread);
}
if (timeoutMillis != 0) {
final long start = System.nanoTime();
try {
if (timeoutMillis < 0) {
while (mReal == null && mCreateThread != null) {
if (timeoutMillis < 0) {
wait();
}
}
} else {
long remaining = timeoutMillis;
while (mReal == null && mCreateThread != null && !mFailed) {
wait(remaining);
long elapsed = (System.nanoTime() - start) / 1000000L;
if ((remaining -= elapsed) <= 0) {
break;
}
}
}
} catch (InterruptedException e) {
}
if (mReal != null) {
return mReal;
}
long elapsed = (System.nanoTime() - start) / 1000000L;
if (elapsed >= timeoutMillis) {
timedOutNotification(elapsed);
}
}
if (mFailedError != null) {
// Take ownership of error. Also stitch traces together for
// context. This gives the illusion that the creation attempt
// occurred in this thread.
Throwable error = mFailedError;
mFailedError = null;
StackTraceElement[] trace = error.getStackTrace();
error.fillInStackTrace();
StackTraceElement[] localTrace = error.getStackTrace();
StackTraceElement[] completeTrace =
new StackTraceElement[trace.length + localTrace.length];
System.arraycopy(trace, 0, completeTrace, 0, trace.length);
System.arraycopy(localTrace, 0, completeTrace, trace.length, localTrace.length);
error.setStackTrace(completeTrace);
ThrowUnchecked.fire(error);
}
if (mBogus == null) {
mRef = new AtomicReference<T>(createBogus());
mBogus = AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
try {
return getWrapper().newInstance(mRef);
} catch (Exception e) {
ThrowUnchecked.fire(e);
return null;
}
}
});
}
return mBogus;
} | [
"public",
"synchronized",
"T",
"get",
"(",
"final",
"int",
"timeoutMillis",
")",
"throws",
"E",
"{",
"if",
"(",
"mReal",
"!=",
"null",
")",
"{",
"return",
"mReal",
";",
"}",
"if",
"(",
"mBogus",
"!=",
"null",
"&&",
"mMinRetryDelayMillis",
"<",
"0",
")"... | Returns real or bogus object. If real object is returned, then future
invocations of this method return the same real object instance. This
method waits for the real object to be created, if it is blocked. If
real object creation fails immediately, then this method will not wait,
returning a bogus object immediately instead.
@param timeoutMillis maximum time to wait for real object before
returning bogus one; if negative, potentially wait forever
@throws E exception thrown from createReal | [
"Returns",
"real",
"or",
"bogus",
"object",
".",
"If",
"real",
"object",
"is",
"returned",
"then",
"future",
"invocations",
"of",
"this",
"method",
"return",
"the",
"same",
"real",
"object",
"instance",
".",
"This",
"method",
"waits",
"for",
"the",
"real",
... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BelatedCreator.java#L123-L207 | train |
cojen/Cojen | src/main/java/org/cojen/util/BelatedCreator.java | BelatedCreator.getWrapper | private Constructor<T> getWrapper() {
Class<T> clazz;
synchronized (cWrapperCache) {
clazz = (Class<T>) cWrapperCache.get(mType);
if (clazz == null) {
clazz = createWrapper();
cWrapperCache.put(mType, clazz);
}
}
try {
return clazz.getConstructor(AtomicReference.class);
} catch (NoSuchMethodException e) {
ThrowUnchecked.fire(e);
return null;
}
} | java | private Constructor<T> getWrapper() {
Class<T> clazz;
synchronized (cWrapperCache) {
clazz = (Class<T>) cWrapperCache.get(mType);
if (clazz == null) {
clazz = createWrapper();
cWrapperCache.put(mType, clazz);
}
}
try {
return clazz.getConstructor(AtomicReference.class);
} catch (NoSuchMethodException e) {
ThrowUnchecked.fire(e);
return null;
}
} | [
"private",
"Constructor",
"<",
"T",
">",
"getWrapper",
"(",
")",
"{",
"Class",
"<",
"T",
">",
"clazz",
";",
"synchronized",
"(",
"cWrapperCache",
")",
"{",
"clazz",
"=",
"(",
"Class",
"<",
"T",
">",
")",
"cWrapperCache",
".",
"get",
"(",
"mType",
")"... | Returns a Constructor that accepts an AtomicReference to the wrapped
object. | [
"Returns",
"a",
"Constructor",
"that",
"accepts",
"an",
"AtomicReference",
"to",
"the",
"wrapped",
"object",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BelatedCreator.java#L281-L297 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/CodeBuilder.java | CodeBuilder.loadLocal | public void loadLocal(LocalVariable local) {
if (local == null) {
throw new IllegalArgumentException("No local variable specified");
}
int stackAdjust = local.getType().isDoubleWord() ? 2 : 1;
mInstructions.new LoadLocalInstruction(stackAdjust, local);
} | java | public void loadLocal(LocalVariable local) {
if (local == null) {
throw new IllegalArgumentException("No local variable specified");
}
int stackAdjust = local.getType().isDoubleWord() ? 2 : 1;
mInstructions.new LoadLocalInstruction(stackAdjust, local);
} | [
"public",
"void",
"loadLocal",
"(",
"LocalVariable",
"local",
")",
"{",
"if",
"(",
"local",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"No local variable specified\"",
")",
";",
"}",
"int",
"stackAdjust",
"=",
"local",
".",
"get... | load-local-to-stack style instructions | [
"load",
"-",
"local",
"-",
"to",
"-",
"stack",
"style",
"instructions"
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/CodeBuilder.java#L465-L471 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/CodeBuilder.java | CodeBuilder.nullConvert | private void nullConvert(Label end) {
LocalVariable temp = createLocalVariable("temp", TypeDesc.OBJECT);
storeLocal(temp);
loadLocal(temp);
Label notNull = createLabel();
ifNullBranch(notNull, false);
loadNull();
branch(end);
notNull.setLocation();
loadLocal(temp);
} | java | private void nullConvert(Label end) {
LocalVariable temp = createLocalVariable("temp", TypeDesc.OBJECT);
storeLocal(temp);
loadLocal(temp);
Label notNull = createLabel();
ifNullBranch(notNull, false);
loadNull();
branch(end);
notNull.setLocation();
loadLocal(temp);
} | [
"private",
"void",
"nullConvert",
"(",
"Label",
"end",
")",
"{",
"LocalVariable",
"temp",
"=",
"createLocalVariable",
"(",
"\"temp\"",
",",
"TypeDesc",
".",
"OBJECT",
")",
";",
"storeLocal",
"(",
"temp",
")",
";",
"loadLocal",
"(",
"temp",
")",
";",
"Label... | a NullPointerException. Assumes that from type and to type are objects. | [
"a",
"NullPointerException",
".",
"Assumes",
"that",
"from",
"type",
"and",
"to",
"type",
"are",
"objects",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/CodeBuilder.java#L1164-L1174 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/CodeBuilder.java | CodeBuilder.invokeVirtual | public void invokeVirtual(String methodName,
TypeDesc ret,
TypeDesc[] params) {
invokeVirtual(mClassFile.getClassName(), methodName, ret, params);
} | java | public void invokeVirtual(String methodName,
TypeDesc ret,
TypeDesc[] params) {
invokeVirtual(mClassFile.getClassName(), methodName, ret, params);
} | [
"public",
"void",
"invokeVirtual",
"(",
"String",
"methodName",
",",
"TypeDesc",
"ret",
",",
"TypeDesc",
"[",
"]",
"params",
")",
"{",
"invokeVirtual",
"(",
"mClassFile",
".",
"getClassName",
"(",
")",
",",
"methodName",
",",
"ret",
",",
"params",
")",
";"... | invocation style instructions | [
"invocation",
"style",
"instructions"
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/CodeBuilder.java#L1186-L1190 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.getContext | private Context getContext(ExecutionContext executionContext) {
// Get context id.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
String parameter = request.getParameter(ID_PARAMETER);
// Return context.
if (parameter != null) {
int id = Integer.parseInt(parameter, 16);
return contexts.get(id);
}
return null;
} | java | private Context getContext(ExecutionContext executionContext) {
// Get context id.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
String parameter = request.getParameter(ID_PARAMETER);
// Return context.
if (parameter != null) {
int id = Integer.parseInt(parameter, 16);
return contexts.get(id);
}
return null;
} | [
"private",
"Context",
"getContext",
"(",
"ExecutionContext",
"executionContext",
")",
"{",
"// Get context id.",
"HttpServletRequest",
"request",
"=",
"executionContext",
".",
"getActionBeanContext",
"(",
")",
".",
"getRequest",
"(",
")",
";",
"String",
"parameter",
"... | Returns wait context based on context id found in request.
@param executionContext execution context
@return wait context | [
"Returns",
"wait",
"context",
"based",
"on",
"context",
"id",
"found",
"in",
"request",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L183-L195 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.createContextAndRedirect | private Resolution createContextAndRedirect(ExecutionContext executionContext, WaitPage annotation) throws IOException {
// Create context used to call the event in background.
Context context = this.createContext(executionContext);
context.actionBean = executionContext.getActionBean();
context.eventHandler = executionContext.getHandler();
context.annotation = annotation;
context.resolution = new ForwardResolution(annotation.path());
context.bindingFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
int id = context.hashCode();
// Id of context.
String ids = Integer.toHexString(id);
// Create background request to execute event.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
UrlBuilder urlBuilder = new UrlBuilder(executionContext.getActionBeanContext().getLocale(), THREAD_URL, false);
// Add parameters from the original request in case there were some parameters that weren't bound but are used
@SuppressWarnings({ "cast", "unchecked" })
Set<Map.Entry<String,String[]>> paramSet = (Set<Map.Entry<String,String[]>>) request.getParameterMap().entrySet();
for (Map.Entry<String,String[]> param : paramSet)
for (String value : param.getValue())
urlBuilder.addParameter(param.getKey(), value);
urlBuilder.addParameter(ID_PARAMETER, ids);
if (context.bindingFlashScope != null) {
urlBuilder.addParameter(StripesConstants.URL_KEY_FLASH_SCOPE_ID, String.valueOf(context.bindingFlashScope.key()));
}
urlBuilder.addParameter(StripesConstants.URL_KEY_SOURCE_PAGE, CryptoUtil.encrypt(executionContext.getActionBeanContext().getSourcePage()));
context.url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + urlBuilder.toString());
context.cookies = request.getHeader("Cookie");
// Save context.
contexts.put(id, context);
// Execute background request.
context.thread = new Thread(context);
context.thread.start();
// Redirect user to wait page.
return new RedirectResolution(StripesFilter.getConfiguration().getActionResolver().getUrlBinding(context.actionBean.getClass())) {
@Override
public RedirectResolution addParameter(String key, Object... value) {
// Leave flash scope to background request.
if (!StripesConstants.URL_KEY_FLASH_SCOPE_ID.equals(key)) {
return super.addParameter(key, value);
}
return this;
}
}.addParameter(ID_PARAMETER, ids);
} | java | private Resolution createContextAndRedirect(ExecutionContext executionContext, WaitPage annotation) throws IOException {
// Create context used to call the event in background.
Context context = this.createContext(executionContext);
context.actionBean = executionContext.getActionBean();
context.eventHandler = executionContext.getHandler();
context.annotation = annotation;
context.resolution = new ForwardResolution(annotation.path());
context.bindingFlashScope = FlashScope.getCurrent(context.actionBean.getContext().getRequest(), false);
int id = context.hashCode();
// Id of context.
String ids = Integer.toHexString(id);
// Create background request to execute event.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
UrlBuilder urlBuilder = new UrlBuilder(executionContext.getActionBeanContext().getLocale(), THREAD_URL, false);
// Add parameters from the original request in case there were some parameters that weren't bound but are used
@SuppressWarnings({ "cast", "unchecked" })
Set<Map.Entry<String,String[]>> paramSet = (Set<Map.Entry<String,String[]>>) request.getParameterMap().entrySet();
for (Map.Entry<String,String[]> param : paramSet)
for (String value : param.getValue())
urlBuilder.addParameter(param.getKey(), value);
urlBuilder.addParameter(ID_PARAMETER, ids);
if (context.bindingFlashScope != null) {
urlBuilder.addParameter(StripesConstants.URL_KEY_FLASH_SCOPE_ID, String.valueOf(context.bindingFlashScope.key()));
}
urlBuilder.addParameter(StripesConstants.URL_KEY_SOURCE_PAGE, CryptoUtil.encrypt(executionContext.getActionBeanContext().getSourcePage()));
context.url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + urlBuilder.toString());
context.cookies = request.getHeader("Cookie");
// Save context.
contexts.put(id, context);
// Execute background request.
context.thread = new Thread(context);
context.thread.start();
// Redirect user to wait page.
return new RedirectResolution(StripesFilter.getConfiguration().getActionResolver().getUrlBinding(context.actionBean.getClass())) {
@Override
public RedirectResolution addParameter(String key, Object... value) {
// Leave flash scope to background request.
if (!StripesConstants.URL_KEY_FLASH_SCOPE_ID.equals(key)) {
return super.addParameter(key, value);
}
return this;
}
}.addParameter(ID_PARAMETER, ids);
} | [
"private",
"Resolution",
"createContextAndRedirect",
"(",
"ExecutionContext",
"executionContext",
",",
"WaitPage",
"annotation",
")",
"throws",
"IOException",
"{",
"// Create context used to call the event in background.",
"Context",
"context",
"=",
"this",
".",
"createContext"... | Create a wait context to execute event in background.
@param executionContext execution context
@param annotation wait page annotation
@return redirect redirect user so that wait page appears
@throws IOException could not create background request | [
"Create",
"a",
"wait",
"context",
"to",
"execute",
"event",
"in",
"background",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L204-L254 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.checkStatus | private Resolution checkStatus(ExecutionContext executionContext, Context context) throws Exception {
// Resolution execution must not be executed while we are checking status.
synchronized (context.actionBean) {
if (context.status == Context.Status.INIT) {
// If a delay was specified we'll just wait here. If event completes while we're waiting the wait page won't be displayed.
if (context.annotation.delay() > 0) context.actionBean.wait(context.annotation.delay());
if (context.status == Context.Status.INIT) {
// We've waited long enough, go to wait page.
context.status = Context.Status.WAITING;
}
}
else if (context.status == Context.Status.WAITING) {
// Wait some time to allow event to complete before refreshing wait page.
log.trace("waiting to be signaled");
context.actionBean.wait(context.annotation.refresh() > 0 ? context.annotation.refresh() : DEFAULT_REFRESH_TIMEOUT);
}
// Default is to go to wait page. This will be changed if an AJAX updater is used.
// If event completed, this will be the resolution returned by event.
Resolution resolution = context.resolution;
// Action to use is the action bean on which event is invoked.
executionContext.setActionBean(context.actionBean);
// Save action bean in request scope to make it available in JSP.
executionContext.getActionBeanContext().getRequest().setAttribute("actionBean", context.actionBean);
// Set action bean in request so form will be populated.
executionContext.getActionBeanContext().getRequest().setAttribute(StripesFilter.getConfiguration().getActionResolver().getUrlBinding(context.actionBean.getClass()), context.actionBean);
// Copy flash scope/messages from action bean's context to execution context.
if (context.bindingFlashScope != null) {
this.copyFlashScope(context.bindingFlashScope, FlashScope.getCurrent(executionContext.getActionBeanContext().getRequest(), true));
}
if (context.eventFlashScope != null) {
this.copyFlashScope(context.eventFlashScope, FlashScope.getCurrent(executionContext.getActionBeanContext().getRequest(), true));
}
if (executionContext.getActionBeanContext().getRequest().getParameter(AJAX) != null)
{
// We are using an AJAX updater. We need to go to AJAX page to allow javascript to validate if event completed.
resolution = new ForwardResolution(context.annotation.ajax().length() > 0 ? context.annotation.ajax() : context.annotation.path());
}
else if (context.status == Context.Status.COMPLETE)
{
log.trace("the processor is finished so we'll remove it from the map");
// Remove context since event completed and we will show resolution returned by event.
contexts.remove(context.hashCode());
// Copy errors from action bean's context to execution context.
this.copyErrors(context.actionBean.getContext(), executionContext.getActionBeanContext());
// Replace request in action bean so that session will be valid.
context.actionBean.setContext(executionContext.getActionBeanContext());
if (context.throwable != null) {
// Event did not complete normally, it thrown an exception.
if (("".equals(context.annotation.error())) && (context.throwable instanceof Exception)) {
// No error page, throw exception.
throw (Exception) context.throwable;
}
else {
// An error page is specified, save error and go to error page.
executionContext.getActionBeanContext().getRequest().setAttribute("exception", context.throwable);
resolution = new ForwardResolution(context.annotation.error());
}
}
// Stripes or user code may use executionContext.getResolution() to obtain resolution instead of returned resolution. So set resolution in executionContext too.
executionContext.setResolution(resolution);
}
// Since context in current execution context is artificial, we should not update context in action bean as it would make action bean in other thread inconsistent.
//context.actionBean.setContext(executionContext.getActionBeanContext());
// Go to wait page or execute resolution from event, if it completed.
return resolution;
}
} | java | private Resolution checkStatus(ExecutionContext executionContext, Context context) throws Exception {
// Resolution execution must not be executed while we are checking status.
synchronized (context.actionBean) {
if (context.status == Context.Status.INIT) {
// If a delay was specified we'll just wait here. If event completes while we're waiting the wait page won't be displayed.
if (context.annotation.delay() > 0) context.actionBean.wait(context.annotation.delay());
if (context.status == Context.Status.INIT) {
// We've waited long enough, go to wait page.
context.status = Context.Status.WAITING;
}
}
else if (context.status == Context.Status.WAITING) {
// Wait some time to allow event to complete before refreshing wait page.
log.trace("waiting to be signaled");
context.actionBean.wait(context.annotation.refresh() > 0 ? context.annotation.refresh() : DEFAULT_REFRESH_TIMEOUT);
}
// Default is to go to wait page. This will be changed if an AJAX updater is used.
// If event completed, this will be the resolution returned by event.
Resolution resolution = context.resolution;
// Action to use is the action bean on which event is invoked.
executionContext.setActionBean(context.actionBean);
// Save action bean in request scope to make it available in JSP.
executionContext.getActionBeanContext().getRequest().setAttribute("actionBean", context.actionBean);
// Set action bean in request so form will be populated.
executionContext.getActionBeanContext().getRequest().setAttribute(StripesFilter.getConfiguration().getActionResolver().getUrlBinding(context.actionBean.getClass()), context.actionBean);
// Copy flash scope/messages from action bean's context to execution context.
if (context.bindingFlashScope != null) {
this.copyFlashScope(context.bindingFlashScope, FlashScope.getCurrent(executionContext.getActionBeanContext().getRequest(), true));
}
if (context.eventFlashScope != null) {
this.copyFlashScope(context.eventFlashScope, FlashScope.getCurrent(executionContext.getActionBeanContext().getRequest(), true));
}
if (executionContext.getActionBeanContext().getRequest().getParameter(AJAX) != null)
{
// We are using an AJAX updater. We need to go to AJAX page to allow javascript to validate if event completed.
resolution = new ForwardResolution(context.annotation.ajax().length() > 0 ? context.annotation.ajax() : context.annotation.path());
}
else if (context.status == Context.Status.COMPLETE)
{
log.trace("the processor is finished so we'll remove it from the map");
// Remove context since event completed and we will show resolution returned by event.
contexts.remove(context.hashCode());
// Copy errors from action bean's context to execution context.
this.copyErrors(context.actionBean.getContext(), executionContext.getActionBeanContext());
// Replace request in action bean so that session will be valid.
context.actionBean.setContext(executionContext.getActionBeanContext());
if (context.throwable != null) {
// Event did not complete normally, it thrown an exception.
if (("".equals(context.annotation.error())) && (context.throwable instanceof Exception)) {
// No error page, throw exception.
throw (Exception) context.throwable;
}
else {
// An error page is specified, save error and go to error page.
executionContext.getActionBeanContext().getRequest().setAttribute("exception", context.throwable);
resolution = new ForwardResolution(context.annotation.error());
}
}
// Stripes or user code may use executionContext.getResolution() to obtain resolution instead of returned resolution. So set resolution in executionContext too.
executionContext.setResolution(resolution);
}
// Since context in current execution context is artificial, we should not update context in action bean as it would make action bean in other thread inconsistent.
//context.actionBean.setContext(executionContext.getActionBeanContext());
// Go to wait page or execute resolution from event, if it completed.
return resolution;
}
} | [
"private",
"Resolution",
"checkStatus",
"(",
"ExecutionContext",
"executionContext",
",",
"Context",
"context",
")",
"throws",
"Exception",
"{",
"// Resolution execution must not be executed while we are checking status.",
"synchronized",
"(",
"context",
".",
"actionBean",
")",... | Return wait page resolution or event's resolution depending on completion status.
@param executionContext execution context
@param context wait context
@return wait page resolution or event's resolution depending on completion status
@throws Exception exception thrown by event if no error page is specified | [
"Return",
"wait",
"page",
"resolution",
"or",
"event",
"s",
"resolution",
"depending",
"on",
"completion",
"status",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L271-L343 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.copyErrors | protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) {
destination.getValidationErrors().putAll(source.getValidationErrors());
} | java | protected void copyErrors(ActionBeanContext source, ActionBeanContext destination) {
destination.getValidationErrors().putAll(source.getValidationErrors());
} | [
"protected",
"void",
"copyErrors",
"(",
"ActionBeanContext",
"source",
",",
"ActionBeanContext",
"destination",
")",
"{",
"destination",
".",
"getValidationErrors",
"(",
")",
".",
"putAll",
"(",
"source",
".",
"getValidationErrors",
"(",
")",
")",
";",
"}"
] | Copy errors from a context to another context.
@param source source containing errors to copy
@param destination where errors will be copied | [
"Copy",
"errors",
"from",
"a",
"context",
"to",
"another",
"context",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L350-L352 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.removeExpired | protected void removeExpired(Map<Integer, Context> contexts) {
Iterator<Context> contextsIter = contexts.values().iterator();
while (contextsIter.hasNext()) {
Context context = contextsIter.next();
if (context.completeMoment != null
&& System.currentTimeMillis() - context.completeMoment > contextTimeout) {
contextsIter.remove();
}
}
} | java | protected void removeExpired(Map<Integer, Context> contexts) {
Iterator<Context> contextsIter = contexts.values().iterator();
while (contextsIter.hasNext()) {
Context context = contextsIter.next();
if (context.completeMoment != null
&& System.currentTimeMillis() - context.completeMoment > contextTimeout) {
contextsIter.remove();
}
}
} | [
"protected",
"void",
"removeExpired",
"(",
"Map",
"<",
"Integer",
",",
"Context",
">",
"contexts",
")",
"{",
"Iterator",
"<",
"Context",
">",
"contextsIter",
"=",
"contexts",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"context... | Remove all contexts that are expired.
@param contexts all contexts currently in memory | [
"Remove",
"all",
"contexts",
"that",
"are",
"expired",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L367-L376 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java | WaitPageInterceptor.init | public void init(Configuration configuration) throws Exception {
if (configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME) != null) {
log.debug("Configuring context timeout with value ", configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME));
try {
contextTimeout = Long.parseLong(configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME));
} catch (NumberFormatException e) {
log.warn("Init parameter ", CONTEXT_TIMEOUT_NAME, " is not a parsable long, timeout will be ", " instead");
contextTimeout = DEFAULT_CONTEXT_TIMEOUT;
}
}
} | java | public void init(Configuration configuration) throws Exception {
if (configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME) != null) {
log.debug("Configuring context timeout with value ", configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME));
try {
contextTimeout = Long.parseLong(configuration.getBootstrapPropertyResolver().getProperty(CONTEXT_TIMEOUT_NAME));
} catch (NumberFormatException e) {
log.warn("Init parameter ", CONTEXT_TIMEOUT_NAME, " is not a parsable long, timeout will be ", " instead");
contextTimeout = DEFAULT_CONTEXT_TIMEOUT;
}
}
} | [
"public",
"void",
"init",
"(",
"Configuration",
"configuration",
")",
"throws",
"Exception",
"{",
"if",
"(",
"configuration",
".",
"getBootstrapPropertyResolver",
"(",
")",
".",
"getProperty",
"(",
"CONTEXT_TIMEOUT_NAME",
")",
"!=",
"null",
")",
"{",
"log",
".",... | Read context timeout, if any. | [
"Read",
"context",
"timeout",
"if",
"any",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/WaitPageInterceptor.java#L381-L391 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/ClassFile.java | ClassFile.getInnerClasses | public ClassFile[] getInnerClasses() {
if (mInnerClasses == null) {
return new ClassFile[0];
}
return mInnerClasses.toArray(new ClassFile[mInnerClasses.size()]);
} | java | public ClassFile[] getInnerClasses() {
if (mInnerClasses == null) {
return new ClassFile[0];
}
return mInnerClasses.toArray(new ClassFile[mInnerClasses.size()]);
} | [
"public",
"ClassFile",
"[",
"]",
"getInnerClasses",
"(",
")",
"{",
"if",
"(",
"mInnerClasses",
"==",
"null",
")",
"{",
"return",
"new",
"ClassFile",
"[",
"0",
"]",
";",
"}",
"return",
"mInnerClasses",
".",
"toArray",
"(",
"new",
"ClassFile",
"[",
"mInner... | Returns all the inner classes defined in this class. If no inner classes
are defined, then an array of length zero is returned. | [
"Returns",
"all",
"the",
"inner",
"classes",
"defined",
"in",
"this",
"class",
".",
"If",
"no",
"inner",
"classes",
"are",
"defined",
"then",
"an",
"array",
"of",
"length",
"zero",
"is",
"returned",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ClassFile.java#L532-L538 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/ClassFile.java | ClassFile.addMethod | public MethodInfo addMethod(String declaration) {
MethodDeclarationParser p = new MethodDeclarationParser(declaration);
return addMethod(p.getModifiers(), p.getMethodName(),
p.getReturnType(), p.getParameters());
} | java | public MethodInfo addMethod(String declaration) {
MethodDeclarationParser p = new MethodDeclarationParser(declaration);
return addMethod(p.getModifiers(), p.getMethodName(),
p.getReturnType(), p.getParameters());
} | [
"public",
"MethodInfo",
"addMethod",
"(",
"String",
"declaration",
")",
"{",
"MethodDeclarationParser",
"p",
"=",
"new",
"MethodDeclarationParser",
"(",
"declaration",
")",
";",
"return",
"addMethod",
"(",
"p",
".",
"getModifiers",
"(",
")",
",",
"p",
".",
"ge... | Add a method to this class by declaration.
@throws IllegalArgumentException if declaration syntax is wrong
@see MethodDeclarationParser | [
"Add",
"a",
"method",
"to",
"this",
"class",
"by",
"declaration",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ClassFile.java#L788-L792 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/ClassFile.java | ClassFile.setTarget | public void setTarget(String target) throws IllegalArgumentException {
int major, minor;
if (target == null || "1.0".equals(target) || "1.1".equals(target)) {
major = 45; minor = 3;
if (target == null) {
target = "1.0";
}
} else if ("1.2".equals(target)) {
major = 46; minor = 0;
} else if ("1.3".equals(target)) {
major = 47; minor = 0;
} else if ("1.4".equals(target)) {
major = 48; minor = 0;
} else if ("1.5".equals(target)) {
major = 49; minor = 0;
} else if ("1.6".equals(target)) {
major = 50; minor = 0;
} else if ("1.7".equals(target)) {
major = 51; minor = 0;
} else {
throw new IllegalArgumentException
("Unsupported target version: " + target);
}
mVersion = (minor << 16) | (major & 0xffff);
mTarget = target.intern();
} | java | public void setTarget(String target) throws IllegalArgumentException {
int major, minor;
if (target == null || "1.0".equals(target) || "1.1".equals(target)) {
major = 45; minor = 3;
if (target == null) {
target = "1.0";
}
} else if ("1.2".equals(target)) {
major = 46; minor = 0;
} else if ("1.3".equals(target)) {
major = 47; minor = 0;
} else if ("1.4".equals(target)) {
major = 48; minor = 0;
} else if ("1.5".equals(target)) {
major = 49; minor = 0;
} else if ("1.6".equals(target)) {
major = 50; minor = 0;
} else if ("1.7".equals(target)) {
major = 51; minor = 0;
} else {
throw new IllegalArgumentException
("Unsupported target version: " + target);
}
mVersion = (minor << 16) | (major & 0xffff);
mTarget = target.intern();
} | [
"public",
"void",
"setTarget",
"(",
"String",
"target",
")",
"throws",
"IllegalArgumentException",
"{",
"int",
"major",
",",
"minor",
";",
"if",
"(",
"target",
"==",
"null",
"||",
"\"1.0\"",
".",
"equals",
"(",
"target",
")",
"||",
"\"1.1\"",
".",
"equals"... | Specify what target virtual machine version classfile should generate
for. Calling this method changes the major and minor version of the
classfile format.
@param target VM version, 1.0, 1.1, etc.
@throws IllegalArgumentException if target is not supported | [
"Specify",
"what",
"target",
"virtual",
"machine",
"version",
"classfile",
"should",
"generate",
"for",
".",
"Calling",
"this",
"method",
"changes",
"the",
"major",
"and",
"minor",
"version",
"of",
"the",
"classfile",
"format",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ClassFile.java#L957-L984 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/ClassFile.java | ClassFile.setVersion | public void setVersion(int major, int minor) {
if (major > 65535 || minor > 65535) {
throw new IllegalArgumentException("Version number element cannot exceed 65535");
}
mVersion = (minor << 16) | (major & 0xffff);
String target;
switch (major) {
default:
target = null;
break;
case 45:
target = minor == 3 ? "1.0" : null;
break;
case 46:
target = minor == 0 ? "1.2" : null;
break;
case 47:
target = minor == 0 ? "1.3" : null;
break;
case 48:
target = minor == 0 ? "1.4" : null;
break;
case 49:
target = minor == 0 ? "1.5" : null;
break;
case 50:
target = minor == 0 ? "1.6" : null;
break;
case 51:
target = minor == 0 ? "1.7" : null;
break;
}
mTarget = target;
} | java | public void setVersion(int major, int minor) {
if (major > 65535 || minor > 65535) {
throw new IllegalArgumentException("Version number element cannot exceed 65535");
}
mVersion = (minor << 16) | (major & 0xffff);
String target;
switch (major) {
default:
target = null;
break;
case 45:
target = minor == 3 ? "1.0" : null;
break;
case 46:
target = minor == 0 ? "1.2" : null;
break;
case 47:
target = minor == 0 ? "1.3" : null;
break;
case 48:
target = minor == 0 ? "1.4" : null;
break;
case 49:
target = minor == 0 ? "1.5" : null;
break;
case 50:
target = minor == 0 ? "1.6" : null;
break;
case 51:
target = minor == 0 ? "1.7" : null;
break;
}
mTarget = target;
} | [
"public",
"void",
"setVersion",
"(",
"int",
"major",
",",
"int",
"minor",
")",
"{",
"if",
"(",
"major",
">",
"65535",
"||",
"minor",
">",
"65535",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Version number element cannot exceed 65535\"",
")",
... | Sets the version to use when writing the generated classfile, overriding
the target. | [
"Sets",
"the",
"version",
"to",
"use",
"when",
"writing",
"the",
"generated",
"classfile",
"overriding",
"the",
"target",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ClassFile.java#L997-L1033 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/DisassemblyTool.java | DisassemblyTool.main | public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("DisassemblyTool [-f <format style>] <file or class name>");
System.out.println();
System.out.println("The format style may be \"assembly\" (the default) or \"builder\"");
return;
}
String style;
String name;
if ("-f".equals(args[0])) {
style = args[1];
name = args[2];
} else {
style = "assembly";
name = args[0];
}
ClassFileDataLoader loader;
InputStream in;
try {
final File file = new File(name);
in = new FileInputStream(file);
loader = new ClassFileDataLoader() {
public InputStream getClassData(String name)
throws IOException
{
name = name.substring(name.lastIndexOf('.') + 1);
File f = new File(file.getParentFile(), name + ".class");
if (f.exists()) {
return new FileInputStream(f);
}
return null;
}
};
} catch (FileNotFoundException e) {
if (name.endsWith(".class")) {
System.err.println(e);
return;
}
loader = new ResourceClassFileDataLoader();
in = loader.getClassData(name);
if (in == null) {
System.err.println(e);
return;
}
}
in = new BufferedInputStream(in);
ClassFile cf = ClassFile.readFrom(in, loader, null);
PrintWriter out = new PrintWriter(System.out);
Printer p;
if (style == null || style.equals("assembly")) {
p = new AssemblyStylePrinter();
} else if (style.equals("builder")) {
p = new BuilderStylePrinter();
} else {
System.err.println("Unknown format style: " + style);
return;
}
p.disassemble(cf, out);
out.flush();
} | java | public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("DisassemblyTool [-f <format style>] <file or class name>");
System.out.println();
System.out.println("The format style may be \"assembly\" (the default) or \"builder\"");
return;
}
String style;
String name;
if ("-f".equals(args[0])) {
style = args[1];
name = args[2];
} else {
style = "assembly";
name = args[0];
}
ClassFileDataLoader loader;
InputStream in;
try {
final File file = new File(name);
in = new FileInputStream(file);
loader = new ClassFileDataLoader() {
public InputStream getClassData(String name)
throws IOException
{
name = name.substring(name.lastIndexOf('.') + 1);
File f = new File(file.getParentFile(), name + ".class");
if (f.exists()) {
return new FileInputStream(f);
}
return null;
}
};
} catch (FileNotFoundException e) {
if (name.endsWith(".class")) {
System.err.println(e);
return;
}
loader = new ResourceClassFileDataLoader();
in = loader.getClassData(name);
if (in == null) {
System.err.println(e);
return;
}
}
in = new BufferedInputStream(in);
ClassFile cf = ClassFile.readFrom(in, loader, null);
PrintWriter out = new PrintWriter(System.out);
Printer p;
if (style == null || style.equals("assembly")) {
p = new AssemblyStylePrinter();
} else if (style.equals("builder")) {
p = new BuilderStylePrinter();
} else {
System.err.println("Unknown format style: " + style);
return;
}
p.disassemble(cf, out);
out.flush();
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"if",
"(",
"args",
".",
"length",
"==",
"0",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"DisassemblyTool [-f <format style>] <file or class name>\... | Disassembles a class file, sending the results to standard out.
<pre>
DisassemblyTool [-f <format style>] <file or class name>
</pre>
The format style may be "assembly" (the default) or "builder". | [
"Disassembles",
"a",
"class",
"file",
"sending",
"the",
"results",
"to",
"standard",
"out",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/DisassemblyTool.java#L63-L135 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java | J2EESecurityManager.determineAccessOnElement | protected Boolean determineAccessOnElement(ActionBean bean, Method handler, AnnotatedElement element)
{
// Default decision: none.
Boolean allowed = null;
if (element.isAnnotationPresent(DenyAll.class))
{
// The element denies access.
allowed = false;
}
else if (element.isAnnotationPresent(PermitAll.class))
{
// The element allows access to all security roles (i.e. any authenticated user).
allowed = isUserAuthenticated(bean, handler);
}
else
{
RolesAllowed rolesAllowed = element.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null)
{
// Still need to check if the users is authorized
allowed = isUserAuthenticated(bean, handler);
if (allowed == null || allowed.booleanValue()) {
// The element allows access if the user has one of the specified roles.
allowed = false;
for (String role : rolesAllowed.value())
{
Boolean hasRole = hasRole(bean, handler, role);
if (hasRole != null && hasRole)
{
allowed = true;
break;
}
}
}
}
}
return allowed;
} | java | protected Boolean determineAccessOnElement(ActionBean bean, Method handler, AnnotatedElement element)
{
// Default decision: none.
Boolean allowed = null;
if (element.isAnnotationPresent(DenyAll.class))
{
// The element denies access.
allowed = false;
}
else if (element.isAnnotationPresent(PermitAll.class))
{
// The element allows access to all security roles (i.e. any authenticated user).
allowed = isUserAuthenticated(bean, handler);
}
else
{
RolesAllowed rolesAllowed = element.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null)
{
// Still need to check if the users is authorized
allowed = isUserAuthenticated(bean, handler);
if (allowed == null || allowed.booleanValue()) {
// The element allows access if the user has one of the specified roles.
allowed = false;
for (String role : rolesAllowed.value())
{
Boolean hasRole = hasRole(bean, handler, role);
if (hasRole != null && hasRole)
{
allowed = true;
break;
}
}
}
}
}
return allowed;
} | [
"protected",
"Boolean",
"determineAccessOnElement",
"(",
"ActionBean",
"bean",
",",
"Method",
"handler",
",",
"AnnotatedElement",
"element",
")",
"{",
"// Default decision: none.",
"Boolean",
"allowed",
"=",
"null",
";",
"if",
"(",
"element",
".",
"isAnnotationPresent... | Decide if the annotated element allows access to the current user.
@param bean the action bean; used for security decisions
@param handler the event handler; used for security decisions
@param element the element to check authorization for
@return {@link Boolean#TRUE TRUE} if access is allowed, {@link Boolean#FALSE FALSE} if access is denied, and {@code null} if undecided
@see DenyAll
@see PermitAll
@see RolesAllowed | [
"Decide",
"if",
"the",
"annotated",
"element",
"allows",
"access",
"to",
"the",
"current",
"user",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/J2EESecurityManager.java#L95-L138 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/jstl/JstlLocalizationBundleFactory.java | JstlLocalizationBundleFactory.init | public void init(Configuration configuration)
throws Exception
{
bundleName = configuration.getServletContext().getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
if (bundleName == null)
{
throw new StripesRuntimeException("JSTL has no resource bundle configured. Please set the context " +
"parameter " + Config.FMT_LOCALIZATION_CONTEXT + " to the name of the " +
"ResourceBundle to use.");
}
} | java | public void init(Configuration configuration)
throws Exception
{
bundleName = configuration.getServletContext().getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
if (bundleName == null)
{
throw new StripesRuntimeException("JSTL has no resource bundle configured. Please set the context " +
"parameter " + Config.FMT_LOCALIZATION_CONTEXT + " to the name of the " +
"ResourceBundle to use.");
}
} | [
"public",
"void",
"init",
"(",
"Configuration",
"configuration",
")",
"throws",
"Exception",
"{",
"bundleName",
"=",
"configuration",
".",
"getServletContext",
"(",
")",
".",
"getInitParameter",
"(",
"Config",
".",
"FMT_LOCALIZATION_CONTEXT",
")",
";",
"if",
"(",
... | Invoked directly after instantiation to allow the configured component to perform
one time initialization. Components are expected to fail loudly if they are not
going to be in a valid state after initialization.
@param configuration the Configuration object being used by Stripes
@throws Exception should be thrown if the component cannot be configured well enough to use. | [
"Invoked",
"directly",
"after",
"instantiation",
"to",
"allow",
"the",
"configured",
"component",
"to",
"perform",
"one",
"time",
"initialization",
".",
"Components",
"are",
"expected",
"to",
"fail",
"loudly",
"if",
"they",
"are",
"not",
"going",
"to",
"be",
"... | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/jstl/JstlLocalizationBundleFactory.java#L36-L46 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/waitpage/Context.java | Context.run | public void run()
{
try
{
// Open connection to URL calling this interceptor.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Pass in the session id cookie to maintain the same session.
log.trace("passing in cookies: ", cookies);
connection.setRequestProperty("Cookie", cookies);
// Invoke event in background.
byte[] buff = new byte[1024 * 4];
InputStream input = connection.getInputStream();
try {
while (input.read(buff) > -1);
} finally {
input.close();
}
}
catch (Exception e)
{
// Log any exception that could have occurred.
log.error(e);
}
} | java | public void run()
{
try
{
// Open connection to URL calling this interceptor.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Pass in the session id cookie to maintain the same session.
log.trace("passing in cookies: ", cookies);
connection.setRequestProperty("Cookie", cookies);
// Invoke event in background.
byte[] buff = new byte[1024 * 4];
InputStream input = connection.getInputStream();
try {
while (input.read(buff) > -1);
} finally {
input.close();
}
}
catch (Exception e)
{
// Log any exception that could have occurred.
log.error(e);
}
} | [
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"// Open connection to URL calling this interceptor.",
"HttpURLConnection",
"connection",
"=",
"(",
"HttpURLConnection",
")",
"url",
".",
"openConnection",
"(",
")",
";",
"// Pass in the session id cookie to maintain the s... | Invoke event in a background request. | [
"Invoke",
"event",
"in",
"a",
"background",
"request",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/waitpage/Context.java#L99-L122 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/RuntimeClassFile.java | RuntimeClassFile.defineClass | public Class defineClass() {
byte[] bytes;
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
writeTo(bout);
bytes = bout.toByteArray();
} catch (IOException e) {
InternalError ie = new InternalError(e.toString());
ie.initCause(e);
throw ie;
}
if (DEBUG) {
File file = new File(getClassName().replace('.', '/') + ".class");
try {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
file = new File(tempDir, file.getPath());
} catch (SecurityException e) {
}
try {
file.getParentFile().mkdirs();
System.out.println("RuntimeClassFile writing to " + file);
OutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return mLoader.define(getClassName(), bytes);
} | java | public Class defineClass() {
byte[] bytes;
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
writeTo(bout);
bytes = bout.toByteArray();
} catch (IOException e) {
InternalError ie = new InternalError(e.toString());
ie.initCause(e);
throw ie;
}
if (DEBUG) {
File file = new File(getClassName().replace('.', '/') + ".class");
try {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
file = new File(tempDir, file.getPath());
} catch (SecurityException e) {
}
try {
file.getParentFile().mkdirs();
System.out.println("RuntimeClassFile writing to " + file);
OutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return mLoader.define(getClassName(), bytes);
} | [
"public",
"Class",
"defineClass",
"(",
")",
"{",
"byte",
"[",
"]",
"bytes",
";",
"try",
"{",
"ByteArrayOutputStream",
"bout",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"writeTo",
"(",
"bout",
")",
";",
"bytes",
"=",
"bout",
".",
"toByteArray",
... | Finishes the class definition. | [
"Finishes",
"the",
"class",
"definition",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/RuntimeClassFile.java#L140-L171 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanPropertyAccessor.java | BeanPropertyAccessor.hashCapacity | private static int hashCapacity(int min) {
BigInteger capacity = BigInteger.valueOf(min * 2 + 1);
while (!capacity.isProbablePrime(10)) {
capacity = capacity.add(BigInteger.valueOf(2));
}
return capacity.intValue();
} | java | private static int hashCapacity(int min) {
BigInteger capacity = BigInteger.valueOf(min * 2 + 1);
while (!capacity.isProbablePrime(10)) {
capacity = capacity.add(BigInteger.valueOf(2));
}
return capacity.intValue();
} | [
"private",
"static",
"int",
"hashCapacity",
"(",
"int",
"min",
")",
"{",
"BigInteger",
"capacity",
"=",
"BigInteger",
".",
"valueOf",
"(",
"min",
"*",
"2",
"+",
"1",
")",
";",
"while",
"(",
"!",
"capacity",
".",
"isProbablePrime",
"(",
"10",
")",
")",
... | Returns a prime number, at least twice as large as needed. This should
minimize hash collisions. Since all the hash keys are known up front,
the capacity could be tweaked until there are no collisions, but this
technique is easier and deterministic. | [
"Returns",
"a",
"prime",
"number",
"at",
"least",
"twice",
"as",
"large",
"as",
"needed",
".",
"This",
"should",
"minimize",
"hash",
"collisions",
".",
"Since",
"all",
"the",
"hash",
"keys",
"are",
"known",
"up",
"front",
"the",
"capacity",
"could",
"be",
... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyAccessor.java#L357-L363 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanPropertyAccessor.java | BeanPropertyAccessor.caseMethods | private static List[] caseMethods(int caseCount,
BeanProperty[] props) {
List[] cases = new List[caseCount];
for (int i=0; i<props.length; i++) {
BeanProperty prop = props[i];
int hashCode = prop.getName().hashCode();
int caseValue = (hashCode & 0x7fffffff) % caseCount;
List matches = cases[caseValue];
if (matches == null) {
matches = cases[caseValue] = new ArrayList();
}
matches.add(prop);
}
return cases;
} | java | private static List[] caseMethods(int caseCount,
BeanProperty[] props) {
List[] cases = new List[caseCount];
for (int i=0; i<props.length; i++) {
BeanProperty prop = props[i];
int hashCode = prop.getName().hashCode();
int caseValue = (hashCode & 0x7fffffff) % caseCount;
List matches = cases[caseValue];
if (matches == null) {
matches = cases[caseValue] = new ArrayList();
}
matches.add(prop);
}
return cases;
} | [
"private",
"static",
"List",
"[",
"]",
"caseMethods",
"(",
"int",
"caseCount",
",",
"BeanProperty",
"[",
"]",
"props",
")",
"{",
"List",
"[",
"]",
"cases",
"=",
"new",
"List",
"[",
"caseCount",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
... | Returns an array of Lists of BeanProperties. The first index
matches a switch case, the second index provides a list of all the
BeanProperties whose name hash matched on the case. | [
"Returns",
"an",
"array",
"of",
"Lists",
"of",
"BeanProperties",
".",
"The",
"first",
"index",
"matches",
"a",
"switch",
"case",
"the",
"second",
"index",
"provides",
"a",
"list",
"of",
"all",
"the",
"BeanProperties",
"whose",
"name",
"hash",
"matched",
"on"... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyAccessor.java#L370-L386 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanPropertyAccessor.java | BeanPropertyAccessor.getBeanProperties | private static BeanProperty[][] getBeanProperties(Class beanType, PropertySet set) {
List readProperties = new ArrayList();
List writeProperties = new ArrayList();
Map map = BeanIntrospector.getAllProperties(beanType);
Iterator it = map.values().iterator();
while (it.hasNext()) {
BeanProperty bp = (BeanProperty)it.next();
if (set == PropertySet.READ_WRITE ||
set == PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS)
{
if (bp.getReadMethod() == null || bp.getWriteMethod() == null) {
continue;
}
}
boolean checkedAllowed =
set != PropertySet.UNCHECKED_EXCEPTIONS &&
set != PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS;
if (bp.getReadMethod() != null) {
if (checkedAllowed || !throwsCheckedException(bp.getReadMethod())) {
readProperties.add(bp);
}
}
if (bp.getWriteMethod() != null) {
if (checkedAllowed || !throwsCheckedException(bp.getWriteMethod())) {
writeProperties.add(bp);
}
}
}
BeanProperty[][] props = new BeanProperty[2][];
props[0] = new BeanProperty[readProperties.size()];
readProperties.toArray(props[0]);
props[1] = new BeanProperty[writeProperties.size()];
writeProperties.toArray(props[1]);
return props;
} | java | private static BeanProperty[][] getBeanProperties(Class beanType, PropertySet set) {
List readProperties = new ArrayList();
List writeProperties = new ArrayList();
Map map = BeanIntrospector.getAllProperties(beanType);
Iterator it = map.values().iterator();
while (it.hasNext()) {
BeanProperty bp = (BeanProperty)it.next();
if (set == PropertySet.READ_WRITE ||
set == PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS)
{
if (bp.getReadMethod() == null || bp.getWriteMethod() == null) {
continue;
}
}
boolean checkedAllowed =
set != PropertySet.UNCHECKED_EXCEPTIONS &&
set != PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS;
if (bp.getReadMethod() != null) {
if (checkedAllowed || !throwsCheckedException(bp.getReadMethod())) {
readProperties.add(bp);
}
}
if (bp.getWriteMethod() != null) {
if (checkedAllowed || !throwsCheckedException(bp.getWriteMethod())) {
writeProperties.add(bp);
}
}
}
BeanProperty[][] props = new BeanProperty[2][];
props[0] = new BeanProperty[readProperties.size()];
readProperties.toArray(props[0]);
props[1] = new BeanProperty[writeProperties.size()];
writeProperties.toArray(props[1]);
return props;
} | [
"private",
"static",
"BeanProperty",
"[",
"]",
"[",
"]",
"getBeanProperties",
"(",
"Class",
"beanType",
",",
"PropertySet",
"set",
")",
"{",
"List",
"readProperties",
"=",
"new",
"ArrayList",
"(",
")",
";",
"List",
"writeProperties",
"=",
"new",
"ArrayList",
... | Returns two arrays of BeanProperties. Array 0 contains read
BeanProperties, array 1 contains the write BeanProperties. | [
"Returns",
"two",
"arrays",
"of",
"BeanProperties",
".",
"Array",
"0",
"contains",
"read",
"BeanProperties",
"array",
"1",
"contains",
"the",
"write",
"BeanProperties",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyAccessor.java#L472-L514 | train |
cojen/Cojen | src/main/java/org/cojen/util/ClassInjector.java | ClassInjector.openStream | public OutputStream openStream() throws IllegalStateException {
if (mClass != null) {
throw new IllegalStateException("New class has already been defined");
}
ByteArrayOutputStream data = mData;
if (data != null) {
throw new IllegalStateException("Stream already opened");
}
mData = data = new ByteArrayOutputStream();
return data;
} | java | public OutputStream openStream() throws IllegalStateException {
if (mClass != null) {
throw new IllegalStateException("New class has already been defined");
}
ByteArrayOutputStream data = mData;
if (data != null) {
throw new IllegalStateException("Stream already opened");
}
mData = data = new ByteArrayOutputStream();
return data;
} | [
"public",
"OutputStream",
"openStream",
"(",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"mClass",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"New class has already been defined\"",
")",
";",
"}",
"ByteArrayOutputStream",
"data... | Open a stream to define the new class into.
@throws IllegalStateException if new class has already been defined
or if a stream has already been opened | [
"Open",
"a",
"stream",
"to",
"define",
"the",
"new",
"class",
"into",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ClassInjector.java#L236-L246 | train |
cojen/Cojen | src/main/java/org/cojen/util/ClassInjector.java | ClassInjector.defineClass | public Class defineClass(ClassFile cf) {
try {
cf.writeTo(openStream());
} catch (IOException e) {
throw new InternalError(e.toString());
}
return getNewClass();
} | java | public Class defineClass(ClassFile cf) {
try {
cf.writeTo(openStream());
} catch (IOException e) {
throw new InternalError(e.toString());
}
return getNewClass();
} | [
"public",
"Class",
"defineClass",
"(",
"ClassFile",
"cf",
")",
"{",
"try",
"{",
"cf",
".",
"writeTo",
"(",
"openStream",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"InternalError",
"(",
"e",
".",
"toString",
... | Define the new class from a ClassFile object.
@return the newly created class
@throws IllegalStateException if new class has already been defined
or if a stream has already been opened | [
"Define",
"the",
"new",
"class",
"from",
"a",
"ClassFile",
"object",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ClassInjector.java#L255-L262 | train |
cojen/Cojen | src/main/java/org/cojen/util/ClassInjector.java | ClassInjector.getNewClass | public Class getNewClass() throws IllegalStateException, ClassFormatError {
if (mClass != null) {
return mClass;
}
ByteArrayOutputStream data = mData;
if (data == null) {
throw new IllegalStateException("Class not defined yet");
}
byte[] bytes = data.toByteArray();
if (DEBUG) {
File file = new File(mName.replace('.', '/') + ".class");
try {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
file = new File(tempDir, file.getPath());
} catch (SecurityException e) {
}
try {
file.getParentFile().mkdirs();
System.out.println("ClassInjector writing to " + file);
OutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
mClass = mLoader.define(mName, bytes);
mData = null;
return mClass;
} | java | public Class getNewClass() throws IllegalStateException, ClassFormatError {
if (mClass != null) {
return mClass;
}
ByteArrayOutputStream data = mData;
if (data == null) {
throw new IllegalStateException("Class not defined yet");
}
byte[] bytes = data.toByteArray();
if (DEBUG) {
File file = new File(mName.replace('.', '/') + ".class");
try {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
file = new File(tempDir, file.getPath());
} catch (SecurityException e) {
}
try {
file.getParentFile().mkdirs();
System.out.println("ClassInjector writing to " + file);
OutputStream out = new FileOutputStream(file);
out.write(bytes);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
mClass = mLoader.define(mName, bytes);
mData = null;
return mClass;
} | [
"public",
"Class",
"getNewClass",
"(",
")",
"throws",
"IllegalStateException",
",",
"ClassFormatError",
"{",
"if",
"(",
"mClass",
"!=",
"null",
")",
"{",
"return",
"mClass",
";",
"}",
"ByteArrayOutputStream",
"data",
"=",
"mData",
";",
"if",
"(",
"data",
"==... | Returns the newly defined class.
@throws IllegalStateException if class was never defined | [
"Returns",
"the",
"newly",
"defined",
"class",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ClassInjector.java#L269-L301 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/util/BaseNCodec.java | BaseNCodec.available | int available(Context context) { // package protected for access from I/O streams
return context.buffer != null ? context.pos - context.readPos : 0;
} | java | int available(Context context) { // package protected for access from I/O streams
return context.buffer != null ? context.pos - context.readPos : 0;
} | [
"int",
"available",
"(",
"Context",
"context",
")",
"{",
"// package protected for access from I/O streams",
"return",
"context",
".",
"buffer",
"!=",
"null",
"?",
"context",
".",
"pos",
"-",
"context",
".",
"readPos",
":",
"0",
";",
"}"
] | Returns the amount of buffered data available for reading.
@param context the context to be used
@return The amount of buffered data available for reading. | [
"Returns",
"the",
"amount",
"of",
"buffered",
"data",
"available",
"for",
"reading",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/util/BaseNCodec.java#L203-L205 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/HttpUtil.java | HttpUtil.parseData | public static Map<String, Object> parseData(String data) {
Map<String, Object> ret = new HashMap<String, Object>();
String[] split = data.split("&");
for (String s : split) {
int idx = s.indexOf('=');
try {
if (idx != -1) {
ret.put(URLDecoder.decode(s.substring(0, idx), "UTF-8"), URLDecoder.decode(s.substring(idx + 1), "UTF-8"));
} else {
ret.put(URLDecoder.decode(s, "UTF-8"), "true");
}
} catch (UnsupportedEncodingException e) {
// Why.
}
}
return ret;
} | java | public static Map<String, Object> parseData(String data) {
Map<String, Object> ret = new HashMap<String, Object>();
String[] split = data.split("&");
for (String s : split) {
int idx = s.indexOf('=');
try {
if (idx != -1) {
ret.put(URLDecoder.decode(s.substring(0, idx), "UTF-8"), URLDecoder.decode(s.substring(idx + 1), "UTF-8"));
} else {
ret.put(URLDecoder.decode(s, "UTF-8"), "true");
}
} catch (UnsupportedEncodingException e) {
// Why.
}
}
return ret;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"parseData",
"(",
"String",
"data",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"ret",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"String",
"[",
"]"... | Parse POST data or GET data from the request URI
@param data The data string
@return A map containing the values | [
"Parse",
"POST",
"data",
"or",
"GET",
"data",
"from",
"the",
"request",
"URI"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/HttpUtil.java#L16-L32 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/HttpUtil.java | HttpUtil.capitalizeHeader | public static String capitalizeHeader(String header) {
StringTokenizer st = new StringTokenizer(header, "-");
StringBuilder out = new StringBuilder();
while (st.hasMoreTokens()) {
String l = st.nextToken();
out.append(Character.toUpperCase(l.charAt(0)));
if (l.length() > 1) {
out.append(l.substring(1));
}
if (st.hasMoreTokens())
out.append('-');
}
return out.toString();
} | java | public static String capitalizeHeader(String header) {
StringTokenizer st = new StringTokenizer(header, "-");
StringBuilder out = new StringBuilder();
while (st.hasMoreTokens()) {
String l = st.nextToken();
out.append(Character.toUpperCase(l.charAt(0)));
if (l.length() > 1) {
out.append(l.substring(1));
}
if (st.hasMoreTokens())
out.append('-');
}
return out.toString();
} | [
"public",
"static",
"String",
"capitalizeHeader",
"(",
"String",
"header",
")",
"{",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"header",
",",
"\"-\"",
")",
";",
"StringBuilder",
"out",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"... | Fixes capitalization on headers
@param header The header input
@return A header with all characters after '-' capitalized | [
"Fixes",
"capitalization",
"on",
"headers"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/HttpUtil.java#L40-L53 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java | MIDDCombiner.combineExternalNodes | private ExternalNode3 combineExternalNodes(ExternalNode3 n1, ExternalNode3 n2) {
if (n1 == null || n2 == null) {
throw new IllegalArgumentException("Input nodes must not be null");
}
DecisionType combinedDecision = algo.combine(n1.getDecision(), n2.getDecision());
ExternalNode3 n = new ExternalNode3(combinedDecision);
// only accept OE that match with combined decision.
List<ObligationExpression> oes1 = getFulfilledObligationExpressions(n1.getObligationExpressions(), combinedDecision);
List<ObligationExpression> oes2 = getFulfilledObligationExpressions(n2.getObligationExpressions(), combinedDecision);
n.getObligationExpressions().addAll(oes1);
n.getObligationExpressions().addAll(oes2);
return n;
} | java | private ExternalNode3 combineExternalNodes(ExternalNode3 n1, ExternalNode3 n2) {
if (n1 == null || n2 == null) {
throw new IllegalArgumentException("Input nodes must not be null");
}
DecisionType combinedDecision = algo.combine(n1.getDecision(), n2.getDecision());
ExternalNode3 n = new ExternalNode3(combinedDecision);
// only accept OE that match with combined decision.
List<ObligationExpression> oes1 = getFulfilledObligationExpressions(n1.getObligationExpressions(), combinedDecision);
List<ObligationExpression> oes2 = getFulfilledObligationExpressions(n2.getObligationExpressions(), combinedDecision);
n.getObligationExpressions().addAll(oes1);
n.getObligationExpressions().addAll(oes2);
return n;
} | [
"private",
"ExternalNode3",
"combineExternalNodes",
"(",
"ExternalNode3",
"n1",
",",
"ExternalNode3",
"n2",
")",
"{",
"if",
"(",
"n1",
"==",
"null",
"||",
"n2",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Input nodes must not be nul... | Combine two external nodes following the algorithm in this.algo
@param n1
@param n2
@return | [
"Combine",
"two",
"external",
"nodes",
"following",
"the",
"algorithm",
"in",
"this",
".",
"algo"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java#L200-L217 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java | MIDDCombiner.getFulfilledObligationExpressions | private List<ObligationExpression> getFulfilledObligationExpressions(
List<ObligationExpression> oes,
DecisionType decision) {
List<ObligationExpression> fulfilledOEs = new ArrayList<ObligationExpression>();
if (oes != null && oes.size() > 0) {
for (ObligationExpression oe : oes) {
if (oe.isFulfilled(decision)) {
fulfilledOEs.add(oe);
}
}
}
return fulfilledOEs;
} | java | private List<ObligationExpression> getFulfilledObligationExpressions(
List<ObligationExpression> oes,
DecisionType decision) {
List<ObligationExpression> fulfilledOEs = new ArrayList<ObligationExpression>();
if (oes != null && oes.size() > 0) {
for (ObligationExpression oe : oes) {
if (oe.isFulfilled(decision)) {
fulfilledOEs.add(oe);
}
}
}
return fulfilledOEs;
} | [
"private",
"List",
"<",
"ObligationExpression",
">",
"getFulfilledObligationExpressions",
"(",
"List",
"<",
"ObligationExpression",
">",
"oes",
",",
"DecisionType",
"decision",
")",
"{",
"List",
"<",
"ObligationExpression",
">",
"fulfilledOEs",
"=",
"new",
"ArrayList"... | Return OE in the list that are fulfilled the indicated decision.
@param oes
@param decision
@return | [
"Return",
"OE",
"in",
"the",
"list",
"that",
"are",
"fulfilled",
"the",
"indicated",
"decision",
"."
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java#L226-L240 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java | MIDDCombiner.combineInternalNodeStates | private InternalNodeState combineInternalNodeStates(InternalNodeState inState, ExternalNode3 externalNode) {
ExternalNode3 n1 = inState.getExternalNode();
ExternalNode3 n = combineExternalNodes(n1, externalNode);
return new InternalNodeState(n);
} | java | private InternalNodeState combineInternalNodeStates(InternalNodeState inState, ExternalNode3 externalNode) {
ExternalNode3 n1 = inState.getExternalNode();
ExternalNode3 n = combineExternalNodes(n1, externalNode);
return new InternalNodeState(n);
} | [
"private",
"InternalNodeState",
"combineInternalNodeStates",
"(",
"InternalNodeState",
"inState",
",",
"ExternalNode3",
"externalNode",
")",
"{",
"ExternalNode3",
"n1",
"=",
"inState",
".",
"getExternalNode",
"(",
")",
";",
"ExternalNode3",
"n",
"=",
"combineExternalNod... | Combine an indeterminate state of an internal node with an external node which use indicated combining
algorithm.
@param inState
@param externalNode
@return | [
"Combine",
"an",
"indeterminate",
"state",
"of",
"an",
"internal",
"node",
"with",
"an",
"external",
"node",
"which",
"use",
"indicated",
"combining",
"algorithm",
"."
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/builders/MIDDCombiner.java#L352-L359 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/RuleParser.java | RuleParser.setEffectNode | @SuppressWarnings("rawtypes")
private void setEffectNode(AbstractNode midd, ExternalNode3 extNode) throws MIDDException {
// Replace current external nodes in the MIDD with the extNode (XACML 3 external node)
if (!(midd instanceof InternalNode)) {
throw new IllegalArgumentException("MIDD argument must not be an ExternalNode");
}
InternalNode currentNode = (InternalNode) midd;
Stack<InternalNode> stackNodes = new Stack<InternalNode>();
stackNodes.push(currentNode);
while (!stackNodes.empty()) {
InternalNode n = stackNodes.pop();
// Change indeterminate state of the internal node,
// - By default is NotApplicable (XACML 3.0, sec 7.3.5, 7.19.3)
// - If the attribute "MustBePresent" is true, then state is "Indeterminate_P" if Effect is "Permit",
// "Indeterminate_D" if Effect is "Deny" - XACML 3.0, section 7.11
if (n.getStateIN() == DecisionType.Indeterminate) { // this attribute has 'MustBePresent'=true
if (ruleEffect == DecisionType.Deny) {
n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.Indeterminate_D));
} else if (ruleEffect == DecisionType.Permit) {
n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.Indeterminate_P));
}
}
// else {
// n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.NotApplicable));
// }
// search for all children of the poped internal node
@SuppressWarnings("unchecked")
Iterator<AbstractEdge> it = n.getEdges().iterator();
while (it.hasNext()) {
AbstractEdge edge = it.next();
AbstractNode child = edge.getSubDiagram();
if (child instanceof InternalNode) {
stackNodes.push((InternalNode) child);
} else {
edge.setSubDiagram(extNode); // set the final edge pointing to the xacml3 external node.
}
}
}
} | java | @SuppressWarnings("rawtypes")
private void setEffectNode(AbstractNode midd, ExternalNode3 extNode) throws MIDDException {
// Replace current external nodes in the MIDD with the extNode (XACML 3 external node)
if (!(midd instanceof InternalNode)) {
throw new IllegalArgumentException("MIDD argument must not be an ExternalNode");
}
InternalNode currentNode = (InternalNode) midd;
Stack<InternalNode> stackNodes = new Stack<InternalNode>();
stackNodes.push(currentNode);
while (!stackNodes.empty()) {
InternalNode n = stackNodes.pop();
// Change indeterminate state of the internal node,
// - By default is NotApplicable (XACML 3.0, sec 7.3.5, 7.19.3)
// - If the attribute "MustBePresent" is true, then state is "Indeterminate_P" if Effect is "Permit",
// "Indeterminate_D" if Effect is "Deny" - XACML 3.0, section 7.11
if (n.getStateIN() == DecisionType.Indeterminate) { // this attribute has 'MustBePresent'=true
if (ruleEffect == DecisionType.Deny) {
n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.Indeterminate_D));
} else if (ruleEffect == DecisionType.Permit) {
n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.Indeterminate_P));
}
}
// else {
// n.setState(new InternalNodeState(nl.uva.sne.midd.DecisionType.NotApplicable));
// }
// search for all children of the poped internal node
@SuppressWarnings("unchecked")
Iterator<AbstractEdge> it = n.getEdges().iterator();
while (it.hasNext()) {
AbstractEdge edge = it.next();
AbstractNode child = edge.getSubDiagram();
if (child instanceof InternalNode) {
stackNodes.push((InternalNode) child);
} else {
edge.setSubDiagram(extNode); // set the final edge pointing to the xacml3 external node.
}
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"private",
"void",
"setEffectNode",
"(",
"AbstractNode",
"midd",
",",
"ExternalNode3",
"extNode",
")",
"throws",
"MIDDException",
"{",
"// Replace current external nodes in the MIDD with the extNode (XACML 3 external node)",
"i... | Set indicated external-xacml3 node to be the leaves of the MIDD
@param midd
@param extNode | [
"Set",
"indicated",
"external",
"-",
"xacml3",
"node",
"to",
"be",
"the",
"leaves",
"of",
"the",
"MIDD"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/RuleParser.java#L190-L236 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/MultipartReader.java | MultipartReader.read | public int read() throws IOException {
if (leftover != null && leftover.remaining() > 0) {
int b = leftover.get();
if (leftover.remaining() == 0) {
leftover = null;
}
return b;
}
return input.read();
} | java | public int read() throws IOException {
if (leftover != null && leftover.remaining() > 0) {
int b = leftover.get();
if (leftover.remaining() == 0) {
leftover = null;
}
return b;
}
return input.read();
} | [
"public",
"int",
"read",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"leftover",
"!=",
"null",
"&&",
"leftover",
".",
"remaining",
"(",
")",
">",
"0",
")",
"{",
"int",
"b",
"=",
"leftover",
".",
"get",
"(",
")",
";",
"if",
"(",
"leftover",
... | Read a single byte, except it will try to use the leftover bytes from the
previous read first.
@return The single byte read
@throws IOException If an error occurs | [
"Read",
"a",
"single",
"byte",
"except",
"it",
"will",
"try",
"to",
"use",
"the",
"leftover",
"bytes",
"from",
"the",
"previous",
"read",
"first",
"."
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/MultipartReader.java#L59-L68 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/MultipartReader.java | MultipartReader.readLine | public String readLine() throws IOException {
StringBuilder bldr = new StringBuilder();
while (true) {
int b = read();
if (b == -1 || b == 10) {
break;
} else if (b != '\r') {
bldr.append((char) ((byte) b));
}
}
return bldr.toString();
} | java | public String readLine() throws IOException {
StringBuilder bldr = new StringBuilder();
while (true) {
int b = read();
if (b == -1 || b == 10) {
break;
} else if (b != '\r') {
bldr.append((char) ((byte) b));
}
}
return bldr.toString();
} | [
"public",
"String",
"readLine",
"(",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"bldr",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"int",
"b",
"=",
"read",
"(",
")",
";",
"if",
"(",
"b",
"==",
"-",
"1",
"||... | Reads a line up until \r\n This will act similar to
BufferedReader.readLine
@return The line
@throws IOException If an error occurs while reading | [
"Reads",
"a",
"line",
"up",
"until",
"\\",
"r",
"\\",
"n",
"This",
"will",
"act",
"similar",
"to",
"BufferedReader",
".",
"readLine"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/MultipartReader.java#L146-L157 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/MultipartReader.java | MultipartReader.readLineUntilBoundary | public String readLineUntilBoundary() throws IOException {
StringBuilder bldr = new StringBuilder();
while (true) {
int b = read();
if (bldr.indexOf(boundary) == 0) {
leftover = ByteBuffer.wrap(boundaryBytes);
return null;
} else if (b == -1 || b == 10) {
break;
} else if (b != '\r') {
bldr.append((char) ((byte) b));
}
}
return bldr.toString();
} | java | public String readLineUntilBoundary() throws IOException {
StringBuilder bldr = new StringBuilder();
while (true) {
int b = read();
if (bldr.indexOf(boundary) == 0) {
leftover = ByteBuffer.wrap(boundaryBytes);
return null;
} else if (b == -1 || b == 10) {
break;
} else if (b != '\r') {
bldr.append((char) ((byte) b));
}
}
return bldr.toString();
} | [
"public",
"String",
"readLineUntilBoundary",
"(",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"bldr",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"int",
"b",
"=",
"read",
"(",
")",
";",
"if",
"(",
"bldr",
".",
"i... | Reads a line up until \r\n OR the boundary This will act similar to
BufferedReader.readLine, except that it will stop at the defined
boundary.
@return The line
@throws IOException If an error occurs while reading | [
"Reads",
"a",
"line",
"up",
"until",
"\\",
"r",
"\\",
"n",
"OR",
"the",
"boundary",
"This",
"will",
"act",
"similar",
"to",
"BufferedReader",
".",
"readLine",
"except",
"that",
"it",
"will",
"stop",
"at",
"the",
"defined",
"boundary",
"."
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/MultipartReader.java#L167-L181 | train |
stefanbirkner/fishbowl | src/main/java/com/github/stefanbirkner/fishbowl/Fishbowl.java | Fishbowl.defaultIfException | public static <V> V defaultIfException(
StatementWithReturnValue<V> statement,
Class<? extends Throwable> exceptionType, V defaultValue) {
try {
return statement.evaluate();
} catch (RuntimeException e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw e;
} catch (Error e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw e;
} catch (Throwable e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw new WrappedException(e);
}
} | java | public static <V> V defaultIfException(
StatementWithReturnValue<V> statement,
Class<? extends Throwable> exceptionType, V defaultValue) {
try {
return statement.evaluate();
} catch (RuntimeException e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw e;
} catch (Error e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw e;
} catch (Throwable e) {
if (exceptionType.isAssignableFrom(e.getClass()))
return defaultValue;
else
throw new WrappedException(e);
}
} | [
"public",
"static",
"<",
"V",
">",
"V",
"defaultIfException",
"(",
"StatementWithReturnValue",
"<",
"V",
">",
"statement",
",",
"Class",
"<",
"?",
"extends",
"Throwable",
">",
"exceptionType",
",",
"V",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"statem... | Executes the given statement and returns the statement's return
value if no exception is thrown or the default value if an
exception of the specified type is thrown.
<pre>
public void doSomething() {
long value = defaultIfException(() -> parseLong("NaN"), NumberFormatException.class, 0L);
//value is 0
}
</pre>
<p>(Any other checked exception is wrapped just as it is wrapped by
{@link #wrapCheckedException(StatementWithReturnValue)}.)
@param statement The statement that is executed.
@param exceptionType the type of exception for which the default
value is returned.
@param defaultValue this value is returned if the statement
throws an exception of the specified type.
@param <V> type of the value that is returned by the statement.
@return the return value of the statement or the default value. | [
"Executes",
"the",
"given",
"statement",
"and",
"returns",
"the",
"statement",
"s",
"return",
"value",
"if",
"no",
"exception",
"is",
"thrown",
"or",
"the",
"default",
"value",
"if",
"an",
"exception",
"of",
"the",
"specified",
"type",
"is",
"thrown",
"."
] | 0ef001f1fc38822ffbe74679ee3001504eb5f23c | https://github.com/stefanbirkner/fishbowl/blob/0ef001f1fc38822ffbe74679ee3001504eb5f23c/src/main/java/com/github/stefanbirkner/fishbowl/Fishbowl.java#L62-L83 | train |
svanoort/rest-compress | demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java | RestMapObject.getValue | public String getValue(String key) {
KeyValue kv = getKV(key);
return kv == null ? null : kv.getValue();
} | java | public String getValue(String key) {
KeyValue kv = getKV(key);
return kv == null ? null : kv.getValue();
} | [
"public",
"String",
"getValue",
"(",
"String",
"key",
")",
"{",
"KeyValue",
"kv",
"=",
"getKV",
"(",
"key",
")",
";",
"return",
"kv",
"==",
"null",
"?",
"null",
":",
"kv",
".",
"getValue",
"(",
")",
";",
"}"
] | Get the value for the key | [
"Get",
"the",
"value",
"for",
"the",
"key"
] | 4e34fcbe0d1b510962a93509a78b6a8ade234606 | https://github.com/svanoort/rest-compress/blob/4e34fcbe0d1b510962a93509a78b6a8ade234606/demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java#L36-L39 | train |
svanoort/rest-compress | demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java | RestMapObject.setValue | public void setValue(String key, String value) {
KeyValue kv = getKV(key);
if (kv != null) {
kv.setValue(value);
} else if (key != null) {
map.add(new KeyValue(key,value));
}
} | java | public void setValue(String key, String value) {
KeyValue kv = getKV(key);
if (kv != null) {
kv.setValue(value);
} else if (key != null) {
map.add(new KeyValue(key,value));
}
} | [
"public",
"void",
"setValue",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"KeyValue",
"kv",
"=",
"getKV",
"(",
"key",
")",
";",
"if",
"(",
"kv",
"!=",
"null",
")",
"{",
"kv",
".",
"setValue",
"(",
"value",
")",
";",
"}",
"else",
"if",... | Null value is totally legal! | [
"Null",
"value",
"is",
"totally",
"legal!"
] | 4e34fcbe0d1b510962a93509a78b6a8ade234606 | https://github.com/svanoort/rest-compress/blob/4e34fcbe0d1b510962a93509a78b6a8ade234606/demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java#L42-L49 | train |
svanoort/rest-compress | demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java | RestMapObject.removeKey | public void removeKey(String key) {
if (key != null && !key.isEmpty()) {
for (int i=0; i<map.size(); i++) {
KeyValue kv = map.get(i);
if (key.equals(kv.getKey())) {
map.remove(i);
return;
}
}
}
} | java | public void removeKey(String key) {
if (key != null && !key.isEmpty()) {
for (int i=0; i<map.size(); i++) {
KeyValue kv = map.get(i);
if (key.equals(kv.getKey())) {
map.remove(i);
return;
}
}
}
} | [
"public",
"void",
"removeKey",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"key",
"!=",
"null",
"&&",
"!",
"key",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"map",
".",
"size",
"(",
")",
";",
"i",
"+... | Remove mappings for given key | [
"Remove",
"mappings",
"for",
"given",
"key"
] | 4e34fcbe0d1b510962a93509a78b6a8ade234606 | https://github.com/svanoort/rest-compress/blob/4e34fcbe0d1b510962a93509a78b6a8ade234606/demo-app/src/main/java/com/restcompress/demoapp/model/RestMapObject.java#L52-L62 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/edges/AbstractEdge.java | AbstractEdge.match | public boolean match(final T value) throws MIDDException {
for (Interval<T> interval : this.intervals) {
if (interval.hasValue(value)) {
return true;
}
}
return false;
} | java | public boolean match(final T value) throws MIDDException {
for (Interval<T> interval : this.intervals) {
if (interval.hasValue(value)) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"match",
"(",
"final",
"T",
"value",
")",
"throws",
"MIDDException",
"{",
"for",
"(",
"Interval",
"<",
"T",
">",
"interval",
":",
"this",
".",
"intervals",
")",
"{",
"if",
"(",
"interval",
".",
"hasValue",
"(",
"value",
")",
")",
... | Check if the value is matched with the edge's intervals
@param value
@return | [
"Check",
"if",
"the",
"value",
"is",
"matched",
"with",
"the",
"edge",
"s",
"intervals"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/edges/AbstractEdge.java#L106-L113 | train |
99soft/guartz | src/main/java/org/nnsoft/guice/guartz/QuartzModule.java | QuartzModule.doBind | protected final <T> void doBind( Multibinder<T> binder, Class<? extends T> type )
{
checkNotNull( type );
binder.addBinding().to( type );
} | java | protected final <T> void doBind( Multibinder<T> binder, Class<? extends T> type )
{
checkNotNull( type );
binder.addBinding().to( type );
} | [
"protected",
"final",
"<",
"T",
">",
"void",
"doBind",
"(",
"Multibinder",
"<",
"T",
">",
"binder",
",",
"Class",
"<",
"?",
"extends",
"T",
">",
"type",
")",
"{",
"checkNotNull",
"(",
"type",
")",
";",
"binder",
".",
"addBinding",
"(",
")",
".",
"t... | Utility method to respect the DRY principle.
@param <T>
@param binder
@param type | [
"Utility",
"method",
"to",
"respect",
"the",
"DRY",
"principle",
"."
] | 3f59096d8dff52475d1677bd5fdff61d12e5fa14 | https://github.com/99soft/guartz/blob/3f59096d8dff52475d1677bd5fdff61d12e5fa14/src/main/java/org/nnsoft/guice/guartz/QuartzModule.java#L206-L210 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java | InternalNode.addChild | @SuppressWarnings("unchecked")
public void addChild(final AbstractEdge<?> edge, final AbstractNode child) {
if (child == null || edge == null ||
edge.getIntervals() == null || edge.getIntervals().size() == 0) {
throw new IllegalArgumentException("Cannot add null child or empty edge");
}
edge.setSubDiagram(child);
edges.add((AbstractEdge<T>) edge);
} | java | @SuppressWarnings("unchecked")
public void addChild(final AbstractEdge<?> edge, final AbstractNode child) {
if (child == null || edge == null ||
edge.getIntervals() == null || edge.getIntervals().size() == 0) {
throw new IllegalArgumentException("Cannot add null child or empty edge");
}
edge.setSubDiagram(child);
edges.add((AbstractEdge<T>) edge);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"addChild",
"(",
"final",
"AbstractEdge",
"<",
"?",
">",
"edge",
",",
"final",
"AbstractNode",
"child",
")",
"{",
"if",
"(",
"child",
"==",
"null",
"||",
"edge",
"==",
"null",
"||",
"e... | Create an out-going edge to the given node. The edge and child node are mutable objects.
If they are used in another tree, it'd better to clone before adding them.
Note: Edge<?> and InternalNode<T> must use the same type
@param edge
@param child | [
"Create",
"an",
"out",
"-",
"going",
"edge",
"to",
"the",
"given",
"node",
".",
"The",
"edge",
"and",
"child",
"node",
"are",
"mutable",
"objects",
".",
"If",
"they",
"are",
"used",
"in",
"another",
"tree",
"it",
"d",
"better",
"to",
"clone",
"before",... | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java#L85-L94 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java | InternalNode.getChild | public AbstractNode getChild(Interval<T> interval) throws MIDDException {
for (AbstractEdge<T> e : this.edges) {
if (e.containsInterval(interval)) {
return e.getSubDiagram();
}
}
return null;
} | java | public AbstractNode getChild(Interval<T> interval) throws MIDDException {
for (AbstractEdge<T> e : this.edges) {
if (e.containsInterval(interval)) {
return e.getSubDiagram();
}
}
return null;
} | [
"public",
"AbstractNode",
"getChild",
"(",
"Interval",
"<",
"T",
">",
"interval",
")",
"throws",
"MIDDException",
"{",
"for",
"(",
"AbstractEdge",
"<",
"T",
">",
"e",
":",
"this",
".",
"edges",
")",
"{",
"if",
"(",
"e",
".",
"containsInterval",
"(",
"i... | Return the child of the current node with equivalent interval on its incoming edge.
@param interval The interval which is the subset of the interval in the incoming edge
@return null if no matching edge found. | [
"Return",
"the",
"child",
"of",
"the",
"current",
"node",
"with",
"equivalent",
"interval",
"on",
"its",
"incoming",
"edge",
"."
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java#L112-L119 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java | InternalNode.getIntervals | @SuppressWarnings("rawtypes")
public List<Interval> getIntervals() {
List<Interval> lstIntervals = new ArrayList<Interval>();
for (AbstractEdge<T> e : this.edges) {
lstIntervals.addAll(e.getIntervals());
}
return lstIntervals;
} | java | @SuppressWarnings("rawtypes")
public List<Interval> getIntervals() {
List<Interval> lstIntervals = new ArrayList<Interval>();
for (AbstractEdge<T> e : this.edges) {
lstIntervals.addAll(e.getIntervals());
}
return lstIntervals;
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"List",
"<",
"Interval",
">",
"getIntervals",
"(",
")",
"{",
"List",
"<",
"Interval",
">",
"lstIntervals",
"=",
"new",
"ArrayList",
"<",
"Interval",
">",
"(",
")",
";",
"for",
"(",
"AbstractEdge"... | Collect all intervals of all outgoing edges
@return | [
"Collect",
"all",
"intervals",
"of",
"all",
"outgoing",
"edges"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java#L138-L146 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java | InternalNode.match | public AbstractEdge<T> match(T value) throws UnmatchedException, MIDDException {
for (AbstractEdge<T> e : this.edges) {
if (e.match(value)) {
return e;
}
}
throw new UnmatchedException("No matching edge found for value " + value);
} | java | public AbstractEdge<T> match(T value) throws UnmatchedException, MIDDException {
for (AbstractEdge<T> e : this.edges) {
if (e.match(value)) {
return e;
}
}
throw new UnmatchedException("No matching edge found for value " + value);
} | [
"public",
"AbstractEdge",
"<",
"T",
">",
"match",
"(",
"T",
"value",
")",
"throws",
"UnmatchedException",
",",
"MIDDException",
"{",
"for",
"(",
"AbstractEdge",
"<",
"T",
">",
"e",
":",
"this",
".",
"edges",
")",
"{",
"if",
"(",
"e",
".",
"match",
"(... | Return an edge to match with input value
@param value
@return
@throws nl.uva.sne.midd.UnmatchedException | [
"Return",
"an",
"edge",
"to",
"match",
"with",
"input",
"value"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/nodes/InternalNode.java#L162-L169 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/AnyOfExpression.java | AnyOfExpression.createFromConjunctionClauses | public AbstractNode createFromConjunctionClauses(Map<String, AttributeInfo> intervals) throws MIDDParsingException, MIDDException {
if (intervals == null || intervals.size() == 0) {
return ExternalNode.newInstance(); // return true-value external node
}
// Create edges from intervals
Map<Integer, AbstractEdge<?>> edges = new HashMap<Integer, AbstractEdge<?>>();
for (String attrId : intervals.keySet()) {
int varId = attrMapper.getVariableId(attrId);
Interval<?> interval = intervals.get(attrId).getInterval();
Class<?> type = interval.getType();
AbstractEdge<?> e = EdgeUtils.createEdge(interval);
edges.put(varId, e);
}
List<Integer> lstVarIds = new ArrayList<Integer>(edges.keySet());
Collections.sort(lstVarIds);
// create a MIDD path from list of edges, start from lowest var-id
InternalNode<?> root = null;
InternalNode<?> currentNode = null;
AbstractEdge<?> currentEdge = null;
Iterator<Integer> lstIt = lstVarIds.iterator();
while (lstIt.hasNext()) {
Integer varId = lstIt.next();
AbstractEdge<?> e = edges.get(varId);
// default is NotApplicable, unless the "MustBePresent" is set to "true"
String attrId = attrMapper.getAttributeId(varId);
boolean isAttrMustBePresent = intervals.get(attrId).isMustBePresent;
InternalNodeState nodeState = new InternalNodeState(isAttrMustBePresent ? DecisionType.Indeterminate : DecisionType.NotApplicable);
InternalNode<?> node = NodeUtils.createInternalNode(varId, nodeState, e.getType());
if (root == null) {
root = node; // root points to the start of the MIDD path
currentNode = node;
currentEdge = e;
} else {
currentNode.addChild(currentEdge, node);
currentNode = node;
currentEdge = e;
}
}
// the tail points to the true clause
currentNode.addChild(currentEdge, ExternalNode.newInstance()); // add a true-value external node
return root;
} | java | public AbstractNode createFromConjunctionClauses(Map<String, AttributeInfo> intervals) throws MIDDParsingException, MIDDException {
if (intervals == null || intervals.size() == 0) {
return ExternalNode.newInstance(); // return true-value external node
}
// Create edges from intervals
Map<Integer, AbstractEdge<?>> edges = new HashMap<Integer, AbstractEdge<?>>();
for (String attrId : intervals.keySet()) {
int varId = attrMapper.getVariableId(attrId);
Interval<?> interval = intervals.get(attrId).getInterval();
Class<?> type = interval.getType();
AbstractEdge<?> e = EdgeUtils.createEdge(interval);
edges.put(varId, e);
}
List<Integer> lstVarIds = new ArrayList<Integer>(edges.keySet());
Collections.sort(lstVarIds);
// create a MIDD path from list of edges, start from lowest var-id
InternalNode<?> root = null;
InternalNode<?> currentNode = null;
AbstractEdge<?> currentEdge = null;
Iterator<Integer> lstIt = lstVarIds.iterator();
while (lstIt.hasNext()) {
Integer varId = lstIt.next();
AbstractEdge<?> e = edges.get(varId);
// default is NotApplicable, unless the "MustBePresent" is set to "true"
String attrId = attrMapper.getAttributeId(varId);
boolean isAttrMustBePresent = intervals.get(attrId).isMustBePresent;
InternalNodeState nodeState = new InternalNodeState(isAttrMustBePresent ? DecisionType.Indeterminate : DecisionType.NotApplicable);
InternalNode<?> node = NodeUtils.createInternalNode(varId, nodeState, e.getType());
if (root == null) {
root = node; // root points to the start of the MIDD path
currentNode = node;
currentEdge = e;
} else {
currentNode.addChild(currentEdge, node);
currentNode = node;
currentEdge = e;
}
}
// the tail points to the true clause
currentNode.addChild(currentEdge, ExternalNode.newInstance()); // add a true-value external node
return root;
} | [
"public",
"AbstractNode",
"createFromConjunctionClauses",
"(",
"Map",
"<",
"String",
",",
"AttributeInfo",
">",
"intervals",
")",
"throws",
"MIDDParsingException",
",",
"MIDDException",
"{",
"if",
"(",
"intervals",
"==",
"null",
"||",
"intervals",
".",
"size",
"("... | Create a MIDD from conjunctions of intervals
@param intervals
@return
@throws MIDDParsingException
@throws MIDDException | [
"Create",
"a",
"MIDD",
"from",
"conjunctions",
"of",
"intervals"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/xacml/policy/parsers/AnyOfExpression.java#L86-L136 | train |
goodow/realtime-json | src/main/java/com/goodow/realtime/json/impl/Base64.java | Base64.getAlphabet | private final static byte[] getAlphabet(final int options) {
if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) {
return Base64._URL_SAFE_ALPHABET;
} else if ((options & Base64.ORDERED) == Base64.ORDERED) {
return Base64._ORDERED_ALPHABET;
} else {
return Base64._STANDARD_ALPHABET;
}
} | java | private final static byte[] getAlphabet(final int options) {
if ((options & Base64.URL_SAFE) == Base64.URL_SAFE) {
return Base64._URL_SAFE_ALPHABET;
} else if ((options & Base64.ORDERED) == Base64.ORDERED) {
return Base64._ORDERED_ALPHABET;
} else {
return Base64._STANDARD_ALPHABET;
}
} | [
"private",
"final",
"static",
"byte",
"[",
"]",
"getAlphabet",
"(",
"final",
"int",
"options",
")",
"{",
"if",
"(",
"(",
"options",
"&",
"Base64",
".",
"URL_SAFE",
")",
"==",
"Base64",
".",
"URL_SAFE",
")",
"{",
"return",
"Base64",
".",
"_URL_SAFE_ALPHAB... | Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's
possible, though silly, to specify ORDERED and URLSAFE in which case one of them will be
picked, though there is no guarantee as to which one will be picked. | [
"Returns",
"one",
"of",
"the",
"_SOMETHING_ALPHABET",
"byte",
"arrays",
"depending",
"on",
"the",
"options",
"specified",
".",
"It",
"s",
"possible",
"though",
"silly",
"to",
"specify",
"ORDERED",
"and",
"URLSAFE",
"in",
"which",
"case",
"one",
"of",
"them",
... | be2f5a8cab27afa052583ae2e09f6f7975d8cb0c | https://github.com/goodow/realtime-json/blob/be2f5a8cab27afa052583ae2e09f6f7975d8cb0c/src/main/java/com/goodow/realtime/json/impl/Base64.java#L1655-L1664 | train |
goodow/realtime-json | src/main/java/com/goodow/realtime/json/impl/Base64.java | Base64.usage | private final static void usage(final String msg) {
System.err.println(msg);
System.err.println("Usage: java Base64 -e|-d inputfile outputfile");
} | java | private final static void usage(final String msg) {
System.err.println(msg);
System.err.println("Usage: java Base64 -e|-d inputfile outputfile");
} | [
"private",
"final",
"static",
"void",
"usage",
"(",
"final",
"String",
"msg",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"msg",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"\"Usage: java Base64 -e|-d inputfile outputfile\"",
")",
";",
"}"
... | Prints command line usage.
@param msg A message to include with usage info. | [
"Prints",
"command",
"line",
"usage",
"."
] | be2f5a8cab27afa052583ae2e09f6f7975d8cb0c | https://github.com/goodow/realtime-json/blob/be2f5a8cab27afa052583ae2e09f6f7975d8cb0c/src/main/java/com/goodow/realtime/json/impl/Base64.java#L1689-L1692 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/impl/HttpCookie.java | HttpCookie.toHeader | public String toHeader() {
StringBuilder header = new StringBuilder();
header.append(name).append('=').append(value);
if (domain != null) {
header.append("; ").append("Domain=").append(domain);
}
if (path != null) {
header.append("; ").append("Path=").append(path);
}
if (expireTime > -1) {
header.append("; ").append("Expires=").append(RFC_DATEFORMAT.format(new Date(expireTime)));
}
if (secure) {
header.append("; ").append("Secure");
}
return header.toString();
} | java | public String toHeader() {
StringBuilder header = new StringBuilder();
header.append(name).append('=').append(value);
if (domain != null) {
header.append("; ").append("Domain=").append(domain);
}
if (path != null) {
header.append("; ").append("Path=").append(path);
}
if (expireTime > -1) {
header.append("; ").append("Expires=").append(RFC_DATEFORMAT.format(new Date(expireTime)));
}
if (secure) {
header.append("; ").append("Secure");
}
return header.toString();
} | [
"public",
"String",
"toHeader",
"(",
")",
"{",
"StringBuilder",
"header",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"header",
".",
"append",
"(",
"name",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"value",
")",
";",
"if",
"(",
"d... | Transforms this cookie into a Set-Cookie header field
@return The header | [
"Transforms",
"this",
"cookie",
"into",
"a",
"Set",
"-",
"Cookie",
"header",
"field"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/impl/HttpCookie.java#L146-L162 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/Util.java | Util.generateRandomString | public static String generateRandomString(int nbytes) {
byte[] salt = new byte[nbytes];
Random r = new SecureRandom();
r.nextBytes(salt);
return bytesToHex(salt);
} | java | public static String generateRandomString(int nbytes) {
byte[] salt = new byte[nbytes];
Random r = new SecureRandom();
r.nextBytes(salt);
return bytesToHex(salt);
} | [
"public",
"static",
"String",
"generateRandomString",
"(",
"int",
"nbytes",
")",
"{",
"byte",
"[",
"]",
"salt",
"=",
"new",
"byte",
"[",
"nbytes",
"]",
";",
"Random",
"r",
"=",
"new",
"SecureRandom",
"(",
")",
";",
"r",
".",
"nextBytes",
"(",
"salt",
... | Generate a random string with a certain entropy.
This creates a random string with the entropy of nbytes and encodes
that string in hex format. That means, the returned string will be
twice as long as the requested entropy.
<p>
The string will be suitable for use in URLs or HTTP headers etc. without
further escaping.
</p>
@param nbytes Number of bytes for entryopy
@return Hex encoded random string of length 2 x nbytes. | [
"Generate",
"a",
"random",
"string",
"with",
"a",
"certain",
"entropy",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/Util.java#L55-L60 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/Util.java | Util.fixedTimeEqual | public static boolean fixedTimeEqual(String lhs, String rhs) {
boolean equal = (lhs.length() == rhs.length() ? true : false);
// If not equal, work on a single operand to have same length.
if(!equal) {
rhs = lhs;
}
int len = lhs.length();
for(int i=0;i<len;i++) {
if(lhs.charAt(i) == rhs.charAt(i)) {
equal = equal && true;
} else {
equal = equal && false;
}
}
return equal;
} | java | public static boolean fixedTimeEqual(String lhs, String rhs) {
boolean equal = (lhs.length() == rhs.length() ? true : false);
// If not equal, work on a single operand to have same length.
if(!equal) {
rhs = lhs;
}
int len = lhs.length();
for(int i=0;i<len;i++) {
if(lhs.charAt(i) == rhs.charAt(i)) {
equal = equal && true;
} else {
equal = equal && false;
}
}
return equal;
} | [
"public",
"static",
"boolean",
"fixedTimeEqual",
"(",
"String",
"lhs",
",",
"String",
"rhs",
")",
"{",
"boolean",
"equal",
"=",
"(",
"lhs",
".",
"length",
"(",
")",
"==",
"rhs",
".",
"length",
"(",
")",
"?",
"true",
":",
"false",
")",
";",
"// If not... | Fixed time comparison of two strings.
Fixed time comparison is necessary in order to prevent attacks analyzing differences in
verification time for corrupted tokens.
@param lhs Left hand side operand
@param rhs Right hadn side operand
@return true if the strings are equal, false otherwise. | [
"Fixed",
"time",
"comparison",
"of",
"two",
"strings",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/Util.java#L71-L89 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/content/ContentTypeMap.java | ContentTypeMap.initialize | private void initialize(InputStream input) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
String line;
Matcher m;
while ((line = reader.readLine()) != null) {
m = TYPE_PATTERN.matcher(line);
if (m.find()) {
String type = m.group(1);
String[] extensions = m.group(2).split(" ");
for (String extension : extensions) {
contentTypes.put(extension, type);
}
}
}
} catch (IOException e) {
// Unable to load
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | java | private void initialize(InputStream input) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(input));
String line;
Matcher m;
while ((line = reader.readLine()) != null) {
m = TYPE_PATTERN.matcher(line);
if (m.find()) {
String type = m.group(1);
String[] extensions = m.group(2).split(" ");
for (String extension : extensions) {
contentTypes.put(extension, type);
}
}
}
} catch (IOException e) {
// Unable to load
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | [
"private",
"void",
"initialize",
"(",
"InputStream",
"input",
")",
"{",
"BufferedReader",
"reader",
"=",
"null",
";",
"try",
"{",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"input",
")",
")",
";",
"String",
"line",
";",
"... | Read and parse the type file.
@param input The input stream to read the file from. | [
"Read",
"and",
"parse",
"the",
"type",
"file",
"."
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/content/ContentTypeMap.java#L51-L84 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/content/ContentTypeMap.java | ContentTypeMap.getExtension | private static final String getExtension(String fileName) {
return fileName.indexOf('.') == -1 ? null : fileName.substring(fileName.lastIndexOf('.') + 1);
} | java | private static final String getExtension(String fileName) {
return fileName.indexOf('.') == -1 ? null : fileName.substring(fileName.lastIndexOf('.') + 1);
} | [
"private",
"static",
"final",
"String",
"getExtension",
"(",
"String",
"fileName",
")",
"{",
"return",
"fileName",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
"?",
"null",
":",
"fileName",
".",
"substring",
"(",
"fileName",
".",
"lastIndexOf",
"(... | Get the extension of a file.
@param fileName The file name.
@return The file extension. | [
"Get",
"the",
"extension",
"of",
"a",
"file",
"."
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/content/ContentTypeMap.java#L97-L99 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/midd/partition/Partition.java | Partition.containsInterval | public boolean containsInterval(Interval<T> i) {
for (Interval<T> item : intervals) {
if (item.contains(i)) {
return true;
}
}
return false;
} | java | public boolean containsInterval(Interval<T> i) {
for (Interval<T> item : intervals) {
if (item.contains(i)) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"containsInterval",
"(",
"Interval",
"<",
"T",
">",
"i",
")",
"{",
"for",
"(",
"Interval",
"<",
"T",
">",
"item",
":",
"intervals",
")",
"{",
"if",
"(",
"item",
".",
"contains",
"(",
"i",
")",
")",
"{",
"return",
"true",
";",
... | Return true if the argument interval is a subset of an interval of the partition
@param i
@return | [
"Return",
"true",
"if",
"the",
"argument",
"interval",
"is",
"a",
"subset",
"of",
"an",
"interval",
"of",
"the",
"partition"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/midd/partition/Partition.java#L55-L64 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java | HttpResponse.addHeader | public void addHeader(String key, Object value) {
List<Object> values = headers.get(key);
if (values == null) {
headers.put(key, values = new ArrayList<Object>());
}
values.add(value);
} | java | public void addHeader(String key, Object value) {
List<Object> values = headers.get(key);
if (values == null) {
headers.put(key, values = new ArrayList<Object>());
}
values.add(value);
} | [
"public",
"void",
"addHeader",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"List",
"<",
"Object",
">",
"values",
"=",
"headers",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"values",
"==",
"null",
")",
"{",
"headers",
".",
"put",
"(",
... | Add a header to the response
@param key The header name
@param value The header value | [
"Add",
"a",
"header",
"to",
"the",
"response"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java#L135-L141 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java | HttpResponse.setResponse | public void setResponse(String response) {
this.response = response;
try {
this.responseLength = response.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
this.responseLength = response.length();
}
} | java | public void setResponse(String response) {
this.response = response;
try {
this.responseLength = response.getBytes("UTF-8").length;
} catch (UnsupportedEncodingException e) {
this.responseLength = response.length();
}
} | [
"public",
"void",
"setResponse",
"(",
"String",
"response",
")",
"{",
"this",
".",
"response",
"=",
"response",
";",
"try",
"{",
"this",
".",
"responseLength",
"=",
"response",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
".",
"length",
";",
"}",
"catch",
"("... | Set the response string
@param response The response to set | [
"Set",
"the",
"response",
"string"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java#L177-L184 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java | HttpResponse.setResponse | public void setResponse(InputStream response) {
this.response = response;
try {
this.responseLength = response.available();
} catch (IOException e) {
// This shouldn't happen.
}
} | java | public void setResponse(InputStream response) {
this.response = response;
try {
this.responseLength = response.available();
} catch (IOException e) {
// This shouldn't happen.
}
} | [
"public",
"void",
"setResponse",
"(",
"InputStream",
"response",
")",
"{",
"this",
".",
"response",
"=",
"response",
";",
"try",
"{",
"this",
".",
"responseLength",
"=",
"response",
".",
"available",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
... | Set the response Input Stream
@param response The response to set | [
"Set",
"the",
"response",
"Input",
"Stream"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/impl/HttpResponse.java#L191-L198 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/HttpServer.java | HttpServer.start | public void start() {
if (socket == null) {
throw new RuntimeException("Cannot bind a server that has not been initialized!");
}
running = true;
Thread t = new Thread(this);
t.setName("HttpServer");
t.start();
} | java | public void start() {
if (socket == null) {
throw new RuntimeException("Cannot bind a server that has not been initialized!");
}
running = true;
Thread t = new Thread(this);
t.setName("HttpServer");
t.start();
} | [
"public",
"void",
"start",
"(",
")",
"{",
"if",
"(",
"socket",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot bind a server that has not been initialized!\"",
")",
";",
"}",
"running",
"=",
"true",
";",
"Thread",
"t",
"=",
"new",
... | Start the server in a new thread | [
"Start",
"the",
"server",
"in",
"a",
"new",
"thread"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/HttpServer.java#L96-L105 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/HttpServer.java | HttpServer.run | @Override
public void run() {
while (running) {
try {
// Read the request
service.execute(new HttpSession(this, socket.accept()));
} catch (IOException e) {
// Ignore mostly.
}
}
} | java | @Override
public void run() {
while (running) {
try {
// Read the request
service.execute(new HttpSession(this, socket.accept()));
} catch (IOException e) {
// Ignore mostly.
}
}
} | [
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"while",
"(",
"running",
")",
"{",
"try",
"{",
"// Read the request",
"service",
".",
"execute",
"(",
"new",
"HttpSession",
"(",
"this",
",",
"socket",
".",
"accept",
"(",
")",
")",
")",
";",
"... | Run and process requests. | [
"Run",
"and",
"process",
"requests",
"."
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/HttpServer.java#L122-L132 | train |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/HttpServer.java | HttpServer.dispatchRequest | public void dispatchRequest(HttpRequest httpRequest) throws IOException {
for (HttpRequestHandler handler : handlers) {
HttpResponse resp = handler.handleRequest(httpRequest);
if (resp != null) {
httpRequest.getSession().sendResponse(resp);
return;
}
}
if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
// If it's still here nothing handled it.
httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
}
} | java | public void dispatchRequest(HttpRequest httpRequest) throws IOException {
for (HttpRequestHandler handler : handlers) {
HttpResponse resp = handler.handleRequest(httpRequest);
if (resp != null) {
httpRequest.getSession().sendResponse(resp);
return;
}
}
if (!hasCapability(HttpCapability.THREADEDRESPONSE)) {
// If it's still here nothing handled it.
httpRequest.getSession().sendResponse(new HttpResponse(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.toString()));
}
} | [
"public",
"void",
"dispatchRequest",
"(",
"HttpRequest",
"httpRequest",
")",
"throws",
"IOException",
"{",
"for",
"(",
"HttpRequestHandler",
"handler",
":",
"handlers",
")",
"{",
"HttpResponse",
"resp",
"=",
"handler",
".",
"handleRequest",
"(",
"httpRequest",
")"... | Dispatch a request to all handlers
@param httpRequest The request to dispatch
@throws IOException If an error occurs while sending the response from the
handler | [
"Dispatch",
"a",
"request",
"to",
"all",
"handlers"
] | 7c965b6910dc6ee4ea46d7ae188c0751b98c2615 | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/HttpServer.java#L179-L191 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java | HawkWwwAuthenticateContext.createWwwAuthenticateHeader | public WwwAuthenticateHeader createWwwAuthenticateHeader()
throws HawkException {
WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader
.wwwAuthenticate();
if (hasTs()) {
if (!hasTsm()) {
String hmac = this.generateHmac();
headerBuilder.ts(getTs()).tsm(hmac);
} else {
headerBuilder.ts(getTs()).tsm(getTsm());
}
if(hasError()) {
throw new IllegalStateException("Context cannot contain error and ts at the same time.");
}
}
if(hasError()) {
headerBuilder.error(this.error);
}
return headerBuilder.build();
} | java | public WwwAuthenticateHeader createWwwAuthenticateHeader()
throws HawkException {
WwwAuthenticateBuilder headerBuilder = WwwAuthenticateHeader
.wwwAuthenticate();
if (hasTs()) {
if (!hasTsm()) {
String hmac = this.generateHmac();
headerBuilder.ts(getTs()).tsm(hmac);
} else {
headerBuilder.ts(getTs()).tsm(getTsm());
}
if(hasError()) {
throw new IllegalStateException("Context cannot contain error and ts at the same time.");
}
}
if(hasError()) {
headerBuilder.error(this.error);
}
return headerBuilder.build();
} | [
"public",
"WwwAuthenticateHeader",
"createWwwAuthenticateHeader",
"(",
")",
"throws",
"HawkException",
"{",
"WwwAuthenticateBuilder",
"headerBuilder",
"=",
"WwwAuthenticateHeader",
".",
"wwwAuthenticate",
"(",
")",
";",
"if",
"(",
"hasTs",
"(",
")",
")",
"{",
"if",
... | Create a WWW-Authenticate header from this HawkWwwAuthenticateContext.
The method returns a new WwwAuthenticateHeader instance from the data
contained in this HawkWwwAuthenticateContext.
<p>
If the context has a timestamp but no timestamp HMAC, a new HMAC for the
timestamp is created using the supplied credentials.
@see net.jalg.hawkj.WwwAuthenticateHeader
@return The newly created header object.
@throws HawkException | [
"Create",
"a",
"WWW",
"-",
"Authenticate",
"header",
"from",
"this",
"HawkWwwAuthenticateContext",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L139-L162 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java | HawkWwwAuthenticateContext.isValidTimestampMac | public boolean isValidTimestampMac(String hmac) throws HawkException {
String this_hmac = this.generateHmac();
return Util.fixedTimeEqual(this_hmac, hmac);
} | java | public boolean isValidTimestampMac(String hmac) throws HawkException {
String this_hmac = this.generateHmac();
return Util.fixedTimeEqual(this_hmac, hmac);
} | [
"public",
"boolean",
"isValidTimestampMac",
"(",
"String",
"hmac",
")",
"throws",
"HawkException",
"{",
"String",
"this_hmac",
"=",
"this",
".",
"generateHmac",
"(",
")",
";",
"return",
"Util",
".",
"fixedTimeEqual",
"(",
"this_hmac",
",",
"hmac",
")",
";",
... | Check whether a given HMAC value matches the HMAC for the timestamp in
this HawkWwwAuthenticateContext.
@param hmac
The HMAC value to test.
@return true if the HMAC matches the HMAC computed for this context,
false otherwise.
@throws HawkException | [
"Check",
"whether",
"a",
"given",
"HMAC",
"value",
"matches",
"the",
"HMAC",
"for",
"the",
"timestamp",
"in",
"this",
"HawkWwwAuthenticateContext",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L174-L177 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java | HawkWwwAuthenticateContext.getBaseString | private String getBaseString() {
if (!hasTs()) {
throw new IllegalStateException(
"This HawkWwwAuthenticateContext has no timestamp");
}
return new StringBuilder(HAWK_TS_PREFIX).append(SLF).append(getTs())
.append(SLF).toString();
} | java | private String getBaseString() {
if (!hasTs()) {
throw new IllegalStateException(
"This HawkWwwAuthenticateContext has no timestamp");
}
return new StringBuilder(HAWK_TS_PREFIX).append(SLF).append(getTs())
.append(SLF).toString();
} | [
"private",
"String",
"getBaseString",
"(",
")",
"{",
"if",
"(",
"!",
"hasTs",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"This HawkWwwAuthenticateContext has no timestamp\"",
")",
";",
"}",
"return",
"new",
"StringBuilder",
"(",
"HAWK_TS_P... | Generate base string for timestamp HMAC generation.
@return | [
"Generate",
"base",
"string",
"for",
"timestamp",
"HMAC",
"generation",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L184-L191 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java | HawkWwwAuthenticateContext.generateHmac | private String generateHmac() throws HawkException {
String baseString = getBaseString();
Mac mac;
try {
mac = Mac.getInstance(getAlgorithm().getMacName());
} catch (NoSuchAlgorithmException e) {
throw new HawkException("Unknown algorithm "
+ getAlgorithm().getMacName(), e);
}
SecretKeySpec secret_key = new SecretKeySpec(getKey().getBytes(
Charsets.UTF_8), getAlgorithm().getMacName());
try {
mac.init(secret_key);
} catch (InvalidKeyException e) {
throw new HawkException("Key is invalid ", e);
}
return new String(Base64.encodeBase64(mac.doFinal(baseString
.getBytes(Charsets.UTF_8))), Charsets.UTF_8);
} | java | private String generateHmac() throws HawkException {
String baseString = getBaseString();
Mac mac;
try {
mac = Mac.getInstance(getAlgorithm().getMacName());
} catch (NoSuchAlgorithmException e) {
throw new HawkException("Unknown algorithm "
+ getAlgorithm().getMacName(), e);
}
SecretKeySpec secret_key = new SecretKeySpec(getKey().getBytes(
Charsets.UTF_8), getAlgorithm().getMacName());
try {
mac.init(secret_key);
} catch (InvalidKeyException e) {
throw new HawkException("Key is invalid ", e);
}
return new String(Base64.encodeBase64(mac.doFinal(baseString
.getBytes(Charsets.UTF_8))), Charsets.UTF_8);
} | [
"private",
"String",
"generateHmac",
"(",
")",
"throws",
"HawkException",
"{",
"String",
"baseString",
"=",
"getBaseString",
"(",
")",
";",
"Mac",
"mac",
";",
"try",
"{",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"getAlgorithm",
"(",
")",
".",
"getMacNam... | Generate an HMAC from the context ts parameter.
@return
@throws HawkException | [
"Generate",
"an",
"HMAC",
"from",
"the",
"context",
"ts",
"parameter",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L205-L227 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java | HawkWwwAuthenticateContext.tsAndTsm | public static HawkWwwAuthenticateContextBuilder_A tsAndTsm(long l,
String tsm) {
return new HawkWwwAuthenticateContextBuilder().ts(l).tsm(tsm);
} | java | public static HawkWwwAuthenticateContextBuilder_A tsAndTsm(long l,
String tsm) {
return new HawkWwwAuthenticateContextBuilder().ts(l).tsm(tsm);
} | [
"public",
"static",
"HawkWwwAuthenticateContextBuilder_A",
"tsAndTsm",
"(",
"long",
"l",
",",
"String",
"tsm",
")",
"{",
"return",
"new",
"HawkWwwAuthenticateContextBuilder",
"(",
")",
".",
"ts",
"(",
"l",
")",
".",
"tsm",
"(",
"tsm",
")",
";",
"}"
] | Create a new HawkWwwAuthenticateContextBuilder_A, initialized with
timestamp and timestamp hmac.
@param l
The timestamp
@param tsm
The timestamp HMAC
@return A new Builder with the parameters set. | [
"Create",
"a",
"new",
"HawkWwwAuthenticateContextBuilder_A",
"initialized",
"with",
"timestamp",
"and",
"timestamp",
"hmac",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkWwwAuthenticateContext.java#L239-L242 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/xacml/AttributeMapper.java | AttributeMapper.addAttribute | public int addAttribute(String attrId) {
if (attributeMapper.containsKey(attrId)) {
return attributeMapper.get(attrId); // attribute-id has existed
}
attributeMapper.put(attrId, varIdCounter);
varIdCounter++;
return attributeMapper.get(attrId);
} | java | public int addAttribute(String attrId) {
if (attributeMapper.containsKey(attrId)) {
return attributeMapper.get(attrId); // attribute-id has existed
}
attributeMapper.put(attrId, varIdCounter);
varIdCounter++;
return attributeMapper.get(attrId);
} | [
"public",
"int",
"addAttribute",
"(",
"String",
"attrId",
")",
"{",
"if",
"(",
"attributeMapper",
".",
"containsKey",
"(",
"attrId",
")",
")",
"{",
"return",
"attributeMapper",
".",
"get",
"(",
"attrId",
")",
";",
"// attribute-id has existed",
"}",
"attribute... | Add a new attribute-id to the map, return the variable id. If the attribute existed, throws exception
@param attrId
@return
@throws MIDDParsingException | [
"Add",
"a",
"new",
"attribute",
"-",
"id",
"to",
"the",
"map",
"return",
"the",
"variable",
"id",
".",
"If",
"the",
"attribute",
"existed",
"throws",
"exception"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/xacml/AttributeMapper.java#L56-L64 | train |
canhnt/sne-xacml | sne-xacml/src/main/java/nl/uva/sne/xacml/AttributeMapper.java | AttributeMapper.getAttributeId | public String getAttributeId(int variableId) throws MIDDParsingException {
if (!attributeMapper.containsValue(variableId)) {
throw new MIDDParsingException("Variable identifier '" + variableId + "' not found");
}
for (String attrId : attributeMapper.keySet()) {
if (attributeMapper.get(attrId) == variableId) {
return attrId;
}
}
throw new MIDDParsingException("Variable identifier '" + variableId + "' not found");
} | java | public String getAttributeId(int variableId) throws MIDDParsingException {
if (!attributeMapper.containsValue(variableId)) {
throw new MIDDParsingException("Variable identifier '" + variableId + "' not found");
}
for (String attrId : attributeMapper.keySet()) {
if (attributeMapper.get(attrId) == variableId) {
return attrId;
}
}
throw new MIDDParsingException("Variable identifier '" + variableId + "' not found");
} | [
"public",
"String",
"getAttributeId",
"(",
"int",
"variableId",
")",
"throws",
"MIDDParsingException",
"{",
"if",
"(",
"!",
"attributeMapper",
".",
"containsValue",
"(",
"variableId",
")",
")",
"{",
"throw",
"new",
"MIDDParsingException",
"(",
"\"Variable identifier... | Return the attribute identifier from the variable-id
@param variableId
@return
@throws MIDDParsingException | [
"Return",
"the",
"attribute",
"identifier",
"from",
"the",
"variable",
"-",
"id"
] | 7ffca16bf558d2c3ee16181d926f066ab1de75b2 | https://github.com/canhnt/sne-xacml/blob/7ffca16bf558d2c3ee16181d926f066ab1de75b2/sne-xacml/src/main/java/nl/uva/sne/xacml/AttributeMapper.java#L84-L96 | train |
svanoort/rest-compress | rest-compress-lib/src/main/java/com/restcompress/provider/LZFEncodingInterceptor.java | LZFEncodingInterceptor.write | public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
if (encoding != null && encoding.toString().equalsIgnoreCase("lzf")) {
OutputStream old = context.getOutputStream();
// constructor writes to underlying OS causing headers to be written.
CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream(old, null);
// Any content length set will be obsolete
context.getHeaders().remove("Content-Length");
context.setOutputStream(lzfOutputStream);
try {
context.proceed();
} finally {
if (lzfOutputStream.getLzf() != null) lzfOutputStream.getLzf().flush();
context.setOutputStream(old);
}
return;
} else {
context.proceed();
}
} | java | public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException {
Object encoding = context.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
if (encoding != null && encoding.toString().equalsIgnoreCase("lzf")) {
OutputStream old = context.getOutputStream();
// constructor writes to underlying OS causing headers to be written.
CommittedLZFOutputStream lzfOutputStream = new CommittedLZFOutputStream(old, null);
// Any content length set will be obsolete
context.getHeaders().remove("Content-Length");
context.setOutputStream(lzfOutputStream);
try {
context.proceed();
} finally {
if (lzfOutputStream.getLzf() != null) lzfOutputStream.getLzf().flush();
context.setOutputStream(old);
}
return;
} else {
context.proceed();
}
} | [
"public",
"void",
"write",
"(",
"MessageBodyWriterContext",
"context",
")",
"throws",
"IOException",
",",
"WebApplicationException",
"{",
"Object",
"encoding",
"=",
"context",
".",
"getHeaders",
"(",
")",
".",
"getFirst",
"(",
"HttpHeaders",
".",
"CONTENT_ENCODING",... | Grab the outgoing message, if encoding is set to LZF, then wrap the OutputStream in an LZF OutputStream
before sending it on its merry way, compressing all the time.
Note: strips out the content-length header because the compression changes that unpredictably
@param context
@throws IOException
@throws WebApplicationException | [
"Grab",
"the",
"outgoing",
"message",
"if",
"encoding",
"is",
"set",
"to",
"LZF",
"then",
"wrap",
"the",
"OutputStream",
"in",
"an",
"LZF",
"OutputStream",
"before",
"sending",
"it",
"on",
"its",
"merry",
"way",
"compressing",
"all",
"the",
"time",
"."
] | 4e34fcbe0d1b510962a93509a78b6a8ade234606 | https://github.com/svanoort/rest-compress/blob/4e34fcbe0d1b510962a93509a78b6a8ade234606/rest-compress-lib/src/main/java/com/restcompress/provider/LZFEncodingInterceptor.java#L65-L87 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkContext.java | HawkContext.createAuthorizationHeader | public AuthorizationHeader createAuthorizationHeader() throws HawkException {
String hmac = this.generateHmac();
AuthorizationBuilder headerBuilder = AuthorizationHeader
.authorization().ts(ts).nonce(nonce).id(getId()).mac(hmac);
if (hasExt()) {
headerBuilder.ext(getExt());
}
if (hasApp()) {
headerBuilder.app(getApp());
if (hasDlg()) {
headerBuilder.dlg(getDlg());
}
}
if (hasHash()) {
headerBuilder.hash(getHash());
}
return headerBuilder.build();
} | java | public AuthorizationHeader createAuthorizationHeader() throws HawkException {
String hmac = this.generateHmac();
AuthorizationBuilder headerBuilder = AuthorizationHeader
.authorization().ts(ts).nonce(nonce).id(getId()).mac(hmac);
if (hasExt()) {
headerBuilder.ext(getExt());
}
if (hasApp()) {
headerBuilder.app(getApp());
if (hasDlg()) {
headerBuilder.dlg(getDlg());
}
}
if (hasHash()) {
headerBuilder.hash(getHash());
}
return headerBuilder.build();
} | [
"public",
"AuthorizationHeader",
"createAuthorizationHeader",
"(",
")",
"throws",
"HawkException",
"{",
"String",
"hmac",
"=",
"this",
".",
"generateHmac",
"(",
")",
";",
"AuthorizationBuilder",
"headerBuilder",
"=",
"AuthorizationHeader",
".",
"authorization",
"(",
"... | Create an Authorization header from this HawkContext.
The method returns a new AuthorizationHeader instance from the data in
this HawkContext. For this the HMAC of the contained data is calculated
and put into the header with the other parameters required by the
specification.
@see net.jalg.hawkj.AuthorizationHeader
@return The newly created header object.
@throws HawkException | [
"Create",
"an",
"Authorization",
"header",
"from",
"this",
"HawkContext",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkContext.java#L208-L229 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkContext.java | HawkContext.verifyServerAuthorizationMatches | public boolean verifyServerAuthorizationMatches(AuthorizationHeader header) {
if (!Util.fixedTimeEqual(header.getId(), this.getId())) {
return false;
}
if (header.getTs() != this.getTs()) {
return false;
}
if (!Util.fixedTimeEqual(header.getNonce(), this.getNonce())) {
return false;
}
return true;
} | java | public boolean verifyServerAuthorizationMatches(AuthorizationHeader header) {
if (!Util.fixedTimeEqual(header.getId(), this.getId())) {
return false;
}
if (header.getTs() != this.getTs()) {
return false;
}
if (!Util.fixedTimeEqual(header.getNonce(), this.getNonce())) {
return false;
}
return true;
} | [
"public",
"boolean",
"verifyServerAuthorizationMatches",
"(",
"AuthorizationHeader",
"header",
")",
"{",
"if",
"(",
"!",
"Util",
".",
"fixedTimeEqual",
"(",
"header",
".",
"getId",
"(",
")",
",",
"this",
".",
"getId",
"(",
")",
")",
")",
"{",
"return",
"fa... | Verify that a given header matches a HawkContext.
This is designed to be used in clients in order to check the incoming
Server-Authorization header.
@param header
The header (usually Server-Authorization)
@return true if the header has the exact same id, ts and nonce. | [
"Verify",
"that",
"a",
"given",
"header",
"matches",
"a",
"HawkContext",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkContext.java#L241-L253 | train |
algermissen/hawkj | src/main/java/net/jalg/hawkj/HawkContext.java | HawkContext.isValidMac | public boolean isValidMac(String hmac) throws HawkException {
String this_hmac = this.generateHmac();
return Util.fixedTimeEqual(this_hmac, hmac);
} | java | public boolean isValidMac(String hmac) throws HawkException {
String this_hmac = this.generateHmac();
return Util.fixedTimeEqual(this_hmac, hmac);
} | [
"public",
"boolean",
"isValidMac",
"(",
"String",
"hmac",
")",
"throws",
"HawkException",
"{",
"String",
"this_hmac",
"=",
"this",
".",
"generateHmac",
"(",
")",
";",
"return",
"Util",
".",
"fixedTimeEqual",
"(",
"this_hmac",
",",
"hmac",
")",
";",
"}"
] | Check whether a given HMAC value matches the HMAC for this HawkContext.
@param hmac
The HMAC value to test.
@return true if the HMAC matches the HMAC computed for this context,
false otherwise.
@throws HawkException | [
"Check",
"whether",
"a",
"given",
"HMAC",
"value",
"matches",
"the",
"HMAC",
"for",
"this",
"HawkContext",
"."
] | f798a20f058474bcfe761f7c5c02afee17326c71 | https://github.com/algermissen/hawkj/blob/f798a20f058474bcfe761f7c5c02afee17326c71/src/main/java/net/jalg/hawkj/HawkContext.java#L264-L267 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.