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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
A-pZ/struts2-thymeleaf3-plugin | src/main/java/serendip/struts/plugins/thymeleaf/diarect/FieldErrorAttributeProcessor.java | FieldErrorAttributeProcessor.getFieldValue | protected Object getFieldValue(String fieldname) {
ActionContext actionCtx = ActionContext.getContext();
ValueStack valueStack = actionCtx.getValueStack();
Object value = valueStack.findValue(fieldname, false);
String overwriteValue = getOverwriteValue(fieldname);
if ( overwriteValue != null ) {
return overwriteValue;
}
return value;
} | java | protected Object getFieldValue(String fieldname) {
ActionContext actionCtx = ActionContext.getContext();
ValueStack valueStack = actionCtx.getValueStack();
Object value = valueStack.findValue(fieldname, false);
String overwriteValue = getOverwriteValue(fieldname);
if ( overwriteValue != null ) {
return overwriteValue;
}
return value;
} | [
"protected",
"Object",
"getFieldValue",
"(",
"String",
"fieldname",
")",
"{",
"ActionContext",
"actionCtx",
"=",
"ActionContext",
".",
"getContext",
"(",
")",
";",
"ValueStack",
"valueStack",
"=",
"actionCtx",
".",
"getValueStack",
"(",
")",
";",
"Object",
"value",
"=",
"valueStack",
".",
"findValue",
"(",
"fieldname",
",",
"false",
")",
";",
"String",
"overwriteValue",
"=",
"getOverwriteValue",
"(",
"fieldname",
")",
";",
"if",
"(",
"overwriteValue",
"!=",
"null",
")",
"{",
"return",
"overwriteValue",
";",
"}",
"return",
"value",
";",
"}"
] | Return Strus2 field value.
@param fieldname fieldname
@return fieldvalue | [
"Return",
"Strus2",
"field",
"value",
"."
] | 36a4609c1d0a36019784c6dba951c9b27dcc8802 | https://github.com/A-pZ/struts2-thymeleaf3-plugin/blob/36a4609c1d0a36019784c6dba951c9b27dcc8802/src/main/java/serendip/struts/plugins/thymeleaf/diarect/FieldErrorAttributeProcessor.java#L131-L142 | train |
A-pZ/struts2-thymeleaf3-plugin | src/main/java/serendip/struts/plugins/thymeleaf/diarect/FieldErrorAttributeProcessor.java | FieldErrorAttributeProcessor.getOverwriteValue | protected String getOverwriteValue(String fieldname) {
ActionContext ctx = ServletActionContext.getContext();
ValueStack stack = ctx.getValueStack();
Map<Object ,Object> overrideMap = stack.getExprOverrides();
// If convertion error has not, do nothing.
if ( overrideMap == null || overrideMap.isEmpty()) {
return null;
}
if (! overrideMap.containsKey(fieldname)) {
return null;
}
String convertionValue = (String)overrideMap.get(fieldname);
// Struts2-Conponent is wrapped String quote, which erase for output value.
String altString = StringEscapeUtils.unescapeJava(convertionValue);
altString = altString.substring(1, altString.length() -1);
return altString;
} | java | protected String getOverwriteValue(String fieldname) {
ActionContext ctx = ServletActionContext.getContext();
ValueStack stack = ctx.getValueStack();
Map<Object ,Object> overrideMap = stack.getExprOverrides();
// If convertion error has not, do nothing.
if ( overrideMap == null || overrideMap.isEmpty()) {
return null;
}
if (! overrideMap.containsKey(fieldname)) {
return null;
}
String convertionValue = (String)overrideMap.get(fieldname);
// Struts2-Conponent is wrapped String quote, which erase for output value.
String altString = StringEscapeUtils.unescapeJava(convertionValue);
altString = altString.substring(1, altString.length() -1);
return altString;
} | [
"protected",
"String",
"getOverwriteValue",
"(",
"String",
"fieldname",
")",
"{",
"ActionContext",
"ctx",
"=",
"ServletActionContext",
".",
"getContext",
"(",
")",
";",
"ValueStack",
"stack",
"=",
"ctx",
".",
"getValueStack",
"(",
")",
";",
"Map",
"<",
"Object",
",",
"Object",
">",
"overrideMap",
"=",
"stack",
".",
"getExprOverrides",
"(",
")",
";",
"// If convertion error has not, do nothing.\r",
"if",
"(",
"overrideMap",
"==",
"null",
"||",
"overrideMap",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"overrideMap",
".",
"containsKey",
"(",
"fieldname",
")",
")",
"{",
"return",
"null",
";",
"}",
"String",
"convertionValue",
"=",
"(",
"String",
")",
"overrideMap",
".",
"get",
"(",
"fieldname",
")",
";",
"// Struts2-Conponent is wrapped String quote, which erase for output value.\r",
"String",
"altString",
"=",
"StringEscapeUtils",
".",
"unescapeJava",
"(",
"convertionValue",
")",
";",
"altString",
"=",
"altString",
".",
"substring",
"(",
"1",
",",
"altString",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"return",
"altString",
";",
"}"
] | If Type-Convertion Error found at Struts2, overwrite request-
parameter same name.
@param fieldname parameter-name
@return request-parameter-value(if convertion error occurs,return from struts2 , not else thymeleaf.) | [
"If",
"Type",
"-",
"Convertion",
"Error",
"found",
"at",
"Struts2",
"overwrite",
"request",
"-",
"parameter",
"same",
"name",
"."
] | 36a4609c1d0a36019784c6dba951c9b27dcc8802 | https://github.com/A-pZ/struts2-thymeleaf3-plugin/blob/36a4609c1d0a36019784c6dba951c9b27dcc8802/src/main/java/serendip/struts/plugins/thymeleaf/diarect/FieldErrorAttributeProcessor.java#L159-L180 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/ProfilePictureView.java | ProfilePictureView.setPresetSize | public final void setPresetSize(int sizeType) {
switch (sizeType) {
case SMALL:
case NORMAL:
case LARGE:
case CUSTOM:
this.presetSizeType = sizeType;
break;
default:
throw new IllegalArgumentException("Must use a predefined preset size");
}
requestLayout();
} | java | public final void setPresetSize(int sizeType) {
switch (sizeType) {
case SMALL:
case NORMAL:
case LARGE:
case CUSTOM:
this.presetSizeType = sizeType;
break;
default:
throw new IllegalArgumentException("Must use a predefined preset size");
}
requestLayout();
} | [
"public",
"final",
"void",
"setPresetSize",
"(",
"int",
"sizeType",
")",
"{",
"switch",
"(",
"sizeType",
")",
"{",
"case",
"SMALL",
":",
"case",
"NORMAL",
":",
"case",
"LARGE",
":",
"case",
"CUSTOM",
":",
"this",
".",
"presetSizeType",
"=",
"sizeType",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Must use a predefined preset size\"",
")",
";",
"}",
"requestLayout",
"(",
")",
";",
"}"
] | Apply a preset size to this profile photo
@param sizeType The size type to apply: SMALL, NORMAL or LARGE | [
"Apply",
"a",
"preset",
"size",
"to",
"this",
"profile",
"photo"
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/ProfilePictureView.java#L166-L180 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/ProfilePictureView.java | ProfilePictureView.setProfileId | public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture();
force = true;
}
this.profileId = profileId;
refreshImage(force);
} | java | public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture();
force = true;
}
this.profileId = profileId;
refreshImage(force);
} | [
"public",
"final",
"void",
"setProfileId",
"(",
"String",
"profileId",
")",
"{",
"boolean",
"force",
"=",
"false",
";",
"if",
"(",
"Utility",
".",
"isNullOrEmpty",
"(",
"this",
".",
"profileId",
")",
"||",
"!",
"this",
".",
"profileId",
".",
"equalsIgnoreCase",
"(",
"profileId",
")",
")",
"{",
"// Clear out the old profilePicture before requesting for the new one.",
"setBlankProfilePicture",
"(",
")",
";",
"force",
"=",
"true",
";",
"}",
"this",
".",
"profileId",
"=",
"profileId",
";",
"refreshImage",
"(",
"force",
")",
";",
"}"
] | Sets the profile Id for this profile photo
@param profileId The profileId
NULL/Empty String will show the blank profile photo | [
"Sets",
"the",
"profile",
"Id",
"for",
"this",
"profile",
"photo"
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/ProfilePictureView.java#L218-L228 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/ProfilePictureView.java | ProfilePictureView.onSaveInstanceState | @Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle instanceState = new Bundle();
instanceState.putParcelable(SUPER_STATE_KEY, superState);
instanceState.putString(PROFILE_ID_KEY, profileId);
instanceState.putInt(PRESET_SIZE_KEY, presetSizeType);
instanceState.putBoolean(IS_CROPPED_KEY, isCropped);
instanceState.putParcelable(BITMAP_KEY, imageContents);
instanceState.putInt(BITMAP_WIDTH_KEY, queryWidth);
instanceState.putInt(BITMAP_HEIGHT_KEY, queryHeight);
instanceState.putBoolean(PENDING_REFRESH_KEY, lastRequest != null);
return instanceState;
} | java | @Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle instanceState = new Bundle();
instanceState.putParcelable(SUPER_STATE_KEY, superState);
instanceState.putString(PROFILE_ID_KEY, profileId);
instanceState.putInt(PRESET_SIZE_KEY, presetSizeType);
instanceState.putBoolean(IS_CROPPED_KEY, isCropped);
instanceState.putParcelable(BITMAP_KEY, imageContents);
instanceState.putInt(BITMAP_WIDTH_KEY, queryWidth);
instanceState.putInt(BITMAP_HEIGHT_KEY, queryHeight);
instanceState.putBoolean(PENDING_REFRESH_KEY, lastRequest != null);
return instanceState;
} | [
"@",
"Override",
"protected",
"Parcelable",
"onSaveInstanceState",
"(",
")",
"{",
"Parcelable",
"superState",
"=",
"super",
".",
"onSaveInstanceState",
"(",
")",
";",
"Bundle",
"instanceState",
"=",
"new",
"Bundle",
"(",
")",
";",
"instanceState",
".",
"putParcelable",
"(",
"SUPER_STATE_KEY",
",",
"superState",
")",
";",
"instanceState",
".",
"putString",
"(",
"PROFILE_ID_KEY",
",",
"profileId",
")",
";",
"instanceState",
".",
"putInt",
"(",
"PRESET_SIZE_KEY",
",",
"presetSizeType",
")",
";",
"instanceState",
".",
"putBoolean",
"(",
"IS_CROPPED_KEY",
",",
"isCropped",
")",
";",
"instanceState",
".",
"putParcelable",
"(",
"BITMAP_KEY",
",",
"imageContents",
")",
";",
"instanceState",
".",
"putInt",
"(",
"BITMAP_WIDTH_KEY",
",",
"queryWidth",
")",
";",
"instanceState",
".",
"putInt",
"(",
"BITMAP_HEIGHT_KEY",
",",
"queryHeight",
")",
";",
"instanceState",
".",
"putBoolean",
"(",
"PENDING_REFRESH_KEY",
",",
"lastRequest",
"!=",
"null",
")",
";",
"return",
"instanceState",
";",
"}"
] | Some of the current state is returned as a Bundle to allow quick restoration
of the ProfilePictureView object in scenarios like orientation changes.
@return a Parcelable containing the current state | [
"Some",
"of",
"the",
"current",
"state",
"is",
"returned",
"as",
"a",
"Bundle",
"to",
"allow",
"quick",
"restoration",
"of",
"the",
"ProfilePictureView",
"object",
"in",
"scenarios",
"like",
"orientation",
"changes",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/ProfilePictureView.java#L315-L329 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/ProfilePictureView.java | ProfilePictureView.onRestoreInstanceState | @Override
protected void onRestoreInstanceState(Parcelable state) {
if (state.getClass() != Bundle.class) {
super.onRestoreInstanceState(state);
} else {
Bundle instanceState = (Bundle)state;
super.onRestoreInstanceState(instanceState.getParcelable(SUPER_STATE_KEY));
profileId = instanceState.getString(PROFILE_ID_KEY);
presetSizeType = instanceState.getInt(PRESET_SIZE_KEY);
isCropped = instanceState.getBoolean(IS_CROPPED_KEY);
queryWidth = instanceState.getInt(BITMAP_WIDTH_KEY);
queryHeight = instanceState.getInt(BITMAP_HEIGHT_KEY);
setImageBitmap((Bitmap)instanceState.getParcelable(BITMAP_KEY));
if (instanceState.getBoolean(PENDING_REFRESH_KEY)) {
refreshImage(true);
}
}
} | java | @Override
protected void onRestoreInstanceState(Parcelable state) {
if (state.getClass() != Bundle.class) {
super.onRestoreInstanceState(state);
} else {
Bundle instanceState = (Bundle)state;
super.onRestoreInstanceState(instanceState.getParcelable(SUPER_STATE_KEY));
profileId = instanceState.getString(PROFILE_ID_KEY);
presetSizeType = instanceState.getInt(PRESET_SIZE_KEY);
isCropped = instanceState.getBoolean(IS_CROPPED_KEY);
queryWidth = instanceState.getInt(BITMAP_WIDTH_KEY);
queryHeight = instanceState.getInt(BITMAP_HEIGHT_KEY);
setImageBitmap((Bitmap)instanceState.getParcelable(BITMAP_KEY));
if (instanceState.getBoolean(PENDING_REFRESH_KEY)) {
refreshImage(true);
}
}
} | [
"@",
"Override",
"protected",
"void",
"onRestoreInstanceState",
"(",
"Parcelable",
"state",
")",
"{",
"if",
"(",
"state",
".",
"getClass",
"(",
")",
"!=",
"Bundle",
".",
"class",
")",
"{",
"super",
".",
"onRestoreInstanceState",
"(",
"state",
")",
";",
"}",
"else",
"{",
"Bundle",
"instanceState",
"=",
"(",
"Bundle",
")",
"state",
";",
"super",
".",
"onRestoreInstanceState",
"(",
"instanceState",
".",
"getParcelable",
"(",
"SUPER_STATE_KEY",
")",
")",
";",
"profileId",
"=",
"instanceState",
".",
"getString",
"(",
"PROFILE_ID_KEY",
")",
";",
"presetSizeType",
"=",
"instanceState",
".",
"getInt",
"(",
"PRESET_SIZE_KEY",
")",
";",
"isCropped",
"=",
"instanceState",
".",
"getBoolean",
"(",
"IS_CROPPED_KEY",
")",
";",
"queryWidth",
"=",
"instanceState",
".",
"getInt",
"(",
"BITMAP_WIDTH_KEY",
")",
";",
"queryHeight",
"=",
"instanceState",
".",
"getInt",
"(",
"BITMAP_HEIGHT_KEY",
")",
";",
"setImageBitmap",
"(",
"(",
"Bitmap",
")",
"instanceState",
".",
"getParcelable",
"(",
"BITMAP_KEY",
")",
")",
";",
"if",
"(",
"instanceState",
".",
"getBoolean",
"(",
"PENDING_REFRESH_KEY",
")",
")",
"{",
"refreshImage",
"(",
"true",
")",
";",
"}",
"}",
"}"
] | If the passed in state is a Bundle, an attempt is made to restore from it.
@param state a Parcelable containing the current state | [
"If",
"the",
"passed",
"in",
"state",
"is",
"a",
"Bundle",
"an",
"attempt",
"is",
"made",
"to",
"restore",
"from",
"it",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/ProfilePictureView.java#L335-L355 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.enhanceFAB | private void enhanceFAB(final FloatingActionButton fab, int dx, int dy) {
if (isEnhancedFAB() && getFab() != null) {
final FloatingActionButton mFloatingActionButton = this.fab;
if (getLinearLayoutManager() != null) {
if (dy > 0) {
if (mFloatingActionButton.getVisibility() == View.VISIBLE) {
mFloatingActionButton.hide();
}
} else {
if (mFloatingActionButton.getVisibility() != View.VISIBLE) {
mFloatingActionButton.show();
}
}
}
}
} | java | private void enhanceFAB(final FloatingActionButton fab, int dx, int dy) {
if (isEnhancedFAB() && getFab() != null) {
final FloatingActionButton mFloatingActionButton = this.fab;
if (getLinearLayoutManager() != null) {
if (dy > 0) {
if (mFloatingActionButton.getVisibility() == View.VISIBLE) {
mFloatingActionButton.hide();
}
} else {
if (mFloatingActionButton.getVisibility() != View.VISIBLE) {
mFloatingActionButton.show();
}
}
}
}
} | [
"private",
"void",
"enhanceFAB",
"(",
"final",
"FloatingActionButton",
"fab",
",",
"int",
"dx",
",",
"int",
"dy",
")",
"{",
"if",
"(",
"isEnhancedFAB",
"(",
")",
"&&",
"getFab",
"(",
")",
"!=",
"null",
")",
"{",
"final",
"FloatingActionButton",
"mFloatingActionButton",
"=",
"this",
".",
"fab",
";",
"if",
"(",
"getLinearLayoutManager",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"dy",
">",
"0",
")",
"{",
"if",
"(",
"mFloatingActionButton",
".",
"getVisibility",
"(",
")",
"==",
"View",
".",
"VISIBLE",
")",
"{",
"mFloatingActionButton",
".",
"hide",
"(",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"mFloatingActionButton",
".",
"getVisibility",
"(",
")",
"!=",
"View",
".",
"VISIBLE",
")",
"{",
"mFloatingActionButton",
".",
"show",
"(",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | Enhanced FAB UX Logic
Handle RecyclerView scrolling
@param fab FloatingActionButton
@param dx scrolling dx
@param dy scrolling dy | [
"Enhanced",
"FAB",
"UX",
"Logic",
"Handle",
"RecyclerView",
"scrolling"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L218-L233 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.enhanceFAB | private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) {
if (hasAllItemsShown()) {
if (fab.getVisibility() != View.VISIBLE) {
fab.show();
}
}
} | java | private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) {
if (hasAllItemsShown()) {
if (fab.getVisibility() != View.VISIBLE) {
fab.show();
}
}
} | [
"private",
"void",
"enhanceFAB",
"(",
"final",
"FloatingActionButton",
"fab",
",",
"MotionEvent",
"e",
")",
"{",
"if",
"(",
"hasAllItemsShown",
"(",
")",
")",
"{",
"if",
"(",
"fab",
".",
"getVisibility",
"(",
")",
"!=",
"View",
".",
"VISIBLE",
")",
"{",
"fab",
".",
"show",
"(",
")",
";",
"}",
"}",
"}"
] | Enhanced FAB UX Logic
Handle RecyclerView scrolled
If all item visible within view port, FAB will show
@param fab FloatingActionButton
@param e MotionEvent | [
"Enhanced",
"FAB",
"UX",
"Logic",
"Handle",
"RecyclerView",
"scrolled",
"If",
"all",
"item",
"visible",
"within",
"view",
"port",
"FAB",
"will",
"show"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L243-L249 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.getHeaderViewType | private int getHeaderViewType(int position) {
if (headerContent != null) {
if (headerContent.getData() == getItem(position) && (position == 0)) {
return headerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | java | private int getHeaderViewType(int position) {
if (headerContent != null) {
if (headerContent.getData() == getItem(position) && (position == 0)) {
return headerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | [
"private",
"int",
"getHeaderViewType",
"(",
"int",
"position",
")",
"{",
"if",
"(",
"headerContent",
"!=",
"null",
")",
"{",
"if",
"(",
"headerContent",
".",
"getData",
"(",
")",
"==",
"getItem",
"(",
"position",
")",
"&&",
"(",
"position",
"==",
"0",
")",
")",
"{",
"return",
"headerContent",
".",
"getViewtype",
"(",
")",
";",
"}",
"}",
"return",
"PeasyHeaderViewHolder",
".",
"VIEWTYPE_NOTHING",
";",
"}"
] | To identify content as Header
@param position position
@return view type | [
"To",
"identify",
"content",
"as",
"Header"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L525-L532 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.getFooterViewType | public int getFooterViewType(int position) {
if (footerContent != null) {
if (footerContent.getData() == getItem(position) && (position == getLastItemIndex())) {
return footerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | java | public int getFooterViewType(int position) {
if (footerContent != null) {
if (footerContent.getData() == getItem(position) && (position == getLastItemIndex())) {
return footerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | [
"public",
"int",
"getFooterViewType",
"(",
"int",
"position",
")",
"{",
"if",
"(",
"footerContent",
"!=",
"null",
")",
"{",
"if",
"(",
"footerContent",
".",
"getData",
"(",
")",
"==",
"getItem",
"(",
"position",
")",
"&&",
"(",
"position",
"==",
"getLastItemIndex",
"(",
")",
")",
")",
"{",
"return",
"footerContent",
".",
"getViewtype",
"(",
")",
";",
"}",
"}",
"return",
"PeasyHeaderViewHolder",
".",
"VIEWTYPE_NOTHING",
";",
"}"
] | To identify content as Footer
@param position position
@return view type | [
"To",
"identify",
"content",
"as",
"Footer"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L540-L547 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java | PeasyRecyclerView.onItemLongClick | public boolean onItemLongClick(final View view, final int viewType, final int position, final T item, final PeasyViewHolder viewHolder) {
return true;
} | java | public boolean onItemLongClick(final View view, final int viewType, final int position, final T item, final PeasyViewHolder viewHolder) {
return true;
} | [
"public",
"boolean",
"onItemLongClick",
"(",
"final",
"View",
"view",
",",
"final",
"int",
"viewType",
",",
"final",
"int",
"position",
",",
"final",
"T",
"item",
",",
"final",
"PeasyViewHolder",
"viewHolder",
")",
"{",
"return",
"true",
";",
"}"
] | Indicate content is clicked with long tap
@param view view
@param viewType viewType
@param position position
@param item item
@param viewHolder viewHolder
@return true by default
@see View.OnLongClickListener#onLongClick(View) Enhanced Implementation | [
"Indicate",
"content",
"is",
"clicked",
"with",
"long",
"tap"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L1076-L1078 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java | ResponseCreationSupport.sendStaticContent | @SuppressWarnings({ "PMD.NcssCount",
"PMD.UseStringBufferForStringAppends" })
public static boolean sendStaticContent(
HttpRequest request, IOSubchannel channel,
Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) {
String path = request.requestUri().getPath();
URL resourceUrl = resolver.apply(path);
ResourceInfo info;
URLConnection resConn;
InputStream resIn;
try {
if (resourceUrl == null) {
throw new IOException();
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
if (Boolean.TRUE.equals(info.isDirectory())) {
throw new IOException();
}
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e1) {
try {
if (!path.endsWith("/")) {
path += "/";
}
path += "index.html";
resourceUrl = resolver.apply(path);
if (resourceUrl == null) {
return false;
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e2) {
return false;
}
}
HttpResponse response = request.response().get();
response.setField(HttpField.LAST_MODIFIED,
Optional.ofNullable(info.getLastModifiedAt())
.orElseGet(() -> Instant.now()));
// Get content type and derive max age
MediaType mediaType = HttpResponse.contentType(
ResponseCreationSupport.uriFromUrl(resourceUrl));
setMaxAge(response,
(maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR
: maxAgeCalculator).maxAge(request, mediaType));
// Check if sending is really required.
Optional<Instant> modifiedSince = request
.findValue(HttpField.IF_MODIFIED_SINCE, Converters.DATE_TIME);
if (modifiedSince.isPresent() && info.getLastModifiedAt() != null
&& !info.getLastModifiedAt().isAfter(modifiedSince.get())) {
response.setStatus(HttpStatus.NOT_MODIFIED);
channel.respond(new Response(response));
} else {
response.setContentType(mediaType);
response.setStatus(HttpStatus.OK);
channel.respond(new Response(response));
// Start sending content (Output events as resonses)
(new InputStreamPipeline(resIn, channel).suppressClose()).run();
}
return true;
} | java | @SuppressWarnings({ "PMD.NcssCount",
"PMD.UseStringBufferForStringAppends" })
public static boolean sendStaticContent(
HttpRequest request, IOSubchannel channel,
Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) {
String path = request.requestUri().getPath();
URL resourceUrl = resolver.apply(path);
ResourceInfo info;
URLConnection resConn;
InputStream resIn;
try {
if (resourceUrl == null) {
throw new IOException();
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
if (Boolean.TRUE.equals(info.isDirectory())) {
throw new IOException();
}
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e1) {
try {
if (!path.endsWith("/")) {
path += "/";
}
path += "index.html";
resourceUrl = resolver.apply(path);
if (resourceUrl == null) {
return false;
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e2) {
return false;
}
}
HttpResponse response = request.response().get();
response.setField(HttpField.LAST_MODIFIED,
Optional.ofNullable(info.getLastModifiedAt())
.orElseGet(() -> Instant.now()));
// Get content type and derive max age
MediaType mediaType = HttpResponse.contentType(
ResponseCreationSupport.uriFromUrl(resourceUrl));
setMaxAge(response,
(maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR
: maxAgeCalculator).maxAge(request, mediaType));
// Check if sending is really required.
Optional<Instant> modifiedSince = request
.findValue(HttpField.IF_MODIFIED_SINCE, Converters.DATE_TIME);
if (modifiedSince.isPresent() && info.getLastModifiedAt() != null
&& !info.getLastModifiedAt().isAfter(modifiedSince.get())) {
response.setStatus(HttpStatus.NOT_MODIFIED);
channel.respond(new Response(response));
} else {
response.setContentType(mediaType);
response.setStatus(HttpStatus.OK);
channel.respond(new Response(response));
// Start sending content (Output events as resonses)
(new InputStreamPipeline(resIn, channel).suppressClose()).run();
}
return true;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"PMD.NcssCount\"",
",",
"\"PMD.UseStringBufferForStringAppends\"",
"}",
")",
"public",
"static",
"boolean",
"sendStaticContent",
"(",
"HttpRequest",
"request",
",",
"IOSubchannel",
"channel",
",",
"Function",
"<",
"String",
",",
"URL",
">",
"resolver",
",",
"MaxAgeCalculator",
"maxAgeCalculator",
")",
"{",
"String",
"path",
"=",
"request",
".",
"requestUri",
"(",
")",
".",
"getPath",
"(",
")",
";",
"URL",
"resourceUrl",
"=",
"resolver",
".",
"apply",
"(",
"path",
")",
";",
"ResourceInfo",
"info",
";",
"URLConnection",
"resConn",
";",
"InputStream",
"resIn",
";",
"try",
"{",
"if",
"(",
"resourceUrl",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
")",
";",
"}",
"info",
"=",
"ResponseCreationSupport",
".",
"resourceInfo",
"(",
"resourceUrl",
")",
";",
"if",
"(",
"Boolean",
".",
"TRUE",
".",
"equals",
"(",
"info",
".",
"isDirectory",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
")",
";",
"}",
"resConn",
"=",
"resourceUrl",
".",
"openConnection",
"(",
")",
";",
"resIn",
"=",
"resConn",
".",
"getInputStream",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e1",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"path",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"path",
"+=",
"\"/\"",
";",
"}",
"path",
"+=",
"\"index.html\"",
";",
"resourceUrl",
"=",
"resolver",
".",
"apply",
"(",
"path",
")",
";",
"if",
"(",
"resourceUrl",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"info",
"=",
"ResponseCreationSupport",
".",
"resourceInfo",
"(",
"resourceUrl",
")",
";",
"resConn",
"=",
"resourceUrl",
".",
"openConnection",
"(",
")",
";",
"resIn",
"=",
"resConn",
".",
"getInputStream",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e2",
")",
"{",
"return",
"false",
";",
"}",
"}",
"HttpResponse",
"response",
"=",
"request",
".",
"response",
"(",
")",
".",
"get",
"(",
")",
";",
"response",
".",
"setField",
"(",
"HttpField",
".",
"LAST_MODIFIED",
",",
"Optional",
".",
"ofNullable",
"(",
"info",
".",
"getLastModifiedAt",
"(",
")",
")",
".",
"orElseGet",
"(",
"(",
")",
"->",
"Instant",
".",
"now",
"(",
")",
")",
")",
";",
"// Get content type and derive max age",
"MediaType",
"mediaType",
"=",
"HttpResponse",
".",
"contentType",
"(",
"ResponseCreationSupport",
".",
"uriFromUrl",
"(",
"resourceUrl",
")",
")",
";",
"setMaxAge",
"(",
"response",
",",
"(",
"maxAgeCalculator",
"==",
"null",
"?",
"DEFAULT_MAX_AGE_CALCULATOR",
":",
"maxAgeCalculator",
")",
".",
"maxAge",
"(",
"request",
",",
"mediaType",
")",
")",
";",
"// Check if sending is really required.",
"Optional",
"<",
"Instant",
">",
"modifiedSince",
"=",
"request",
".",
"findValue",
"(",
"HttpField",
".",
"IF_MODIFIED_SINCE",
",",
"Converters",
".",
"DATE_TIME",
")",
";",
"if",
"(",
"modifiedSince",
".",
"isPresent",
"(",
")",
"&&",
"info",
".",
"getLastModifiedAt",
"(",
")",
"!=",
"null",
"&&",
"!",
"info",
".",
"getLastModifiedAt",
"(",
")",
".",
"isAfter",
"(",
"modifiedSince",
".",
"get",
"(",
")",
")",
")",
"{",
"response",
".",
"setStatus",
"(",
"HttpStatus",
".",
"NOT_MODIFIED",
")",
";",
"channel",
".",
"respond",
"(",
"new",
"Response",
"(",
"response",
")",
")",
";",
"}",
"else",
"{",
"response",
".",
"setContentType",
"(",
"mediaType",
")",
";",
"response",
".",
"setStatus",
"(",
"HttpStatus",
".",
"OK",
")",
";",
"channel",
".",
"respond",
"(",
"new",
"Response",
"(",
"response",
")",
")",
";",
"// Start sending content (Output events as resonses)",
"(",
"new",
"InputStreamPipeline",
"(",
"resIn",
",",
"channel",
")",
".",
"suppressClose",
"(",
")",
")",
".",
"run",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Creates and sends a response with static content. The content
is looked up by invoking the resolver with the path from the request.
The response includes a max-age header with a default value of
600. The value may be modified by specifying validity infos.
@param request the request
@param channel the channel
@param resolver the resolver
@param maxAgeCalculator the max age calculator, if `null`
the default calculator is used.
@return `true` if a response was sent | [
"Creates",
"and",
"sends",
"a",
"response",
"with",
"static",
"content",
".",
"The",
"content",
"is",
"looked",
"up",
"by",
"invoking",
"the",
"resolver",
"with",
"the",
"path",
"from",
"the",
"request",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java#L128-L192 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java | ResponseCreationSupport.resourceInfo | @SuppressWarnings("PMD.EmptyCatchBlock")
public static ResourceInfo resourceInfo(URL resource) {
try {
Path path = Paths.get(resource.toURI());
return new ResourceInfo(Files.isDirectory(path),
Files.getLastModifiedTime(path).toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (FileSystemNotFoundException | IOException
| URISyntaxException e) {
// Fall through
}
if ("jar".equals(resource.getProtocol())) {
try {
JarURLConnection conn
= (JarURLConnection) resource.openConnection();
JarEntry entry = conn.getJarEntry();
return new ResourceInfo(entry.isDirectory(),
entry.getLastModifiedTime().toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (IOException e) {
// Fall through
}
}
try {
URLConnection conn = resource.openConnection();
long lastModified = conn.getLastModified();
if (lastModified != 0) {
return new ResourceInfo(null, Instant.ofEpochMilli(
lastModified).with(ChronoField.NANO_OF_SECOND, 0));
}
} catch (IOException e) {
// Fall through
}
return new ResourceInfo(null, null);
} | java | @SuppressWarnings("PMD.EmptyCatchBlock")
public static ResourceInfo resourceInfo(URL resource) {
try {
Path path = Paths.get(resource.toURI());
return new ResourceInfo(Files.isDirectory(path),
Files.getLastModifiedTime(path).toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (FileSystemNotFoundException | IOException
| URISyntaxException e) {
// Fall through
}
if ("jar".equals(resource.getProtocol())) {
try {
JarURLConnection conn
= (JarURLConnection) resource.openConnection();
JarEntry entry = conn.getJarEntry();
return new ResourceInfo(entry.isDirectory(),
entry.getLastModifiedTime().toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (IOException e) {
// Fall through
}
}
try {
URLConnection conn = resource.openConnection();
long lastModified = conn.getLastModified();
if (lastModified != 0) {
return new ResourceInfo(null, Instant.ofEpochMilli(
lastModified).with(ChronoField.NANO_OF_SECOND, 0));
}
} catch (IOException e) {
// Fall through
}
return new ResourceInfo(null, null);
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.EmptyCatchBlock\"",
")",
"public",
"static",
"ResourceInfo",
"resourceInfo",
"(",
"URL",
"resource",
")",
"{",
"try",
"{",
"Path",
"path",
"=",
"Paths",
".",
"get",
"(",
"resource",
".",
"toURI",
"(",
")",
")",
";",
"return",
"new",
"ResourceInfo",
"(",
"Files",
".",
"isDirectory",
"(",
"path",
")",
",",
"Files",
".",
"getLastModifiedTime",
"(",
"path",
")",
".",
"toInstant",
"(",
")",
".",
"with",
"(",
"ChronoField",
".",
"NANO_OF_SECOND",
",",
"0",
")",
")",
";",
"}",
"catch",
"(",
"FileSystemNotFoundException",
"|",
"IOException",
"|",
"URISyntaxException",
"e",
")",
"{",
"// Fall through",
"}",
"if",
"(",
"\"jar\"",
".",
"equals",
"(",
"resource",
".",
"getProtocol",
"(",
")",
")",
")",
"{",
"try",
"{",
"JarURLConnection",
"conn",
"=",
"(",
"JarURLConnection",
")",
"resource",
".",
"openConnection",
"(",
")",
";",
"JarEntry",
"entry",
"=",
"conn",
".",
"getJarEntry",
"(",
")",
";",
"return",
"new",
"ResourceInfo",
"(",
"entry",
".",
"isDirectory",
"(",
")",
",",
"entry",
".",
"getLastModifiedTime",
"(",
")",
".",
"toInstant",
"(",
")",
".",
"with",
"(",
"ChronoField",
".",
"NANO_OF_SECOND",
",",
"0",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Fall through",
"}",
"}",
"try",
"{",
"URLConnection",
"conn",
"=",
"resource",
".",
"openConnection",
"(",
")",
";",
"long",
"lastModified",
"=",
"conn",
".",
"getLastModified",
"(",
")",
";",
"if",
"(",
"lastModified",
"!=",
"0",
")",
"{",
"return",
"new",
"ResourceInfo",
"(",
"null",
",",
"Instant",
".",
"ofEpochMilli",
"(",
"lastModified",
")",
".",
"with",
"(",
"ChronoField",
".",
"NANO_OF_SECOND",
",",
"0",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Fall through",
"}",
"return",
"new",
"ResourceInfo",
"(",
"null",
",",
"null",
")",
";",
"}"
] | Attempts to lookup the additional resource information for the
given URL.
If a {@link URL} references a file, it is easy to find out if
the resource referenced is a directory and to get its last
modification time. Getting the same information
for a {@link URL} that references resources in a jar is a bit
more difficult. This method handles both cases.
@param resource the resource URL
@return the resource info | [
"Attempts",
"to",
"lookup",
"the",
"additional",
"resource",
"information",
"for",
"the",
"given",
"URL",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java#L265-L299 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java | ResponseCreationSupport.setMaxAge | public static long setMaxAge(HttpResponse response, int maxAge) {
List<Directive> directives = new ArrayList<>();
directives.add(new Directive("max-age", maxAge));
response.setField(HttpField.CACHE_CONTROL, directives);
return maxAge;
} | java | public static long setMaxAge(HttpResponse response, int maxAge) {
List<Directive> directives = new ArrayList<>();
directives.add(new Directive("max-age", maxAge));
response.setField(HttpField.CACHE_CONTROL, directives);
return maxAge;
} | [
"public",
"static",
"long",
"setMaxAge",
"(",
"HttpResponse",
"response",
",",
"int",
"maxAge",
")",
"{",
"List",
"<",
"Directive",
">",
"directives",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"directives",
".",
"add",
"(",
"new",
"Directive",
"(",
"\"max-age\"",
",",
"maxAge",
")",
")",
";",
"response",
".",
"setField",
"(",
"HttpField",
".",
"CACHE_CONTROL",
",",
"directives",
")",
";",
"return",
"maxAge",
";",
"}"
] | Sets the cache control header in the given response.
@param response the response
@param maxAge the max age
@return the value set | [
"Sets",
"the",
"cache",
"control",
"header",
"in",
"the",
"given",
"response",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/ResponseCreationSupport.java#L343-L348 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FriendPickerFragment.java | FriendPickerFragment.setSelection | public void setSelection(List<GraphUser> graphUsers) {
List<String> userIds = new ArrayList<String>();
for(GraphUser graphUser: graphUsers) {
userIds.add(graphUser.getId());
}
setSelectionByIds(userIds);
} | java | public void setSelection(List<GraphUser> graphUsers) {
List<String> userIds = new ArrayList<String>();
for(GraphUser graphUser: graphUsers) {
userIds.add(graphUser.getId());
}
setSelectionByIds(userIds);
} | [
"public",
"void",
"setSelection",
"(",
"List",
"<",
"GraphUser",
">",
"graphUsers",
")",
"{",
"List",
"<",
"String",
">",
"userIds",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"GraphUser",
"graphUser",
":",
"graphUsers",
")",
"{",
"userIds",
".",
"add",
"(",
"graphUser",
".",
"getId",
"(",
")",
")",
";",
"}",
"setSelectionByIds",
"(",
"userIds",
")",
";",
"}"
] | Sets the list of friends for pre selection. These friends will be selected by default.
@param graphUsers list of friends as GraphUsers | [
"Sets",
"the",
"list",
"of",
"friends",
"for",
"pre",
"selection",
".",
"These",
"friends",
"will",
"be",
"selected",
"by",
"default",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FriendPickerFragment.java#L181-L187 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.authorize | private void authorize(Activity activity, String[] permissions, int activityCode,
SessionLoginBehavior behavior, final DialogListener listener) {
checkUserSession("authorize");
pendingOpeningSession = new Session.Builder(activity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
pendingAuthorizationActivity = activity;
pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
StatusCallback callback = new StatusCallback() {
@Override
public void call(Session callbackSession, SessionState state, Exception exception) {
// Invoke user-callback.
onSessionCallback(callbackSession, state, exception, listener);
}
};
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setCallback(callback).
setLoginBehavior(behavior).
setRequestCode(activityCode).
setPermissions(Arrays.asList(pendingAuthorizationPermissions));
openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
} | java | private void authorize(Activity activity, String[] permissions, int activityCode,
SessionLoginBehavior behavior, final DialogListener listener) {
checkUserSession("authorize");
pendingOpeningSession = new Session.Builder(activity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
pendingAuthorizationActivity = activity;
pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
StatusCallback callback = new StatusCallback() {
@Override
public void call(Session callbackSession, SessionState state, Exception exception) {
// Invoke user-callback.
onSessionCallback(callbackSession, state, exception, listener);
}
};
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setCallback(callback).
setLoginBehavior(behavior).
setRequestCode(activityCode).
setPermissions(Arrays.asList(pendingAuthorizationPermissions));
openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
} | [
"private",
"void",
"authorize",
"(",
"Activity",
"activity",
",",
"String",
"[",
"]",
"permissions",
",",
"int",
"activityCode",
",",
"SessionLoginBehavior",
"behavior",
",",
"final",
"DialogListener",
"listener",
")",
"{",
"checkUserSession",
"(",
"\"authorize\"",
")",
";",
"pendingOpeningSession",
"=",
"new",
"Session",
".",
"Builder",
"(",
"activity",
")",
".",
"setApplicationId",
"(",
"mAppId",
")",
".",
"setTokenCachingStrategy",
"(",
"getTokenCache",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"pendingAuthorizationActivity",
"=",
"activity",
";",
"pendingAuthorizationPermissions",
"=",
"(",
"permissions",
"!=",
"null",
")",
"?",
"permissions",
":",
"new",
"String",
"[",
"0",
"]",
";",
"StatusCallback",
"callback",
"=",
"new",
"StatusCallback",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"call",
"(",
"Session",
"callbackSession",
",",
"SessionState",
"state",
",",
"Exception",
"exception",
")",
"{",
"// Invoke user-callback.",
"onSessionCallback",
"(",
"callbackSession",
",",
"state",
",",
"exception",
",",
"listener",
")",
";",
"}",
"}",
";",
"Session",
".",
"OpenRequest",
"openRequest",
"=",
"new",
"Session",
".",
"OpenRequest",
"(",
"activity",
")",
".",
"setCallback",
"(",
"callback",
")",
".",
"setLoginBehavior",
"(",
"behavior",
")",
".",
"setRequestCode",
"(",
"activityCode",
")",
".",
"setPermissions",
"(",
"Arrays",
".",
"asList",
"(",
"pendingAuthorizationPermissions",
")",
")",
";",
"openSession",
"(",
"pendingOpeningSession",
",",
"openRequest",
",",
"pendingAuthorizationPermissions",
".",
"length",
">",
"0",
")",
";",
"}"
] | Full authorize method.
Starts either an Activity or a dialog which prompts the user to log in to
Facebook and grant the requested permissions to the given application.
This method will, when possible, use Facebook's single sign-on for
Android to obtain an access token. This involves proxying a call through
the Facebook for Android stand-alone application, which will handle the
authentication flow, and return an OAuth access token for making API
calls.
Because this process will not be available for all users, if single
sign-on is not possible, this method will automatically fall back to the
OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
by Facebook in an embedded WebView, not by the client application. As
such, the dialog makes a network request and renders HTML content rather
than a native UI. The access token is retrieved from a redirect to a
special URL that the WebView handles.
Note that User credentials could be handled natively using the OAuth 2.0
Username and Password Flow, but this is not supported by this SDK.
See http://developers.facebook.com/docs/authentication/ and
http://wiki.oauth.net/OAuth-2 for more details.
Note that this method is asynchronous and the callback will be invoked in
the original calling thread (not in a background thread).
Also note that requests may be made to the API without calling authorize
first, in which case only public information is returned.
IMPORTANT: Note that single sign-on authentication will not function
correctly if you do not include a call to the authorizeCallback() method
in your onActivityResult() function! Please see below for more
information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
as the activityCode parameter in your call to authorize().
@param activity
The Android activity in which we want to display the
authorization dialog.
@param permissions
A list of permissions required for this application: e.g.
"read_stream", "publish_stream", "offline_access", etc. see
http://developers.facebook.com/docs/authentication/permissions
This parameter should not be null -- if you do not require any
permissions, then pass in an empty String array.
@param activityCode
Single sign-on requires an activity result to be called back
to the client application -- if you are waiting on other
activities to return data, pass a custom activity code here to
avoid collisions. If you would like to force the use of legacy
dialog-based authorization, pass FORCE_DIALOG_AUTH for this
parameter. Otherwise just omit this parameter and Facebook
will use a suitable default. See
http://developer.android.com/reference/android/
app/Activity.html for more information.
@param behavior
The {@link SessionLoginBehavior SessionLoginBehavior} that
specifies what behaviors should be attempted during
authorization.
@param listener
Callback interface for notifying the calling application when
the authentication dialog has completed, failed, or been
canceled. | [
"Full",
"authorize",
"method",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L290-L314 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.validateServiceIntent | private boolean validateServiceIntent(Context context, Intent intent) {
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return false;
}
return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
} | java | private boolean validateServiceIntent(Context context, Intent intent) {
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return false;
}
return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
} | [
"private",
"boolean",
"validateServiceIntent",
"(",
"Context",
"context",
",",
"Intent",
"intent",
")",
"{",
"ResolveInfo",
"resolveInfo",
"=",
"context",
".",
"getPackageManager",
"(",
")",
".",
"resolveService",
"(",
"intent",
",",
"0",
")",
";",
"if",
"(",
"resolveInfo",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"validateAppSignatureForPackage",
"(",
"context",
",",
"resolveInfo",
".",
"serviceInfo",
".",
"packageName",
")",
";",
"}"
] | Helper to validate a service intent by resolving and checking the
provider's package signature.
@param context
@param intent
@return true if the service intent resolution happens successfully and
the signatures match. | [
"Helper",
"to",
"validate",
"a",
"service",
"intent",
"by",
"resolving",
"and",
"checking",
"the",
"provider",
"s",
"package",
"signature",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L372-L379 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.validateAppSignatureForPackage | private boolean validateAppSignatureForPackage(Context context, String packageName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
return true;
}
}
return false;
} | java | private boolean validateAppSignatureForPackage(Context context, String packageName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"validateAppSignatureForPackage",
"(",
"Context",
"context",
",",
"String",
"packageName",
")",
"{",
"PackageInfo",
"packageInfo",
";",
"try",
"{",
"packageInfo",
"=",
"context",
".",
"getPackageManager",
"(",
")",
".",
"getPackageInfo",
"(",
"packageName",
",",
"PackageManager",
".",
"GET_SIGNATURES",
")",
";",
"}",
"catch",
"(",
"NameNotFoundException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"Signature",
"signature",
":",
"packageInfo",
".",
"signatures",
")",
"{",
"if",
"(",
"signature",
".",
"toCharsString",
"(",
")",
".",
"equals",
"(",
"FB_APP_SIGNATURE",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Query the signature for the application that would be invoked by the
given intent and verify that it matches the FB application's signature.
@param context
@param packageName
@return true if the app's signature matches the expected signature. | [
"Query",
"the",
"signature",
"for",
"the",
"application",
"that",
"would",
"be",
"invoked",
"by",
"the",
"given",
"intent",
"and",
"verify",
"that",
"it",
"matches",
"the",
"FB",
"application",
"s",
"signature",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L389-L404 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.requestImpl | @SuppressWarnings("deprecation")
String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
} | java | @SuppressWarnings("deprecation")
String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"String",
"requestImpl",
"(",
"String",
"graphPath",
",",
"Bundle",
"params",
",",
"String",
"httpMethod",
")",
"throws",
"FileNotFoundException",
",",
"MalformedURLException",
",",
"IOException",
"{",
"params",
".",
"putString",
"(",
"\"format\"",
",",
"\"json\"",
")",
";",
"if",
"(",
"isSessionValid",
"(",
")",
")",
"{",
"params",
".",
"putString",
"(",
"TOKEN",
",",
"getAccessToken",
"(",
")",
")",
";",
"}",
"String",
"url",
"=",
"(",
"graphPath",
"!=",
"null",
")",
"?",
"GRAPH_BASE_URL",
"+",
"graphPath",
":",
"RESTSERVER_URL",
";",
"return",
"Util",
".",
"openUrl",
"(",
"url",
",",
"httpMethod",
",",
"params",
")",
";",
"}"
] | Internal call to avoid deprecated warnings. | [
"Internal",
"call",
"to",
"avoid",
"deprecated",
"warnings",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L796-L805 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.setSession | @Deprecated
public void setSession(Session session) {
if (session == null) {
throw new IllegalArgumentException("session cannot be null");
}
synchronized (this.lock) {
this.userSetSession = session;
}
} | java | @Deprecated
public void setSession(Session session) {
if (session == null) {
throw new IllegalArgumentException("session cannot be null");
}
synchronized (this.lock) {
this.userSetSession = session;
}
} | [
"@",
"Deprecated",
"public",
"void",
"setSession",
"(",
"Session",
"session",
")",
"{",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"session cannot be null\"",
")",
";",
"}",
"synchronized",
"(",
"this",
".",
"lock",
")",
"{",
"this",
".",
"userSetSession",
"=",
"session",
";",
"}",
"}"
] | Allows the user to set a Session for the Facebook class to use.
If a Session is set here, then one should not use the authorize, logout,
or extendAccessToken methods which alter the Session object since that may
result in undefined behavior. Using those methods after setting the
session here will result in exceptions being thrown.
@param session the Session object to use, cannot be null | [
"Allows",
"the",
"user",
"to",
"set",
"a",
"Session",
"for",
"the",
"Facebook",
"class",
"to",
"use",
".",
"If",
"a",
"Session",
"is",
"set",
"here",
"then",
"one",
"should",
"not",
"use",
"the",
"authorize",
"logout",
"or",
"extendAccessToken",
"methods",
"which",
"alter",
"the",
"Session",
"object",
"since",
"that",
"may",
"result",
"in",
"undefined",
"behavior",
".",
"Using",
"those",
"methods",
"after",
"setting",
"the",
"session",
"here",
"will",
"result",
"in",
"exceptions",
"being",
"thrown",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L891-L899 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Facebook.java | Facebook.getSession | @Deprecated
public final Session getSession() {
while (true) {
String cachedToken = null;
Session oldSession = null;
synchronized (this.lock) {
if (userSetSession != null) {
return userSetSession;
}
if ((session != null) || !sessionInvalidated) {
return session;
}
cachedToken = accessToken;
oldSession = session;
}
if (cachedToken == null) {
return null;
}
// At this point we do not have a valid session, but mAccessToken is
// non-null.
// So we can try building a session based on that.
List<String> permissions;
if (oldSession != null) {
permissions = oldSession.getPermissions();
} else if (pendingAuthorizationPermissions != null) {
permissions = Arrays.asList(pendingAuthorizationPermissions);
} else {
permissions = Collections.<String>emptyList();
}
Session newSession = new Session.Builder(pendingAuthorizationActivity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
return null;
}
Session.OpenRequest openRequest =
new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
openSession(newSession, openRequest, !permissions.isEmpty());
Session invalidatedSession = null;
Session returnSession = null;
synchronized (this.lock) {
if (sessionInvalidated || (session == null)) {
invalidatedSession = session;
returnSession = session = newSession;
sessionInvalidated = false;
}
}
if (invalidatedSession != null) {
invalidatedSession.close();
}
if (returnSession != null) {
return returnSession;
}
// Else token state changed between the synchronized blocks, so
// retry..
}
} | java | @Deprecated
public final Session getSession() {
while (true) {
String cachedToken = null;
Session oldSession = null;
synchronized (this.lock) {
if (userSetSession != null) {
return userSetSession;
}
if ((session != null) || !sessionInvalidated) {
return session;
}
cachedToken = accessToken;
oldSession = session;
}
if (cachedToken == null) {
return null;
}
// At this point we do not have a valid session, but mAccessToken is
// non-null.
// So we can try building a session based on that.
List<String> permissions;
if (oldSession != null) {
permissions = oldSession.getPermissions();
} else if (pendingAuthorizationPermissions != null) {
permissions = Arrays.asList(pendingAuthorizationPermissions);
} else {
permissions = Collections.<String>emptyList();
}
Session newSession = new Session.Builder(pendingAuthorizationActivity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
return null;
}
Session.OpenRequest openRequest =
new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
openSession(newSession, openRequest, !permissions.isEmpty());
Session invalidatedSession = null;
Session returnSession = null;
synchronized (this.lock) {
if (sessionInvalidated || (session == null)) {
invalidatedSession = session;
returnSession = session = newSession;
sessionInvalidated = false;
}
}
if (invalidatedSession != null) {
invalidatedSession.close();
}
if (returnSession != null) {
return returnSession;
}
// Else token state changed between the synchronized blocks, so
// retry..
}
} | [
"@",
"Deprecated",
"public",
"final",
"Session",
"getSession",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"String",
"cachedToken",
"=",
"null",
";",
"Session",
"oldSession",
"=",
"null",
";",
"synchronized",
"(",
"this",
".",
"lock",
")",
"{",
"if",
"(",
"userSetSession",
"!=",
"null",
")",
"{",
"return",
"userSetSession",
";",
"}",
"if",
"(",
"(",
"session",
"!=",
"null",
")",
"||",
"!",
"sessionInvalidated",
")",
"{",
"return",
"session",
";",
"}",
"cachedToken",
"=",
"accessToken",
";",
"oldSession",
"=",
"session",
";",
"}",
"if",
"(",
"cachedToken",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// At this point we do not have a valid session, but mAccessToken is",
"// non-null.",
"// So we can try building a session based on that.",
"List",
"<",
"String",
">",
"permissions",
";",
"if",
"(",
"oldSession",
"!=",
"null",
")",
"{",
"permissions",
"=",
"oldSession",
".",
"getPermissions",
"(",
")",
";",
"}",
"else",
"if",
"(",
"pendingAuthorizationPermissions",
"!=",
"null",
")",
"{",
"permissions",
"=",
"Arrays",
".",
"asList",
"(",
"pendingAuthorizationPermissions",
")",
";",
"}",
"else",
"{",
"permissions",
"=",
"Collections",
".",
"<",
"String",
">",
"emptyList",
"(",
")",
";",
"}",
"Session",
"newSession",
"=",
"new",
"Session",
".",
"Builder",
"(",
"pendingAuthorizationActivity",
")",
".",
"setApplicationId",
"(",
"mAppId",
")",
".",
"setTokenCachingStrategy",
"(",
"getTokenCache",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"if",
"(",
"newSession",
".",
"getState",
"(",
")",
"!=",
"SessionState",
".",
"CREATED_TOKEN_LOADED",
")",
"{",
"return",
"null",
";",
"}",
"Session",
".",
"OpenRequest",
"openRequest",
"=",
"new",
"Session",
".",
"OpenRequest",
"(",
"pendingAuthorizationActivity",
")",
".",
"setPermissions",
"(",
"permissions",
")",
";",
"openSession",
"(",
"newSession",
",",
"openRequest",
",",
"!",
"permissions",
".",
"isEmpty",
"(",
")",
")",
";",
"Session",
"invalidatedSession",
"=",
"null",
";",
"Session",
"returnSession",
"=",
"null",
";",
"synchronized",
"(",
"this",
".",
"lock",
")",
"{",
"if",
"(",
"sessionInvalidated",
"||",
"(",
"session",
"==",
"null",
")",
")",
"{",
"invalidatedSession",
"=",
"session",
";",
"returnSession",
"=",
"session",
"=",
"newSession",
";",
"sessionInvalidated",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"invalidatedSession",
"!=",
"null",
")",
"{",
"invalidatedSession",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"returnSession",
"!=",
"null",
")",
"{",
"return",
"returnSession",
";",
"}",
"// Else token state changed between the synchronized blocks, so",
"// retry..",
"}",
"}"
] | Get the underlying Session object to use with 3.0 api.
@return Session - underlying session | [
"Get",
"the",
"underlying",
"Session",
"object",
"to",
"use",
"with",
"3",
".",
"0",
"api",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L913-L979 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java | NioDispatcher.onStart | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null && !runner.isInterrupted()) {
return;
}
runner = new Thread(this, Components.simpleObjectName(this));
runner.start();
}
} | java | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null && !runner.isInterrupted()) {
return;
}
runner = new Thread(this, Components.simpleObjectName(this));
runner.start();
}
} | [
"@",
"Handler",
"public",
"void",
"onStart",
"(",
"Start",
"event",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"runner",
"!=",
"null",
"&&",
"!",
"runner",
".",
"isInterrupted",
"(",
")",
")",
"{",
"return",
";",
"}",
"runner",
"=",
"new",
"Thread",
"(",
"this",
",",
"Components",
".",
"simpleObjectName",
"(",
"this",
")",
")",
";",
"runner",
".",
"start",
"(",
")",
";",
"}",
"}"
] | Starts this dispatcher. A dispatcher has an associated thread that
keeps it running.
@param event the event | [
"Starts",
"this",
"dispatcher",
".",
"A",
"dispatcher",
"has",
"an",
"associated",
"thread",
"that",
"keeps",
"it",
"running",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java#L60-L69 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java | NioDispatcher.onStop | @Handler(priority = -10000)
public void onStop(Stop event) throws InterruptedException {
synchronized (this) {
if (runner == null) {
return;
}
// It just might happen that the wakeup() occurs between the
// check for running and the select() in the thread's run loop,
// but we -- obviously -- cannot put the select() in a
// synchronized(this).
while (runner.isAlive()) {
runner.interrupt(); // *Should* be sufficient, but...
selector.wakeup(); // Make sure
runner.join(10);
}
runner = null;
}
} | java | @Handler(priority = -10000)
public void onStop(Stop event) throws InterruptedException {
synchronized (this) {
if (runner == null) {
return;
}
// It just might happen that the wakeup() occurs between the
// check for running and the select() in the thread's run loop,
// but we -- obviously -- cannot put the select() in a
// synchronized(this).
while (runner.isAlive()) {
runner.interrupt(); // *Should* be sufficient, but...
selector.wakeup(); // Make sure
runner.join(10);
}
runner = null;
}
} | [
"@",
"Handler",
"(",
"priority",
"=",
"-",
"10000",
")",
"public",
"void",
"onStop",
"(",
"Stop",
"event",
")",
"throws",
"InterruptedException",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"runner",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// It just might happen that the wakeup() occurs between the",
"// check for running and the select() in the thread's run loop,",
"// but we -- obviously -- cannot put the select() in a",
"// synchronized(this).",
"while",
"(",
"runner",
".",
"isAlive",
"(",
")",
")",
"{",
"runner",
".",
"interrupt",
"(",
")",
";",
"// *Should* be sufficient, but...",
"selector",
".",
"wakeup",
"(",
")",
";",
"// Make sure",
"runner",
".",
"join",
"(",
"10",
")",
";",
"}",
"runner",
"=",
"null",
";",
"}",
"}"
] | Stops the thread that is associated with this dispatcher.
@param event the event
@throws InterruptedException if the execution is interrupted | [
"Stops",
"the",
"thread",
"that",
"is",
"associated",
"with",
"this",
"dispatcher",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java#L77-L94 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java | NioDispatcher.onNioRegistration | @Handler
public void onNioRegistration(NioRegistration event)
throws IOException {
SelectableChannel channel = event.ioChannel();
channel.configureBlocking(false);
SelectionKey key;
synchronized (selectorGate) {
selector.wakeup(); // make sure selector isn't blocking
key = channel.register(
selector, event.ops(), event.handler());
}
event.setResult(new Registration(key));
} | java | @Handler
public void onNioRegistration(NioRegistration event)
throws IOException {
SelectableChannel channel = event.ioChannel();
channel.configureBlocking(false);
SelectionKey key;
synchronized (selectorGate) {
selector.wakeup(); // make sure selector isn't blocking
key = channel.register(
selector, event.ops(), event.handler());
}
event.setResult(new Registration(key));
} | [
"@",
"Handler",
"public",
"void",
"onNioRegistration",
"(",
"NioRegistration",
"event",
")",
"throws",
"IOException",
"{",
"SelectableChannel",
"channel",
"=",
"event",
".",
"ioChannel",
"(",
")",
";",
"channel",
".",
"configureBlocking",
"(",
"false",
")",
";",
"SelectionKey",
"key",
";",
"synchronized",
"(",
"selectorGate",
")",
"{",
"selector",
".",
"wakeup",
"(",
")",
";",
"// make sure selector isn't blocking",
"key",
"=",
"channel",
".",
"register",
"(",
"selector",
",",
"event",
".",
"ops",
"(",
")",
",",
"event",
".",
"handler",
"(",
")",
")",
";",
"}",
"event",
".",
"setResult",
"(",
"new",
"Registration",
"(",
"key",
")",
")",
";",
"}"
] | Handle the NIO registration.
@param event the event
@throws IOException Signals that an I/O exception has occurred. | [
"Handle",
"the",
"NIO",
"registration",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/NioDispatcher.java#L137-L149 | train |
meridor/perspective-backend | perspective-sql/src/main/java/org/meridor/perspective/sql/impl/task/strategy/ScanStrategy.java | ScanStrategy.innerJoin | private DataContainer innerJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition) {
return crossJoin(left, right, joinCondition, JoinType.INNER);
} | java | private DataContainer innerJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition) {
return crossJoin(left, right, joinCondition, JoinType.INNER);
} | [
"private",
"DataContainer",
"innerJoin",
"(",
"DataContainer",
"left",
",",
"DataContainer",
"right",
",",
"Optional",
"<",
"BooleanExpression",
">",
"joinCondition",
")",
"{",
"return",
"crossJoin",
"(",
"left",
",",
"right",
",",
"joinCondition",
",",
"JoinType",
".",
"INNER",
")",
";",
"}"
] | A naive implementation filtering cross join by condition | [
"A",
"naive",
"implementation",
"filtering",
"cross",
"join",
"by",
"condition"
] | 5f98083977a57115988678e97d1642ee83431258 | https://github.com/meridor/perspective-backend/blob/5f98083977a57115988678e97d1642ee83431258/perspective-sql/src/main/java/org/meridor/perspective/sql/impl/task/strategy/ScanStrategy.java#L81-L83 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/SessionManager.java | SessionManager.derivePattern | @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
protected static String derivePattern(String path) {
String pattern;
if ("/".equals(path)) {
pattern = "/**";
} else {
String patternBase = path;
if (patternBase.endsWith("/")) {
patternBase = path.substring(0, path.length() - 1);
}
pattern = path + "," + path + "/**";
}
return pattern;
} | java | @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
protected static String derivePattern(String path) {
String pattern;
if ("/".equals(path)) {
pattern = "/**";
} else {
String patternBase = path;
if (patternBase.endsWith("/")) {
patternBase = path.substring(0, path.length() - 1);
}
pattern = path + "," + path + "/**";
}
return pattern;
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.DataflowAnomalyAnalysis\"",
")",
"protected",
"static",
"String",
"derivePattern",
"(",
"String",
"path",
")",
"{",
"String",
"pattern",
";",
"if",
"(",
"\"/\"",
".",
"equals",
"(",
"path",
")",
")",
"{",
"pattern",
"=",
"\"/**\"",
";",
"}",
"else",
"{",
"String",
"patternBase",
"=",
"path",
";",
"if",
"(",
"patternBase",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"patternBase",
"=",
"path",
".",
"substring",
"(",
"0",
",",
"path",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"}",
"pattern",
"=",
"path",
"+",
"\",\"",
"+",
"path",
"+",
"\"/**\"",
";",
"}",
"return",
"pattern",
";",
"}"
] | Derives the resource pattern from the path.
@param path the path
@return the pattern | [
"Derives",
"the",
"resource",
"pattern",
"from",
"the",
"path",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/SessionManager.java#L143-L156 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/SessionManager.java | SessionManager.createSessionId | protected String createSessionId(HttpResponse response) {
StringBuilder sessionIdBuilder = new StringBuilder();
byte[] bytes = new byte[16];
secureRandom.nextBytes(bytes);
for (byte b : bytes) {
sessionIdBuilder.append(Integer.toHexString(b & 0xff));
}
String sessionId = sessionIdBuilder.toString();
HttpCookie sessionCookie = new HttpCookie(idName(), sessionId);
sessionCookie.setPath(path);
sessionCookie.setHttpOnly(true);
response.computeIfAbsent(HttpField.SET_COOKIE, CookieList::new)
.value().add(sessionCookie);
response.computeIfAbsent(
HttpField.CACHE_CONTROL, CacheControlDirectives::new)
.value().add(new Directive("no-cache", "SetCookie, Set-Cookie2"));
return sessionId;
} | java | protected String createSessionId(HttpResponse response) {
StringBuilder sessionIdBuilder = new StringBuilder();
byte[] bytes = new byte[16];
secureRandom.nextBytes(bytes);
for (byte b : bytes) {
sessionIdBuilder.append(Integer.toHexString(b & 0xff));
}
String sessionId = sessionIdBuilder.toString();
HttpCookie sessionCookie = new HttpCookie(idName(), sessionId);
sessionCookie.setPath(path);
sessionCookie.setHttpOnly(true);
response.computeIfAbsent(HttpField.SET_COOKIE, CookieList::new)
.value().add(sessionCookie);
response.computeIfAbsent(
HttpField.CACHE_CONTROL, CacheControlDirectives::new)
.value().add(new Directive("no-cache", "SetCookie, Set-Cookie2"));
return sessionId;
} | [
"protected",
"String",
"createSessionId",
"(",
"HttpResponse",
"response",
")",
"{",
"StringBuilder",
"sessionIdBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"16",
"]",
";",
"secureRandom",
".",
"nextBytes",
"(",
"bytes",
")",
";",
"for",
"(",
"byte",
"b",
":",
"bytes",
")",
"{",
"sessionIdBuilder",
".",
"append",
"(",
"Integer",
".",
"toHexString",
"(",
"b",
"&",
"0xff",
")",
")",
";",
"}",
"String",
"sessionId",
"=",
"sessionIdBuilder",
".",
"toString",
"(",
")",
";",
"HttpCookie",
"sessionCookie",
"=",
"new",
"HttpCookie",
"(",
"idName",
"(",
")",
",",
"sessionId",
")",
";",
"sessionCookie",
".",
"setPath",
"(",
"path",
")",
";",
"sessionCookie",
".",
"setHttpOnly",
"(",
"true",
")",
";",
"response",
".",
"computeIfAbsent",
"(",
"HttpField",
".",
"SET_COOKIE",
",",
"CookieList",
"::",
"new",
")",
".",
"value",
"(",
")",
".",
"add",
"(",
"sessionCookie",
")",
";",
"response",
".",
"computeIfAbsent",
"(",
"HttpField",
".",
"CACHE_CONTROL",
",",
"CacheControlDirectives",
"::",
"new",
")",
".",
"value",
"(",
")",
".",
"add",
"(",
"new",
"Directive",
"(",
"\"no-cache\"",
",",
"\"SetCookie, Set-Cookie2\"",
")",
")",
";",
"return",
"sessionId",
";",
"}"
] | Creates a session id and adds the corresponding cookie to the
response.
@param response the response
@return the session id | [
"Creates",
"a",
"session",
"id",
"and",
"adds",
"the",
"corresponding",
"cookie",
"to",
"the",
"response",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/SessionManager.java#L343-L360 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/SessionManager.java | SessionManager.discard | @Handler(channels = Channel.class)
public void discard(DiscardSession event) {
removeSession(event.session().id());
} | java | @Handler(channels = Channel.class)
public void discard(DiscardSession event) {
removeSession(event.session().id());
} | [
"@",
"Handler",
"(",
"channels",
"=",
"Channel",
".",
"class",
")",
"public",
"void",
"discard",
"(",
"DiscardSession",
"event",
")",
"{",
"removeSession",
"(",
"event",
".",
"session",
"(",
")",
".",
"id",
"(",
")",
")",
";",
"}"
] | Discards the given session.
@param event the event | [
"Discards",
"the",
"given",
"session",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/SessionManager.java#L367-L370 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/SessionManager.java | SessionManager.onProtocolSwitchAccepted | @Handler(priority = 1000)
public void onProtocolSwitchAccepted(
ProtocolSwitchAccepted event, IOSubchannel channel) {
event.requestEvent().associated(Session.class)
.ifPresent(session -> {
channel.setAssociated(Session.class, session);
});
} | java | @Handler(priority = 1000)
public void onProtocolSwitchAccepted(
ProtocolSwitchAccepted event, IOSubchannel channel) {
event.requestEvent().associated(Session.class)
.ifPresent(session -> {
channel.setAssociated(Session.class, session);
});
} | [
"@",
"Handler",
"(",
"priority",
"=",
"1000",
")",
"public",
"void",
"onProtocolSwitchAccepted",
"(",
"ProtocolSwitchAccepted",
"event",
",",
"IOSubchannel",
"channel",
")",
"{",
"event",
".",
"requestEvent",
"(",
")",
".",
"associated",
"(",
"Session",
".",
"class",
")",
".",
"ifPresent",
"(",
"session",
"->",
"{",
"channel",
".",
"setAssociated",
"(",
"Session",
".",
"class",
",",
"session",
")",
";",
"}",
")",
";",
"}"
] | Associates the channel with the session from the upgrade request.
@param event the event
@param channel the channel | [
"Associates",
"the",
"channel",
"with",
"the",
"session",
"from",
"the",
"upgrade",
"request",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/SessionManager.java#L378-L385 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java | TcpConnector.onOpenConnection | @Handler
public void onOpenConnection(OpenTcpConnection event) {
try {
SocketChannel socketChannel = SocketChannel.open(event.address());
channels.add(new TcpChannelImpl(socketChannel));
} catch (ConnectException e) {
fire(new ConnectError(event, "Connection refused.", e));
} catch (IOException e) {
fire(new ConnectError(event, "Failed to open TCP connection.", e));
}
} | java | @Handler
public void onOpenConnection(OpenTcpConnection event) {
try {
SocketChannel socketChannel = SocketChannel.open(event.address());
channels.add(new TcpChannelImpl(socketChannel));
} catch (ConnectException e) {
fire(new ConnectError(event, "Connection refused.", e));
} catch (IOException e) {
fire(new ConnectError(event, "Failed to open TCP connection.", e));
}
} | [
"@",
"Handler",
"public",
"void",
"onOpenConnection",
"(",
"OpenTcpConnection",
"event",
")",
"{",
"try",
"{",
"SocketChannel",
"socketChannel",
"=",
"SocketChannel",
".",
"open",
"(",
"event",
".",
"address",
"(",
")",
")",
";",
"channels",
".",
"add",
"(",
"new",
"TcpChannelImpl",
"(",
"socketChannel",
")",
")",
";",
"}",
"catch",
"(",
"ConnectException",
"e",
")",
"{",
"fire",
"(",
"new",
"ConnectError",
"(",
"event",
",",
"\"Connection refused.\"",
",",
"e",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"fire",
"(",
"new",
"ConnectError",
"(",
"event",
",",
"\"Failed to open TCP connection.\"",
",",
"e",
")",
")",
";",
"}",
"}"
] | Opens a connection to the end point specified in the event.
@param event the event | [
"Opens",
"a",
"connection",
"to",
"the",
"end",
"point",
"specified",
"in",
"the",
"event",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java#L85-L95 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java | TcpConnector.onRegistered | @Handler(channels = Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (!(handler instanceof TcpChannelImpl)) {
return;
}
if (event.event().get() == null) {
fire(new Error(event, "Registration failed, no NioDispatcher?",
new Throwable()));
return;
}
TcpChannelImpl channel = (TcpChannelImpl) handler;
channel.registrationComplete(event.event());
channel.downPipeline()
.fire(new Connected(channel.nioChannel().getLocalAddress(),
channel.nioChannel().getRemoteAddress()), channel);
} | java | @Handler(channels = Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (!(handler instanceof TcpChannelImpl)) {
return;
}
if (event.event().get() == null) {
fire(new Error(event, "Registration failed, no NioDispatcher?",
new Throwable()));
return;
}
TcpChannelImpl channel = (TcpChannelImpl) handler;
channel.registrationComplete(event.event());
channel.downPipeline()
.fire(new Connected(channel.nioChannel().getLocalAddress(),
channel.nioChannel().getRemoteAddress()), channel);
} | [
"@",
"Handler",
"(",
"channels",
"=",
"Self",
".",
"class",
")",
"public",
"void",
"onRegistered",
"(",
"NioRegistration",
".",
"Completed",
"event",
")",
"throws",
"InterruptedException",
",",
"IOException",
"{",
"NioHandler",
"handler",
"=",
"event",
".",
"event",
"(",
")",
".",
"handler",
"(",
")",
";",
"if",
"(",
"!",
"(",
"handler",
"instanceof",
"TcpChannelImpl",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"event",
".",
"event",
"(",
")",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"fire",
"(",
"new",
"Error",
"(",
"event",
",",
"\"Registration failed, no NioDispatcher?\"",
",",
"new",
"Throwable",
"(",
")",
")",
")",
";",
"return",
";",
"}",
"TcpChannelImpl",
"channel",
"=",
"(",
"TcpChannelImpl",
")",
"handler",
";",
"channel",
".",
"registrationComplete",
"(",
"event",
".",
"event",
"(",
")",
")",
";",
"channel",
".",
"downPipeline",
"(",
")",
".",
"fire",
"(",
"new",
"Connected",
"(",
"channel",
".",
"nioChannel",
"(",
")",
".",
"getLocalAddress",
"(",
")",
",",
"channel",
".",
"nioChannel",
"(",
")",
".",
"getRemoteAddress",
"(",
")",
")",
",",
"channel",
")",
";",
"}"
] | Called when the new socket channel has successfully been registered
with the nio dispatcher.
@param event the event
@throws InterruptedException the interrupted exception
@throws IOException Signals that an I/O exception has occurred. | [
"Called",
"when",
"the",
"new",
"socket",
"channel",
"has",
"successfully",
"been",
"registered",
"with",
"the",
"nio",
"dispatcher",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java#L105-L122 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java | TcpConnector.onClose | @Handler
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onClose(Close event) throws IOException, InterruptedException {
for (Channel channel : event.channels()) {
if (channel instanceof TcpChannelImpl
&& channels.contains(channel)) {
((TcpChannelImpl) channel).close();
}
}
} | java | @Handler
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onClose(Close event) throws IOException, InterruptedException {
for (Channel channel : event.channels()) {
if (channel instanceof TcpChannelImpl
&& channels.contains(channel)) {
((TcpChannelImpl) channel).close();
}
}
} | [
"@",
"Handler",
"@",
"SuppressWarnings",
"(",
"\"PMD.DataflowAnomalyAnalysis\"",
")",
"public",
"void",
"onClose",
"(",
"Close",
"event",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"for",
"(",
"Channel",
"channel",
":",
"event",
".",
"channels",
"(",
")",
")",
"{",
"if",
"(",
"channel",
"instanceof",
"TcpChannelImpl",
"&&",
"channels",
".",
"contains",
"(",
"channel",
")",
")",
"{",
"(",
"(",
"TcpChannelImpl",
")",
"channel",
")",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | Shuts down the one of the connections.
@param event the event
@throws IOException if an I/O exception occurred
@throws InterruptedException if the execution was interrupted | [
"Shuts",
"down",
"the",
"one",
"of",
"the",
"connections",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/net/TcpConnector.java#L131-L140 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/validity/ValidatorFactoryMaker.java | ValidatorFactoryMaker.newValidator | @Override
public Validator newValidator(String identifier) {
if (identifier==null) {
return null;
}
ValidatorFactory template;
synchronized (map) {
verifyMapIntegrity();
template = map.get(identifier);
}
if (template!=null) {
try {
return template.newValidator(identifier);
} catch (ValidatorFactoryException e) {
logger.log(Level.WARNING, "Failed to create validator.", e);
return null;
}
} else {
return null;
}
} | java | @Override
public Validator newValidator(String identifier) {
if (identifier==null) {
return null;
}
ValidatorFactory template;
synchronized (map) {
verifyMapIntegrity();
template = map.get(identifier);
}
if (template!=null) {
try {
return template.newValidator(identifier);
} catch (ValidatorFactoryException e) {
logger.log(Level.WARNING, "Failed to create validator.", e);
return null;
}
} else {
return null;
}
} | [
"@",
"Override",
"public",
"Validator",
"newValidator",
"(",
"String",
"identifier",
")",
"{",
"if",
"(",
"identifier",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"ValidatorFactory",
"template",
";",
"synchronized",
"(",
"map",
")",
"{",
"verifyMapIntegrity",
"(",
")",
";",
"template",
"=",
"map",
".",
"get",
"(",
"identifier",
")",
";",
"}",
"if",
"(",
"template",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"template",
".",
"newValidator",
"(",
"identifier",
")",
";",
"}",
"catch",
"(",
"ValidatorFactoryException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to create validator.\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Obtains a new instance of a Validator with the given identifier
@param identifier a string that identifies the desired implementation
@return returns a Validator for the given identifier, or null if none is found | [
"Obtains",
"a",
"new",
"instance",
"of",
"a",
"Validator",
"with",
"the",
"given",
"identifier"
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/validity/ValidatorFactoryMaker.java#L104-L124 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/ResourcePattern.java | ResourcePattern.matches | @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity",
"PMD.CollapsibleIfStatements", "PMD.DataflowAnomalyAnalysis" })
public int matches(URI resource) {
if (protocol != null && !protocol.equals("*")) {
if (resource.getScheme() == null) {
return -1;
}
if (Arrays.stream(protocol.split(","))
.noneMatch(proto -> proto.equals(resource.getScheme()))) {
return -1;
}
}
if (host != null && !host.equals("*")) {
if (resource.getHost() == null
|| !resource.getHost().equals(host)) {
return -1;
}
}
if (port != null && !port.equals("*")) {
if (Integer.parseInt(port) != resource.getPort()) {
return -1;
}
}
String[] reqElements = PathSpliterator.stream(resource.getPath())
.skip(1).toArray(size -> new String[size]);
String[] reqElementsPlus = null; // Created lazily
for (int pathIdx = 0; pathIdx < pathPatternElements.length; pathIdx++) {
String[] pathPattern = pathPatternElements[pathIdx];
if (prefixSegs[pathIdx] == pathPattern.length - 1
&& lastIsEmpty(pathPattern)) {
// Special case, pattern ends with vertical bar
if (reqElementsPlus == null) {
reqElementsPlus = reqElements;
if (!lastIsEmpty(reqElementsPlus)) {
reqElementsPlus = Arrays.copyOf(
reqElementsPlus, reqElementsPlus.length + 1);
reqElementsPlus[reqElementsPlus.length - 1] = "";
}
}
if (matchPath(pathPattern, reqElementsPlus)) {
return prefixSegs[pathIdx];
}
} else {
if (matchPath(pathPattern, reqElements)) {
return prefixSegs[pathIdx];
}
}
}
return -1;
} | java | @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity",
"PMD.CollapsibleIfStatements", "PMD.DataflowAnomalyAnalysis" })
public int matches(URI resource) {
if (protocol != null && !protocol.equals("*")) {
if (resource.getScheme() == null) {
return -1;
}
if (Arrays.stream(protocol.split(","))
.noneMatch(proto -> proto.equals(resource.getScheme()))) {
return -1;
}
}
if (host != null && !host.equals("*")) {
if (resource.getHost() == null
|| !resource.getHost().equals(host)) {
return -1;
}
}
if (port != null && !port.equals("*")) {
if (Integer.parseInt(port) != resource.getPort()) {
return -1;
}
}
String[] reqElements = PathSpliterator.stream(resource.getPath())
.skip(1).toArray(size -> new String[size]);
String[] reqElementsPlus = null; // Created lazily
for (int pathIdx = 0; pathIdx < pathPatternElements.length; pathIdx++) {
String[] pathPattern = pathPatternElements[pathIdx];
if (prefixSegs[pathIdx] == pathPattern.length - 1
&& lastIsEmpty(pathPattern)) {
// Special case, pattern ends with vertical bar
if (reqElementsPlus == null) {
reqElementsPlus = reqElements;
if (!lastIsEmpty(reqElementsPlus)) {
reqElementsPlus = Arrays.copyOf(
reqElementsPlus, reqElementsPlus.length + 1);
reqElementsPlus[reqElementsPlus.length - 1] = "";
}
}
if (matchPath(pathPattern, reqElementsPlus)) {
return prefixSegs[pathIdx];
}
} else {
if (matchPath(pathPattern, reqElements)) {
return prefixSegs[pathIdx];
}
}
}
return -1;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"PMD.CyclomaticComplexity\"",
",",
"\"PMD.NPathComplexity\"",
",",
"\"PMD.CollapsibleIfStatements\"",
",",
"\"PMD.DataflowAnomalyAnalysis\"",
"}",
")",
"public",
"int",
"matches",
"(",
"URI",
"resource",
")",
"{",
"if",
"(",
"protocol",
"!=",
"null",
"&&",
"!",
"protocol",
".",
"equals",
"(",
"\"*\"",
")",
")",
"{",
"if",
"(",
"resource",
".",
"getScheme",
"(",
")",
"==",
"null",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"Arrays",
".",
"stream",
"(",
"protocol",
".",
"split",
"(",
"\",\"",
")",
")",
".",
"noneMatch",
"(",
"proto",
"->",
"proto",
".",
"equals",
"(",
"resource",
".",
"getScheme",
"(",
")",
")",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"if",
"(",
"host",
"!=",
"null",
"&&",
"!",
"host",
".",
"equals",
"(",
"\"*\"",
")",
")",
"{",
"if",
"(",
"resource",
".",
"getHost",
"(",
")",
"==",
"null",
"||",
"!",
"resource",
".",
"getHost",
"(",
")",
".",
"equals",
"(",
"host",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"if",
"(",
"port",
"!=",
"null",
"&&",
"!",
"port",
".",
"equals",
"(",
"\"*\"",
")",
")",
"{",
"if",
"(",
"Integer",
".",
"parseInt",
"(",
"port",
")",
"!=",
"resource",
".",
"getPort",
"(",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"String",
"[",
"]",
"reqElements",
"=",
"PathSpliterator",
".",
"stream",
"(",
"resource",
".",
"getPath",
"(",
")",
")",
".",
"skip",
"(",
"1",
")",
".",
"toArray",
"(",
"size",
"->",
"new",
"String",
"[",
"size",
"]",
")",
";",
"String",
"[",
"]",
"reqElementsPlus",
"=",
"null",
";",
"// Created lazily",
"for",
"(",
"int",
"pathIdx",
"=",
"0",
";",
"pathIdx",
"<",
"pathPatternElements",
".",
"length",
";",
"pathIdx",
"++",
")",
"{",
"String",
"[",
"]",
"pathPattern",
"=",
"pathPatternElements",
"[",
"pathIdx",
"]",
";",
"if",
"(",
"prefixSegs",
"[",
"pathIdx",
"]",
"==",
"pathPattern",
".",
"length",
"-",
"1",
"&&",
"lastIsEmpty",
"(",
"pathPattern",
")",
")",
"{",
"// Special case, pattern ends with vertical bar",
"if",
"(",
"reqElementsPlus",
"==",
"null",
")",
"{",
"reqElementsPlus",
"=",
"reqElements",
";",
"if",
"(",
"!",
"lastIsEmpty",
"(",
"reqElementsPlus",
")",
")",
"{",
"reqElementsPlus",
"=",
"Arrays",
".",
"copyOf",
"(",
"reqElementsPlus",
",",
"reqElementsPlus",
".",
"length",
"+",
"1",
")",
";",
"reqElementsPlus",
"[",
"reqElementsPlus",
".",
"length",
"-",
"1",
"]",
"=",
"\"\"",
";",
"}",
"}",
"if",
"(",
"matchPath",
"(",
"pathPattern",
",",
"reqElementsPlus",
")",
")",
"{",
"return",
"prefixSegs",
"[",
"pathIdx",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"matchPath",
"(",
"pathPattern",
",",
"reqElements",
")",
")",
"{",
"return",
"prefixSegs",
"[",
"pathIdx",
"]",
";",
"}",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Matches the given resource URI against the pattern.
@param resource the URI specifying the resource to match
@return -1 if the resource does not match, else the number
of prefix segments (which may be 0) | [
"Matches",
"the",
"given",
"resource",
"URI",
"against",
"the",
"pattern",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/ResourcePattern.java#L195-L245 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/ResourcePattern.java | ResourcePattern.matches | public static boolean matches(String pattern, URI resource)
throws ParseException {
return (new ResourcePattern(pattern)).matches(resource) >= 0;
} | java | public static boolean matches(String pattern, URI resource)
throws ParseException {
return (new ResourcePattern(pattern)).matches(resource) >= 0;
} | [
"public",
"static",
"boolean",
"matches",
"(",
"String",
"pattern",
",",
"URI",
"resource",
")",
"throws",
"ParseException",
"{",
"return",
"(",
"new",
"ResourcePattern",
"(",
"pattern",
")",
")",
".",
"matches",
"(",
"resource",
")",
">=",
"0",
";",
"}"
] | Matches the given pattern against the given resource URI.
@param pattern the pattern to match
@param resource the URI specifying the resource to match
@return {@code true} if the resource URI matches
@throws ParseException if an invalid pattern is specified | [
"Matches",
"the",
"given",
"pattern",
"against",
"the",
"given",
"resource",
"URI",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/ResourcePattern.java#L255-L258 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/StaticContentDispatcher.java | StaticContentDispatcher.onGet | @RequestHandler(dynamic = true)
public void onGet(Request.In.Get event, IOSubchannel channel)
throws ParseException, IOException {
int prefixSegs = resourcePattern.matches(event.requestUri());
if (prefixSegs < 0) {
return;
}
if (contentDirectory == null) {
getFromUri(event, channel, prefixSegs);
} else {
getFromFileSystem(event, channel, prefixSegs);
}
} | java | @RequestHandler(dynamic = true)
public void onGet(Request.In.Get event, IOSubchannel channel)
throws ParseException, IOException {
int prefixSegs = resourcePattern.matches(event.requestUri());
if (prefixSegs < 0) {
return;
}
if (contentDirectory == null) {
getFromUri(event, channel, prefixSegs);
} else {
getFromFileSystem(event, channel, prefixSegs);
}
} | [
"@",
"RequestHandler",
"(",
"dynamic",
"=",
"true",
")",
"public",
"void",
"onGet",
"(",
"Request",
".",
"In",
".",
"Get",
"event",
",",
"IOSubchannel",
"channel",
")",
"throws",
"ParseException",
",",
"IOException",
"{",
"int",
"prefixSegs",
"=",
"resourcePattern",
".",
"matches",
"(",
"event",
".",
"requestUri",
"(",
")",
")",
";",
"if",
"(",
"prefixSegs",
"<",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"contentDirectory",
"==",
"null",
")",
"{",
"getFromUri",
"(",
"event",
",",
"channel",
",",
"prefixSegs",
")",
";",
"}",
"else",
"{",
"getFromFileSystem",
"(",
"event",
",",
"channel",
",",
"prefixSegs",
")",
";",
"}",
"}"
] | Handles a `GET` request.
@param event the event
@param channel the channel
@throws ParseException the parse exception
@throws IOException Signals that an I/O exception has occurred. | [
"Handles",
"a",
"GET",
"request",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/StaticContentDispatcher.java#L135-L147 | train |
mnlipp/jgrapes | examples/src/org/jgrapes/examples/io/consoleinput/EchoUntilQuit.java | EchoUntilQuit.onInput | @Handler
@SuppressWarnings("PMD.SystemPrintln")
public void onInput(Input<ByteBuffer> event) {
String data = Charset.defaultCharset().decode(event.data()).toString();
System.out.print(data);
if (data.trim().equals("QUIT")) {
fire(new Stop());
}
} | java | @Handler
@SuppressWarnings("PMD.SystemPrintln")
public void onInput(Input<ByteBuffer> event) {
String data = Charset.defaultCharset().decode(event.data()).toString();
System.out.print(data);
if (data.trim().equals("QUIT")) {
fire(new Stop());
}
} | [
"@",
"Handler",
"@",
"SuppressWarnings",
"(",
"\"PMD.SystemPrintln\"",
")",
"public",
"void",
"onInput",
"(",
"Input",
"<",
"ByteBuffer",
">",
"event",
")",
"{",
"String",
"data",
"=",
"Charset",
".",
"defaultCharset",
"(",
")",
".",
"decode",
"(",
"event",
".",
"data",
"(",
")",
")",
".",
"toString",
"(",
")",
";",
"System",
".",
"out",
".",
"print",
"(",
"data",
")",
";",
"if",
"(",
"data",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"QUIT\"",
")",
")",
"{",
"fire",
"(",
"new",
"Stop",
"(",
")",
")",
";",
"}",
"}"
] | Handle input.
@param event the event | [
"Handle",
"input",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/examples/src/org/jgrapes/examples/io/consoleinput/EchoUntilQuit.java#L67-L75 | train |
mnlipp/jgrapes | org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java | ConfigurationUpdate.removePath | public ConfigurationUpdate removePath(String path) {
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("Path must start with \"/\".");
}
paths.put(path, null);
return this;
} | java | public ConfigurationUpdate removePath(String path) {
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("Path must start with \"/\".");
}
paths.put(path, null);
return this;
} | [
"public",
"ConfigurationUpdate",
"removePath",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"==",
"null",
"||",
"!",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Path must start with \\\"/\\\".\"",
")",
";",
"}",
"paths",
".",
"put",
"(",
"path",
",",
"null",
")",
";",
"return",
"this",
";",
"}"
] | Remove a path from the configuration.
@param path the path to be removed
@return the event for easy chaining | [
"Remove",
"a",
"path",
"from",
"the",
"configuration",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java#L71-L77 | train |
mnlipp/jgrapes | org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java | ConfigurationUpdate.values | public Optional<Map<String,String>> values(String path) {
Map<String,String> result = paths.get(path);
if (result == null) {
return Optional.empty();
}
return Optional.of(Collections.unmodifiableMap(result));
} | java | public Optional<Map<String,String>> values(String path) {
Map<String,String> result = paths.get(path);
if (result == null) {
return Optional.empty();
}
return Optional.of(Collections.unmodifiableMap(result));
} | [
"public",
"Optional",
"<",
"Map",
"<",
"String",
",",
"String",
">",
">",
"values",
"(",
"String",
"path",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"result",
"=",
"paths",
".",
"get",
"(",
"path",
")",
";",
"if",
"(",
"result",
"==",
"null",
")",
"{",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"return",
"Optional",
".",
"of",
"(",
"Collections",
".",
"unmodifiableMap",
"(",
"result",
")",
")",
";",
"}"
] | Return the values for a given path if they exists.
@param path the path
@return the updated values or `null` if the path has been
removed (implies the removal of all values for that path). | [
"Return",
"the",
"values",
"for",
"a",
"given",
"path",
"if",
"they",
"exists",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java#L95-L101 | train |
mnlipp/jgrapes | org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java | ConfigurationUpdate.value | public Optional<String> value(String path, String key) {
return Optional.ofNullable(paths.get(path))
.flatMap(map -> Optional.ofNullable(map.get(key)));
} | java | public Optional<String> value(String path, String key) {
return Optional.ofNullable(paths.get(path))
.flatMap(map -> Optional.ofNullable(map.get(key)));
} | [
"public",
"Optional",
"<",
"String",
">",
"value",
"(",
"String",
"path",
",",
"String",
"key",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"paths",
".",
"get",
"(",
"path",
")",
")",
".",
"flatMap",
"(",
"map",
"->",
"Optional",
".",
"ofNullable",
"(",
"map",
".",
"get",
"(",
"key",
")",
")",
")",
";",
"}"
] | Return the value with the given path and key if it exists.
@param path the path
@param key the key
@return the value | [
"Return",
"the",
"value",
"with",
"the",
"given",
"path",
"and",
"key",
"if",
"it",
"exists",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.util/src/org/jgrapes/util/events/ConfigurationUpdate.java#L110-L113 | train |
meridor/perspective-backend | perspective-shell/src/main/java/org/meridor/perspective/shell/common/repository/impl/TextUtils.java | TextUtils.isRange | public static boolean isRange(String value) {
if (value == null) {
return false;
}
try {
Set<Integer> values = parseRange(value);
return values.size() > 0;
} catch (Exception e) {
return false;
}
} | java | public static boolean isRange(String value) {
if (value == null) {
return false;
}
try {
Set<Integer> values = parseRange(value);
return values.size() > 0;
} catch (Exception e) {
return false;
}
} | [
"public",
"static",
"boolean",
"isRange",
"(",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"Set",
"<",
"Integer",
">",
"values",
"=",
"parseRange",
"(",
"value",
")",
";",
"return",
"values",
".",
"size",
"(",
")",
">",
"0",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Returns whether passed value is a range
@param value string to process
@return true if range, false otherwise | [
"Returns",
"whether",
"passed",
"value",
"is",
"a",
"range"
] | 5f98083977a57115988678e97d1642ee83431258 | https://github.com/meridor/perspective-backend/blob/5f98083977a57115988678e97d1642ee83431258/perspective-shell/src/main/java/org/meridor/perspective/shell/common/repository/impl/TextUtils.java#L187-L197 | train |
inversoft/restify | src/main/java/com/inversoft/net/ssl/SSLTools.java | SSLTools.disableSSLValidation | public static void disableSSLValidation() {
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[]{new UnsafeTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | public static void disableSSLValidation() {
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[]{new UnsafeTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"void",
"disableSSLValidation",
"(",
")",
"{",
"try",
"{",
"SSLContext",
"context",
"=",
"SSLContext",
".",
"getInstance",
"(",
"\"SSL\"",
")",
";",
"context",
".",
"init",
"(",
"null",
",",
"new",
"TrustManager",
"[",
"]",
"{",
"new",
"UnsafeTrustManager",
"(",
")",
"}",
",",
"null",
")",
";",
"HttpsURLConnection",
".",
"setDefaultSSLSocketFactory",
"(",
"context",
".",
"getSocketFactory",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Disabling SSL validation is strongly discouraged. This is generally only intended for use during testing or perhaps
when used in a private network with a self signed certificate.
<p>Even when using with a self signed certificate it is recommended that instead of disabling SSL validation you
instead add your self signed certificate to the Java keystore.</p> | [
"Disabling",
"SSL",
"validation",
"is",
"strongly",
"discouraged",
".",
"This",
"is",
"generally",
"only",
"intended",
"for",
"use",
"during",
"testing",
"or",
"perhaps",
"when",
"used",
"in",
"a",
"private",
"network",
"with",
"a",
"self",
"signed",
"certificate",
"."
] | f2426d9082e00a9d958af28f78ccda61802c6700 | https://github.com/inversoft/restify/blob/f2426d9082e00a9d958af28f78ccda61802c6700/src/main/java/com/inversoft/net/ssl/SSLTools.java#L90-L98 | train |
inversoft/restify | src/main/java/com/inversoft/net/ssl/SSLTools.java | SSLTools.enableSSLValidation | public static void enableSSLValidation() {
try {
SSLContext.getInstance("SSL").init(null, null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | public static void enableSSLValidation() {
try {
SSLContext.getInstance("SSL").init(null, null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"void",
"enableSSLValidation",
"(",
")",
"{",
"try",
"{",
"SSLContext",
".",
"getInstance",
"(",
"\"SSL\"",
")",
".",
"init",
"(",
"null",
",",
"null",
",",
"null",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Enable SSL Validation. | [
"Enable",
"SSL",
"Validation",
"."
] | f2426d9082e00a9d958af28f78ccda61802c6700 | https://github.com/inversoft/restify/blob/f2426d9082e00a9d958af28f78ccda61802c6700/src/main/java/com/inversoft/net/ssl/SSLTools.java#L103-L109 | train |
inversoft/restify | src/main/java/com/inversoft/net/ssl/SSLTools.java | SSLTools.validCertificateString | public static boolean validCertificateString(String certificateString) {
try {
byte[] certBytes = parseDERFromPEM(certificateString, CERT_START, CERT_END);
generateCertificateFromDER(certBytes);
} catch (Exception e) {
return false;
}
return true;
} | java | public static boolean validCertificateString(String certificateString) {
try {
byte[] certBytes = parseDERFromPEM(certificateString, CERT_START, CERT_END);
generateCertificateFromDER(certBytes);
} catch (Exception e) {
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"validCertificateString",
"(",
"String",
"certificateString",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"certBytes",
"=",
"parseDERFromPEM",
"(",
"certificateString",
",",
"CERT_START",
",",
"CERT_END",
")",
";",
"generateCertificateFromDER",
"(",
"certBytes",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Checks the given certificate String to ensure it is a PEM formatted certificate.
@param certificateString The certificate String.
@return True if the certificate String is valid, false if it isn't (this happens when an exception is thrown
attempting to parse the PEM format). | [
"Checks",
"the",
"given",
"certificate",
"String",
"to",
"ensure",
"it",
"is",
"a",
"PEM",
"formatted",
"certificate",
"."
] | f2426d9082e00a9d958af28f78ccda61802c6700 | https://github.com/inversoft/restify/blob/f2426d9082e00a9d958af28f78ccda61802c6700/src/main/java/com/inversoft/net/ssl/SSLTools.java#L212-L220 | train |
inversoft/restify | src/main/java/com/inversoft/rest/RESTClient.java | RESTClient.urlParameter | public RESTClient<RS, ERS> urlParameter(String name, Object value) {
if (value == null) {
return this;
}
List<Object> values = this.parameters.get(name);
if (values == null) {
values = new ArrayList<>();
this.parameters.put(name, values);
}
if (value instanceof ZonedDateTime) {
values.add(((ZonedDateTime) value).toInstant().toEpochMilli());
} else if (value instanceof Collection) {
values.addAll((Collection) value);
} else {
values.add(value);
}
return this;
} | java | public RESTClient<RS, ERS> urlParameter(String name, Object value) {
if (value == null) {
return this;
}
List<Object> values = this.parameters.get(name);
if (values == null) {
values = new ArrayList<>();
this.parameters.put(name, values);
}
if (value instanceof ZonedDateTime) {
values.add(((ZonedDateTime) value).toInstant().toEpochMilli());
} else if (value instanceof Collection) {
values.addAll((Collection) value);
} else {
values.add(value);
}
return this;
} | [
"public",
"RESTClient",
"<",
"RS",
",",
"ERS",
">",
"urlParameter",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"List",
"<",
"Object",
">",
"values",
"=",
"this",
".",
"parameters",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"values",
"==",
"null",
")",
"{",
"values",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"this",
".",
"parameters",
".",
"put",
"(",
"name",
",",
"values",
")",
";",
"}",
"if",
"(",
"value",
"instanceof",
"ZonedDateTime",
")",
"{",
"values",
".",
"add",
"(",
"(",
"(",
"ZonedDateTime",
")",
"value",
")",
".",
"toInstant",
"(",
")",
".",
"toEpochMilli",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Collection",
")",
"{",
"values",
".",
"addAll",
"(",
"(",
"Collection",
")",
"value",
")",
";",
"}",
"else",
"{",
"values",
".",
"add",
"(",
"value",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Add a URL parameter as a key value pair.
@param name The URL parameter name.
@param value The url parameter value. The <code>.toString()</code> method will be used to
get the <code>String</code> used in the URL parameter. If the object type is a
{@link Collection} a key value pair will be added for each value in the collection.
{@link ZonedDateTime} will also be handled uniquely in that the <code>long</code> will
be used to set in the request using <code>ZonedDateTime.toInstant().toEpochMilli()</code>
@return This. | [
"Add",
"a",
"URL",
"parameter",
"as",
"a",
"key",
"value",
"pair",
"."
] | f2426d9082e00a9d958af28f78ccda61802c6700 | https://github.com/inversoft/restify/blob/f2426d9082e00a9d958af28f78ccda61802c6700/src/main/java/com/inversoft/rest/RESTClient.java#L320-L339 | train |
kawasima/websocket-classloader | src/main/java/net/unit8/wscl/WebSocketClassLoader.java | WebSocketClassLoader.findResources | @Override
protected Enumeration<URL> findResources(String name) {
URL url = findResource(name);
Vector<URL> urls = new Vector<>();
if (url != null) {
urls.add(url);
}
return urls.elements();
} | java | @Override
protected Enumeration<URL> findResources(String name) {
URL url = findResource(name);
Vector<URL> urls = new Vector<>();
if (url != null) {
urls.add(url);
}
return urls.elements();
} | [
"@",
"Override",
"protected",
"Enumeration",
"<",
"URL",
">",
"findResources",
"(",
"String",
"name",
")",
"{",
"URL",
"url",
"=",
"findResource",
"(",
"name",
")",
";",
"Vector",
"<",
"URL",
">",
"urls",
"=",
"new",
"Vector",
"<>",
"(",
")",
";",
"if",
"(",
"url",
"!=",
"null",
")",
"{",
"urls",
".",
"add",
"(",
"url",
")",
";",
"}",
"return",
"urls",
".",
"elements",
"(",
")",
";",
"}"
] | Returns an enumeration of URL objects representing all the resources with th given name.
Currently, WebSocketClassLoader returns only the first element.
@param name The name of a resource.
@return All founded resources. | [
"Returns",
"an",
"enumeration",
"of",
"URL",
"objects",
"representing",
"all",
"the",
"resources",
"with",
"th",
"given",
"name",
"."
] | 2172e43202b3185e34a1357c46778f63d5339de0 | https://github.com/kawasima/websocket-classloader/blob/2172e43202b3185e34a1357c46778f63d5339de0/src/main/java/net/unit8/wscl/WebSocketClassLoader.java#L120-L128 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/ConfigurationsCatalog.java | ConfigurationsCatalog.unsetUserConfigurations | public void unsetUserConfigurations(UserConfigurationsProvider provider) {
if (userConfigurations.isPresent() && userConfigurations.get().equals(provider)) {
this.userConfigurations = Optional.empty();
}
} | java | public void unsetUserConfigurations(UserConfigurationsProvider provider) {
if (userConfigurations.isPresent() && userConfigurations.get().equals(provider)) {
this.userConfigurations = Optional.empty();
}
} | [
"public",
"void",
"unsetUserConfigurations",
"(",
"UserConfigurationsProvider",
"provider",
")",
"{",
"if",
"(",
"userConfigurations",
".",
"isPresent",
"(",
")",
"&&",
"userConfigurations",
".",
"get",
"(",
")",
".",
"equals",
"(",
"provider",
")",
")",
"{",
"this",
".",
"userConfigurations",
"=",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"}"
] | Unset reference added automatically from setUserConfigurations annotation | [
"Unset",
"reference",
"added",
"automatically",
"from",
"setUserConfigurations",
"annotation"
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/ConfigurationsCatalog.java#L122-L126 | train |
anotheria/configureme | src/main/java/org/configureme/repository/Artefact.java | Artefact.getAttribute | public Attribute getAttribute(final String attributeName) {
final Attribute a = attributes.get(attributeName);
if (a == null)
throw new IllegalArgumentException("Attribute " + attributeName + " doesn't exists");
return a;
} | java | public Attribute getAttribute(final String attributeName) {
final Attribute a = attributes.get(attributeName);
if (a == null)
throw new IllegalArgumentException("Attribute " + attributeName + " doesn't exists");
return a;
} | [
"public",
"Attribute",
"getAttribute",
"(",
"final",
"String",
"attributeName",
")",
"{",
"final",
"Attribute",
"a",
"=",
"attributes",
".",
"get",
"(",
"attributeName",
")",
";",
"if",
"(",
"a",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Attribute \"",
"+",
"attributeName",
"+",
"\" doesn't exists\"",
")",
";",
"return",
"a",
";",
"}"
] | Returns the attribute with the given name. Throws an IllegalArgumentException if there is no such attribute.
@param attributeName a {@link java.lang.String} object.
@return the attribute with the given name | [
"Returns",
"the",
"attribute",
"with",
"the",
"given",
"name",
".",
"Throws",
"an",
"IllegalArgumentException",
"if",
"there",
"is",
"no",
"such",
"attribute",
"."
] | 1f52dd9109349623190586bdf5a592de8016e1fa | https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/repository/Artefact.java#L77-L82 | train |
anotheria/configureme | src/main/java/org/configureme/repository/Artefact.java | Artefact.addAttributeValue | public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) {
if (in == null)
in = GlobalEnvironment.INSTANCE;
Attribute attr = attributes.get(attributeName);
if (attr == null) {
attr = new Attribute(attributeName);
attributes.put(attr.getName(), attr);
}
attr.addValue(attributeValue, in);
Map<String, Object> valueMap = contentMap.get(in);
if(valueMap == null)
valueMap = new HashMap<>();
valueMap.put(attributeName, attributeValue.getRaw());
contentMap.put(in, valueMap);
//TODO check for loops and process such situation
if (attributeValue instanceof IncludeValue)
externalConfigurations.add(((IncludeValue) attributeValue).getConfigName());
} | java | public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) {
if (in == null)
in = GlobalEnvironment.INSTANCE;
Attribute attr = attributes.get(attributeName);
if (attr == null) {
attr = new Attribute(attributeName);
attributes.put(attr.getName(), attr);
}
attr.addValue(attributeValue, in);
Map<String, Object> valueMap = contentMap.get(in);
if(valueMap == null)
valueMap = new HashMap<>();
valueMap.put(attributeName, attributeValue.getRaw());
contentMap.put(in, valueMap);
//TODO check for loops and process such situation
if (attributeValue instanceof IncludeValue)
externalConfigurations.add(((IncludeValue) attributeValue).getConfigName());
} | [
"public",
"void",
"addAttributeValue",
"(",
"final",
"String",
"attributeName",
",",
"final",
"Value",
"attributeValue",
",",
"Environment",
"in",
")",
"{",
"if",
"(",
"in",
"==",
"null",
")",
"in",
"=",
"GlobalEnvironment",
".",
"INSTANCE",
";",
"Attribute",
"attr",
"=",
"attributes",
".",
"get",
"(",
"attributeName",
")",
";",
"if",
"(",
"attr",
"==",
"null",
")",
"{",
"attr",
"=",
"new",
"Attribute",
"(",
"attributeName",
")",
";",
"attributes",
".",
"put",
"(",
"attr",
".",
"getName",
"(",
")",
",",
"attr",
")",
";",
"}",
"attr",
".",
"addValue",
"(",
"attributeValue",
",",
"in",
")",
";",
"Map",
"<",
"String",
",",
"Object",
">",
"valueMap",
"=",
"contentMap",
".",
"get",
"(",
"in",
")",
";",
"if",
"(",
"valueMap",
"==",
"null",
")",
"valueMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"valueMap",
".",
"put",
"(",
"attributeName",
",",
"attributeValue",
".",
"getRaw",
"(",
")",
")",
";",
"contentMap",
".",
"put",
"(",
"in",
",",
"valueMap",
")",
";",
"//TODO check for loops and process such situation",
"if",
"(",
"attributeValue",
"instanceof",
"IncludeValue",
")",
"externalConfigurations",
".",
"add",
"(",
"(",
"(",
"IncludeValue",
")",
"attributeValue",
")",
".",
"getConfigName",
"(",
")",
")",
";",
"}"
] | Adds an attribute value. If the attribute doesn't exist it will be created.
@param attributeName the name of the attribute.
@param attributeValue the value of the attribute in the given environment.
@param in the environment in which the attribute value applies | [
"Adds",
"an",
"attribute",
"value",
".",
"If",
"the",
"attribute",
"doesn",
"t",
"exist",
"it",
"will",
"be",
"created",
"."
] | 1f52dd9109349623190586bdf5a592de8016e1fa | https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/repository/Artefact.java#L91-L109 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/HttpServer.java | HttpServer.onClose | @Handler
public void onClose(Close event, WebAppMsgChannel appChannel)
throws InterruptedException {
appChannel.handleClose(event);
} | java | @Handler
public void onClose(Close event, WebAppMsgChannel appChannel)
throws InterruptedException {
appChannel.handleClose(event);
} | [
"@",
"Handler",
"public",
"void",
"onClose",
"(",
"Close",
"event",
",",
"WebAppMsgChannel",
"appChannel",
")",
"throws",
"InterruptedException",
"{",
"appChannel",
".",
"handleClose",
"(",
"event",
")",
";",
"}"
] | Handles a close event from downstream by closing the upstream
connections.
@param event
the close event
@throws InterruptedException if the execution was interrupted | [
"Handles",
"a",
"close",
"event",
"from",
"downstream",
"by",
"closing",
"the",
"upstream",
"connections",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/HttpServer.java#L333-L337 | train |
mnlipp/jgrapes | org.jgrapes.http/src/org/jgrapes/http/HttpServer.java | HttpServer.onOptions | @Handler(priority = Integer.MIN_VALUE)
public void onOptions(Request.In.Options event, IOSubchannel appChannel) {
if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) {
HttpResponse response = event.httpRequest().response().get();
response.setStatus(HttpStatus.OK);
appChannel.respond(new Response(response));
event.setResult(true);
event.stop();
}
} | java | @Handler(priority = Integer.MIN_VALUE)
public void onOptions(Request.In.Options event, IOSubchannel appChannel) {
if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) {
HttpResponse response = event.httpRequest().response().get();
response.setStatus(HttpStatus.OK);
appChannel.respond(new Response(response));
event.setResult(true);
event.stop();
}
} | [
"@",
"Handler",
"(",
"priority",
"=",
"Integer",
".",
"MIN_VALUE",
")",
"public",
"void",
"onOptions",
"(",
"Request",
".",
"In",
".",
"Options",
"event",
",",
"IOSubchannel",
"appChannel",
")",
"{",
"if",
"(",
"event",
".",
"requestUri",
"(",
")",
"==",
"HttpRequest",
".",
"ASTERISK_REQUEST",
")",
"{",
"HttpResponse",
"response",
"=",
"event",
".",
"httpRequest",
"(",
")",
".",
"response",
"(",
")",
".",
"get",
"(",
")",
";",
"response",
".",
"setStatus",
"(",
"HttpStatus",
".",
"OK",
")",
";",
"appChannel",
".",
"respond",
"(",
"new",
"Response",
"(",
"response",
")",
")",
";",
"event",
".",
"setResult",
"(",
"true",
")",
";",
"event",
".",
"stop",
"(",
")",
";",
"}",
"}"
] | Provides a fallback handler for an OPTIONS request with asterisk. Simply
responds with "OK".
@param event the event
@param appChannel the application channel | [
"Provides",
"a",
"fallback",
"handler",
"for",
"an",
"OPTIONS",
"request",
"with",
"asterisk",
".",
"Simply",
"responds",
"with",
"OK",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.http/src/org/jgrapes/http/HttpServer.java#L386-L395 | train |
tommyettinger/RegExodus | src/main/java/regexodus/Pattern.java | Pattern.matcher | public Matcher matcher(CharSequence s) {
Matcher m = new Matcher(this);
m.setTarget(s);
return m;
} | java | public Matcher matcher(CharSequence s) {
Matcher m = new Matcher(this);
m.setTarget(s);
return m;
} | [
"public",
"Matcher",
"matcher",
"(",
"CharSequence",
"s",
")",
"{",
"Matcher",
"m",
"=",
"new",
"Matcher",
"(",
"this",
")",
";",
"m",
".",
"setTarget",
"(",
"s",
")",
";",
"return",
"m",
";",
"}"
] | Returns a matcher for a specified string. | [
"Returns",
"a",
"matcher",
"for",
"a",
"specified",
"string",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/Pattern.java#L491-L495 | train |
tommyettinger/RegExodus | src/main/java/regexodus/Pattern.java | Pattern.matcher | public Matcher matcher(char[] data, int start, int end) {
Matcher m = new Matcher(this);
m.setTarget(data, start, end);
return m;
} | java | public Matcher matcher(char[] data, int start, int end) {
Matcher m = new Matcher(this);
m.setTarget(data, start, end);
return m;
} | [
"public",
"Matcher",
"matcher",
"(",
"char",
"[",
"]",
"data",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"Matcher",
"m",
"=",
"new",
"Matcher",
"(",
"this",
")",
";",
"m",
".",
"setTarget",
"(",
"data",
",",
"start",
",",
"end",
")",
";",
"return",
"m",
";",
"}"
] | Returns a matcher for a specified region. | [
"Returns",
"a",
"matcher",
"for",
"a",
"specified",
"region",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/Pattern.java#L500-L504 | train |
tommyettinger/RegExodus | src/main/java/regexodus/Pattern.java | Pattern.matcher | public Matcher matcher(MatchResult res, String groupName) {
Integer id = res.pattern().groupId(groupName);
if (id == null) throw new IllegalArgumentException("group not found:" + groupName);
int group = id;
return matcher(res, group);
} | java | public Matcher matcher(MatchResult res, String groupName) {
Integer id = res.pattern().groupId(groupName);
if (id == null) throw new IllegalArgumentException("group not found:" + groupName);
int group = id;
return matcher(res, group);
} | [
"public",
"Matcher",
"matcher",
"(",
"MatchResult",
"res",
",",
"String",
"groupName",
")",
"{",
"Integer",
"id",
"=",
"res",
".",
"pattern",
"(",
")",
".",
"groupId",
"(",
"groupName",
")",
";",
"if",
"(",
"id",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"group not found:\"",
"+",
"groupName",
")",
";",
"int",
"group",
"=",
"id",
";",
"return",
"matcher",
"(",
"res",
",",
"group",
")",
";",
"}"
] | Just as above, yet with symbolic group name.
@throws NullPointerException if there is no group with such name | [
"Just",
"as",
"above",
"yet",
"with",
"symbolic",
"group",
"name",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/Pattern.java#L527-L532 | train |
meridor/perspective-backend | perspective-sql/src/main/java/org/meridor/perspective/sql/impl/expression/ColumnRelation.java | ColumnRelation.toList | public List<ColumnRelation> toList() {
List<ColumnRelation> ret = new ArrayList<>();
ret.add(this);
if (getNextRelation().isPresent()) {
ret.addAll(getNextRelation().get().toList());
}
return ret;
} | java | public List<ColumnRelation> toList() {
List<ColumnRelation> ret = new ArrayList<>();
ret.add(this);
if (getNextRelation().isPresent()) {
ret.addAll(getNextRelation().get().toList());
}
return ret;
} | [
"public",
"List",
"<",
"ColumnRelation",
">",
"toList",
"(",
")",
"{",
"List",
"<",
"ColumnRelation",
">",
"ret",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"ret",
".",
"add",
"(",
"this",
")",
";",
"if",
"(",
"getNextRelation",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"ret",
".",
"addAll",
"(",
"getNextRelation",
"(",
")",
".",
"get",
"(",
")",
".",
"toList",
"(",
")",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Returns a chain of column relations as list | [
"Returns",
"a",
"chain",
"of",
"column",
"relations",
"as",
"list"
] | 5f98083977a57115988678e97d1642ee83431258 | https://github.com/meridor/perspective-backend/blob/5f98083977a57115988678e97d1642ee83431258/perspective-sql/src/main/java/org/meridor/perspective/sql/impl/expression/ColumnRelation.java#L97-L104 | train |
meridor/perspective-backend | perspective-sql/src/main/java/org/meridor/perspective/sql/impl/parser/DataSourceUtils.java | DataSourceUtils.addToDataSource | public static void addToDataSource(DataSource parent, DataSource child) {
if (!parent.getLeftDataSource().isPresent()) {
parent.setLeftDataSource(child);
} else if (!parent.getRightDataSource().isPresent()) {
parent.setRightDataSource(child);
} else {
DataSource newLeftDataSource = new DataSource(parent.getLeftDataSource().get());
newLeftDataSource.setRightDataSource(parent.getRightDataSource().get());
parent.setLeftDataSource(newLeftDataSource);
parent.setRightDataSource(child);
}
} | java | public static void addToDataSource(DataSource parent, DataSource child) {
if (!parent.getLeftDataSource().isPresent()) {
parent.setLeftDataSource(child);
} else if (!parent.getRightDataSource().isPresent()) {
parent.setRightDataSource(child);
} else {
DataSource newLeftDataSource = new DataSource(parent.getLeftDataSource().get());
newLeftDataSource.setRightDataSource(parent.getRightDataSource().get());
parent.setLeftDataSource(newLeftDataSource);
parent.setRightDataSource(child);
}
} | [
"public",
"static",
"void",
"addToDataSource",
"(",
"DataSource",
"parent",
",",
"DataSource",
"child",
")",
"{",
"if",
"(",
"!",
"parent",
".",
"getLeftDataSource",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"parent",
".",
"setLeftDataSource",
"(",
"child",
")",
";",
"}",
"else",
"if",
"(",
"!",
"parent",
".",
"getRightDataSource",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"parent",
".",
"setRightDataSource",
"(",
"child",
")",
";",
"}",
"else",
"{",
"DataSource",
"newLeftDataSource",
"=",
"new",
"DataSource",
"(",
"parent",
".",
"getLeftDataSource",
"(",
")",
".",
"get",
"(",
")",
")",
";",
"newLeftDataSource",
".",
"setRightDataSource",
"(",
"parent",
".",
"getRightDataSource",
"(",
")",
".",
"get",
"(",
")",
")",
";",
"parent",
".",
"setLeftDataSource",
"(",
"newLeftDataSource",
")",
";",
"parent",
".",
"setRightDataSource",
"(",
"child",
")",
";",
"}",
"}"
] | Builds optimized data source as a tree
@param parent data source to add child to
@param child child data source | [
"Builds",
"optimized",
"data",
"source",
"as",
"a",
"tree"
] | 5f98083977a57115988678e97d1642ee83431258 | https://github.com/meridor/perspective-backend/blob/5f98083977a57115988678e97d1642ee83431258/perspective-sql/src/main/java/org/meridor/perspective/sql/impl/parser/DataSourceUtils.java#L31-L42 | train |
dmerkushov/log-helper | src/main/java/ru/dmerkushov/loghelper/formatter/DefaultFormatter.java | DefaultFormatter.format | @Override
public String format (LogRecord logRecord) {
StringBuilder resultBuilder = new StringBuilder ();
String prefix = logRecord.getLevel ().getName () + "\t";
resultBuilder.append (prefix);
resultBuilder.append (Thread.currentThread ().getName ())
.append (" ")
.append (sdf.format (new java.util.Date (logRecord.getMillis ())))
.append (": ")
.append (logRecord.getSourceClassName ())
.append (":")
.append (logRecord.getSourceMethodName ())
.append (": ")
.append (logRecord.getMessage ());
Object[] params = logRecord.getParameters ();
if (params != null) {
resultBuilder.append ("\nParameters:");
if (params.length < 1) {
resultBuilder.append (" (none)");
} else {
for (int paramIndex = 0; paramIndex < params.length; paramIndex++) {
Object param = params[paramIndex];
if (param != null) {
String paramString = param.toString ();
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is a ")
.append (param.getClass ().getName ())
.append (": >")
.append (paramString)
.append ("<");
} else {
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is null.");
}
}
}
}
Throwable t = logRecord.getThrown ();
if (t != null) {
resultBuilder.append ("\nThrowing:\n")
.append (getFullThrowableMsg (t));
}
String result = resultBuilder.toString ().replaceAll ("\n", "\n" + prefix) + "\n";
return result;
} | java | @Override
public String format (LogRecord logRecord) {
StringBuilder resultBuilder = new StringBuilder ();
String prefix = logRecord.getLevel ().getName () + "\t";
resultBuilder.append (prefix);
resultBuilder.append (Thread.currentThread ().getName ())
.append (" ")
.append (sdf.format (new java.util.Date (logRecord.getMillis ())))
.append (": ")
.append (logRecord.getSourceClassName ())
.append (":")
.append (logRecord.getSourceMethodName ())
.append (": ")
.append (logRecord.getMessage ());
Object[] params = logRecord.getParameters ();
if (params != null) {
resultBuilder.append ("\nParameters:");
if (params.length < 1) {
resultBuilder.append (" (none)");
} else {
for (int paramIndex = 0; paramIndex < params.length; paramIndex++) {
Object param = params[paramIndex];
if (param != null) {
String paramString = param.toString ();
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is a ")
.append (param.getClass ().getName ())
.append (": >")
.append (paramString)
.append ("<");
} else {
resultBuilder.append ("\nParameter ")
.append (String.valueOf (paramIndex))
.append (" is null.");
}
}
}
}
Throwable t = logRecord.getThrown ();
if (t != null) {
resultBuilder.append ("\nThrowing:\n")
.append (getFullThrowableMsg (t));
}
String result = resultBuilder.toString ().replaceAll ("\n", "\n" + prefix) + "\n";
return result;
} | [
"@",
"Override",
"public",
"String",
"format",
"(",
"LogRecord",
"logRecord",
")",
"{",
"StringBuilder",
"resultBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"String",
"prefix",
"=",
"logRecord",
".",
"getLevel",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"\\t\"",
";",
"resultBuilder",
".",
"append",
"(",
"prefix",
")",
";",
"resultBuilder",
".",
"append",
"(",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\" \"",
")",
".",
"append",
"(",
"sdf",
".",
"format",
"(",
"new",
"java",
".",
"util",
".",
"Date",
"(",
"logRecord",
".",
"getMillis",
"(",
")",
")",
")",
")",
".",
"append",
"(",
"\": \"",
")",
".",
"append",
"(",
"logRecord",
".",
"getSourceClassName",
"(",
")",
")",
".",
"append",
"(",
"\":\"",
")",
".",
"append",
"(",
"logRecord",
".",
"getSourceMethodName",
"(",
")",
")",
".",
"append",
"(",
"\": \"",
")",
".",
"append",
"(",
"logRecord",
".",
"getMessage",
"(",
")",
")",
";",
"Object",
"[",
"]",
"params",
"=",
"logRecord",
".",
"getParameters",
"(",
")",
";",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"resultBuilder",
".",
"append",
"(",
"\"\\nParameters:\"",
")",
";",
"if",
"(",
"params",
".",
"length",
"<",
"1",
")",
"{",
"resultBuilder",
".",
"append",
"(",
"\" (none)\"",
")",
";",
"}",
"else",
"{",
"for",
"(",
"int",
"paramIndex",
"=",
"0",
";",
"paramIndex",
"<",
"params",
".",
"length",
";",
"paramIndex",
"++",
")",
"{",
"Object",
"param",
"=",
"params",
"[",
"paramIndex",
"]",
";",
"if",
"(",
"param",
"!=",
"null",
")",
"{",
"String",
"paramString",
"=",
"param",
".",
"toString",
"(",
")",
";",
"resultBuilder",
".",
"append",
"(",
"\"\\nParameter \"",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"paramIndex",
")",
")",
".",
"append",
"(",
"\" is a \"",
")",
".",
"append",
"(",
"param",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\": >\"",
")",
".",
"append",
"(",
"paramString",
")",
".",
"append",
"(",
"\"<\"",
")",
";",
"}",
"else",
"{",
"resultBuilder",
".",
"append",
"(",
"\"\\nParameter \"",
")",
".",
"append",
"(",
"String",
".",
"valueOf",
"(",
"paramIndex",
")",
")",
".",
"append",
"(",
"\" is null.\"",
")",
";",
"}",
"}",
"}",
"}",
"Throwable",
"t",
"=",
"logRecord",
".",
"getThrown",
"(",
")",
";",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"resultBuilder",
".",
"append",
"(",
"\"\\nThrowing:\\n\"",
")",
".",
"append",
"(",
"getFullThrowableMsg",
"(",
"t",
")",
")",
";",
"}",
"String",
"result",
"=",
"resultBuilder",
".",
"toString",
"(",
")",
".",
"replaceAll",
"(",
"\"\\n\"",
",",
"\"\\n\"",
"+",
"prefix",
")",
"+",
"\"\\n\"",
";",
"return",
"result",
";",
"}"
] | Format a logging message
@param logRecord
@return | [
"Format",
"a",
"logging",
"message"
] | 3b7d3d30faa7f1437b27cd07c10fa579a995de23 | https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/formatter/DefaultFormatter.java#L25-L79 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/option/UserOption.java | UserOption.acceptsValue | public boolean acceptsValue(String value) {
if (value==null) {
return false;
} else if (hasValues()) {
return getValuesList().contains(value);
} else {
return true;
}
} | java | public boolean acceptsValue(String value) {
if (value==null) {
return false;
} else if (hasValues()) {
return getValuesList().contains(value);
} else {
return true;
}
} | [
"public",
"boolean",
"acceptsValue",
"(",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"hasValues",
"(",
")",
")",
"{",
"return",
"getValuesList",
"(",
")",
".",
"contains",
"(",
"value",
")",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
] | Returns true if this option accepts the specified value
@param value the value to test
@return true if the option accepts the value, false otherwise | [
"Returns",
"true",
"if",
"this",
"option",
"accepts",
"the",
"specified",
"value"
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/option/UserOption.java#L150-L158 | train |
spothero/volley-jackson-extension | Library/src/com/spothero/volley/JacksonRequest.java | JacksonRequest.getUrl | private static String getUrl(int method, String baseUrl, String endpoint, Map<String, String> params) {
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() == null || entry.getValue().equals("null")) {
entry.setValue("");
}
}
}
if (method == Method.GET && params != null && !params.isEmpty()) {
final StringBuilder result = new StringBuilder(baseUrl + endpoint);
final int startLength = result.length();
for (String key : params.keySet()) {
try {
final String encodedKey = URLEncoder.encode(key, "UTF-8");
final String encodedValue = URLEncoder.encode(params.get(key), "UTF-8");
if (result.length() > startLength) {
result.append("&");
} else {
result.append("?");
}
result.append(encodedKey);
result.append("=");
result.append(encodedValue);
} catch (Exception e) { }
}
return result.toString();
} else {
return baseUrl + endpoint;
}
} | java | private static String getUrl(int method, String baseUrl, String endpoint, Map<String, String> params) {
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() == null || entry.getValue().equals("null")) {
entry.setValue("");
}
}
}
if (method == Method.GET && params != null && !params.isEmpty()) {
final StringBuilder result = new StringBuilder(baseUrl + endpoint);
final int startLength = result.length();
for (String key : params.keySet()) {
try {
final String encodedKey = URLEncoder.encode(key, "UTF-8");
final String encodedValue = URLEncoder.encode(params.get(key), "UTF-8");
if (result.length() > startLength) {
result.append("&");
} else {
result.append("?");
}
result.append(encodedKey);
result.append("=");
result.append(encodedValue);
} catch (Exception e) { }
}
return result.toString();
} else {
return baseUrl + endpoint;
}
} | [
"private",
"static",
"String",
"getUrl",
"(",
"int",
"method",
",",
"String",
"baseUrl",
",",
"String",
"endpoint",
",",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"{",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"params",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"==",
"null",
"||",
"entry",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"\"null\"",
")",
")",
"{",
"entry",
".",
"setValue",
"(",
"\"\"",
")",
";",
"}",
"}",
"}",
"if",
"(",
"method",
"==",
"Method",
".",
"GET",
"&&",
"params",
"!=",
"null",
"&&",
"!",
"params",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
"baseUrl",
"+",
"endpoint",
")",
";",
"final",
"int",
"startLength",
"=",
"result",
".",
"length",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"params",
".",
"keySet",
"(",
")",
")",
"{",
"try",
"{",
"final",
"String",
"encodedKey",
"=",
"URLEncoder",
".",
"encode",
"(",
"key",
",",
"\"UTF-8\"",
")",
";",
"final",
"String",
"encodedValue",
"=",
"URLEncoder",
".",
"encode",
"(",
"params",
".",
"get",
"(",
"key",
")",
",",
"\"UTF-8\"",
")",
";",
"if",
"(",
"result",
".",
"length",
"(",
")",
">",
"startLength",
")",
"{",
"result",
".",
"append",
"(",
"\"&\"",
")",
";",
"}",
"else",
"{",
"result",
".",
"append",
"(",
"\"?\"",
")",
";",
"}",
"result",
".",
"append",
"(",
"encodedKey",
")",
";",
"result",
".",
"append",
"(",
"\"=\"",
")",
";",
"result",
".",
"append",
"(",
"encodedValue",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"baseUrl",
"+",
"endpoint",
";",
"}",
"}"
] | Converts a base URL, endpoint, and parameters into a full URL
@param method The {@link com.android.volley.Request.Method} of the URL
@param baseUrl The base URL
@param endpoint The endpoint being hit
@param params The parameters to be appended to the URL if a GET method is used
@return The full URL | [
"Converts",
"a",
"base",
"URL",
"endpoint",
"and",
"parameters",
"into",
"a",
"full",
"URL"
] | 9b02df3e3e8fc648c80aec2dfae456de949fb74b | https://github.com/spothero/volley-jackson-extension/blob/9b02df3e3e8fc648c80aec2dfae456de949fb74b/Library/src/com/spothero/volley/JacksonRequest.java#L127-L157 | train |
dmerkushov/log-helper | src/main/java/ru/dmerkushov/loghelper/configure/LogHelperConfigurator.java | LogHelperConfigurator.configure | public static boolean configure (File configFile) {
boolean goOn = true;
if (!configFile.exists ()) {
LogHelperDebug.printError ("File " + configFile.getAbsolutePath () + " does not exist", false);
goOn = false;
}
DocumentBuilderFactory documentBuilderFactory = null;
DocumentBuilder documentBuilder = null;
if (goOn) {
documentBuilderFactory = DocumentBuilderFactory.newInstance ();
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder ();
} catch (ParserConfigurationException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
Document configDocument = null;
if (goOn) {
try {
configDocument = documentBuilder.parse (configFile);
} catch (SAXException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
} catch (IOException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
NodeList configNodeList = null;
if (goOn) {
configNodeList = configDocument.getElementsByTagName ("log-helper");
if (configNodeList == null) {
LogHelperDebug.printError ("configNodeList is null", false);
goOn = false;
} else if (configNodeList.getLength () < 1) {
LogHelperDebug.printError ("configNodeList is empty", false);
goOn = false;
}
}
Node configNode = null;
if (goOn) {
configNode = configNodeList.item (0);
if (configNode == null) {
LogHelperDebug.printError ("configNode is null", false);
goOn = false;
}
}
boolean success = false;
if (goOn) {
success = configure (configNode);
}
return success;
} | java | public static boolean configure (File configFile) {
boolean goOn = true;
if (!configFile.exists ()) {
LogHelperDebug.printError ("File " + configFile.getAbsolutePath () + " does not exist", false);
goOn = false;
}
DocumentBuilderFactory documentBuilderFactory = null;
DocumentBuilder documentBuilder = null;
if (goOn) {
documentBuilderFactory = DocumentBuilderFactory.newInstance ();
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder ();
} catch (ParserConfigurationException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
Document configDocument = null;
if (goOn) {
try {
configDocument = documentBuilder.parse (configFile);
} catch (SAXException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
} catch (IOException ex) {
LogHelperDebug.printError (ex.getMessage (), ex, false);
goOn = false;
}
}
NodeList configNodeList = null;
if (goOn) {
configNodeList = configDocument.getElementsByTagName ("log-helper");
if (configNodeList == null) {
LogHelperDebug.printError ("configNodeList is null", false);
goOn = false;
} else if (configNodeList.getLength () < 1) {
LogHelperDebug.printError ("configNodeList is empty", false);
goOn = false;
}
}
Node configNode = null;
if (goOn) {
configNode = configNodeList.item (0);
if (configNode == null) {
LogHelperDebug.printError ("configNode is null", false);
goOn = false;
}
}
boolean success = false;
if (goOn) {
success = configure (configNode);
}
return success;
} | [
"public",
"static",
"boolean",
"configure",
"(",
"File",
"configFile",
")",
"{",
"boolean",
"goOn",
"=",
"true",
";",
"if",
"(",
"!",
"configFile",
".",
"exists",
"(",
")",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"\"File \"",
"+",
"configFile",
".",
"getAbsolutePath",
"(",
")",
"+",
"\" does not exist\"",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"DocumentBuilderFactory",
"documentBuilderFactory",
"=",
"null",
";",
"DocumentBuilder",
"documentBuilder",
"=",
"null",
";",
"if",
"(",
"goOn",
")",
"{",
"documentBuilderFactory",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"try",
"{",
"documentBuilder",
"=",
"documentBuilderFactory",
".",
"newDocumentBuilder",
"(",
")",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"ex",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"}",
"Document",
"configDocument",
"=",
"null",
";",
"if",
"(",
"goOn",
")",
"{",
"try",
"{",
"configDocument",
"=",
"documentBuilder",
".",
"parse",
"(",
"configFile",
")",
";",
"}",
"catch",
"(",
"SAXException",
"ex",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"}",
"NodeList",
"configNodeList",
"=",
"null",
";",
"if",
"(",
"goOn",
")",
"{",
"configNodeList",
"=",
"configDocument",
".",
"getElementsByTagName",
"(",
"\"log-helper\"",
")",
";",
"if",
"(",
"configNodeList",
"==",
"null",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"\"configNodeList is null\"",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"configNodeList",
".",
"getLength",
"(",
")",
"<",
"1",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"\"configNodeList is empty\"",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"}",
"Node",
"configNode",
"=",
"null",
";",
"if",
"(",
"goOn",
")",
"{",
"configNode",
"=",
"configNodeList",
".",
"item",
"(",
"0",
")",
";",
"if",
"(",
"configNode",
"==",
"null",
")",
"{",
"LogHelperDebug",
".",
"printError",
"(",
"\"configNode is null\"",
",",
"false",
")",
";",
"goOn",
"=",
"false",
";",
"}",
"}",
"boolean",
"success",
"=",
"false",
";",
"if",
"(",
"goOn",
")",
"{",
"success",
"=",
"configure",
"(",
"configNode",
")",
";",
"}",
"return",
"success",
";",
"}"
] | Configure the log-helper library to the values in the given XML config file
@param configFile
@return <code>true</code> on success, <code>false</code> otherwise | [
"Configure",
"the",
"log",
"-",
"helper",
"library",
"to",
"the",
"values",
"in",
"the",
"given",
"XML",
"config",
"file"
] | 3b7d3d30faa7f1437b27cd07c10fa579a995de23 | https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/configure/LogHelperConfigurator.java#L74-L135 | train |
dmerkushov/log-helper | src/main/java/ru/dmerkushov/loghelper/configure/LogHelperConfigurator.java | LogHelperConfigurator.configureLoggerWrapper | private static void configureLoggerWrapper (Node configNode) {
Node lwNameNode = configNode.getAttributes ().getNamedItem ("name");
String lwName;
if (lwNameNode != null) {
lwName = lwNameNode.getTextContent ();
} else {
lwName = "LoggerWrapper_" + String.valueOf ((new Date ()).getTime ());
}
LoggerWrapper loggerWrapper = LogHelper.getLoggerWrapper (lwName);
NodeList lwSubnodes = configNode.getChildNodes ();
for (int subnodeIndex = 0; subnodeIndex < lwSubnodes.getLength (); subnodeIndex++) {
Node subnode = lwSubnodes.item (subnodeIndex);
String subnodeName = subnode.getNodeName ().trim ().toLowerCase ();
if (subnodeName.equals ("configurator")) {
configureLoggerWrapperByConfigurator (loggerWrapper, subnode);
}
}
} | java | private static void configureLoggerWrapper (Node configNode) {
Node lwNameNode = configNode.getAttributes ().getNamedItem ("name");
String lwName;
if (lwNameNode != null) {
lwName = lwNameNode.getTextContent ();
} else {
lwName = "LoggerWrapper_" + String.valueOf ((new Date ()).getTime ());
}
LoggerWrapper loggerWrapper = LogHelper.getLoggerWrapper (lwName);
NodeList lwSubnodes = configNode.getChildNodes ();
for (int subnodeIndex = 0; subnodeIndex < lwSubnodes.getLength (); subnodeIndex++) {
Node subnode = lwSubnodes.item (subnodeIndex);
String subnodeName = subnode.getNodeName ().trim ().toLowerCase ();
if (subnodeName.equals ("configurator")) {
configureLoggerWrapperByConfigurator (loggerWrapper, subnode);
}
}
} | [
"private",
"static",
"void",
"configureLoggerWrapper",
"(",
"Node",
"configNode",
")",
"{",
"Node",
"lwNameNode",
"=",
"configNode",
".",
"getAttributes",
"(",
")",
".",
"getNamedItem",
"(",
"\"name\"",
")",
";",
"String",
"lwName",
";",
"if",
"(",
"lwNameNode",
"!=",
"null",
")",
"{",
"lwName",
"=",
"lwNameNode",
".",
"getTextContent",
"(",
")",
";",
"}",
"else",
"{",
"lwName",
"=",
"\"LoggerWrapper_\"",
"+",
"String",
".",
"valueOf",
"(",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
")",
";",
"}",
"LoggerWrapper",
"loggerWrapper",
"=",
"LogHelper",
".",
"getLoggerWrapper",
"(",
"lwName",
")",
";",
"NodeList",
"lwSubnodes",
"=",
"configNode",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"subnodeIndex",
"=",
"0",
";",
"subnodeIndex",
"<",
"lwSubnodes",
".",
"getLength",
"(",
")",
";",
"subnodeIndex",
"++",
")",
"{",
"Node",
"subnode",
"=",
"lwSubnodes",
".",
"item",
"(",
"subnodeIndex",
")",
";",
"String",
"subnodeName",
"=",
"subnode",
".",
"getNodeName",
"(",
")",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"subnodeName",
".",
"equals",
"(",
"\"configurator\"",
")",
")",
"{",
"configureLoggerWrapperByConfigurator",
"(",
"loggerWrapper",
",",
"subnode",
")",
";",
"}",
"}",
"}"
] | Configure a LoggerWrapper to the values of a DOM node. It MUST have an attribute named "name", storing the LoggerWrapper's name. It may have subnodes named "configurator", keeping the properties for
@param configNode | [
"Configure",
"a",
"LoggerWrapper",
"to",
"the",
"values",
"of",
"a",
"DOM",
"node",
".",
"It",
"MUST",
"have",
"an",
"attribute",
"named",
"name",
"storing",
"the",
"LoggerWrapper",
"s",
"name",
".",
"It",
"may",
"have",
"subnodes",
"named",
"configurator",
"keeping",
"the",
"properties",
"for"
] | 3b7d3d30faa7f1437b27cd07c10fa579a995de23 | https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/configure/LogHelperConfigurator.java#L174-L194 | train |
mnlipp/jgrapes | org.jgrapes.io/src/org/jgrapes/io/util/PermitsPool.java | PermitsPool.removeListener | public PermitsPool removeListener(AvailabilityListener listener) {
synchronized (listeners) {
for (Iterator<WeakReference<AvailabilityListener>> iter
= listeners.iterator(); iter.hasNext();) {
WeakReference<AvailabilityListener> item = iter.next();
if (item.get() == null || item.get() == listener) {
iter.remove();
}
}
}
return this;
} | java | public PermitsPool removeListener(AvailabilityListener listener) {
synchronized (listeners) {
for (Iterator<WeakReference<AvailabilityListener>> iter
= listeners.iterator(); iter.hasNext();) {
WeakReference<AvailabilityListener> item = iter.next();
if (item.get() == null || item.get() == listener) {
iter.remove();
}
}
}
return this;
} | [
"public",
"PermitsPool",
"removeListener",
"(",
"AvailabilityListener",
"listener",
")",
"{",
"synchronized",
"(",
"listeners",
")",
"{",
"for",
"(",
"Iterator",
"<",
"WeakReference",
"<",
"AvailabilityListener",
">",
">",
"iter",
"=",
"listeners",
".",
"iterator",
"(",
")",
";",
"iter",
".",
"hasNext",
"(",
")",
";",
")",
"{",
"WeakReference",
"<",
"AvailabilityListener",
">",
"item",
"=",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"item",
".",
"get",
"(",
")",
"==",
"null",
"||",
"item",
".",
"get",
"(",
")",
"==",
"listener",
")",
"{",
"iter",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}",
"return",
"this",
";",
"}"
] | Removes the listener.
@param listener the AvailabilityListener
@return the permits pool | [
"Removes",
"the",
"listener",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.io/src/org/jgrapes/io/util/PermitsPool.java#L123-L134 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Components.java | Components.className | public static String className(Class<?> clazz) {
if (CoreUtils.classNames.isLoggable(Level.FINER)) {
return clazz.getName();
} else {
return simpleClassName(clazz);
}
} | java | public static String className(Class<?> clazz) {
if (CoreUtils.classNames.isLoggable(Level.FINER)) {
return clazz.getName();
} else {
return simpleClassName(clazz);
}
} | [
"public",
"static",
"String",
"className",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"if",
"(",
"CoreUtils",
".",
"classNames",
".",
"isLoggable",
"(",
"Level",
".",
"FINER",
")",
")",
"{",
"return",
"clazz",
".",
"getName",
"(",
")",
";",
"}",
"else",
"{",
"return",
"simpleClassName",
"(",
"clazz",
")",
";",
"}",
"}"
] | Returns the full name or simple name of the class depending
on the log level.
@param clazz the class
@return the name | [
"Returns",
"the",
"full",
"name",
"or",
"simple",
"name",
"of",
"the",
"class",
"depending",
"on",
"the",
"log",
"level",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Components.java#L279-L285 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Components.java | Components.schedule | public static Timer schedule(
TimeoutHandler timeoutHandler, Instant scheduledFor) {
return scheduler.schedule(timeoutHandler, scheduledFor);
} | java | public static Timer schedule(
TimeoutHandler timeoutHandler, Instant scheduledFor) {
return scheduler.schedule(timeoutHandler, scheduledFor);
} | [
"public",
"static",
"Timer",
"schedule",
"(",
"TimeoutHandler",
"timeoutHandler",
",",
"Instant",
"scheduledFor",
")",
"{",
"return",
"scheduler",
".",
"schedule",
"(",
"timeoutHandler",
",",
"scheduledFor",
")",
";",
"}"
] | Schedules the given timeout handler for the given instance.
@param timeoutHandler the handler
@param scheduledFor the instance in time
@return the timer | [
"Schedules",
"the",
"given",
"timeout",
"handler",
"for",
"the",
"given",
"instance",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Components.java#L548-L551 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Components.java | Components.schedule | public static Timer schedule(
TimeoutHandler timeoutHandler, Duration scheduledFor) {
return scheduler.schedule(
timeoutHandler, Instant.now().plus(scheduledFor));
} | java | public static Timer schedule(
TimeoutHandler timeoutHandler, Duration scheduledFor) {
return scheduler.schedule(
timeoutHandler, Instant.now().plus(scheduledFor));
} | [
"public",
"static",
"Timer",
"schedule",
"(",
"TimeoutHandler",
"timeoutHandler",
",",
"Duration",
"scheduledFor",
")",
"{",
"return",
"scheduler",
".",
"schedule",
"(",
"timeoutHandler",
",",
"Instant",
".",
"now",
"(",
")",
".",
"plus",
"(",
"scheduledFor",
")",
")",
";",
"}"
] | Schedules the given timeout handler for the given
offset from now.
@param timeoutHandler the handler
@param scheduledFor the time to wait
@return the timer | [
"Schedules",
"the",
"given",
"timeout",
"handler",
"for",
"the",
"given",
"offset",
"from",
"now",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Components.java#L561-L565 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Util.java | Util.encodePostBody | @Deprecated
public static String encodePostBody(Bundle parameters, String boundary) {
if (parameters == null) return "";
StringBuilder sb = new StringBuilder();
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
sb.append("Content-Disposition: form-data; name=\"" + key +
"\"\r\n\r\n" + (String)parameter);
sb.append("\r\n" + "--" + boundary + "\r\n");
}
return sb.toString();
} | java | @Deprecated
public static String encodePostBody(Bundle parameters, String boundary) {
if (parameters == null) return "";
StringBuilder sb = new StringBuilder();
for (String key : parameters.keySet()) {
Object parameter = parameters.get(key);
if (!(parameter instanceof String)) {
continue;
}
sb.append("Content-Disposition: form-data; name=\"" + key +
"\"\r\n\r\n" + (String)parameter);
sb.append("\r\n" + "--" + boundary + "\r\n");
}
return sb.toString();
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"encodePostBody",
"(",
"Bundle",
"parameters",
",",
"String",
"boundary",
")",
"{",
"if",
"(",
"parameters",
"==",
"null",
")",
"return",
"\"\"",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"parameters",
".",
"keySet",
"(",
")",
")",
"{",
"Object",
"parameter",
"=",
"parameters",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"(",
"parameter",
"instanceof",
"String",
")",
")",
"{",
"continue",
";",
"}",
"sb",
".",
"append",
"(",
"\"Content-Disposition: form-data; name=\\\"\"",
"+",
"key",
"+",
"\"\\\"\\r\\n\\r\\n\"",
"+",
"(",
"String",
")",
"parameter",
")",
";",
"sb",
".",
"append",
"(",
"\"\\r\\n\"",
"+",
"\"--\"",
"+",
"boundary",
"+",
"\"\\r\\n\"",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Generate the multi-part post body providing the parameters and boundary
string
@param parameters the parameters need to be posted
@param boundary the random string as boundary
@return a string of the post body | [
"Generate",
"the",
"multi",
"-",
"part",
"post",
"body",
"providing",
"the",
"parameters",
"and",
"boundary",
"string"
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Util.java#L56-L73 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Util.java | Util.parseUrl | @Deprecated
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
} | java | @Deprecated
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
} | [
"@",
"Deprecated",
"public",
"static",
"Bundle",
"parseUrl",
"(",
"String",
"url",
")",
"{",
"// hack to prevent MalformedURLException",
"url",
"=",
"url",
".",
"replace",
"(",
"\"fbconnect\"",
",",
"\"http\"",
")",
";",
"try",
"{",
"URL",
"u",
"=",
"new",
"URL",
"(",
"url",
")",
";",
"Bundle",
"b",
"=",
"decodeUrl",
"(",
"u",
".",
"getQuery",
"(",
")",
")",
";",
"b",
".",
"putAll",
"(",
"decodeUrl",
"(",
"u",
".",
"getRef",
"(",
")",
")",
")",
";",
"return",
"b",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"return",
"new",
"Bundle",
"(",
")",
";",
"}",
"}"
] | Parse a URL query and fragment parameters into a key-value bundle.
@param url the URL to parse
@return a dictionary bundle of keys and values | [
"Parse",
"a",
"URL",
"query",
"and",
"fragment",
"parameters",
"into",
"a",
"key",
"-",
"value",
"bundle",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Util.java#L125-L137 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/android/Util.java | Util.openUrl | @Deprecated
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Utility.logd("Facebook-Util", method + " URL: " + url);
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
Object parameter = params.get(key);
if (parameter instanceof byte[]) {
dataparams.putByteArray(key, (byte[])parameter);
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
if (params.containsKey("access_token")) {
String decoded_token =
URLDecoder.decode(params.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type",
"multipart/form-data;boundary="+strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
try {
os.write(("--" + strBoundary +endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key: dataparams.keySet()){
os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine).getBytes());
}
}
os.flush();
} finally {
os.close();
}
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
@Deprecated
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
@Deprecated
public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
} | java | @Deprecated
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
Utility.logd("Facebook-Util", method + " URL: " + url);
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
Object parameter = params.get(key);
if (parameter instanceof byte[]) {
dataparams.putByteArray(key, (byte[])parameter);
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", method);
}
if (params.containsKey("access_token")) {
String decoded_token =
URLDecoder.decode(params.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty(
"Content-Type",
"multipart/form-data;boundary="+strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
try {
os.write(("--" + strBoundary +endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key: dataparams.keySet()){
os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine).getBytes());
}
}
os.flush();
} finally {
os.close();
}
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
@Deprecated
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
@Deprecated
public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
} | [
"@",
"Deprecated",
"public",
"static",
"String",
"openUrl",
"(",
"String",
"url",
",",
"String",
"method",
",",
"Bundle",
"params",
")",
"throws",
"MalformedURLException",
",",
"IOException",
"{",
"// random string as boundary for multi-part http post",
"String",
"strBoundary",
"=",
"\"3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f\"",
";",
"String",
"endLine",
"=",
"\"\\r\\n\"",
";",
"OutputStream",
"os",
";",
"if",
"(",
"method",
".",
"equals",
"(",
"\"GET\"",
")",
")",
"{",
"url",
"=",
"url",
"+",
"\"?\"",
"+",
"encodeUrl",
"(",
"params",
")",
";",
"}",
"Utility",
".",
"logd",
"(",
"\"Facebook-Util\"",
",",
"method",
"+",
"\" URL: \"",
"+",
"url",
")",
";",
"HttpURLConnection",
"conn",
"=",
"(",
"HttpURLConnection",
")",
"new",
"URL",
"(",
"url",
")",
".",
"openConnection",
"(",
")",
";",
"conn",
".",
"setRequestProperty",
"(",
"\"User-Agent\"",
",",
"System",
".",
"getProperties",
"(",
")",
".",
"getProperty",
"(",
"\"http.agent\"",
")",
"+",
"\" FacebookAndroidSDK\"",
")",
";",
"if",
"(",
"!",
"method",
".",
"equals",
"(",
"\"GET\"",
")",
")",
"{",
"Bundle",
"dataparams",
"=",
"new",
"Bundle",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"params",
".",
"keySet",
"(",
")",
")",
"{",
"Object",
"parameter",
"=",
"params",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"parameter",
"instanceof",
"byte",
"[",
"]",
")",
"{",
"dataparams",
".",
"putByteArray",
"(",
"key",
",",
"(",
"byte",
"[",
"]",
")",
"parameter",
")",
";",
"}",
"}",
"// use method override",
"if",
"(",
"!",
"params",
".",
"containsKey",
"(",
"\"",
"method",
"\"",
")",
")",
"{",
"params",
".",
"putString",
"(",
"\"",
"method",
"\"",
",",
"method",
")",
";",
"}",
"if",
"(",
"params",
".",
"containsKey",
"(",
"\"access_token\"",
")",
")",
"{",
"String",
"decoded_token",
"=",
"URLDecoder",
".",
"decode",
"(",
"params",
".",
"getString",
"(",
"\"access_token\"",
")",
")",
";",
"params",
".",
"putString",
"(",
"\"access_token\"",
",",
"decoded_token",
")",
";",
"}",
"conn",
".",
"setRequestMethod",
"(",
"\"POST\"",
")",
";",
"conn",
".",
"setRequestProperty",
"(",
"\"Content-Type\"",
",",
"\"multipart/form-data;boundary=\"",
"+",
"strBoundary",
")",
";",
"conn",
".",
"setDoOutput",
"(",
"true",
")",
";",
"conn",
".",
"setDoInput",
"(",
"true",
")",
";",
"conn",
".",
"setRequestProperty",
"(",
"\"Connection\"",
",",
"\"Keep-Alive\"",
")",
";",
"conn",
".",
"connect",
"(",
")",
";",
"os",
"=",
"new",
"BufferedOutputStream",
"(",
"conn",
".",
"getOutputStream",
"(",
")",
")",
";",
"try",
"{",
"os",
".",
"write",
"(",
"(",
"\"--\"",
"+",
"strBoundary",
"+",
"endLine",
")",
".",
"getBytes",
"(",
")",
")",
";",
"os",
".",
"write",
"(",
"(",
"encodePostBody",
"(",
"params",
",",
"strBoundary",
")",
")",
".",
"getBytes",
"(",
")",
")",
";",
"os",
".",
"write",
"(",
"(",
"endLine",
"+",
"\"--\"",
"+",
"strBoundary",
"+",
"endLine",
")",
".",
"getBytes",
"(",
")",
")",
";",
"if",
"(",
"!",
"dataparams",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"String",
"key",
":",
"dataparams",
".",
"keySet",
"(",
")",
")",
"{",
"os",
".",
"write",
"(",
"(",
"\"Content-Disposition: form-data; filename=\\\"\"",
"+",
"key",
"+",
"\"\\\"\"",
"+",
"endLine",
")",
".",
"getBytes",
"(",
")",
")",
";",
"os",
".",
"write",
"(",
"(",
"\"Content-Type: content/unknown\"",
"+",
"endLine",
"+",
"endLine",
")",
".",
"getBytes",
"(",
")",
")",
";",
"os",
".",
"write",
"(",
"dataparams",
".",
"getByteArray",
"(",
"key",
")",
")",
";",
"os",
".",
"write",
"(",
"(",
"endLine",
"+",
"\"--\"",
"+",
"strBoundary",
"+",
"endLine",
")",
".",
"getBytes",
"(",
")",
")",
";",
"}",
"}",
"os",
".",
"flush",
"(",
")",
";",
"}",
"finally",
"{",
"os",
".",
"close",
"(",
")",
";",
"}",
"}",
"String",
"response",
"=",
"\"\"",
";",
"try",
"{",
"response",
"=",
"read",
"(",
"conn",
".",
"getInputStream",
"(",
")",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"// Error Stream contains JSON that we can parse to a FB error",
"response",
"=",
"read",
"(",
"conn",
".",
"getErrorStream",
"(",
")",
")",
";",
"}",
"return",
"response",
";",
"}",
"@",
"Deprecated",
"private",
"static",
"String",
"read",
"",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"BufferedReader",
"r",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"in",
")",
",",
"1000",
")",
";",
"for",
"(",
"String",
"line",
"=",
"r",
".",
"readLine",
"(",
")",
";",
"line",
"!=",
"null",
";",
"line",
"=",
"r",
".",
"readLine",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"line",
")",
";",
"}",
"in",
".",
"close",
"(",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Parse a server response into a JSON Object. This is a basic\n * implementation using org.json.JSONObject representation. More\n * sophisticated applications may wish to do their own parsing.\n *\n * The parsed JSON is checked for a variety of error fields and\n * a FacebookException is thrown if an error condition is set,\n * populated with the error message and error type or code if\n * available.\n *\n * @param response - string representation of the response\n * @return the response as a JSON Object\n * @throws JSONException - if the response is not valid JSON\n * @throws FacebookError - if an error condition is set\n */",
"@",
"Deprecated",
"public",
"static",
"JSONObject",
"parseJson",
"",
"(",
"String",
"response",
")",
"throws",
"JSONException",
",",
"FacebookError",
"{",
"// Edge case: when sending a POST request to /[post_id]/likes",
"// the return value is 'true' or 'false'. Unfortunately",
"// these values cause the JSONObject constructor to throw",
"// an exception.",
"if",
"(",
"response",
".",
"equals",
"(",
"\"false\"",
")",
")",
"{",
"throw",
"new",
"FacebookError",
"(",
"\"request failed\"",
")",
";",
"}",
"if",
"(",
"response",
".",
"equals",
"(",
"\"true\"",
")",
")",
"{",
"response",
"=",
"\"{value : true}\"",
";",
"}",
"JSONObject",
"json",
"=",
"new",
"JSONObject",
"(",
"response",
")",
";",
"// errors set by the server are not consistent",
"// they depend on the method and endpoint",
"if",
"(",
"json",
".",
"has",
"(",
"\"error\"",
")",
")",
"{",
"JSONObject",
"error",
"=",
"json",
".",
"getJSONObject",
"(",
"\"error\"",
")",
";",
"throw",
"new",
"FacebookError",
"(",
"error",
".",
"getString",
"(",
"\"message\"",
")",
",",
"error",
".",
"getString",
"(",
"\"type\"",
")",
",",
"0",
")",
";",
"}",
"if",
"(",
"json",
".",
"has",
"(",
"\"error_code\"",
")",
"&&",
"json",
".",
"has",
"(",
"\"error_msg\"",
")",
")",
"{",
"throw",
"new",
"FacebookError",
"(",
"json",
".",
"getString",
"(",
"\"error_msg\"",
")",
",",
"\"\"",
",",
"Integer",
".",
"parseInt",
"(",
"json",
".",
"getString",
"(",
"\"error_code\"",
")",
")",
")",
";",
"}",
"if",
"(",
"json",
".",
"has",
"(",
"\"error_code\"",
")",
")",
"{",
"throw",
"new",
"FacebookError",
"(",
"\"request failed\"",
",",
"\"\"",
",",
"Integer",
".",
"parseInt",
"(",
"json",
".",
"getString",
"(",
"\"error_code\"",
")",
")",
")",
";",
"}",
"if",
"(",
"json",
".",
"has",
"(",
"\"error_msg\"",
")",
")",
"{",
"throw",
"new",
"FacebookError",
"(",
"json",
".",
"getString",
"(",
"\"error_msg\"",
")",
")",
";",
"}",
"if",
"(",
"json",
".",
"has",
"(",
"\"error_reason\"",
")",
")",
"{",
"throw",
"new",
"FacebookError",
"(",
"json",
".",
"getString",
"(",
"\"error_reason\"",
")",
")",
";",
"}",
"return",
"json",
";",
"}"
] | Connect to an HTTP URL and return the response as a string.
Note that the HTTP method override is used on non-GET requests. (i.e.
requests are made as "POST" with method specified in the body).
@param url - the resource to open: must be a welformed URL
@param method - the HTTP method to use ("GET", "POST", etc.)
@param params - the query parameter for the URL (e.g. access_token=foo)
@return the URL contents as a String
@throws MalformedURLException - if the URL format is invalid
@throws IOException - if a network problem occurs | [
"Connect",
"to",
"an",
"HTTP",
"URL",
"and",
"return",
"the",
"response",
"as",
"a",
"string",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Util.java#L153-L295 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/NativeAppCallContentProvider.java | NativeAppCallContentProvider.getAttachmentUrl | public static String getAttachmentUrl(String applicationId, UUID callId, String attachmentName) {
return String.format("%s%s/%s/%s", ATTACHMENT_URL_BASE, applicationId, callId.toString(), attachmentName);
} | java | public static String getAttachmentUrl(String applicationId, UUID callId, String attachmentName) {
return String.format("%s%s/%s/%s", ATTACHMENT_URL_BASE, applicationId, callId.toString(), attachmentName);
} | [
"public",
"static",
"String",
"getAttachmentUrl",
"(",
"String",
"applicationId",
",",
"UUID",
"callId",
",",
"String",
"attachmentName",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s%s/%s/%s\"",
",",
"ATTACHMENT_URL_BASE",
",",
"applicationId",
",",
"callId",
".",
"toString",
"(",
")",
",",
"attachmentName",
")",
";",
"}"
] | Returns the name of the content provider formatted correctly for constructing URLs.
@param applicationId the Facebook application ID of the application
@return the String to use as the authority portion of a content URI. | [
"Returns",
"the",
"name",
"of",
"the",
"content",
"provider",
"formatted",
"correctly",
"for",
"constructing",
"URLs",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/NativeAppCallContentProvider.java#L70-L72 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.set | @Deprecated
public Character set(final int index, final Character ok) {
return set(index, ok.charValue());
} | java | @Deprecated
public Character set(final int index, final Character ok) {
return set(index, ok.charValue());
} | [
"@",
"Deprecated",
"public",
"Character",
"set",
"(",
"final",
"int",
"index",
",",
"final",
"Character",
"ok",
")",
"{",
"return",
"set",
"(",
"index",
",",
"ok",
".",
"charValue",
"(",
")",
")",
";",
"}"
] | Delegates to the corresponding type-specific method.
@deprecated Please use the corresponding type-specific method instead. | [
"Delegates",
"to",
"the",
"corresponding",
"type",
"-",
"specific",
"method",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L258-L261 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.getElements | private void getElements(final int from, final char[] a, final int offset, final int length) {
CharArrays.ensureOffsetLength(a, offset, length);
System.arraycopy(this.a, from, a, offset, length);
} | java | private void getElements(final int from, final char[] a, final int offset, final int length) {
CharArrays.ensureOffsetLength(a, offset, length);
System.arraycopy(this.a, from, a, offset, length);
} | [
"private",
"void",
"getElements",
"(",
"final",
"int",
"from",
",",
"final",
"char",
"[",
"]",
"a",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"CharArrays",
".",
"ensureOffsetLength",
"(",
"a",
",",
"offset",
",",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"this",
".",
"a",
",",
"from",
",",
"a",
",",
"offset",
",",
"length",
")",
";",
"}"
] | Copies element of this type-specific list into the given array using optimized system calls.
@param from the start index (inclusive).
@param a the destination array.
@param offset the offset into the destination array where to store the first element copied.
@param length the number of elements to be copied. | [
"Copies",
"element",
"of",
"this",
"type",
"-",
"specific",
"list",
"into",
"the",
"given",
"array",
"using",
"optimized",
"system",
"calls",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L469-L472 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.removeElements | public void removeElements(final int from, final int to) {
CharArrays.ensureFromTo(size, from, to);
System.arraycopy(a, to, a, from, size - to);
size -= (to - from);
} | java | public void removeElements(final int from, final int to) {
CharArrays.ensureFromTo(size, from, to);
System.arraycopy(a, to, a, from, size - to);
size -= (to - from);
} | [
"public",
"void",
"removeElements",
"(",
"final",
"int",
"from",
",",
"final",
"int",
"to",
")",
"{",
"CharArrays",
".",
"ensureFromTo",
"(",
"size",
",",
"from",
",",
"to",
")",
";",
"System",
".",
"arraycopy",
"(",
"a",
",",
"to",
",",
"a",
",",
"from",
",",
"size",
"-",
"to",
")",
";",
"size",
"-=",
"(",
"to",
"-",
"from",
")",
";",
"}"
] | Removes elements of this type-specific list using optimized system calls.
@param from the start index (inclusive).
@param to the end index (exclusive). | [
"Removes",
"elements",
"of",
"this",
"type",
"-",
"specific",
"list",
"using",
"optimized",
"system",
"calls",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L481-L485 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.addElements | public void addElements(final int index, final char a[], final int offset, final int length) {
ensureIndex(index);
CharArrays.ensureOffsetLength(a, offset, length);
grow(size + length);
System.arraycopy(this.a, index, this.a, index + length, size - index);
System.arraycopy(a, offset, this.a, index, length);
size += length;
} | java | public void addElements(final int index, final char a[], final int offset, final int length) {
ensureIndex(index);
CharArrays.ensureOffsetLength(a, offset, length);
grow(size + length);
System.arraycopy(this.a, index, this.a, index + length, size - index);
System.arraycopy(a, offset, this.a, index, length);
size += length;
} | [
"public",
"void",
"addElements",
"(",
"final",
"int",
"index",
",",
"final",
"char",
"a",
"[",
"]",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"{",
"ensureIndex",
"(",
"index",
")",
";",
"CharArrays",
".",
"ensureOffsetLength",
"(",
"a",
",",
"offset",
",",
"length",
")",
";",
"grow",
"(",
"size",
"+",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"this",
".",
"a",
",",
"index",
",",
"this",
".",
"a",
",",
"index",
"+",
"length",
",",
"size",
"-",
"index",
")",
";",
"System",
".",
"arraycopy",
"(",
"a",
",",
"offset",
",",
"this",
".",
"a",
",",
"index",
",",
"length",
")",
";",
"size",
"+=",
"length",
";",
"}"
] | Adds elements to this type-specific list using optimized system calls.
@param index the index at which to add elements.
@param a the array containing the elements.
@param offset the offset of the first element to add.
@param length the number of elements to add. | [
"Adds",
"elements",
"to",
"this",
"type",
"-",
"specific",
"list",
"using",
"optimized",
"system",
"calls",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L495-L502 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.ensureIndex | private void ensureIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index > size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")");
} | java | private void ensureIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index > size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")");
} | [
"private",
"void",
"ensureIndex",
"(",
"final",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index (\"",
"+",
"index",
"+",
"\") is negative\"",
")",
";",
"if",
"(",
"index",
">",
"size",
"(",
")",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index (\"",
"+",
"index",
"+",
"\") is greater than list size (\"",
"+",
"(",
"size",
"(",
")",
")",
"+",
"\")\"",
")",
";",
"}"
] | Ensures that the given index is non-negative and not greater than the list size.
@param index an index.
@throws IndexOutOfBoundsException if the given index is negative or greater than the list size. | [
"Ensures",
"that",
"the",
"given",
"index",
"is",
"non",
"-",
"negative",
"and",
"not",
"greater",
"than",
"the",
"list",
"size",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L779-L783 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.ensureRestrictedIndex | protected void ensureRestrictedIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index >= size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")");
} | java | protected void ensureRestrictedIndex(final int index) {
if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative");
if (index >= size())
throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")");
} | [
"protected",
"void",
"ensureRestrictedIndex",
"(",
"final",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index (\"",
"+",
"index",
"+",
"\") is negative\"",
")",
";",
"if",
"(",
"index",
">=",
"size",
"(",
")",
")",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"Index (\"",
"+",
"index",
"+",
"\") is greater than or equal to list size (\"",
"+",
"(",
"size",
"(",
")",
")",
"+",
"\")\"",
")",
";",
"}"
] | Ensures that the given index is non-negative and smaller than the list size.
@param index an index.
@throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size. | [
"Ensures",
"that",
"the",
"given",
"index",
"is",
"non",
"-",
"negative",
"and",
"smaller",
"than",
"the",
"list",
"size",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L791-L795 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.containsAll | public boolean containsAll(Collection<?> c) {
int n = c.size();
final Iterator<?> i = c.iterator();
while (n-- != 0)
if (!contains(i.next())) return false;
return true;
} | java | public boolean containsAll(Collection<?> c) {
int n = c.size();
final Iterator<?> i = c.iterator();
while (n-- != 0)
if (!contains(i.next())) return false;
return true;
} | [
"public",
"boolean",
"containsAll",
"(",
"Collection",
"<",
"?",
">",
"c",
")",
"{",
"int",
"n",
"=",
"c",
".",
"size",
"(",
")",
";",
"final",
"Iterator",
"<",
"?",
">",
"i",
"=",
"c",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"n",
"--",
"!=",
"0",
")",
"if",
"(",
"!",
"contains",
"(",
"i",
".",
"next",
"(",
")",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
] | Checks whether this collection contains all elements from the given collection.
@param c a collection.
@return <code>true</code> if this collection contains all elements of the argument. | [
"Checks",
"whether",
"this",
"collection",
"contains",
"all",
"elements",
"from",
"the",
"given",
"collection",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L892-L898 | train |
tommyettinger/RegExodus | src/main/java/regexodus/ds/CharArrayList.java | CharArrayList.addAll | public boolean addAll(Collection<? extends Character> c) {
boolean retVal = false;
final Iterator<? extends Character> i = c.iterator();
int n = c.size();
while (n-- != 0)
if (add(i.next())) retVal = true;
return retVal;
} | java | public boolean addAll(Collection<? extends Character> c) {
boolean retVal = false;
final Iterator<? extends Character> i = c.iterator();
int n = c.size();
while (n-- != 0)
if (add(i.next())) retVal = true;
return retVal;
} | [
"public",
"boolean",
"addAll",
"(",
"Collection",
"<",
"?",
"extends",
"Character",
">",
"c",
")",
"{",
"boolean",
"retVal",
"=",
"false",
";",
"final",
"Iterator",
"<",
"?",
"extends",
"Character",
">",
"i",
"=",
"c",
".",
"iterator",
"(",
")",
";",
"int",
"n",
"=",
"c",
".",
"size",
"(",
")",
";",
"while",
"(",
"n",
"--",
"!=",
"0",
")",
"if",
"(",
"add",
"(",
"i",
".",
"next",
"(",
")",
")",
")",
"retVal",
"=",
"true",
";",
"return",
"retVal",
";",
"}"
] | Adds all elements of the given collection to this collection.
@param c a collection.
@return <code>true</code> if this collection changed as a result of the call. | [
"Adds",
"all",
"elements",
"of",
"the",
"given",
"collection",
"to",
"this",
"collection",
"."
] | d4af9bb7c132c5f9d29f45b76121f93b2f89de16 | https://github.com/tommyettinger/RegExodus/blob/d4af9bb7c132c5f9d29f45b76121f93b2f89de16/src/main/java/regexodus/ds/CharArrayList.java#L906-L913 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.getConfigurationDetails | public synchronized Set<ConfigurationDetails> getConfigurationDetails() {
return inventory.entries().stream()
.map(c->c.getConfiguration().orElse(null))
.filter(v->v!=null)
.map(v->v.getDetails())
.collect(Collectors.toSet());
} | java | public synchronized Set<ConfigurationDetails> getConfigurationDetails() {
return inventory.entries().stream()
.map(c->c.getConfiguration().orElse(null))
.filter(v->v!=null)
.map(v->v.getDetails())
.collect(Collectors.toSet());
} | [
"public",
"synchronized",
"Set",
"<",
"ConfigurationDetails",
">",
"getConfigurationDetails",
"(",
")",
"{",
"return",
"inventory",
".",
"entries",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"c",
"->",
"c",
".",
"getConfiguration",
"(",
")",
".",
"orElse",
"(",
"null",
")",
")",
".",
"filter",
"(",
"v",
"->",
"v",
"!=",
"null",
")",
".",
"map",
"(",
"v",
"->",
"v",
".",
"getDetails",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"}"
] | Gets configuration details.
@return the configuration details | [
"Gets",
"configuration",
"details",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L75-L81 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.getConfiguration | public synchronized Map<String, Object> getConfiguration(String key) {
return Optional.ofNullable(inventory.get(key))
.flatMap(v->v.getConfiguration())
.map(v->v.getMap())
.orElse(null);
} | java | public synchronized Map<String, Object> getConfiguration(String key) {
return Optional.ofNullable(inventory.get(key))
.flatMap(v->v.getConfiguration())
.map(v->v.getMap())
.orElse(null);
} | [
"public",
"synchronized",
"Map",
"<",
"String",
",",
"Object",
">",
"getConfiguration",
"(",
"String",
"key",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"inventory",
".",
"get",
"(",
"key",
")",
")",
".",
"flatMap",
"(",
"v",
"->",
"v",
".",
"getConfiguration",
"(",
")",
")",
".",
"map",
"(",
"v",
"->",
"v",
".",
"getMap",
"(",
")",
")",
".",
"orElse",
"(",
"null",
")",
";",
"}"
] | Gets a configuration.
@param key the configuration key
@return a map, or null if the key is not found | [
"Gets",
"a",
"configuration",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L88-L93 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.addConfiguration | public synchronized Optional<String> addConfiguration(String niceName, String description, Map<String, Object> config) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()-> {
ConfigurationDetails p = new ConfigurationDetails.Builder(inventory.nextIdentifier())
.niceName(niceName)
.description(description).build();
try {
InventoryEntry ret = InventoryEntry.create(new Configuration(p, new HashMap<>(config)), newConfigurationFile());
inventory.add(ret);
return Optional.of(ret.getIdentifier());
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to add configuration.", e);
return Optional.empty();
}
});
} catch (IOException e) {
logger.log(Level.WARNING, "Could not add configuration", e);
return Optional.empty();
}
} | java | public synchronized Optional<String> addConfiguration(String niceName, String description, Map<String, Object> config) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()-> {
ConfigurationDetails p = new ConfigurationDetails.Builder(inventory.nextIdentifier())
.niceName(niceName)
.description(description).build();
try {
InventoryEntry ret = InventoryEntry.create(new Configuration(p, new HashMap<>(config)), newConfigurationFile());
inventory.add(ret);
return Optional.of(ret.getIdentifier());
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to add configuration.", e);
return Optional.empty();
}
});
} catch (IOException e) {
logger.log(Level.WARNING, "Could not add configuration", e);
return Optional.empty();
}
} | [
"public",
"synchronized",
"Optional",
"<",
"String",
">",
"addConfiguration",
"(",
"String",
"niceName",
",",
"String",
"description",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"config",
")",
"{",
"try",
"{",
"if",
"(",
"catalog",
"==",
"null",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
")",
";",
"}",
"return",
"sync",
"(",
"(",
")",
"->",
"{",
"ConfigurationDetails",
"p",
"=",
"new",
"ConfigurationDetails",
".",
"Builder",
"(",
"inventory",
".",
"nextIdentifier",
"(",
")",
")",
".",
"niceName",
"(",
"niceName",
")",
".",
"description",
"(",
"description",
")",
".",
"build",
"(",
")",
";",
"try",
"{",
"InventoryEntry",
"ret",
"=",
"InventoryEntry",
".",
"create",
"(",
"new",
"Configuration",
"(",
"p",
",",
"new",
"HashMap",
"<>",
"(",
"config",
")",
")",
",",
"newConfigurationFile",
"(",
")",
")",
";",
"inventory",
".",
"add",
"(",
"ret",
")",
";",
"return",
"Optional",
".",
"of",
"(",
"ret",
".",
"getIdentifier",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to add configuration.\"",
",",
"e",
")",
";",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Could not add configuration\"",
",",
"e",
")",
";",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"}"
] | Adds a configuration to this catalog.
@param niceName the display name
@param description the configuration description
@param config the configuration details
@return the identifier for the new configuration, or an empty optional if the configuration could not be added | [
"Adds",
"a",
"configuration",
"to",
"this",
"catalog",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L102-L124 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.removeConfiguration | public synchronized boolean removeConfiguration(String key) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()->inventory.remove(key)!=null);
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to remove configuration.", e);
return false;
}
} | java | public synchronized boolean removeConfiguration(String key) {
try {
if (catalog==null) {
throw new FileNotFoundException();
}
return sync(()->inventory.remove(key)!=null);
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to remove configuration.", e);
return false;
}
} | [
"public",
"synchronized",
"boolean",
"removeConfiguration",
"(",
"String",
"key",
")",
"{",
"try",
"{",
"if",
"(",
"catalog",
"==",
"null",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
")",
";",
"}",
"return",
"sync",
"(",
"(",
")",
"->",
"inventory",
".",
"remove",
"(",
"key",
")",
"!=",
"null",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to remove configuration.\"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Removes the configuration with the specified identifier.
@param key the identifier
@return true if the configuration was successfully removed, false otherwise | [
"Removes",
"the",
"configuration",
"with",
"the",
"specified",
"identifier",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L131-L141 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.cleanupInventory | private boolean cleanupInventory() {
boolean modified = false;
modified |= removeUnreadable();
modified |= recreateMismatching();
modified |= importConfigurations();
return modified;
} | java | private boolean cleanupInventory() {
boolean modified = false;
modified |= removeUnreadable();
modified |= recreateMismatching();
modified |= importConfigurations();
return modified;
} | [
"private",
"boolean",
"cleanupInventory",
"(",
")",
"{",
"boolean",
"modified",
"=",
"false",
";",
"modified",
"|=",
"removeUnreadable",
"(",
")",
";",
"modified",
"|=",
"recreateMismatching",
"(",
")",
";",
"modified",
"|=",
"importConfigurations",
"(",
")",
";",
"return",
"modified",
";",
"}"
] | Cleans up the inventory.
@return true if the inventory was touched, false otherwise. | [
"Cleans",
"up",
"the",
"inventory",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L208-L214 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.removeUnreadable | private boolean removeUnreadable() {
List<File> unreadable = inventory.removeUnreadable();
unreadable.forEach(v->v.delete());
return !unreadable.isEmpty();
} | java | private boolean removeUnreadable() {
List<File> unreadable = inventory.removeUnreadable();
unreadable.forEach(v->v.delete());
return !unreadable.isEmpty();
} | [
"private",
"boolean",
"removeUnreadable",
"(",
")",
"{",
"List",
"<",
"File",
">",
"unreadable",
"=",
"inventory",
".",
"removeUnreadable",
"(",
")",
";",
"unreadable",
".",
"forEach",
"(",
"v",
"->",
"v",
".",
"delete",
"(",
")",
")",
";",
"return",
"!",
"unreadable",
".",
"isEmpty",
"(",
")",
";",
"}"
] | Removes unreadable configurations from the file system.
@return true if some configurations were removed, false otherwise | [
"Removes",
"unreadable",
"configurations",
"from",
"the",
"file",
"system",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L220-L224 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.recreateMismatching | private boolean recreateMismatching() {
List<Configuration> mismatching = inventory.removeMismatching();
mismatching.forEach(entry->{
try {
inventory.add(InventoryEntry.create(entry.copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
} catch (IOException e1) {
logger.log(Level.WARNING, "Failed to write a configuration.", e1);
}
});
return !mismatching.isEmpty();
} | java | private boolean recreateMismatching() {
List<Configuration> mismatching = inventory.removeMismatching();
mismatching.forEach(entry->{
try {
inventory.add(InventoryEntry.create(entry.copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
} catch (IOException e1) {
logger.log(Level.WARNING, "Failed to write a configuration.", e1);
}
});
return !mismatching.isEmpty();
} | [
"private",
"boolean",
"recreateMismatching",
"(",
")",
"{",
"List",
"<",
"Configuration",
">",
"mismatching",
"=",
"inventory",
".",
"removeMismatching",
"(",
")",
";",
"mismatching",
".",
"forEach",
"(",
"entry",
"->",
"{",
"try",
"{",
"inventory",
".",
"add",
"(",
"InventoryEntry",
".",
"create",
"(",
"entry",
".",
"copyWithIdentifier",
"(",
"inventory",
".",
"nextIdentifier",
"(",
")",
")",
",",
"newConfigurationFile",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e1",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Failed to write a configuration.\"",
",",
"e1",
")",
";",
"}",
"}",
")",
";",
"return",
"!",
"mismatching",
".",
"isEmpty",
"(",
")",
";",
"}"
] | Recreates mismatching configurations.
@return true if some configurations were recreated, false otherwise | [
"Recreates",
"mismatching",
"configurations",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L230-L240 | train |
ologolo/streamline-api | src/org/daisy/streamline/api/config/UserConfigurationsCollection.java | UserConfigurationsCollection.importConfigurations | private boolean importConfigurations() {
// Create a set of files in the inventory
Set<File> files = inventory.entries().stream().map(v->v.getPath()).collect(Collectors.toSet());
List<File> entriesToImport = Arrays.asList(baseDir.listFiles(f->
f.isFile()
&& !f.equals(catalog) // Exclude the master catalog (should it have the same extension as entries)
&& f.getName().endsWith(CONFIG_EXT)
&& !files.contains(f)) // Exclude files already in the inventory
);
entriesToImport.forEach(f->{
try {
inventory.add(InventoryEntry.create(Configuration.read(f).copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
f.delete();
} catch (IOException e) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Failed to read: " + f, e);
}
}
});
return !entriesToImport.isEmpty();
} | java | private boolean importConfigurations() {
// Create a set of files in the inventory
Set<File> files = inventory.entries().stream().map(v->v.getPath()).collect(Collectors.toSet());
List<File> entriesToImport = Arrays.asList(baseDir.listFiles(f->
f.isFile()
&& !f.equals(catalog) // Exclude the master catalog (should it have the same extension as entries)
&& f.getName().endsWith(CONFIG_EXT)
&& !files.contains(f)) // Exclude files already in the inventory
);
entriesToImport.forEach(f->{
try {
inventory.add(InventoryEntry.create(Configuration.read(f).copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile()));
f.delete();
} catch (IOException e) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Failed to read: " + f, e);
}
}
});
return !entriesToImport.isEmpty();
} | [
"private",
"boolean",
"importConfigurations",
"(",
")",
"{",
"// Create a set of files in the inventory",
"Set",
"<",
"File",
">",
"files",
"=",
"inventory",
".",
"entries",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"v",
"->",
"v",
".",
"getPath",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"List",
"<",
"File",
">",
"entriesToImport",
"=",
"Arrays",
".",
"asList",
"(",
"baseDir",
".",
"listFiles",
"(",
"f",
"->",
"f",
".",
"isFile",
"(",
")",
"&&",
"!",
"f",
".",
"equals",
"(",
"catalog",
")",
"// Exclude the master catalog (should it have the same extension as entries)",
"&&",
"f",
".",
"getName",
"(",
")",
".",
"endsWith",
"(",
"CONFIG_EXT",
")",
"&&",
"!",
"files",
".",
"contains",
"(",
"f",
")",
")",
"// Exclude files already in the inventory",
")",
";",
"entriesToImport",
".",
"forEach",
"(",
"f",
"->",
"{",
"try",
"{",
"inventory",
".",
"add",
"(",
"InventoryEntry",
".",
"create",
"(",
"Configuration",
".",
"read",
"(",
"f",
")",
".",
"copyWithIdentifier",
"(",
"inventory",
".",
"nextIdentifier",
"(",
")",
")",
",",
"newConfigurationFile",
"(",
")",
")",
")",
";",
"f",
".",
"delete",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Failed to read: \"",
"+",
"f",
",",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"!",
"entriesToImport",
".",
"isEmpty",
"(",
")",
";",
"}"
] | Imports new configurations from the file system.
@return true if something was imported, false otherwise | [
"Imports",
"new",
"configurations",
"from",
"the",
"file",
"system",
"."
] | 4934b6da1de06e364ae90d6ea9b0929500da9cdb | https://github.com/ologolo/streamline-api/blob/4934b6da1de06e364ae90d6ea9b0929500da9cdb/src/org/daisy/streamline/api/config/UserConfigurationsCollection.java#L246-L266 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Event.java | Event.channels | @SuppressWarnings({ "unchecked", "PMD.ShortVariable",
"PMD.AvoidDuplicateLiterals" })
public <C> C[] channels(Class<C> type) {
return Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass())).toArray(
size -> (C[]) Array.newInstance(type, size));
} | java | @SuppressWarnings({ "unchecked", "PMD.ShortVariable",
"PMD.AvoidDuplicateLiterals" })
public <C> C[] channels(Class<C> type) {
return Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass())).toArray(
size -> (C[]) Array.newInstance(type, size));
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"PMD.ShortVariable\"",
",",
"\"PMD.AvoidDuplicateLiterals\"",
"}",
")",
"public",
"<",
"C",
">",
"C",
"[",
"]",
"channels",
"(",
"Class",
"<",
"C",
">",
"type",
")",
"{",
"return",
"Arrays",
".",
"stream",
"(",
"channels",
")",
".",
"filter",
"(",
"c",
"->",
"type",
".",
"isAssignableFrom",
"(",
"c",
".",
"getClass",
"(",
")",
")",
")",
".",
"toArray",
"(",
"size",
"->",
"(",
"C",
"[",
"]",
")",
"Array",
".",
"newInstance",
"(",
"type",
",",
"size",
")",
")",
";",
"}"
] | Returns the subset of channels that are assignable to the given type.
@param <C> the given type's class
@param type the class to look for
@return the filtered channels
@see #channels() | [
"Returns",
"the",
"subset",
"of",
"channels",
"that",
"are",
"assignable",
"to",
"the",
"given",
"type",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Event.java#L171-L177 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Event.java | Event.forChannels | @SuppressWarnings({ "unchecked", "PMD.ShortVariable" })
public <E extends EventBase<?>, C extends Channel> void forChannels(
Class<C> type, BiConsumer<E, C> handler) {
Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass()))
.forEach(c -> handler.accept((E) this, (C) c));
} | java | @SuppressWarnings({ "unchecked", "PMD.ShortVariable" })
public <E extends EventBase<?>, C extends Channel> void forChannels(
Class<C> type, BiConsumer<E, C> handler) {
Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass()))
.forEach(c -> handler.accept((E) this, (C) c));
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"PMD.ShortVariable\"",
"}",
")",
"public",
"<",
"E",
"extends",
"EventBase",
"<",
"?",
">",
",",
"C",
"extends",
"Channel",
">",
"void",
"forChannels",
"(",
"Class",
"<",
"C",
">",
"type",
",",
"BiConsumer",
"<",
"E",
",",
"C",
">",
"handler",
")",
"{",
"Arrays",
".",
"stream",
"(",
"channels",
")",
".",
"filter",
"(",
"c",
"->",
"type",
".",
"isAssignableFrom",
"(",
"c",
".",
"getClass",
"(",
")",
")",
")",
".",
"forEach",
"(",
"c",
"->",
"handler",
".",
"accept",
"(",
"(",
"E",
")",
"this",
",",
"(",
"C",
")",
"c",
")",
")",
";",
"}"
] | Execute the given handler for all channels of the given type.
@param <E> the type of the event
@param <C> the type of the channel
@param type the channel type
@param handler the handler | [
"Execute",
"the",
"given",
"handler",
"for",
"all",
"channels",
"of",
"the",
"given",
"type",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Event.java#L187-L193 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Event.java | Event.setResult | public Event<T> setResult(T result) {
synchronized (this) {
if (results == null) {
// Make sure that we have a valid result before
// calling decrementOpen
results = new ArrayList<T>();
results.add(result);
firstResultAssigned();
return this;
}
results.add(result);
return this;
}
} | java | public Event<T> setResult(T result) {
synchronized (this) {
if (results == null) {
// Make sure that we have a valid result before
// calling decrementOpen
results = new ArrayList<T>();
results.add(result);
firstResultAssigned();
return this;
}
results.add(result);
return this;
}
} | [
"public",
"Event",
"<",
"T",
">",
"setResult",
"(",
"T",
"result",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"results",
"==",
"null",
")",
"{",
"// Make sure that we have a valid result before",
"// calling decrementOpen",
"results",
"=",
"new",
"ArrayList",
"<",
"T",
">",
"(",
")",
";",
"results",
".",
"add",
"(",
"result",
")",
";",
"firstResultAssigned",
"(",
")",
";",
"return",
"this",
";",
"}",
"results",
".",
"add",
"(",
"result",
")",
";",
"return",
"this",
";",
"}",
"}"
] | Sets the result of handling this event. If this method is invoked
more then once, the various results are collected in a list. This
can happen if the event is handled by several components.
@param result the result to set
@return the object for easy chaining | [
"Sets",
"the",
"result",
"of",
"handling",
"this",
"event",
".",
"If",
"this",
"method",
"is",
"invoked",
"more",
"then",
"once",
"the",
"various",
"results",
"are",
"collected",
"in",
"a",
"list",
".",
"This",
"can",
"happen",
"if",
"the",
"event",
"is",
"handled",
"by",
"several",
"components",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Event.java#L320-L333 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/Event.java | Event.currentResults | protected List<T> currentResults() {
return results == null ? Collections.emptyList()
: Collections.unmodifiableList(results);
} | java | protected List<T> currentResults() {
return results == null ? Collections.emptyList()
: Collections.unmodifiableList(results);
} | [
"protected",
"List",
"<",
"T",
">",
"currentResults",
"(",
")",
"{",
"return",
"results",
"==",
"null",
"?",
"Collections",
".",
"emptyList",
"(",
")",
":",
"Collections",
".",
"unmodifiableList",
"(",
"results",
")",
";",
"}"
] | Allows access to the intermediate result before the
completion of the event.
@return the intermediate results (which may be an empty list) | [
"Allows",
"access",
"to",
"the",
"intermediate",
"result",
"before",
"the",
"completion",
"of",
"the",
"event",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/Event.java#L341-L344 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java | PeasyViewHolder.inflateView | public static View inflateView(LayoutInflater inflater, ViewGroup parent, int layoutId) {
return inflater.inflate(layoutId, parent, false);
} | java | public static View inflateView(LayoutInflater inflater, ViewGroup parent, int layoutId) {
return inflater.inflate(layoutId, parent, false);
} | [
"public",
"static",
"View",
"inflateView",
"(",
"LayoutInflater",
"inflater",
",",
"ViewGroup",
"parent",
",",
"int",
"layoutId",
")",
"{",
"return",
"inflater",
".",
"inflate",
"(",
"layoutId",
",",
"parent",
",",
"false",
")",
";",
"}"
] | Static method to help inflate parent view with layoutId
@param inflater inflater
@param parent parent
@param layoutId layoutId
@return View | [
"Static",
"method",
"to",
"help",
"inflate",
"parent",
"view",
"with",
"layoutId"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java#L25-L27 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java | PeasyViewHolder.GetViewHolder | public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) {
return cls.cast(vh);
} | java | public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) {
return cls.cast(vh);
} | [
"public",
"static",
"<",
"VH",
"extends",
"PeasyViewHolder",
">",
"VH",
"GetViewHolder",
"(",
"PeasyViewHolder",
"vh",
",",
"Class",
"<",
"VH",
">",
"cls",
")",
"{",
"return",
"cls",
".",
"cast",
"(",
"vh",
")",
";",
"}"
] | Help to cast provided PeasyViewHolder to its child class instance
@param vh PeasyViewHolder Parent Class
@param cls Class of PeasyViewHolder
@param <VH> PeasyViewHolder Child Class
@return VH as Child Class Instance | [
"Help",
"to",
"cast",
"provided",
"PeasyViewHolder",
"to",
"its",
"child",
"class",
"instance"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java#L37-L39 | train |
kopihao/peasy-recyclerview | peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java | PeasyViewHolder.bindWith | <T> void bindWith(final PeasyRecyclerView<T> binder, final int viewType) {
this.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (position != RecyclerView.NO_POSITION) {
binder.onItemClick(v, viewType, position, binder.getItem(position), getInstance());
}
}
});
this.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (getLayoutPosition() != RecyclerView.NO_POSITION) {
return binder.onItemLongClick(v, viewType, position, binder.getItem(position), getInstance());
}
return false;
}
});
} | java | <T> void bindWith(final PeasyRecyclerView<T> binder, final int viewType) {
this.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (position != RecyclerView.NO_POSITION) {
binder.onItemClick(v, viewType, position, binder.getItem(position), getInstance());
}
}
});
this.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int position = getLayoutPosition();
position = (position <= binder.getLastItemIndex()) ? position : getAdapterPosition();
position = (position <= binder.getLastItemIndex()) ? position : RecyclerView.NO_POSITION;
if (getLayoutPosition() != RecyclerView.NO_POSITION) {
return binder.onItemLongClick(v, viewType, position, binder.getItem(position), getInstance());
}
return false;
}
});
} | [
"<",
"T",
">",
"void",
"bindWith",
"(",
"final",
"PeasyRecyclerView",
"<",
"T",
">",
"binder",
",",
"final",
"int",
"viewType",
")",
"{",
"this",
".",
"itemView",
".",
"setOnClickListener",
"(",
"new",
"View",
".",
"OnClickListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onClick",
"(",
"View",
"v",
")",
"{",
"int",
"position",
"=",
"getLayoutPosition",
"(",
")",
";",
"position",
"=",
"(",
"position",
"<=",
"binder",
".",
"getLastItemIndex",
"(",
")",
")",
"?",
"position",
":",
"getAdapterPosition",
"(",
")",
";",
"position",
"=",
"(",
"position",
"<=",
"binder",
".",
"getLastItemIndex",
"(",
")",
")",
"?",
"position",
":",
"RecyclerView",
".",
"NO_POSITION",
";",
"if",
"(",
"position",
"!=",
"RecyclerView",
".",
"NO_POSITION",
")",
"{",
"binder",
".",
"onItemClick",
"(",
"v",
",",
"viewType",
",",
"position",
",",
"binder",
".",
"getItem",
"(",
"position",
")",
",",
"getInstance",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"this",
".",
"itemView",
".",
"setOnLongClickListener",
"(",
"new",
"View",
".",
"OnLongClickListener",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"onLongClick",
"(",
"View",
"v",
")",
"{",
"int",
"position",
"=",
"getLayoutPosition",
"(",
")",
";",
"position",
"=",
"(",
"position",
"<=",
"binder",
".",
"getLastItemIndex",
"(",
")",
")",
"?",
"position",
":",
"getAdapterPosition",
"(",
")",
";",
"position",
"=",
"(",
"position",
"<=",
"binder",
".",
"getLastItemIndex",
"(",
")",
")",
"?",
"position",
":",
"RecyclerView",
".",
"NO_POSITION",
";",
"if",
"(",
"getLayoutPosition",
"(",
")",
"!=",
"RecyclerView",
".",
"NO_POSITION",
")",
"{",
"return",
"binder",
".",
"onItemLongClick",
"(",
"v",
",",
"viewType",
",",
"position",
",",
"binder",
".",
"getItem",
"(",
"position",
")",
",",
"getInstance",
"(",
")",
")",
";",
"}",
"return",
"false",
";",
"}",
"}",
")",
";",
"}"
] | Will bind onClick and setOnLongClickListener here
@param binder {@link PeasyViewHolder} itself
@param viewType viewType ID | [
"Will",
"bind",
"onClick",
"and",
"setOnLongClickListener",
"here"
] | a26071849e5d5b5b1febe685f205558b49908f87 | https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyViewHolder.java#L55-L79 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/internal/ComponentTree.java | ComponentTree.fire | @SuppressWarnings("PMD.UseVarargs")
public void fire(Event<?> event, Channel[] channels) {
eventPipeline.add(event, channels);
} | java | @SuppressWarnings("PMD.UseVarargs")
public void fire(Event<?> event, Channel[] channels) {
eventPipeline.add(event, channels);
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.UseVarargs\"",
")",
"public",
"void",
"fire",
"(",
"Event",
"<",
"?",
">",
"event",
",",
"Channel",
"[",
"]",
"channels",
")",
"{",
"eventPipeline",
".",
"add",
"(",
"event",
",",
"channels",
")",
";",
"}"
] | Forward to the thread's event manager.
@param event the event
@param channels the channels | [
"Forward",
"to",
"the",
"thread",
"s",
"event",
"manager",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/internal/ComponentTree.java#L158-L161 | train |
mnlipp/jgrapes | org.jgrapes.core/src/org/jgrapes/core/internal/ComponentTree.java | ComponentTree.dispatch | @SuppressWarnings("PMD.UseVarargs")
/* default */ void dispatch(EventPipeline pipeline,
EventBase<?> event, Channel[] channels) {
HandlerList handlers = getEventHandlers(event, channels);
handlers.process(pipeline, event);
} | java | @SuppressWarnings("PMD.UseVarargs")
/* default */ void dispatch(EventPipeline pipeline,
EventBase<?> event, Channel[] channels) {
HandlerList handlers = getEventHandlers(event, channels);
handlers.process(pipeline, event);
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.UseVarargs\"",
")",
"/* default */",
"void",
"dispatch",
"(",
"EventPipeline",
"pipeline",
",",
"EventBase",
"<",
"?",
">",
"event",
",",
"Channel",
"[",
"]",
"channels",
")",
"{",
"HandlerList",
"handlers",
"=",
"getEventHandlers",
"(",
"event",
",",
"channels",
")",
";",
"handlers",
".",
"process",
"(",
"pipeline",
",",
"event",
")",
";",
"}"
] | Send the event to all matching handlers.
@param event the event
@param channels the channels the event is sent to | [
"Send",
"the",
"event",
"to",
"all",
"matching",
"handlers",
"."
] | 8b5d874935d84c34a52d3e3d3745e869b5203fa0 | https://github.com/mnlipp/jgrapes/blob/8b5d874935d84c34a52d3e3d3745e869b5203fa0/org.jgrapes.core/src/org/jgrapes/core/internal/ComponentTree.java#L180-L185 | train |
anotheria/configureme | src/main/java/org/configureme/util/IOUtils.java | IOUtils.readlineFromStdIn | public static String readlineFromStdIn() throws IOException {
StringBuilder ret = new StringBuilder();
int c;
while ((c = System.in.read()) != '\n' && c != -1) {
if (c != '\r')
ret.append((char) c);
}
return ret.toString();
} | java | public static String readlineFromStdIn() throws IOException {
StringBuilder ret = new StringBuilder();
int c;
while ((c = System.in.read()) != '\n' && c != -1) {
if (c != '\r')
ret.append((char) c);
}
return ret.toString();
} | [
"public",
"static",
"String",
"readlineFromStdIn",
"(",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"ret",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"c",
";",
"while",
"(",
"(",
"c",
"=",
"System",
".",
"in",
".",
"read",
"(",
")",
")",
"!=",
"'",
"'",
"&&",
"c",
"!=",
"-",
"1",
")",
"{",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"ret",
".",
"append",
"(",
"(",
"char",
")",
"c",
")",
";",
"}",
"return",
"ret",
".",
"toString",
"(",
")",
";",
"}"
] | Reads a line from standard input.
@throws java.io.IOException if any.
@return a {@link java.lang.String} object. | [
"Reads",
"a",
"line",
"from",
"standard",
"input",
"."
] | 1f52dd9109349623190586bdf5a592de8016e1fa | https://github.com/anotheria/configureme/blob/1f52dd9109349623190586bdf5a592de8016e1fa/src/main/java/org/configureme/util/IOUtils.java#L159-L167 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FacebookFragment.java | FacebookFragment.getSessionState | protected final SessionState getSessionState() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getState() : null;
}
return null;
} | java | protected final SessionState getSessionState() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getState() : null;
}
return null;
} | [
"protected",
"final",
"SessionState",
"getSessionState",
"(",
")",
"{",
"if",
"(",
"sessionTracker",
"!=",
"null",
")",
"{",
"Session",
"currentSession",
"=",
"sessionTracker",
".",
"getSession",
"(",
")",
";",
"return",
"(",
"currentSession",
"!=",
"null",
")",
"?",
"currentSession",
".",
"getState",
"(",
")",
":",
"null",
";",
"}",
"return",
"null",
";",
"}"
] | Gets the current state of the session or null if no session has been created.
@return the current state of the session | [
"Gets",
"the",
"current",
"state",
"of",
"the",
"session",
"or",
"null",
"if",
"no",
"session",
"has",
"been",
"created",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookFragment.java#L123-L129 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FacebookFragment.java | FacebookFragment.getAccessToken | protected final String getAccessToken() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getAccessToken() : null;
}
return null;
} | java | protected final String getAccessToken() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getAccessToken() : null;
}
return null;
} | [
"protected",
"final",
"String",
"getAccessToken",
"(",
")",
"{",
"if",
"(",
"sessionTracker",
"!=",
"null",
")",
"{",
"Session",
"currentSession",
"=",
"sessionTracker",
".",
"getOpenSession",
"(",
")",
";",
"return",
"(",
"currentSession",
"!=",
"null",
")",
"?",
"currentSession",
".",
"getAccessToken",
"(",
")",
":",
"null",
";",
"}",
"return",
"null",
";",
"}"
] | Gets the access token associated with the current session or null if no
session has been created.
@return the access token | [
"Gets",
"the",
"access",
"token",
"associated",
"with",
"the",
"current",
"session",
"or",
"null",
"if",
"no",
"session",
"has",
"been",
"created",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookFragment.java#L137-L143 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FacebookFragment.java | FacebookFragment.getExpirationDate | protected final Date getExpirationDate() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getExpirationDate() : null;
}
return null;
} | java | protected final Date getExpirationDate() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
return (currentSession != null) ? currentSession.getExpirationDate() : null;
}
return null;
} | [
"protected",
"final",
"Date",
"getExpirationDate",
"(",
")",
"{",
"if",
"(",
"sessionTracker",
"!=",
"null",
")",
"{",
"Session",
"currentSession",
"=",
"sessionTracker",
".",
"getOpenSession",
"(",
")",
";",
"return",
"(",
"currentSession",
"!=",
"null",
")",
"?",
"currentSession",
".",
"getExpirationDate",
"(",
")",
":",
"null",
";",
"}",
"return",
"null",
";",
"}"
] | Gets the date at which the current session will expire or null if no session
has been created.
@return the date at which the current session will expire | [
"Gets",
"the",
"date",
"at",
"which",
"the",
"current",
"session",
"will",
"expire",
"or",
"null",
"if",
"no",
"session",
"has",
"been",
"created",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookFragment.java#L151-L157 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FacebookFragment.java | FacebookFragment.closeSessionAndClearTokenInformation | protected final void closeSessionAndClearTokenInformation() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
}
}
} | java | protected final void closeSessionAndClearTokenInformation() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getOpenSession();
if (currentSession != null) {
currentSession.closeAndClearTokenInformation();
}
}
} | [
"protected",
"final",
"void",
"closeSessionAndClearTokenInformation",
"(",
")",
"{",
"if",
"(",
"sessionTracker",
"!=",
"null",
")",
"{",
"Session",
"currentSession",
"=",
"sessionTracker",
".",
"getOpenSession",
"(",
")",
";",
"if",
"(",
"currentSession",
"!=",
"null",
")",
"{",
"currentSession",
".",
"closeAndClearTokenInformation",
"(",
")",
";",
"}",
"}",
"}"
] | Closes the current session as well as clearing the token cache. | [
"Closes",
"the",
"current",
"session",
"as",
"well",
"as",
"clearing",
"the",
"token",
"cache",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookFragment.java#L174-L181 | train |
avianey/facebook-api-android-maven | facebook/src/main/java/com/facebook/widget/FacebookFragment.java | FacebookFragment.getSessionPermissions | protected final List<String> getSessionPermissions() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getPermissions() : null;
}
return null;
} | java | protected final List<String> getSessionPermissions() {
if (sessionTracker != null) {
Session currentSession = sessionTracker.getSession();
return (currentSession != null) ? currentSession.getPermissions() : null;
}
return null;
} | [
"protected",
"final",
"List",
"<",
"String",
">",
"getSessionPermissions",
"(",
")",
"{",
"if",
"(",
"sessionTracker",
"!=",
"null",
")",
"{",
"Session",
"currentSession",
"=",
"sessionTracker",
".",
"getSession",
"(",
")",
";",
"return",
"(",
"currentSession",
"!=",
"null",
")",
"?",
"currentSession",
".",
"getPermissions",
"(",
")",
":",
"null",
";",
"}",
"return",
"null",
";",
"}"
] | Gets the permissions associated with the current session or null if no session
has been created.
@return the permissions associated with the current session | [
"Gets",
"the",
"permissions",
"associated",
"with",
"the",
"current",
"session",
"or",
"null",
"if",
"no",
"session",
"has",
"been",
"created",
"."
] | ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede | https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookFragment.java#L189-L195 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.