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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/JsfFaceletScannerPlugin.java | JsfFaceletScannerPlugin.configure | @Override
public void configure() {
if (getProperties().containsKey(PROPERTY_NAME_FILE_PATTERN)) {
filePattern = Pattern.compile(getProperties().get(PROPERTY_NAME_FILE_PATTERN).toString());
} else {
filePattern = Pattern.compile(DEFAULT_FILE_PATTERN);
}
} | java | @Override
public void configure() {
if (getProperties().containsKey(PROPERTY_NAME_FILE_PATTERN)) {
filePattern = Pattern.compile(getProperties().get(PROPERTY_NAME_FILE_PATTERN).toString());
} else {
filePattern = Pattern.compile(DEFAULT_FILE_PATTERN);
}
} | [
"@",
"Override",
"public",
"void",
"configure",
"(",
")",
"{",
"if",
"(",
"getProperties",
"(",
")",
".",
"containsKey",
"(",
"PROPERTY_NAME_FILE_PATTERN",
")",
")",
"{",
"filePattern",
"=",
"Pattern",
".",
"compile",
"(",
"getProperties",
"(",
")",
".",
"... | end method initialize | [
"end",
"method",
"initialize"
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/JsfFaceletScannerPlugin.java#L110-L117 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/ElementRef.java | ElementRef.compareTo | @Override
public int compareTo(ElementRef o) {
int diff = pageRef.compareTo(o.pageRef);
if(diff != 0) return diff;
return id.compareTo(o.id);
} | java | @Override
public int compareTo(ElementRef o) {
int diff = pageRef.compareTo(o.pageRef);
if(diff != 0) return diff;
return id.compareTo(o.id);
} | [
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"ElementRef",
"o",
")",
"{",
"int",
"diff",
"=",
"pageRef",
".",
"compareTo",
"(",
"o",
".",
"pageRef",
")",
";",
"if",
"(",
"diff",
"!=",
"0",
")",
"return",
"diff",
";",
"return",
"id",
".",
"co... | Orders by page then id.
@see PageRef#compareTo(com.semanticcms.core.model.PageRef) | [
"Orders",
"by",
"page",
"then",
"id",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/ElementRef.java#L81-L86 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/TextOnlyLayout.java | TextOnlyLayout.endContentLine | @Override
public void endContentLine(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, int rowspan, boolean endsInternal) {
out.print(" </td>\n"
+ " </tr>\n");
} | java | @Override
public void endContentLine(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, int rowspan, boolean endsInternal) {
out.print(" </td>\n"
+ " </tr>\n");
} | [
"@",
"Override",
"public",
"void",
"endContentLine",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"int",
"rowspan",
",",
"boolean",
"endsInternal",
")",
"{",
"out",
".",
"print",
"(",
"\" </td>\\n\"",
"+",
... | Ends one line of content. | [
"Ends",
"one",
"line",
"of",
"content",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/TextOnlyLayout.java#L428-L432 | train |
bremersee/sms | src/main/java/org/bremersee/sms/AbstractSmsService.java | AbstractSmsService.getSender | protected String getSender(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getSender())) {
return smsSendRequestDto.getSender();
}
Validate.notEmpty(defaultSender, "defaultSender must not be null or blank");
return defaultSender;
} | java | protected String getSender(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getSender())) {
return smsSendRequestDto.getSender();
}
Validate.notEmpty(defaultSender, "defaultSender must not be null or blank");
return defaultSender;
} | [
"protected",
"String",
"getSender",
"(",
"final",
"SmsSendRequestDto",
"smsSendRequestDto",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"smsSendRequestDto",
".",
"getSender",
"(",
")",
")",
")",
"{",
"return",
"smsSendRequestDto",
".",
"getSender",... | Returns the sender of the request. If no sender is specified the default sender will be
returned.
@param smsSendRequestDto the sms request
@return the sender
@throws IllegalArgumentException if no sender is specified at all | [
"Returns",
"the",
"sender",
"of",
"the",
"request",
".",
"If",
"no",
"sender",
"is",
"specified",
"the",
"default",
"sender",
"will",
"be",
"returned",
"."
] | 4e5e87ea98616dd316573b544f54cac56750d2f9 | https://github.com/bremersee/sms/blob/4e5e87ea98616dd316573b544f54cac56750d2f9/src/main/java/org/bremersee/sms/AbstractSmsService.java#L226-L232 | train |
bremersee/sms | src/main/java/org/bremersee/sms/AbstractSmsService.java | AbstractSmsService.getReceiver | protected String getReceiver(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getReceiver())) {
return smsSendRequestDto.getReceiver();
}
Validate.notEmpty(defaultReceiver, "defaultReceiver must not be null or blank");
return defaultReceiver;
} | java | protected String getReceiver(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getReceiver())) {
return smsSendRequestDto.getReceiver();
}
Validate.notEmpty(defaultReceiver, "defaultReceiver must not be null or blank");
return defaultReceiver;
} | [
"protected",
"String",
"getReceiver",
"(",
"final",
"SmsSendRequestDto",
"smsSendRequestDto",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"smsSendRequestDto",
".",
"getReceiver",
"(",
")",
")",
")",
"{",
"return",
"smsSendRequestDto",
".",
"getRece... | Returns the receiver of the request. If no receiver is specified the default receiver will be
returned.
@param smsSendRequestDto the sms request
@return the receiver
@throws IllegalArgumentException if no receiver is specified at all | [
"Returns",
"the",
"receiver",
"of",
"the",
"request",
".",
"If",
"no",
"receiver",
"is",
"specified",
"the",
"default",
"receiver",
"will",
"be",
"returned",
"."
] | 4e5e87ea98616dd316573b544f54cac56750d2f9 | https://github.com/bremersee/sms/blob/4e5e87ea98616dd316573b544f54cac56750d2f9/src/main/java/org/bremersee/sms/AbstractSmsService.java#L242-L248 | train |
bremersee/sms | src/main/java/org/bremersee/sms/AbstractSmsService.java | AbstractSmsService.getMessage | protected String getMessage(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getMessage())) {
return smsSendRequestDto.getMessage();
}
Validate.notEmpty(defaultMessage, "defaultMessage must not be null or blank");
return defaultMessage;
} | java | protected String getMessage(final SmsSendRequestDto smsSendRequestDto) {
if (StringUtils.isNotBlank(smsSendRequestDto.getMessage())) {
return smsSendRequestDto.getMessage();
}
Validate.notEmpty(defaultMessage, "defaultMessage must not be null or blank");
return defaultMessage;
} | [
"protected",
"String",
"getMessage",
"(",
"final",
"SmsSendRequestDto",
"smsSendRequestDto",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"smsSendRequestDto",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"return",
"smsSendRequestDto",
".",
"getMessag... | Returns the message of the request. If no message is specified the default message will be
returned.
@param smsSendRequestDto the sms request
@return the message
@throws IllegalArgumentException if no message is specified at all | [
"Returns",
"the",
"message",
"of",
"the",
"request",
".",
"If",
"no",
"message",
"is",
"specified",
"the",
"default",
"message",
"will",
"be",
"returned",
"."
] | 4e5e87ea98616dd316573b544f54cac56750d2f9 | https://github.com/bremersee/sms/blob/4e5e87ea98616dd316573b544f54cac56750d2f9/src/main/java/org/bremersee/sms/AbstractSmsService.java#L258-L264 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/md5/MD5.java | MD5.Update | final public void Update (String s) {
byte[] chars=s.getBytes();
// Changed on 2004-04-10 due to getBytes(int,int,char[],byte) being deprecated
//byte chars[];
//chars = new byte[s.length()];
//s.getBytes(0, s.length(), chars, 0);
Update(chars, chars.length);
} | java | final public void Update (String s) {
byte[] chars=s.getBytes();
// Changed on 2004-04-10 due to getBytes(int,int,char[],byte) being deprecated
//byte chars[];
//chars = new byte[s.length()];
//s.getBytes(0, s.length(), chars, 0);
Update(chars, chars.length);
} | [
"final",
"public",
"void",
"Update",
"(",
"String",
"s",
")",
"{",
"byte",
"[",
"]",
"chars",
"=",
"s",
".",
"getBytes",
"(",
")",
";",
"// Changed on 2004-04-10 due to getBytes(int,int,char[],byte) being deprecated",
"//byte\tchars[];",
"//chars = new byte[s.length()];",... | Update buffer with given string.
@param s String to be update to hash (is used as
s.getBytes()) | [
"Update",
"buffer",
"with",
"given",
"string",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/md5/MD5.java#L382-L390 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/md5/MD5.java | MD5.asHex | public static String asHex (byte[] hash) {
StringBuilder buf = new StringBuilder(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++) {
if (((int) hash[i] & 0xff) < 0x10)
buf.append("0");
buf.append(Long.toString((int) hash[i] & 0xff, 16));
}
return buf.toString();
} | java | public static String asHex (byte[] hash) {
StringBuilder buf = new StringBuilder(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++) {
if (((int) hash[i] & 0xff) < 0x10)
buf.append("0");
buf.append(Long.toString((int) hash[i] & 0xff, 16));
}
return buf.toString();
} | [
"public",
"static",
"String",
"asHex",
"(",
"byte",
"[",
"]",
"hash",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"hash",
".",
"length",
"*",
"2",
")",
";",
"int",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"hash"... | Turns array of bytes into string representing each byte as
unsigned hex number.
@param hash Array of bytes to convert to hex-string
@return Generated hex string | [
"Turns",
"array",
"of",
"bytes",
"into",
"string",
"representing",
"each",
"byte",
"as",
"unsigned",
"hex",
"number",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/md5/MD5.java#L458-L470 | train |
aoindustries/semanticcms-news-servlet | src/main/java/com/semanticcms/news/servlet/NewsUtils.java | NewsUtils.findAllNews | public static List<News> findAllNews(
ServletContext servletContext,
HttpServletRequest request,
HttpServletResponse response,
Page page
) throws ServletException, IOException {
final List<News> found = new ArrayList<>();
final SemanticCMS semanticCMS = SemanticCMS.getInstance(servletContext);
CapturePage.traversePagesAnyOrder(
servletContext,
request,
response,
page,
CaptureLevel.META,
new CapturePage.PageHandler<Void>() {
@Override
public Void handlePage(Page page) throws ServletException, IOException {
for(Element element : page.getElements()) {
if(element instanceof News) {
found.add((News)element);
}
}
return null;
}
},
new CapturePage.TraversalEdges() {
@Override
public Collection<ChildRef> getEdges(Page page) {
return page.getChildRefs();
}
},
new CapturePage.EdgeFilter() {
@Override
public boolean applyEdge(PageRef childPage) {
return semanticCMS.getBook(childPage.getBookRef()).isAccessible();
}
}
);
Collections.sort(found);
return Collections.unmodifiableList(found);
} | java | public static List<News> findAllNews(
ServletContext servletContext,
HttpServletRequest request,
HttpServletResponse response,
Page page
) throws ServletException, IOException {
final List<News> found = new ArrayList<>();
final SemanticCMS semanticCMS = SemanticCMS.getInstance(servletContext);
CapturePage.traversePagesAnyOrder(
servletContext,
request,
response,
page,
CaptureLevel.META,
new CapturePage.PageHandler<Void>() {
@Override
public Void handlePage(Page page) throws ServletException, IOException {
for(Element element : page.getElements()) {
if(element instanceof News) {
found.add((News)element);
}
}
return null;
}
},
new CapturePage.TraversalEdges() {
@Override
public Collection<ChildRef> getEdges(Page page) {
return page.getChildRefs();
}
},
new CapturePage.EdgeFilter() {
@Override
public boolean applyEdge(PageRef childPage) {
return semanticCMS.getBook(childPage.getBookRef()).isAccessible();
}
}
);
Collections.sort(found);
return Collections.unmodifiableList(found);
} | [
"public",
"static",
"List",
"<",
"News",
">",
"findAllNews",
"(",
"ServletContext",
"servletContext",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"Page",
"page",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"fina... | Gets all the new items in the given page and below, sorted by news natural order.
@see News#compareTo(com.semanticcms.news.model.News) | [
"Gets",
"all",
"the",
"new",
"items",
"in",
"the",
"given",
"page",
"and",
"below",
"sorted",
"by",
"news",
"natural",
"order",
"."
] | 3899c14fedffb4decc7be3e1560930e82cb5c933 | https://github.com/aoindustries/semanticcms-news-servlet/blob/3899c14fedffb4decc7be3e1560930e82cb5c933/src/main/java/com/semanticcms/news/servlet/NewsUtils.java#L55-L95 | train |
NessComputing/components-ness-httpserver | src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java | HttpServerHandlerBinder.bindHandler | public static LinkedBindingBuilder<Handler> bindHandler(final Binder binder)
{
final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, HANDLER_NAMED);
return handlers.addBinding();
} | java | public static LinkedBindingBuilder<Handler> bindHandler(final Binder binder)
{
final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, HANDLER_NAMED);
return handlers.addBinding();
} | [
"public",
"static",
"LinkedBindingBuilder",
"<",
"Handler",
">",
"bindHandler",
"(",
"final",
"Binder",
"binder",
")",
"{",
"final",
"Multibinder",
"<",
"Handler",
">",
"handlers",
"=",
"Multibinder",
".",
"newSetBinder",
"(",
"binder",
",",
"Handler",
".",
"c... | Bind a new handler into the jetty service. These handlers are bound before the servlet handler and can handle parts
of the URI space before a servlet sees it.
Do not use this method to bind logging handlers as they would be called before any functionality has been executed and
logging information would be incomplete. Use {@link HttpServerHandlerBinder#bindLoggingHandler(Binder) instead. | [
"Bind",
"a",
"new",
"handler",
"into",
"the",
"jetty",
"service",
".",
"These",
"handlers",
"are",
"bound",
"before",
"the",
"servlet",
"handler",
"and",
"can",
"handle",
"parts",
"of",
"the",
"URI",
"space",
"before",
"a",
"servlet",
"sees",
"it",
"."
] | 6a26bb852e8408e3499ad5d139961cdc6a96e857 | https://github.com/NessComputing/components-ness-httpserver/blob/6a26bb852e8408e3499ad5d139961cdc6a96e857/src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java#L60-L64 | train |
NessComputing/components-ness-httpserver | src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java | HttpServerHandlerBinder.bindLoggingHandler | public static LinkedBindingBuilder<Handler> bindLoggingHandler(final Binder binder)
{
final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, LOGGING_NAMED);
return handlers.addBinding();
} | java | public static LinkedBindingBuilder<Handler> bindLoggingHandler(final Binder binder)
{
final Multibinder<Handler> handlers = Multibinder.newSetBinder(binder, Handler.class, LOGGING_NAMED);
return handlers.addBinding();
} | [
"public",
"static",
"LinkedBindingBuilder",
"<",
"Handler",
">",
"bindLoggingHandler",
"(",
"final",
"Binder",
"binder",
")",
"{",
"final",
"Multibinder",
"<",
"Handler",
">",
"handlers",
"=",
"Multibinder",
".",
"newSetBinder",
"(",
"binder",
",",
"Handler",
".... | Bind a new handler into the jetty service. These handlers are bound after the servlet handler and will not see any requests before they
have been handled. This is intended to bind logging, statistics etc. which want to operate on the results of a request to the server.
Any handler intended to manage content or a part of the URI space should use {@link HttpServerHandlerBinder#bindHandler(Binder)}. | [
"Bind",
"a",
"new",
"handler",
"into",
"the",
"jetty",
"service",
".",
"These",
"handlers",
"are",
"bound",
"after",
"the",
"servlet",
"handler",
"and",
"will",
"not",
"see",
"any",
"requests",
"before",
"they",
"have",
"been",
"handled",
".",
"This",
"is"... | 6a26bb852e8408e3499ad5d139961cdc6a96e857 | https://github.com/NessComputing/components-ness-httpserver/blob/6a26bb852e8408e3499ad5d139961cdc6a96e857/src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java#L72-L76 | train |
NessComputing/components-ness-httpserver | src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java | HttpServerHandlerBinder.bindSecurityHandler | public static LinkedBindingBuilder<HandlerWrapper> bindSecurityHandler(final Binder binder)
{
return binder.bind(HandlerWrapper.class).annotatedWith(SECURITY_NAMED);
} | java | public static LinkedBindingBuilder<HandlerWrapper> bindSecurityHandler(final Binder binder)
{
return binder.bind(HandlerWrapper.class).annotatedWith(SECURITY_NAMED);
} | [
"public",
"static",
"LinkedBindingBuilder",
"<",
"HandlerWrapper",
">",
"bindSecurityHandler",
"(",
"final",
"Binder",
"binder",
")",
"{",
"return",
"binder",
".",
"bind",
"(",
"HandlerWrapper",
".",
"class",
")",
".",
"annotatedWith",
"(",
"SECURITY_NAMED",
")",
... | Bind a delegating security handler. Any request will be routed through this handler and can be allowed or denied by this handler. If no handler
is bound, requests are forwarded to the internal handler collection. | [
"Bind",
"a",
"delegating",
"security",
"handler",
".",
"Any",
"request",
"will",
"be",
"routed",
"through",
"this",
"handler",
"and",
"can",
"be",
"allowed",
"or",
"denied",
"by",
"this",
"handler",
".",
"If",
"no",
"handler",
"is",
"bound",
"requests",
"a... | 6a26bb852e8408e3499ad5d139961cdc6a96e857 | https://github.com/NessComputing/components-ness-httpserver/blob/6a26bb852e8408e3499ad5d139961cdc6a96e857/src/main/java/com/nesscomputing/httpserver/HttpServerHandlerBinder.java#L82-L85 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/DescriptionAutoListPage.java | DescriptionAutoListPage.printContentStart | @Override
public void printContentStart(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws IOException, SQLException {
out.print(getDescription());
} | java | @Override
public void printContentStart(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws IOException, SQLException {
out.print(getDescription());
} | [
"@",
"Override",
"public",
"void",
"printContentStart",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"out",
".",
"print",
"(",
"getDescription",
"(",
")",
")"... | Prints the content that will be put before the auto-generated list. | [
"Prints",
"the",
"content",
"that",
"will",
"be",
"put",
"before",
"the",
"auto",
"-",
"generated",
"list",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/DescriptionAutoListPage.java#L54-L61 | train |
aoindustries/semanticcms-file-model | src/main/java/com/semanticcms/file/model/File.java | File.getElementIdTemplate | @Override
protected String getElementIdTemplate() {
ResourceRef rr = getResourceRef();
if(rr != null) {
String path = rr.getPath().toString();
int slashBefore;
if(path.endsWith(Path.SEPARATOR_STRING)) {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR, path.length() - 2);
} else {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR);
}
String filename = path.substring(slashBefore + 1);
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for file: " + path);
// Strip extension if will not leave empty
int lastDot = filename.lastIndexOf('.');
if(lastDot > 0) filename = filename.substring(0, lastDot);
return filename;
}
throw new IllegalStateException("Path not set");
} | java | @Override
protected String getElementIdTemplate() {
ResourceRef rr = getResourceRef();
if(rr != null) {
String path = rr.getPath().toString();
int slashBefore;
if(path.endsWith(Path.SEPARATOR_STRING)) {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR, path.length() - 2);
} else {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR);
}
String filename = path.substring(slashBefore + 1);
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for file: " + path);
// Strip extension if will not leave empty
int lastDot = filename.lastIndexOf('.');
if(lastDot > 0) filename = filename.substring(0, lastDot);
return filename;
}
throw new IllegalStateException("Path not set");
} | [
"@",
"Override",
"protected",
"String",
"getElementIdTemplate",
"(",
")",
"{",
"ResourceRef",
"rr",
"=",
"getResourceRef",
"(",
")",
";",
"if",
"(",
"rr",
"!=",
"null",
")",
"{",
"String",
"path",
"=",
"rr",
".",
"getPath",
"(",
")",
".",
"toString",
"... | Does not include the size on the ID template, also strips any file extension if it will not leave the filename empty. | [
"Does",
"not",
"include",
"the",
"size",
"on",
"the",
"ID",
"template",
"also",
"strips",
"any",
"file",
"extension",
"if",
"it",
"will",
"not",
"leave",
"the",
"filename",
"empty",
"."
] | 5995223e56140c81230b57f45021ecd8fa7b53bb | https://github.com/aoindustries/semanticcms-file-model/blob/5995223e56140c81230b57f45021ecd8fa7b53bb/src/main/java/com/semanticcms/file/model/File.java#L47-L66 | train |
aoindustries/semanticcms-file-model | src/main/java/com/semanticcms/file/model/File.java | File.getLabel | @Override
public String getLabel() {
ResourceStore rs;
ResourceRef rr;
synchronized(lock) {
rs = this.resourceStore;
rr = this.resourceRef;
}
if(rr != null) {
String path = rr.getPath().toString();
boolean isDirectory = path.endsWith(Path.SEPARATOR_STRING);
int slashBefore;
if(isDirectory) {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR, path.length() - 2);
} else {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR);
}
String filename = path.substring(slashBefore + 1);
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for file: " + path);
if(!isDirectory) {
if(rs != null) {
try {
try (ResourceConnection conn = rs.getResource(rr.getPath()).open()) {
if(conn.exists()) {
return
filename
+ " ("
+ StringUtility.getApproximateSize(conn.getLength())
+ ')'
;
}
}
} catch(FileNotFoundException e) {
// Resource removed between calls to exists() and getLength()
// fall-through to return filename
} catch(IOException e) {
throw new WrappedException(e);
}
}
}
return filename;
}
throw new IllegalStateException("Path not set");
} | java | @Override
public String getLabel() {
ResourceStore rs;
ResourceRef rr;
synchronized(lock) {
rs = this.resourceStore;
rr = this.resourceRef;
}
if(rr != null) {
String path = rr.getPath().toString();
boolean isDirectory = path.endsWith(Path.SEPARATOR_STRING);
int slashBefore;
if(isDirectory) {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR, path.length() - 2);
} else {
slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR);
}
String filename = path.substring(slashBefore + 1);
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for file: " + path);
if(!isDirectory) {
if(rs != null) {
try {
try (ResourceConnection conn = rs.getResource(rr.getPath()).open()) {
if(conn.exists()) {
return
filename
+ " ("
+ StringUtility.getApproximateSize(conn.getLength())
+ ')'
;
}
}
} catch(FileNotFoundException e) {
// Resource removed between calls to exists() and getLength()
// fall-through to return filename
} catch(IOException e) {
throw new WrappedException(e);
}
}
}
return filename;
}
throw new IllegalStateException("Path not set");
} | [
"@",
"Override",
"public",
"String",
"getLabel",
"(",
")",
"{",
"ResourceStore",
"rs",
";",
"ResourceRef",
"rr",
";",
"synchronized",
"(",
"lock",
")",
"{",
"rs",
"=",
"this",
".",
"resourceStore",
";",
"rr",
"=",
"this",
".",
"resourceRef",
";",
"}",
... | The label is always the filename. | [
"The",
"label",
"is",
"always",
"the",
"filename",
"."
] | 5995223e56140c81230b57f45021ecd8fa7b53bb | https://github.com/aoindustries/semanticcms-file-model/blob/5995223e56140c81230b57f45021ecd8fa7b53bb/src/main/java/com/semanticcms/file/model/File.java#L71-L114 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/servlet/http/Dispatcher.java | Dispatcher.getDispatchedPage | public static String getDispatchedPage(ServletRequest request) {
String dispatchedPage = (String)request.getAttribute(DISPATCHED_PAGE_REQUEST_ATTRIBUTE);
if(logger.isLoggable(Level.FINE)) logger.log(
Level.FINE,
"request={0}, dispatchedPage={1}",
new Object[] {
request,
dispatchedPage
}
);
return dispatchedPage;
} | java | public static String getDispatchedPage(ServletRequest request) {
String dispatchedPage = (String)request.getAttribute(DISPATCHED_PAGE_REQUEST_ATTRIBUTE);
if(logger.isLoggable(Level.FINE)) logger.log(
Level.FINE,
"request={0}, dispatchedPage={1}",
new Object[] {
request,
dispatchedPage
}
);
return dispatchedPage;
} | [
"public",
"static",
"String",
"getDispatchedPage",
"(",
"ServletRequest",
"request",
")",
"{",
"String",
"dispatchedPage",
"=",
"(",
"String",
")",
"request",
".",
"getAttribute",
"(",
"DISPATCHED_PAGE_REQUEST_ATTRIBUTE",
")",
";",
"if",
"(",
"logger",
".",
"isLog... | Gets the current-thread dispatched page or null if not set.
@see #getCurrentPagePath(javax.servlet.http.HttpServletRequest) for the version that uses current request as a default. | [
"Gets",
"the",
"current",
"-",
"thread",
"dispatched",
"page",
"or",
"null",
"if",
"not",
"set",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/Dispatcher.java#L100-L111 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/servlet/http/Dispatcher.java | Dispatcher.setDispatchedPage | public static void setDispatchedPage(ServletRequest request, String dispatchedPage) {
if(logger.isLoggable(Level.FINE)) logger.log(
Level.FINE,
"request={0}, dispatchedPage={1}",
new Object[] {
request,
dispatchedPage
}
);
request.setAttribute(DISPATCHED_PAGE_REQUEST_ATTRIBUTE, dispatchedPage);
} | java | public static void setDispatchedPage(ServletRequest request, String dispatchedPage) {
if(logger.isLoggable(Level.FINE)) logger.log(
Level.FINE,
"request={0}, dispatchedPage={1}",
new Object[] {
request,
dispatchedPage
}
);
request.setAttribute(DISPATCHED_PAGE_REQUEST_ATTRIBUTE, dispatchedPage);
} | [
"public",
"static",
"void",
"setDispatchedPage",
"(",
"ServletRequest",
"request",
",",
"String",
"dispatchedPage",
")",
"{",
"if",
"(",
"logger",
".",
"isLoggable",
"(",
"Level",
".",
"FINE",
")",
")",
"logger",
".",
"log",
"(",
"Level",
".",
"FINE",
",",... | Sets the current-thread dispatched page. | [
"Sets",
"the",
"current",
"-",
"thread",
"dispatched",
"page",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/Dispatcher.java#L116-L126 | train |
aoindustries/semanticcms-dia-model | src/main/java/com/semanticcms/dia/model/Dia.java | Dia.getLabel | @Override
public String getLabel() {
String l = label;
if(l != null) return l;
String p = path;
if(p != null) {
String filename = p.substring(p.lastIndexOf('/') + 1);
if(filename.endsWith(DOT_EXTENSION)) filename = filename.substring(0, filename.length() - DOT_EXTENSION.length());
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for diagram: " + p);
return filename;
}
throw new IllegalStateException("Cannot get label, neither label nor path set");
} | java | @Override
public String getLabel() {
String l = label;
if(l != null) return l;
String p = path;
if(p != null) {
String filename = p.substring(p.lastIndexOf('/') + 1);
if(filename.endsWith(DOT_EXTENSION)) filename = filename.substring(0, filename.length() - DOT_EXTENSION.length());
if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for diagram: " + p);
return filename;
}
throw new IllegalStateException("Cannot get label, neither label nor path set");
} | [
"@",
"Override",
"public",
"String",
"getLabel",
"(",
")",
"{",
"String",
"l",
"=",
"label",
";",
"if",
"(",
"l",
"!=",
"null",
")",
"return",
"l",
";",
"String",
"p",
"=",
"path",
";",
"if",
"(",
"p",
"!=",
"null",
")",
"{",
"String",
"filename"... | If not set, defaults to the last path segment of path, with any ".dia" extension stripped. | [
"If",
"not",
"set",
"defaults",
"to",
"the",
"last",
"path",
"segment",
"of",
"path",
"with",
"any",
".",
"dia",
"extension",
"stripped",
"."
] | 3855b92a491ccf9c61511604d40b68ed72e5a0a8 | https://github.com/aoindustries/semanticcms-dia-model/blob/3855b92a491ccf9c61511604d40b68ed72e5a0a8/src/main/java/com/semanticcms/dia/model/Dia.java#L45-L57 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.fromStringWithSourceMap | public static SourceNode fromStringWithSourceMap(String aGeneratedCode, SourceMapConsumer aSourceMapConsumer, final String aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
final SourceNode node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are removed from this array, by calling `shiftNextLine`.
List<String> remainingLines = new ArrayList<>(Util.split(aGeneratedCode, REGEX_NEWLINE));
// We need to remember the position of "remainingLines"
int[] lastGeneratedLine = new int[] { 1 };
int[] lastGeneratedColumn = new int[] { 0 };
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
Mapping[] lastMapping = new Mapping[1];
aSourceMapConsumer.eachMapping().forEach(mapping -> {
if (lastMapping[0] != null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine[0] < mapping.generated.line) {
// Associate first line with "lastMapping"
addMappingWithCode(node, aRelativePath, lastMapping[0], shiftNextLine(remainingLines));
lastGeneratedLine[0]++;
lastGeneratedColumn[0] = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
String nextLine = remainingLines.get(0);
String code = Util.substr(nextLine, 0, mapping.generated.column - lastGeneratedColumn[0]);
remainingLines.set(0, Util.substr(nextLine, mapping.generated.column - lastGeneratedColumn[0]));
lastGeneratedColumn[0] = mapping.generated.column;
addMappingWithCode(node, aRelativePath, lastMapping[0], code);
// No more remaining code, continue
lastMapping[0] = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine[0] < mapping.generated.line) {
node.add(shiftNextLine(remainingLines));
lastGeneratedLine[0]++;
}
if (lastGeneratedColumn[0] < mapping.generated.column && !remainingLines.isEmpty()) {
String nextLine = remainingLines.get(0);
node.add(Util.substr(nextLine, 0, mapping.generated.column));
remainingLines.set(0, Util.substr(nextLine, mapping.generated.column));
lastGeneratedColumn[0] = mapping.generated.column;
}
lastMapping[0] = mapping;
});
// We have processed all mappings.
if (remainingLines.size() > 0) {
if (lastMapping[0] != null) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(node, aRelativePath, lastMapping[0], shiftNextLine(remainingLines));
}
// and add the remaining lines without any mapping
node.add(Util.join(remainingLines, ""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources().forEach(sourceFile -> {
String content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = Util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
} | java | public static SourceNode fromStringWithSourceMap(String aGeneratedCode, SourceMapConsumer aSourceMapConsumer, final String aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
final SourceNode node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are removed from this array, by calling `shiftNextLine`.
List<String> remainingLines = new ArrayList<>(Util.split(aGeneratedCode, REGEX_NEWLINE));
// We need to remember the position of "remainingLines"
int[] lastGeneratedLine = new int[] { 1 };
int[] lastGeneratedColumn = new int[] { 0 };
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
Mapping[] lastMapping = new Mapping[1];
aSourceMapConsumer.eachMapping().forEach(mapping -> {
if (lastMapping[0] != null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine[0] < mapping.generated.line) {
// Associate first line with "lastMapping"
addMappingWithCode(node, aRelativePath, lastMapping[0], shiftNextLine(remainingLines));
lastGeneratedLine[0]++;
lastGeneratedColumn[0] = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
String nextLine = remainingLines.get(0);
String code = Util.substr(nextLine, 0, mapping.generated.column - lastGeneratedColumn[0]);
remainingLines.set(0, Util.substr(nextLine, mapping.generated.column - lastGeneratedColumn[0]));
lastGeneratedColumn[0] = mapping.generated.column;
addMappingWithCode(node, aRelativePath, lastMapping[0], code);
// No more remaining code, continue
lastMapping[0] = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine[0] < mapping.generated.line) {
node.add(shiftNextLine(remainingLines));
lastGeneratedLine[0]++;
}
if (lastGeneratedColumn[0] < mapping.generated.column && !remainingLines.isEmpty()) {
String nextLine = remainingLines.get(0);
node.add(Util.substr(nextLine, 0, mapping.generated.column));
remainingLines.set(0, Util.substr(nextLine, mapping.generated.column));
lastGeneratedColumn[0] = mapping.generated.column;
}
lastMapping[0] = mapping;
});
// We have processed all mappings.
if (remainingLines.size() > 0) {
if (lastMapping[0] != null) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(node, aRelativePath, lastMapping[0], shiftNextLine(remainingLines));
}
// and add the remaining lines without any mapping
node.add(Util.join(remainingLines, ""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources().forEach(sourceFile -> {
String content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = Util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
} | [
"public",
"static",
"SourceNode",
"fromStringWithSourceMap",
"(",
"String",
"aGeneratedCode",
",",
"SourceMapConsumer",
"aSourceMapConsumer",
",",
"final",
"String",
"aRelativePath",
")",
"{",
"// The SourceNode we want to fill with the generated code",
"// and the SourceMap",
"f... | Creates a SourceNode from generated code and a SourceMapConsumer.
@param aGeneratedCode
The generated code
@param aSourceMapConsumer
The SourceMap for the generated code
@param aRelativePath
Optional. The path that relative sources in the SourceMapConsumer should be relative to. | [
"Creates",
"a",
"SourceNode",
"from",
"generated",
"code",
"and",
"a",
"SourceMapConsumer",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L110-L191 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.add | public void add(Object... aChunk) {
List<Object> list;
if (aChunk.length == 1 && aChunk[0] instanceof List) {
@SuppressWarnings("unchecked")
List<Object> l = (List<Object>) aChunk[0];
list = l;
} else {
list = Arrays.asList(aChunk);
}
list.forEach(chunk -> {
if (chunk instanceof String) {
this.add((String) chunk);
} else if (chunk instanceof SourceNode) {
this.add((SourceNode) chunk);
} else {
throw new IllegalArgumentException();
}
});
} | java | public void add(Object... aChunk) {
List<Object> list;
if (aChunk.length == 1 && aChunk[0] instanceof List) {
@SuppressWarnings("unchecked")
List<Object> l = (List<Object>) aChunk[0];
list = l;
} else {
list = Arrays.asList(aChunk);
}
list.forEach(chunk -> {
if (chunk instanceof String) {
this.add((String) chunk);
} else if (chunk instanceof SourceNode) {
this.add((SourceNode) chunk);
} else {
throw new IllegalArgumentException();
}
});
} | [
"public",
"void",
"add",
"(",
"Object",
"...",
"aChunk",
")",
"{",
"List",
"<",
"Object",
">",
"list",
";",
"if",
"(",
"aChunk",
".",
"length",
"==",
"1",
"&&",
"aChunk",
"[",
"0",
"]",
"instanceof",
"List",
")",
"{",
"@",
"SuppressWarnings",
"(",
... | Add a chunk of generated JS to this source node.
@param aChunk
A string snippet of generated JS code, another instance of SourceNode, or an array where each member is one of those things. | [
"Add",
"a",
"chunk",
"of",
"generated",
"JS",
"to",
"this",
"source",
"node",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L199-L217 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.prepend | public void prepend(Object... aChunk) {
for (int i = aChunk.length - 1; i >= 0; i--) {
if (aChunk[i] instanceof String) {
this.prepend((String) aChunk[i]);
} else if (aChunk[i] instanceof SourceNode) {
this.prepend((SourceNode) aChunk[i]);
} else {
throw new IllegalArgumentException();
}
}
} | java | public void prepend(Object... aChunk) {
for (int i = aChunk.length - 1; i >= 0; i--) {
if (aChunk[i] instanceof String) {
this.prepend((String) aChunk[i]);
} else if (aChunk[i] instanceof SourceNode) {
this.prepend((SourceNode) aChunk[i]);
} else {
throw new IllegalArgumentException();
}
}
} | [
"public",
"void",
"prepend",
"(",
"Object",
"...",
"aChunk",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"aChunk",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"aChunk",
"[",
"i",
"]",
"instanceof",
"String",
")... | Add a chunk of generated JS to the beginning of this source node.
@param aChunk
A string snippet of generated JS code, another instance of SourceNode, or an array where each member is one of those things. | [
"Add",
"a",
"chunk",
"of",
"generated",
"JS",
"to",
"the",
"beginning",
"of",
"this",
"source",
"node",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L233-L243 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.join | public void join(String aSep) {
List<Object> newChildren;
int i;
int len = this.children.size();
if (len > 0) {
newChildren = new ArrayList<>();
for (i = 0; i < len - 1; i++) {
newChildren.add(this.children.get(i));
newChildren.add(aSep);
}
newChildren.add(this.children.get(i));
this.children = newChildren;
}
} | java | public void join(String aSep) {
List<Object> newChildren;
int i;
int len = this.children.size();
if (len > 0) {
newChildren = new ArrayList<>();
for (i = 0; i < len - 1; i++) {
newChildren.add(this.children.get(i));
newChildren.add(aSep);
}
newChildren.add(this.children.get(i));
this.children = newChildren;
}
} | [
"public",
"void",
"join",
"(",
"String",
"aSep",
")",
"{",
"List",
"<",
"Object",
">",
"newChildren",
";",
"int",
"i",
";",
"int",
"len",
"=",
"this",
".",
"children",
".",
"size",
"(",
")",
";",
"if",
"(",
"len",
">",
"0",
")",
"{",
"newChildren... | Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between each of `this.children`.
@param aSep
The separator. | [
"Like",
"String",
".",
"prototype",
".",
"join",
"except",
"for",
"SourceNodes",
".",
"Inserts",
"aStr",
"between",
"each",
"of",
"this",
".",
"children",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L284-L297 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.replaceRight | public void replaceRight(Pattern aPattern, String aReplacement) {
Object lastChild = this.children.get(this.children.size() - 1);
if (lastChild instanceof SourceNode) {
((SourceNode) lastChild).replaceRight(aPattern, aReplacement);
} else if (lastChild instanceof String) {
this.children.set(this.children.size() - 1, aPattern.matcher(((String) lastChild)).replaceFirst(aReplacement));
} else {
this.children.add(aPattern.matcher("").replaceFirst(aReplacement));
}
} | java | public void replaceRight(Pattern aPattern, String aReplacement) {
Object lastChild = this.children.get(this.children.size() - 1);
if (lastChild instanceof SourceNode) {
((SourceNode) lastChild).replaceRight(aPattern, aReplacement);
} else if (lastChild instanceof String) {
this.children.set(this.children.size() - 1, aPattern.matcher(((String) lastChild)).replaceFirst(aReplacement));
} else {
this.children.add(aPattern.matcher("").replaceFirst(aReplacement));
}
} | [
"public",
"void",
"replaceRight",
"(",
"Pattern",
"aPattern",
",",
"String",
"aReplacement",
")",
"{",
"Object",
"lastChild",
"=",
"this",
".",
"children",
".",
"get",
"(",
"this",
".",
"children",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"if",
"(",
... | Call String.prototype.replace on the very right-most source snippet. Useful for trimming whitespace from the end of a source node, etc.
@param aPattern
The pattern to replace.
@param aReplacement
The thing to replace the pattern with. | [
"Call",
"String",
".",
"prototype",
".",
"replace",
"on",
"the",
"very",
"right",
"-",
"most",
"source",
"snippet",
".",
"Useful",
"for",
"trimming",
"whitespace",
"from",
"the",
"end",
"of",
"a",
"source",
"node",
"etc",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L307-L316 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java | SourceNode.walkSourceContents | public void walkSourceContents(SourceWalker walker) {
for (int i = 0, len = this.children.size(); i < len; i++) {
if (this.children.get(i) instanceof SourceNode) {
((SourceNode) this.children.get(i)).walkSourceContents(walker);
}
}
for (Entry<String, String> entry : this.sourceContents.entrySet()) {
walker.walk(entry.getKey(), entry.getValue());
}
} | java | public void walkSourceContents(SourceWalker walker) {
for (int i = 0, len = this.children.size(); i < len; i++) {
if (this.children.get(i) instanceof SourceNode) {
((SourceNode) this.children.get(i)).walkSourceContents(walker);
}
}
for (Entry<String, String> entry : this.sourceContents.entrySet()) {
walker.walk(entry.getKey(), entry.getValue());
}
} | [
"public",
"void",
"walkSourceContents",
"(",
"SourceWalker",
"walker",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"len",
"=",
"this",
".",
"children",
".",
"size",
"(",
")",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"this",... | Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content.
@param aFn
The traversal function. | [
"Walk",
"over",
"the",
"tree",
"of",
"SourceNodes",
".",
"The",
"walking",
"function",
"is",
"called",
"for",
"each",
"source",
"file",
"content",
"and",
"is",
"passed",
"the",
"filename",
"and",
"source",
"content",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceNode.java#L340-L350 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.getProperty | public Map<String,Object> getProperty() {
// TODO: If we have properties volatile, could do the null and frozen cases outside the synchronized block
// TODO: Would this be faster?
synchronized(lock) {
if(properties == null) return Collections.emptyMap();
if(frozen) return properties;
return AoCollections.unmodifiableCopyMap(properties);
}
} | java | public Map<String,Object> getProperty() {
// TODO: If we have properties volatile, could do the null and frozen cases outside the synchronized block
// TODO: Would this be faster?
synchronized(lock) {
if(properties == null) return Collections.emptyMap();
if(frozen) return properties;
return AoCollections.unmodifiableCopyMap(properties);
}
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"getProperty",
"(",
")",
"{",
"// TODO: If we have properties volatile, could do the null and frozen cases outside the synchronized block",
"// TODO: Would this be faster?",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
... | Gets an unmodifiable snapshot of all properties associated with a node.
The returned map will not change, even if properties are added to the node. | [
"Gets",
"an",
"unmodifiable",
"snapshot",
"of",
"all",
"properties",
"associated",
"with",
"a",
"node",
".",
"The",
"returned",
"map",
"will",
"not",
"change",
"even",
"if",
"properties",
"are",
"added",
"to",
"the",
"node",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L135-L143 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.getChildElements | public List<Element> getChildElements() {
synchronized(lock) {
if(childElements == null) return Collections.emptyList();
if(frozen) return childElements;
return AoCollections.unmodifiableCopyList(childElements);
}
} | java | public List<Element> getChildElements() {
synchronized(lock) {
if(childElements == null) return Collections.emptyList();
if(frozen) return childElements;
return AoCollections.unmodifiableCopyList(childElements);
}
} | [
"public",
"List",
"<",
"Element",
">",
"getChildElements",
"(",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"childElements",
"==",
"null",
")",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"if",
"(",
"frozen",
")",
"return",
... | Every node may potentially have child elements. | [
"Every",
"node",
"may",
"potentially",
"have",
"child",
"elements",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L170-L176 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.addChildElement | public Long addChildElement(Element childElement, ElementWriter elementWriter) {
synchronized(lock) {
checkNotFrozen();
if(childElements == null) childElements = new ArrayList<>();
childElements.add(childElement);
if(elementWriters == null) elementWriters = new HashMap<>();
IdGenerator idGenerator = idGenerators.get();
while(true) {
Long elementKey = idGenerator.getNextId();
if(!elementWriters.containsKey(elementKey)) {
elementWriters.put(elementKey, elementWriter);
return elementKey;
} else {
// Reset generator when duplicate found (this should be extremely rare)
idGenerator.reset();
}
}
}
} | java | public Long addChildElement(Element childElement, ElementWriter elementWriter) {
synchronized(lock) {
checkNotFrozen();
if(childElements == null) childElements = new ArrayList<>();
childElements.add(childElement);
if(elementWriters == null) elementWriters = new HashMap<>();
IdGenerator idGenerator = idGenerators.get();
while(true) {
Long elementKey = idGenerator.getNextId();
if(!elementWriters.containsKey(elementKey)) {
elementWriters.put(elementKey, elementWriter);
return elementKey;
} else {
// Reset generator when duplicate found (this should be extremely rare)
idGenerator.reset();
}
}
}
} | [
"public",
"Long",
"addChildElement",
"(",
"Element",
"childElement",
",",
"ElementWriter",
"elementWriter",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"checkNotFrozen",
"(",
")",
";",
"if",
"(",
"childElements",
"==",
"null",
")",
"childElements",
"=",
"... | Adds a child element to this node. | [
"Adds",
"a",
"child",
"element",
"to",
"this",
"node",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L181-L199 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.getPageLinks | public Set<PageRef> getPageLinks() {
synchronized(lock) {
if(pageLinks == null) return Collections.emptySet();
if(frozen) return pageLinks;
return AoCollections.unmodifiableCopySet(pageLinks);
}
} | java | public Set<PageRef> getPageLinks() {
synchronized(lock) {
if(pageLinks == null) return Collections.emptySet();
if(frozen) return pageLinks;
return AoCollections.unmodifiableCopySet(pageLinks);
}
} | [
"public",
"Set",
"<",
"PageRef",
">",
"getPageLinks",
"(",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"pageLinks",
"==",
"null",
")",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"if",
"(",
"frozen",
")",
"return",
"pageLin... | Gets the set of all pages this node directly links to; this does not
include pages linked to by child elements. | [
"Gets",
"the",
"set",
"of",
"all",
"pages",
"this",
"node",
"directly",
"links",
"to",
";",
"this",
"does",
"not",
"include",
"pages",
"linked",
"to",
"by",
"child",
"elements",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L211-L217 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.getBody | public BufferResult getBody() {
BufferResult b = body;
if(b == null) return EmptyResult.getInstance();
return b;
} | java | public BufferResult getBody() {
BufferResult b = body;
if(b == null) return EmptyResult.getInstance();
return b;
} | [
"public",
"BufferResult",
"getBody",
"(",
")",
"{",
"BufferResult",
"b",
"=",
"body",
";",
"if",
"(",
"b",
"==",
"null",
")",
"return",
"EmptyResult",
".",
"getInstance",
"(",
")",
";",
"return",
"b",
";",
"}"
] | Every node may potentially have HTML body. | [
"Every",
"node",
"may",
"potentially",
"have",
"HTML",
"body",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L230-L234 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.getLabel | public String getLabel() {
StringBuilder sb = new StringBuilder();
try {
appendLabel(sb);
} catch(IOException e) {
throw new AssertionError("Should not happen because using StringBuilder", e);
}
return sb.toString();
} | java | public String getLabel() {
StringBuilder sb = new StringBuilder();
try {
appendLabel(sb);
} catch(IOException e) {
throw new AssertionError("Should not happen because using StringBuilder", e);
}
return sb.toString();
} | [
"public",
"String",
"getLabel",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"try",
"{",
"appendLabel",
"(",
"sb",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"\... | Gets a short description, useful for links and lists, for this node.
This default implementation calls {@link #appendLabel(java.lang.Appendable)}, thus you *must*
override at least this method or {@link #appendLabel(java.lang.Appendable)}.
@throws StackOverflowError if {@link #appendLabel(java.lang.Appendable)} not overridden. | [
"Gets",
"a",
"short",
"description",
"useful",
"for",
"links",
"and",
"lists",
"for",
"this",
"node",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L254-L262 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Node.java | Node.findTopLevelElementsRecurse | private static <E extends Element> List<E> findTopLevelElementsRecurse(Class<E> elementType, Node node, List<E> matches) {
for(Element elem : node.getChildElements()) {
if(elementType.isInstance(elem)) {
// Found match
if(matches == null) matches = new ArrayList<>();
matches.add(elementType.cast(elem));
} else {
// Look further down the tree
matches = findTopLevelElementsRecurse(elementType, elem, matches);
}
}
return matches;
} | java | private static <E extends Element> List<E> findTopLevelElementsRecurse(Class<E> elementType, Node node, List<E> matches) {
for(Element elem : node.getChildElements()) {
if(elementType.isInstance(elem)) {
// Found match
if(matches == null) matches = new ArrayList<>();
matches.add(elementType.cast(elem));
} else {
// Look further down the tree
matches = findTopLevelElementsRecurse(elementType, elem, matches);
}
}
return matches;
} | [
"private",
"static",
"<",
"E",
"extends",
"Element",
">",
"List",
"<",
"E",
">",
"findTopLevelElementsRecurse",
"(",
"Class",
"<",
"E",
">",
"elementType",
",",
"Node",
"node",
",",
"List",
"<",
"E",
">",
"matches",
")",
"{",
"for",
"(",
"Element",
"el... | Recursive component of findTopLevelElements.
@see #findTopLevelElements | [
"Recursive",
"component",
"of",
"findTopLevelElements",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Node.java#L299-L311 | train |
aoindustries/ao-messaging-base | src/main/java/com/aoindustries/messaging/base/AbstractSocket.java | AbstractSocket.setRemoteSocketAddress | protected void setRemoteSocketAddress(final SocketAddress newRemoteSocketAddress) {
synchronized(remoteSocketAddressLock) {
final SocketAddress oldRemoteSocketAddress = this.remoteSocketAddress;
if(!newRemoteSocketAddress.equals(oldRemoteSocketAddress)) {
this.remoteSocketAddress = newRemoteSocketAddress;
listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketListener>() {
@Override
public Runnable createCall(final SocketListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onRemoteSocketAddressChange(
AbstractSocket.this,
oldRemoteSocketAddress,
newRemoteSocketAddress
);
}
};
}
}
);
}
}
} | java | protected void setRemoteSocketAddress(final SocketAddress newRemoteSocketAddress) {
synchronized(remoteSocketAddressLock) {
final SocketAddress oldRemoteSocketAddress = this.remoteSocketAddress;
if(!newRemoteSocketAddress.equals(oldRemoteSocketAddress)) {
this.remoteSocketAddress = newRemoteSocketAddress;
listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketListener>() {
@Override
public Runnable createCall(final SocketListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onRemoteSocketAddressChange(
AbstractSocket.this,
oldRemoteSocketAddress,
newRemoteSocketAddress
);
}
};
}
}
);
}
}
} | [
"protected",
"void",
"setRemoteSocketAddress",
"(",
"final",
"SocketAddress",
"newRemoteSocketAddress",
")",
"{",
"synchronized",
"(",
"remoteSocketAddressLock",
")",
"{",
"final",
"SocketAddress",
"oldRemoteSocketAddress",
"=",
"this",
".",
"remoteSocketAddress",
";",
"i... | Sets the most recently seen remote address.
If the provided value is different than the previous, will notify all listeners. | [
"Sets",
"the",
"most",
"recently",
"seen",
"remote",
"address",
".",
"If",
"the",
"provided",
"value",
"is",
"different",
"than",
"the",
"previous",
"will",
"notify",
"all",
"listeners",
"."
] | 77921e05e06cf7999f313755d0bff1cc8b6b0228 | https://github.com/aoindustries/ao-messaging-base/blob/77921e05e06cf7999f313755d0bff1cc8b6b0228/src/main/java/com/aoindustries/messaging/base/AbstractSocket.java#L121-L145 | train |
aoindustries/ao-messaging-base | src/main/java/com/aoindustries/messaging/base/AbstractSocket.java | AbstractSocket.start | @Override
public void start(
Callback<? super Socket> onStart,
Callback<? super Exception> onError
) throws IllegalStateException {
if(isClosed()) throw new IllegalStateException("Socket is closed");
startImpl(onStart, onError);
} | java | @Override
public void start(
Callback<? super Socket> onStart,
Callback<? super Exception> onError
) throws IllegalStateException {
if(isClosed()) throw new IllegalStateException("Socket is closed");
startImpl(onStart, onError);
} | [
"@",
"Override",
"public",
"void",
"start",
"(",
"Callback",
"<",
"?",
"super",
"Socket",
">",
"onStart",
",",
"Callback",
"<",
"?",
"super",
"Exception",
">",
"onError",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"isClosed",
"(",
")",
")",
... | Makes sure the socket is not already closed then calls startImpl.
@see #startImpl(com.aoindustries.util.concurrent.Callback, com.aoindustries.util.concurrent.Callback) | [
"Makes",
"sure",
"the",
"socket",
"is",
"not",
"already",
"closed",
"then",
"calls",
"startImpl",
"."
] | 77921e05e06cf7999f313755d0bff1cc8b6b0228 | https://github.com/aoindustries/ao-messaging-base/blob/77921e05e06cf7999f313755d0bff1cc8b6b0228/src/main/java/com/aoindustries/messaging/base/AbstractSocket.java#L152-L159 | train |
aoindustries/semanticcms-news-view | src/main/java/com/semanticcms/news/view/NewsView.java | NewsView.getLastModified | @Override
public ReadableInstant getLastModified(
ServletContext servletContext,
HttpServletRequest request,
HttpServletResponse response,
Page page
) throws ServletException, IOException {
List<News> news = NewsUtils.findAllNews(servletContext, request, response, page);
return news.isEmpty() ? null : news.get(0).getPubDate();
} | java | @Override
public ReadableInstant getLastModified(
ServletContext servletContext,
HttpServletRequest request,
HttpServletResponse response,
Page page
) throws ServletException, IOException {
List<News> news = NewsUtils.findAllNews(servletContext, request, response, page);
return news.isEmpty() ? null : news.get(0).getPubDate();
} | [
"@",
"Override",
"public",
"ReadableInstant",
"getLastModified",
"(",
"ServletContext",
"servletContext",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"Page",
"page",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"List... | The last modified time of news view is the pubDate of the most recent news entry. | [
"The",
"last",
"modified",
"time",
"of",
"news",
"view",
"is",
"the",
"pubDate",
"of",
"the",
"most",
"recent",
"news",
"entry",
"."
] | 5d45895afa2942b4a8ea9207c55a8d8b566584a8 | https://github.com/aoindustries/semanticcms-news-view/blob/5d45895afa2942b4a8ea9207c55a8d8b566584a8/src/main/java/com/semanticcms/news/view/NewsView.java#L82-L91 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/DumpURLs.java | DumpURLs.search | @Override
public void search(
String[] words,
WebSiteRequest req,
HttpServletResponse response,
List<SearchResult> results,
AoByteArrayOutputStream bytes,
List<WebPage> finishedPages
) {
} | java | @Override
public void search(
String[] words,
WebSiteRequest req,
HttpServletResponse response,
List<SearchResult> results,
AoByteArrayOutputStream bytes,
List<WebPage> finishedPages
) {
} | [
"@",
"Override",
"public",
"void",
"search",
"(",
"String",
"[",
"]",
"words",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"response",
",",
"List",
"<",
"SearchResult",
">",
"results",
",",
"AoByteArrayOutputStream",
"bytes",
",",
"List",
"<",
"W... | Do not include this in the search results. | [
"Do",
"not",
"include",
"this",
"in",
"the",
"search",
"results",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/DumpURLs.java#L90-L99 | train |
probedock/probedock-java | src/main/java/io/probedock/client/core/connector/Connector.java | Connector.send | public boolean send(ProbeTestRun testRun) throws MalformedURLException {
LOGGER.info("Connected to Probe Dock API at " + configuration.getServerConfiguration().getApiUrl());
// Print the payload to the outout stream
if (configuration.isPayloadPrint()) {
try (OutputStreamWriter testRunOsw = new OutputStreamWriter(System.out)) {
serializer.serializePayload(testRunOsw, testRun, true);
}
catch (IOException ioe) {}
}
return sendTestRun(testRun);
} | java | public boolean send(ProbeTestRun testRun) throws MalformedURLException {
LOGGER.info("Connected to Probe Dock API at " + configuration.getServerConfiguration().getApiUrl());
// Print the payload to the outout stream
if (configuration.isPayloadPrint()) {
try (OutputStreamWriter testRunOsw = new OutputStreamWriter(System.out)) {
serializer.serializePayload(testRunOsw, testRun, true);
}
catch (IOException ioe) {}
}
return sendTestRun(testRun);
} | [
"public",
"boolean",
"send",
"(",
"ProbeTestRun",
"testRun",
")",
"throws",
"MalformedURLException",
"{",
"LOGGER",
".",
"info",
"(",
"\"Connected to Probe Dock API at \"",
"+",
"configuration",
".",
"getServerConfiguration",
"(",
")",
".",
"getApiUrl",
"(",
")",
")... | Send a payload to Probe Dock
@param testRun The test run to send
@return True if the test run successfully sent to Probe Dock
@throws MalformedURLException | [
"Send",
"a",
"payload",
"to",
"Probe",
"Dock"
] | 92ee6634ba4fe3fdffeb4e202f5372ef947a67c3 | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/core/connector/Connector.java#L50-L62 | train |
probedock/probedock-java | src/main/java/io/probedock/client/core/connector/Connector.java | Connector.openConnection | private HttpURLConnection openConnection(ServerConfiguration configuration, URL url) throws IOException {
if (configuration.hasProxyConfiguration()) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(configuration.getProxyConfiguration().getHost(), configuration.getProxyConfiguration().getPort()));
return (HttpURLConnection) url.openConnection(proxy);
}
else {
return (HttpURLConnection) url.openConnection();
}
} | java | private HttpURLConnection openConnection(ServerConfiguration configuration, URL url) throws IOException {
if (configuration.hasProxyConfiguration()) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(configuration.getProxyConfiguration().getHost(), configuration.getProxyConfiguration().getPort()));
return (HttpURLConnection) url.openConnection(proxy);
}
else {
return (HttpURLConnection) url.openConnection();
}
} | [
"private",
"HttpURLConnection",
"openConnection",
"(",
"ServerConfiguration",
"configuration",
",",
"URL",
"url",
")",
"throws",
"IOException",
"{",
"if",
"(",
"configuration",
".",
"hasProxyConfiguration",
"(",
")",
")",
"{",
"Proxy",
"proxy",
"=",
"new",
"Proxy"... | Open a connection regarding the configuration and the URL
@param configuration The configuration to get the proxy information if necessary
@param url The URL to open the connection from
@return The opened connection
@throws IOException In case of error when opening the connection | [
"Open",
"a",
"connection",
"regarding",
"the",
"configuration",
"and",
"the",
"URL"
] | 92ee6634ba4fe3fdffeb4e202f5372ef947a67c3 | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/core/connector/Connector.java#L172-L180 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/awt/ImageLoader.java | ImageLoader.loadImage | public void loadImage() throws InterruptedException {
synchronized(this) {
status=0;
image.getSource().startProduction(this);
while((status&(IMAGEABORTED|IMAGEERROR|SINGLEFRAMEDONE|STATICIMAGEDONE))==0) {
wait();
}
}
} | java | public void loadImage() throws InterruptedException {
synchronized(this) {
status=0;
image.getSource().startProduction(this);
while((status&(IMAGEABORTED|IMAGEERROR|SINGLEFRAMEDONE|STATICIMAGEDONE))==0) {
wait();
}
}
} | [
"public",
"void",
"loadImage",
"(",
")",
"throws",
"InterruptedException",
"{",
"synchronized",
"(",
"this",
")",
"{",
"status",
"=",
"0",
";",
"image",
".",
"getSource",
"(",
")",
".",
"startProduction",
"(",
"this",
")",
";",
"while",
"(",
"(",
"status... | Loads an image and returns when a frame is done, the image is done, an error occurs, or the image is aborted. | [
"Loads",
"an",
"image",
"and",
"returns",
"when",
"a",
"frame",
"is",
"done",
"the",
"image",
"is",
"done",
"an",
"error",
"occurs",
"or",
"the",
"image",
"is",
"aborted",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/awt/ImageLoader.java#L57-L65 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.createFilter | private FilterDescriptor createFilter(FilterType filterType, Map<String, FilterDescriptor> filters, ScannerContext context) {
Store store = context.getStore();
FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterType.getFilterName().getValue(), filters, store);
setAsyncSupported(filterDescriptor, filterType.getAsyncSupported());
for (DescriptionType descriptionType : filterType.getDescription()) {
filterDescriptor.getDescriptions().add(XmlDescriptorHelper.createDescription(descriptionType, store));
}
for (DisplayNameType displayNameType : filterType.getDisplayName()) {
filterDescriptor.getDisplayNames().add(XmlDescriptorHelper.createDisplayName(displayNameType, store));
}
FullyQualifiedClassType filterClass = filterType.getFilterClass();
if (filterClass != null) {
TypeResolver typeResolver = context.peek(TypeResolver.class);
TypeCache.CachedType<TypeDescriptor> filterClassDescriptor = typeResolver.resolve(filterClass.getValue(), context);
filterDescriptor.setType(filterClassDescriptor.getTypeDescriptor());
}
for (IconType iconType : filterType.getIcon()) {
IconDescriptor iconDescriptor = XmlDescriptorHelper.createIcon(iconType, store);
filterDescriptor.getIcons().add(iconDescriptor);
}
for (ParamValueType paramValueType : filterType.getInitParam()) {
ParamValueDescriptor paramValueDescriptor = createParamValue(paramValueType, store);
filterDescriptor.getInitParams().add(paramValueDescriptor);
}
return filterDescriptor;
} | java | private FilterDescriptor createFilter(FilterType filterType, Map<String, FilterDescriptor> filters, ScannerContext context) {
Store store = context.getStore();
FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterType.getFilterName().getValue(), filters, store);
setAsyncSupported(filterDescriptor, filterType.getAsyncSupported());
for (DescriptionType descriptionType : filterType.getDescription()) {
filterDescriptor.getDescriptions().add(XmlDescriptorHelper.createDescription(descriptionType, store));
}
for (DisplayNameType displayNameType : filterType.getDisplayName()) {
filterDescriptor.getDisplayNames().add(XmlDescriptorHelper.createDisplayName(displayNameType, store));
}
FullyQualifiedClassType filterClass = filterType.getFilterClass();
if (filterClass != null) {
TypeResolver typeResolver = context.peek(TypeResolver.class);
TypeCache.CachedType<TypeDescriptor> filterClassDescriptor = typeResolver.resolve(filterClass.getValue(), context);
filterDescriptor.setType(filterClassDescriptor.getTypeDescriptor());
}
for (IconType iconType : filterType.getIcon()) {
IconDescriptor iconDescriptor = XmlDescriptorHelper.createIcon(iconType, store);
filterDescriptor.getIcons().add(iconDescriptor);
}
for (ParamValueType paramValueType : filterType.getInitParam()) {
ParamValueDescriptor paramValueDescriptor = createParamValue(paramValueType, store);
filterDescriptor.getInitParams().add(paramValueDescriptor);
}
return filterDescriptor;
} | [
"private",
"FilterDescriptor",
"createFilter",
"(",
"FilterType",
"filterType",
",",
"Map",
"<",
"String",
",",
"FilterDescriptor",
">",
"filters",
",",
"ScannerContext",
"context",
")",
"{",
"Store",
"store",
"=",
"context",
".",
"getStore",
"(",
")",
";",
"F... | Create a filter descriptor.
@param filterType
The XML filter type.
@param context
The scanner context.
@return The filter descriptor. | [
"Create",
"a",
"filter",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L269-L294 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.createFilterMapping | private FilterMappingDescriptor createFilterMapping(FilterMappingType filterMappingType, Map<String, FilterDescriptor> filters,
Map<String, ServletDescriptor> servlets, Store store) {
FilterMappingDescriptor filterMappingDescriptor = store.create(FilterMappingDescriptor.class);
FilterNameType filterName = filterMappingType.getFilterName();
FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterName.getValue(), filters, store);
filterDescriptor.getMappings().add(filterMappingDescriptor);
for (Object urlPatternOrServletName : filterMappingType.getUrlPatternOrServletName()) {
if (urlPatternOrServletName instanceof UrlPatternType) {
UrlPatternType urlPatternType = (UrlPatternType) urlPatternOrServletName;
UrlPatternDescriptor urlPatternDescriptor = createUrlPattern(urlPatternType, store);
filterMappingDescriptor.getUrlPatterns().add(urlPatternDescriptor);
} else if (urlPatternOrServletName instanceof ServletNameType) {
ServletNameType servletNameType = (ServletNameType) urlPatternOrServletName;
ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor(ServletDescriptor.class, servletNameType.getValue(), servlets, store);
filterMappingDescriptor.setServlet(servletDescriptor);
}
}
for (DispatcherType dispatcherType : filterMappingType.getDispatcher()) {
DispatcherDescriptor dispatcherDescriptor = store.create(DispatcherDescriptor.class);
dispatcherDescriptor.setValue(dispatcherType.getValue());
filterMappingDescriptor.getDispatchers().add(dispatcherDescriptor);
}
return filterMappingDescriptor;
} | java | private FilterMappingDescriptor createFilterMapping(FilterMappingType filterMappingType, Map<String, FilterDescriptor> filters,
Map<String, ServletDescriptor> servlets, Store store) {
FilterMappingDescriptor filterMappingDescriptor = store.create(FilterMappingDescriptor.class);
FilterNameType filterName = filterMappingType.getFilterName();
FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterName.getValue(), filters, store);
filterDescriptor.getMappings().add(filterMappingDescriptor);
for (Object urlPatternOrServletName : filterMappingType.getUrlPatternOrServletName()) {
if (urlPatternOrServletName instanceof UrlPatternType) {
UrlPatternType urlPatternType = (UrlPatternType) urlPatternOrServletName;
UrlPatternDescriptor urlPatternDescriptor = createUrlPattern(urlPatternType, store);
filterMappingDescriptor.getUrlPatterns().add(urlPatternDescriptor);
} else if (urlPatternOrServletName instanceof ServletNameType) {
ServletNameType servletNameType = (ServletNameType) urlPatternOrServletName;
ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor(ServletDescriptor.class, servletNameType.getValue(), servlets, store);
filterMappingDescriptor.setServlet(servletDescriptor);
}
}
for (DispatcherType dispatcherType : filterMappingType.getDispatcher()) {
DispatcherDescriptor dispatcherDescriptor = store.create(DispatcherDescriptor.class);
dispatcherDescriptor.setValue(dispatcherType.getValue());
filterMappingDescriptor.getDispatchers().add(dispatcherDescriptor);
}
return filterMappingDescriptor;
} | [
"private",
"FilterMappingDescriptor",
"createFilterMapping",
"(",
"FilterMappingType",
"filterMappingType",
",",
"Map",
"<",
"String",
",",
"FilterDescriptor",
">",
"filters",
",",
"Map",
"<",
"String",
",",
"ServletDescriptor",
">",
"servlets",
",",
"Store",
"store",... | Create a filter mapping descriptor.
@param filterMappingType
The XML filter mapping type.
@param servlets
The map of known servlets.
@param store
The store.
@return The filter mapping descriptor. | [
"Create",
"a",
"filter",
"mapping",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L307-L331 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.getOrCreateNamedDescriptor | private <T extends NamedDescriptor> T getOrCreateNamedDescriptor(Class<T> type, String name, Map<String, T> descriptors, Store store) {
T descriptor = descriptors.get(name);
if (descriptor == null) {
descriptor = store.create(type);
descriptor.setName(name);
descriptors.put(name, descriptor);
}
return descriptor;
} | java | private <T extends NamedDescriptor> T getOrCreateNamedDescriptor(Class<T> type, String name, Map<String, T> descriptors, Store store) {
T descriptor = descriptors.get(name);
if (descriptor == null) {
descriptor = store.create(type);
descriptor.setName(name);
descriptors.put(name, descriptor);
}
return descriptor;
} | [
"private",
"<",
"T",
"extends",
"NamedDescriptor",
">",
"T",
"getOrCreateNamedDescriptor",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"name",
",",
"Map",
"<",
"String",
",",
"T",
">",
"descriptors",
",",
"Store",
"store",
")",
"{",
"T",
"descrip... | Get or create a named descriptor.
@param type
The descriptor type.
@param name
The name.
@param descriptors
The map of known named descriptors.
@param store
The store.
@return The servlet descriptor. | [
"Get",
"or",
"create",
"a",
"named",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L439-L447 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.createParamValue | private ParamValueDescriptor createParamValue(ParamValueType paramValueType, Store store) {
ParamValueDescriptor paramValueDescriptor = store.create(ParamValueDescriptor.class);
for (DescriptionType descriptionType : paramValueType.getDescription()) {
DescriptionDescriptor descriptionDescriptor = XmlDescriptorHelper.createDescription(descriptionType, store);
paramValueDescriptor.getDescriptions().add(descriptionDescriptor);
}
paramValueDescriptor.setName(paramValueType.getParamName().getValue());
XsdStringType paramValue = paramValueType.getParamValue();
if (paramValue != null) {
paramValueDescriptor.setValue(paramValue.getValue());
}
return paramValueDescriptor;
} | java | private ParamValueDescriptor createParamValue(ParamValueType paramValueType, Store store) {
ParamValueDescriptor paramValueDescriptor = store.create(ParamValueDescriptor.class);
for (DescriptionType descriptionType : paramValueType.getDescription()) {
DescriptionDescriptor descriptionDescriptor = XmlDescriptorHelper.createDescription(descriptionType, store);
paramValueDescriptor.getDescriptions().add(descriptionDescriptor);
}
paramValueDescriptor.setName(paramValueType.getParamName().getValue());
XsdStringType paramValue = paramValueType.getParamValue();
if (paramValue != null) {
paramValueDescriptor.setValue(paramValue.getValue());
}
return paramValueDescriptor;
} | [
"private",
"ParamValueDescriptor",
"createParamValue",
"(",
"ParamValueType",
"paramValueType",
",",
"Store",
"store",
")",
"{",
"ParamValueDescriptor",
"paramValueDescriptor",
"=",
"store",
".",
"create",
"(",
"ParamValueDescriptor",
".",
"class",
")",
";",
"for",
"(... | Create a param value descriptor.
@param paramValueType
The XML param value type.
@param store
The store.
@return The param value descriptor. | [
"Create",
"a",
"param",
"value",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L458-L470 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.setAsyncSupported | private void setAsyncSupported(AsyncSupportedDescriptor asyncSupportedDescriptor, TrueFalseType asyncSupported) {
if (asyncSupported != null) {
asyncSupportedDescriptor.setAsyncSupported(asyncSupported.isValue());
}
} | java | private void setAsyncSupported(AsyncSupportedDescriptor asyncSupportedDescriptor, TrueFalseType asyncSupported) {
if (asyncSupported != null) {
asyncSupportedDescriptor.setAsyncSupported(asyncSupported.isValue());
}
} | [
"private",
"void",
"setAsyncSupported",
"(",
"AsyncSupportedDescriptor",
"asyncSupportedDescriptor",
",",
"TrueFalseType",
"asyncSupported",
")",
"{",
"if",
"(",
"asyncSupported",
"!=",
"null",
")",
"{",
"asyncSupportedDescriptor",
".",
"setAsyncSupported",
"(",
"asyncSup... | Set the value for an async supported on the given descriptor.
@param asyncSupportedDescriptor
The async supported descriptor.
@param asyncSupported
The value. | [
"Set",
"the",
"value",
"for",
"an",
"async",
"supported",
"on",
"the",
"given",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L480-L484 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.createServletMapping | private ServletMappingDescriptor createServletMapping(ServletMappingType servletMappingType, Map<String, ServletDescriptor> servlets, Store store) {
ServletMappingDescriptor servletMappingDescriptor = store.create(ServletMappingDescriptor.class);
ServletNameType servletName = servletMappingType.getServletName();
ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor(ServletDescriptor.class, servletName.getValue(), servlets, store);
servletDescriptor.getMappings().add(servletMappingDescriptor);
for (UrlPatternType urlPatternType : servletMappingType.getUrlPattern()) {
UrlPatternDescriptor urlPatternDescriptor = createUrlPattern(urlPatternType, store);
servletMappingDescriptor.getUrlPatterns().add(urlPatternDescriptor);
}
return servletMappingDescriptor;
} | java | private ServletMappingDescriptor createServletMapping(ServletMappingType servletMappingType, Map<String, ServletDescriptor> servlets, Store store) {
ServletMappingDescriptor servletMappingDescriptor = store.create(ServletMappingDescriptor.class);
ServletNameType servletName = servletMappingType.getServletName();
ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor(ServletDescriptor.class, servletName.getValue(), servlets, store);
servletDescriptor.getMappings().add(servletMappingDescriptor);
for (UrlPatternType urlPatternType : servletMappingType.getUrlPattern()) {
UrlPatternDescriptor urlPatternDescriptor = createUrlPattern(urlPatternType, store);
servletMappingDescriptor.getUrlPatterns().add(urlPatternDescriptor);
}
return servletMappingDescriptor;
} | [
"private",
"ServletMappingDescriptor",
"createServletMapping",
"(",
"ServletMappingType",
"servletMappingType",
",",
"Map",
"<",
"String",
",",
"ServletDescriptor",
">",
"servlets",
",",
"Store",
"store",
")",
"{",
"ServletMappingDescriptor",
"servletMappingDescriptor",
"="... | Create a servlet mapping descriptor.
@param servletMappingType
The XML servlet mapping type.
@param store
The store.
@return The servlet mapping descriptor. | [
"Create",
"a",
"servlet",
"mapping",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L495-L505 | train |
buschmais/jqa-javaee6-plugin | src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java | WebXmlScannerPlugin.createSessionConfig | private SessionConfigDescriptor createSessionConfig(SessionConfigType sessionConfigType, Store store) {
SessionConfigDescriptor sessionConfigDescriptor = store.create(SessionConfigDescriptor.class);
XsdIntegerType sessionTimeout = sessionConfigType.getSessionTimeout();
if (sessionTimeout != null) {
sessionConfigDescriptor.setSessionTimeout(sessionTimeout.getValue().intValue());
}
return sessionConfigDescriptor;
} | java | private SessionConfigDescriptor createSessionConfig(SessionConfigType sessionConfigType, Store store) {
SessionConfigDescriptor sessionConfigDescriptor = store.create(SessionConfigDescriptor.class);
XsdIntegerType sessionTimeout = sessionConfigType.getSessionTimeout();
if (sessionTimeout != null) {
sessionConfigDescriptor.setSessionTimeout(sessionTimeout.getValue().intValue());
}
return sessionConfigDescriptor;
} | [
"private",
"SessionConfigDescriptor",
"createSessionConfig",
"(",
"SessionConfigType",
"sessionConfigType",
",",
"Store",
"store",
")",
"{",
"SessionConfigDescriptor",
"sessionConfigDescriptor",
"=",
"store",
".",
"create",
"(",
"SessionConfigDescriptor",
".",
"class",
")",... | Create a session config descriptor.
@param sessionConfigType
The XML session config type.
@param store
The store.
@return The session config descriptor. | [
"Create",
"a",
"session",
"config",
"descriptor",
"."
] | f5776604d9255206807e5aca90b8767bde494e14 | https://github.com/buschmais/jqa-javaee6-plugin/blob/f5776604d9255206807e5aca90b8767bde494e14/src/main/java/com/buschmais/jqassistant/plugin/javaee6/impl/scanner/WebXmlScannerPlugin.java#L516-L523 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/PaddingOutputStream.java | PaddingOutputStream.finish | public void finish() throws IOException {
int lastBlockSize = (int)(byteCount % blockSize);
if(lastBlockSize!=0) {
while(lastBlockSize<blockSize) {
out.write(padding);
byteCount++;
lastBlockSize++;
}
}
out.flush();
} | java | public void finish() throws IOException {
int lastBlockSize = (int)(byteCount % blockSize);
if(lastBlockSize!=0) {
while(lastBlockSize<blockSize) {
out.write(padding);
byteCount++;
lastBlockSize++;
}
}
out.flush();
} | [
"public",
"void",
"finish",
"(",
")",
"throws",
"IOException",
"{",
"int",
"lastBlockSize",
"=",
"(",
"int",
")",
"(",
"byteCount",
"%",
"blockSize",
")",
";",
"if",
"(",
"lastBlockSize",
"!=",
"0",
")",
"{",
"while",
"(",
"lastBlockSize",
"<",
"blockSiz... | Pads and flushes without closing the underlying stream. | [
"Pads",
"and",
"flushes",
"without",
"closing",
"the",
"underlying",
"stream",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/PaddingOutputStream.java#L67-L77 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/LogFollower.java | LogFollower.detectFileChange | private void detectFileChange() throws IOException {
checkClosed();
assert Thread.holdsLock(filePosLock);
while(!file.exists()) {
try {
System.err.println("File not found, waiting: " + file.getPath());
Thread.sleep(pollInterval);
} catch(InterruptedException e) {
InterruptedIOException newExc = new InterruptedIOException(e.getMessage());
newExc.initCause(e);
throw newExc;
}
checkClosed();
}
long fileLen = file.length();
if(fileLen<filePos) filePos = 0;
} | java | private void detectFileChange() throws IOException {
checkClosed();
assert Thread.holdsLock(filePosLock);
while(!file.exists()) {
try {
System.err.println("File not found, waiting: " + file.getPath());
Thread.sleep(pollInterval);
} catch(InterruptedException e) {
InterruptedIOException newExc = new InterruptedIOException(e.getMessage());
newExc.initCause(e);
throw newExc;
}
checkClosed();
}
long fileLen = file.length();
if(fileLen<filePos) filePos = 0;
} | [
"private",
"void",
"detectFileChange",
"(",
")",
"throws",
"IOException",
"{",
"checkClosed",
"(",
")",
";",
"assert",
"Thread",
".",
"holdsLock",
"(",
"filePosLock",
")",
";",
"while",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"try",
"{",
"... | Checks the current position in the file.
Detects if the file has changed in length.
If closed, throws an exception.
If file doesn't exist, waits until it does exist. | [
"Checks",
"the",
"current",
"position",
"in",
"the",
"file",
".",
"Detects",
"if",
"the",
"file",
"has",
"changed",
"in",
"length",
".",
"If",
"closed",
"throws",
"an",
"exception",
".",
"If",
"file",
"doesn",
"t",
"exist",
"waits",
"until",
"it",
"does"... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/LogFollower.java#L84-L100 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/author/composer/TcpServerComposer.java | TcpServerComposer.processSynAckPacket | protected void processSynAckPacket(Packet packet) {
String serverIp = packet.getSrcIpAddr();
int serverPort = packet.getSrcPort();
String clientIp = packet.getDestIpAddr();
int clientPort = packet.getDestPort();
String clientId = makeClientId(clientIp, clientPort);
TcpServerScript serverFragmentWriter = scriptFragments.get(clientId);
if ( serverFragmentWriter == null ) {
serverFragmentWriter = new TcpServerScript(emitterFactory.getRptScriptEmitter(OUTPUT_TYPE,
"tcp-server-"
+ serverIp + "-" + serverPort + "-client-" + clientIp + "-" + clientPort + "-ServerSide"));
}
else if ( serverFragmentWriter.getState() != ScriptState.CLOSED ) {
throw new RptScriptsCreatorFailureException(
"Attempting to open already opened tcp connection from server composer:" + clientId);
}
serverFragmentWriter.writeAccept(serverIp, serverPort, packet);
scriptFragments.put(clientId, serverFragmentWriter);
} | java | protected void processSynAckPacket(Packet packet) {
String serverIp = packet.getSrcIpAddr();
int serverPort = packet.getSrcPort();
String clientIp = packet.getDestIpAddr();
int clientPort = packet.getDestPort();
String clientId = makeClientId(clientIp, clientPort);
TcpServerScript serverFragmentWriter = scriptFragments.get(clientId);
if ( serverFragmentWriter == null ) {
serverFragmentWriter = new TcpServerScript(emitterFactory.getRptScriptEmitter(OUTPUT_TYPE,
"tcp-server-"
+ serverIp + "-" + serverPort + "-client-" + clientIp + "-" + clientPort + "-ServerSide"));
}
else if ( serverFragmentWriter.getState() != ScriptState.CLOSED ) {
throw new RptScriptsCreatorFailureException(
"Attempting to open already opened tcp connection from server composer:" + clientId);
}
serverFragmentWriter.writeAccept(serverIp, serverPort, packet);
scriptFragments.put(clientId, serverFragmentWriter);
} | [
"protected",
"void",
"processSynAckPacket",
"(",
"Packet",
"packet",
")",
"{",
"String",
"serverIp",
"=",
"packet",
".",
"getSrcIpAddr",
"(",
")",
";",
"int",
"serverPort",
"=",
"packet",
".",
"getSrcPort",
"(",
")",
";",
"String",
"clientIp",
"=",
"packet",... | Processes the syn-ack packet which notes the start of tcp conversation
@param packet | [
"Processes",
"the",
"syn",
"-",
"ack",
"packet",
"which",
"notes",
"the",
"start",
"of",
"tcp",
"conversation"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/author/composer/TcpServerComposer.java#L124-L142 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/author/composer/TcpClientComposer.java | TcpClientComposer.processSynAckPacket | protected void processSynAckPacket(Packet packet) {
Integer clientPort = packet.getDestPort();
Integer serverPort = packet.getSrcPort();
String serverIp = packet.getSrcIpAddr();
TcpClientScript scriptFragmentWriter = scripts.get(clientPort);
if ( scriptFragmentWriter == null ) {
scriptFragmentWriter = new TcpClientScript(emitterFactory.getRptScriptEmitter(OUTPUT_TYPE, "tcp-server-"
+ serverIp + "-" + serverPort + "-client-" + ipaddress + "-" + clientPort + "-ClientSide"));
}
else if ( scriptFragmentWriter.getState() != ScriptState.CLOSED ) {
throw new RptScriptsCreatorFailureException(
"Attempting to open already opened tcp connection from client port:" + clientPort);
}
scriptFragmentWriter.writeConnect(serverIp, serverPort, packet);
scripts.put(clientPort, scriptFragmentWriter);
} | java | protected void processSynAckPacket(Packet packet) {
Integer clientPort = packet.getDestPort();
Integer serverPort = packet.getSrcPort();
String serverIp = packet.getSrcIpAddr();
TcpClientScript scriptFragmentWriter = scripts.get(clientPort);
if ( scriptFragmentWriter == null ) {
scriptFragmentWriter = new TcpClientScript(emitterFactory.getRptScriptEmitter(OUTPUT_TYPE, "tcp-server-"
+ serverIp + "-" + serverPort + "-client-" + ipaddress + "-" + clientPort + "-ClientSide"));
}
else if ( scriptFragmentWriter.getState() != ScriptState.CLOSED ) {
throw new RptScriptsCreatorFailureException(
"Attempting to open already opened tcp connection from client port:" + clientPort);
}
scriptFragmentWriter.writeConnect(serverIp, serverPort, packet);
scripts.put(clientPort, scriptFragmentWriter);
} | [
"protected",
"void",
"processSynAckPacket",
"(",
"Packet",
"packet",
")",
"{",
"Integer",
"clientPort",
"=",
"packet",
".",
"getDestPort",
"(",
")",
";",
"Integer",
"serverPort",
"=",
"packet",
".",
"getSrcPort",
"(",
")",
";",
"String",
"serverIp",
"=",
"pa... | Process a connection packet which is read as an syn-ack
@param packet | [
"Process",
"a",
"connection",
"packet",
"which",
"is",
"read",
"as",
"an",
"syn",
"-",
"ack"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/author/composer/TcpClientComposer.java#L126-L143 | train |
k3po/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/ReadByteArrayBytesDecoder.java | ReadByteArrayBytesDecoder.readBuffer | @Override
public byte[] readBuffer(final ChannelBuffer buffer) {
int len = getLength();
byte[] matched = new byte[len];
buffer.readBytes(matched);
return matched;
} | java | @Override
public byte[] readBuffer(final ChannelBuffer buffer) {
int len = getLength();
byte[] matched = new byte[len];
buffer.readBytes(matched);
return matched;
} | [
"@",
"Override",
"public",
"byte",
"[",
"]",
"readBuffer",
"(",
"final",
"ChannelBuffer",
"buffer",
")",
"{",
"int",
"len",
"=",
"getLength",
"(",
")",
";",
"byte",
"[",
"]",
"matched",
"=",
"new",
"byte",
"[",
"len",
"]",
";",
"buffer",
".",
"readBy... | Read the data into an array of bytes | [
"Read",
"the",
"data",
"into",
"an",
"array",
"of",
"bytes"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/ReadByteArrayBytesDecoder.java#L35-L41 | train |
k3po/k3po | specification/ws/src/main/java/org/kaazing/specification/ws/internal/Functions.java | Functions.randomizeLetterCase | @Function
public static String randomizeLetterCase(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (RANDOM.nextBoolean()) {
c = toUpperCase(c);
} else {
c = toLowerCase(c);
}
result.append(c);
}
return result.toString();
} | java | @Function
public static String randomizeLetterCase(String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (RANDOM.nextBoolean()) {
c = toUpperCase(c);
} else {
c = toLowerCase(c);
}
result.append(c);
}
return result.toString();
} | [
"@",
"Function",
"public",
"static",
"String",
"randomizeLetterCase",
"(",
"String",
"text",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"text",
".",
"length",
"(",
"... | Takes a string and randomizes which letters in the text are upper or
lower case
@param text
@return | [
"Takes",
"a",
"string",
"and",
"randomizes",
"which",
"letters",
"in",
"the",
"text",
"are",
"upper",
"or",
"lower",
"case"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/ws/src/main/java/org/kaazing/specification/ws/internal/Functions.java#L116-L129 | train |
k3po/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/visitor/GenerateConfigurationVisitor.java | GenerateConfigurationVisitor.visit | @Override
public Configuration visit(AstConnectNode connectNode, State state) {
// masking is a no-op by default for each stream
state.readUnmasker = Masker.IDENTITY_MASKER;
state.writeMasker = Masker.IDENTITY_MASKER;
state.pipelineAsMap = new LinkedHashMap<>();
for (AstStreamableNode streamable : connectNode.getStreamables()) {
streamable.accept(this, state);
}
/* Add the completion handler */
String handlerName = String.format("completion#%d", state.pipelineAsMap.size() + 1);
CompletionHandler completionHandler = new CompletionHandler();
completionHandler.setRegionInfo(connectNode.getRegionInfo());
state.pipelineAsMap.put(handlerName, completionHandler);
String awaitName = connectNode.getAwaitName();
Barrier awaitBarrier = null;
if (awaitName != null) {
awaitBarrier = state.lookupBarrier(awaitName);
}
final ChannelPipeline pipeline = pipelineFromMap(state.pipelineAsMap);
/*
* TODO. This is weird. I will only have one pipeline per connect. But if I don't set a factory When a connect
* occurs it will create a shallow copy of the pipeline I set. This doesn't work due to the beforeAdd methods in
* ExecutionHandler. Namely when the pipeline is cloned it uses the same handler objects so the handler future
* is not null and we fail with an assertion error.
*/
ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
private int numCalled;
@Override
public ChannelPipeline getPipeline() {
if (numCalled++ != 0) {
throw new RobotException("getPipeline called more than once");
}
return pipeline;
}
};
// Now that connect supports barrier and expression value, connect uri may not be available at this point.
// To defer the evaluation of connect uri and initialization of ClientBootstrap, LocationResolver and
// ClientResolver are created with information necessary to create ClientBootstrap when the connect uri
// is available.
Supplier<URI> locationResolver = connectNode.getLocation()::getValue;
OptionsResolver optionsResolver = new OptionsResolver(connectNode.getOptions());
ClientBootstrapResolver clientResolver = new ClientBootstrapResolver(bootstrapFactory, addressFactory,
pipelineFactory, locationResolver, optionsResolver, awaitBarrier, connectNode.getRegionInfo());
// retain pipelines for tear down
state.configuration.getClientAndServerPipelines().add(pipeline);
state.configuration.getClientResolvers().add(clientResolver);
return state.configuration;
} | java | @Override
public Configuration visit(AstConnectNode connectNode, State state) {
// masking is a no-op by default for each stream
state.readUnmasker = Masker.IDENTITY_MASKER;
state.writeMasker = Masker.IDENTITY_MASKER;
state.pipelineAsMap = new LinkedHashMap<>();
for (AstStreamableNode streamable : connectNode.getStreamables()) {
streamable.accept(this, state);
}
/* Add the completion handler */
String handlerName = String.format("completion#%d", state.pipelineAsMap.size() + 1);
CompletionHandler completionHandler = new CompletionHandler();
completionHandler.setRegionInfo(connectNode.getRegionInfo());
state.pipelineAsMap.put(handlerName, completionHandler);
String awaitName = connectNode.getAwaitName();
Barrier awaitBarrier = null;
if (awaitName != null) {
awaitBarrier = state.lookupBarrier(awaitName);
}
final ChannelPipeline pipeline = pipelineFromMap(state.pipelineAsMap);
/*
* TODO. This is weird. I will only have one pipeline per connect. But if I don't set a factory When a connect
* occurs it will create a shallow copy of the pipeline I set. This doesn't work due to the beforeAdd methods in
* ExecutionHandler. Namely when the pipeline is cloned it uses the same handler objects so the handler future
* is not null and we fail with an assertion error.
*/
ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
private int numCalled;
@Override
public ChannelPipeline getPipeline() {
if (numCalled++ != 0) {
throw new RobotException("getPipeline called more than once");
}
return pipeline;
}
};
// Now that connect supports barrier and expression value, connect uri may not be available at this point.
// To defer the evaluation of connect uri and initialization of ClientBootstrap, LocationResolver and
// ClientResolver are created with information necessary to create ClientBootstrap when the connect uri
// is available.
Supplier<URI> locationResolver = connectNode.getLocation()::getValue;
OptionsResolver optionsResolver = new OptionsResolver(connectNode.getOptions());
ClientBootstrapResolver clientResolver = new ClientBootstrapResolver(bootstrapFactory, addressFactory,
pipelineFactory, locationResolver, optionsResolver, awaitBarrier, connectNode.getRegionInfo());
// retain pipelines for tear down
state.configuration.getClientAndServerPipelines().add(pipeline);
state.configuration.getClientResolvers().add(clientResolver);
return state.configuration;
} | [
"@",
"Override",
"public",
"Configuration",
"visit",
"(",
"AstConnectNode",
"connectNode",
",",
"State",
"state",
")",
"{",
"// masking is a no-op by default for each stream",
"state",
".",
"readUnmasker",
"=",
"Masker",
".",
"IDENTITY_MASKER",
";",
"state",
".",
"wri... | Creates the pipeline, visits all streamable nodes and the creates the ClientBootstrap with the pipeline and
remote address, | [
"Creates",
"the",
"pipeline",
"visits",
"all",
"streamable",
"nodes",
"and",
"the",
"creates",
"the",
"ClientBootstrap",
"with",
"the",
"pipeline",
"and",
"remote",
"address"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/visitor/GenerateConfigurationVisitor.java#L349-L409 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/SpringComponent.java | SpringComponent.init | protected void init(Map stormConf, TopologyContext topologyContext) {
setId(topologyContext.getThisComponentId());
try {
method = inputSignature.findMethod(beanType);
logger.info("{} uses {}", this, method.toGenericString());
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Unusable input signature", e);
}
if (spring == null)
spring = SingletonApplicationContext.get(stormConf, topologyContext);
spring.getBean(beanType);
logger.debug("Bean lookup successful");
} | java | protected void init(Map stormConf, TopologyContext topologyContext) {
setId(topologyContext.getThisComponentId());
try {
method = inputSignature.findMethod(beanType);
logger.info("{} uses {}", this, method.toGenericString());
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Unusable input signature", e);
}
if (spring == null)
spring = SingletonApplicationContext.get(stormConf, topologyContext);
spring.getBean(beanType);
logger.debug("Bean lookup successful");
} | [
"protected",
"void",
"init",
"(",
"Map",
"stormConf",
",",
"TopologyContext",
"topologyContext",
")",
"{",
"setId",
"(",
"topologyContext",
".",
"getThisComponentId",
"(",
")",
")",
";",
"try",
"{",
"method",
"=",
"inputSignature",
".",
"findMethod",
"(",
"bea... | Instantiates the non-serializable state. | [
"Instantiates",
"the",
"non",
"-",
"serializable",
"state",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/SpringComponent.java#L69-L84 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/SpringComponent.java | SpringComponent.invoke | protected Object[] invoke(Object[] arguments)
throws InvocationTargetException, IllegalAccessException {
Object returnValue = invoke(method, arguments);
if (! scatterOutput) {
logger.trace("Using return as is");
return new Object[] {returnValue};
}
if (returnValue instanceof Object[]) {
logger.trace("Scatter array return");
return (Object[]) returnValue;
}
if (returnValue instanceof Collection) {
logger.trace("Scatter collection return");
return ((Collection) returnValue).toArray();
}
logger.debug("Scatter singleton return");
return returnValue == null ? EMPTY_ARRAY : new Object[] {returnValue};
} | java | protected Object[] invoke(Object[] arguments)
throws InvocationTargetException, IllegalAccessException {
Object returnValue = invoke(method, arguments);
if (! scatterOutput) {
logger.trace("Using return as is");
return new Object[] {returnValue};
}
if (returnValue instanceof Object[]) {
logger.trace("Scatter array return");
return (Object[]) returnValue;
}
if (returnValue instanceof Collection) {
logger.trace("Scatter collection return");
return ((Collection) returnValue).toArray();
}
logger.debug("Scatter singleton return");
return returnValue == null ? EMPTY_ARRAY : new Object[] {returnValue};
} | [
"protected",
"Object",
"[",
"]",
"invoke",
"(",
"Object",
"[",
"]",
"arguments",
")",
"throws",
"InvocationTargetException",
",",
"IllegalAccessException",
"{",
"Object",
"returnValue",
"=",
"invoke",
"(",
"method",
",",
"arguments",
")",
";",
"if",
"(",
"!",
... | Gets the bean invocation return entries. | [
"Gets",
"the",
"bean",
"invocation",
"return",
"entries",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/SpringComponent.java#L106-L127 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/SpringComponent.java | SpringComponent.invoke | protected Object invoke(Method method, Object[] arguments)
throws InvocationTargetException, IllegalAccessException {
logger.trace("Lookup for call {}", method);
Object bean = spring.getBean(beanType);
try {
return method.invoke(bean, arguments);
} catch (IllegalArgumentException e) {
StringBuilder msg = new StringBuilder(method.toGenericString());
msg.append(" invoked with incompatible arguments:");
for (Object a : arguments) {
msg.append(' ');
if (a == null)
msg.append("null");
else
msg.append(a.getClass().getName());
}
logger.error(msg.toString());
throw e;
}
} | java | protected Object invoke(Method method, Object[] arguments)
throws InvocationTargetException, IllegalAccessException {
logger.trace("Lookup for call {}", method);
Object bean = spring.getBean(beanType);
try {
return method.invoke(bean, arguments);
} catch (IllegalArgumentException e) {
StringBuilder msg = new StringBuilder(method.toGenericString());
msg.append(" invoked with incompatible arguments:");
for (Object a : arguments) {
msg.append(' ');
if (a == null)
msg.append("null");
else
msg.append(a.getClass().getName());
}
logger.error(msg.toString());
throw e;
}
} | [
"protected",
"Object",
"invoke",
"(",
"Method",
"method",
",",
"Object",
"[",
"]",
"arguments",
")",
"throws",
"InvocationTargetException",
",",
"IllegalAccessException",
"{",
"logger",
".",
"trace",
"(",
"\"Lookup for call {}\"",
",",
"method",
")",
";",
"Object"... | Gets the bean invocation return value. | [
"Gets",
"the",
"bean",
"invocation",
"return",
"value",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/SpringComponent.java#L132-L152 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/SpringComponent.java | SpringComponent.setOutputBinding | public void setOutputBinding(Map<String,String> value) {
outputBinding.clear();
outputBindingDefinitions.clear();
for (Map.Entry<String,String> entry : value.entrySet())
putOutputBinding(entry.getKey(), entry.getValue());
}
/**
* Registers an expression for a field.
* @param field the name.
* @param expression the SpEL definition.
*/
public void putOutputBinding(String field, String expression) {
outputBindingDefinitions.put(field, expression);
}
private Expression getOutputBinding(String field) {
Expression binding = outputBinding.get(field);
if (binding == null) {
String definition = outputBindingDefinitions.get(field);
if (definition == null) {
if (outputFields.length == 1 && outputFields[0].equals(field))
definition = "#root";
else
definition = "#root?." + field;
}
logger.debug("Field {} bound as #{{}}", field, definition);
binding = expressionParser.parseExpression(definition);
outputBinding.put(field, binding);
}
return binding;
}
/**
* Gets whether items in collection and array returns
* should be emitted as individual output tuples.
*/
public boolean getScatterOutput() {
return scatterOutput;
}
/**
* Sets whether items in collection and array returns
* should be emitted as individual output tuples.
*/
public void setScatterOutput(boolean value) {
scatterOutput = value;
}
@Override
public Number getParallelism() {
return parallelism;
}
/**
* Sets the Storm parallelism hint.
*/
public void setParallelism(Number value) {
parallelism = value;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String value) {
id = value;
}
@Override
public void setApplicationContext(ApplicationContext value) {
spring = value;
} | java | public void setOutputBinding(Map<String,String> value) {
outputBinding.clear();
outputBindingDefinitions.clear();
for (Map.Entry<String,String> entry : value.entrySet())
putOutputBinding(entry.getKey(), entry.getValue());
}
/**
* Registers an expression for a field.
* @param field the name.
* @param expression the SpEL definition.
*/
public void putOutputBinding(String field, String expression) {
outputBindingDefinitions.put(field, expression);
}
private Expression getOutputBinding(String field) {
Expression binding = outputBinding.get(field);
if (binding == null) {
String definition = outputBindingDefinitions.get(field);
if (definition == null) {
if (outputFields.length == 1 && outputFields[0].equals(field))
definition = "#root";
else
definition = "#root?." + field;
}
logger.debug("Field {} bound as #{{}}", field, definition);
binding = expressionParser.parseExpression(definition);
outputBinding.put(field, binding);
}
return binding;
}
/**
* Gets whether items in collection and array returns
* should be emitted as individual output tuples.
*/
public boolean getScatterOutput() {
return scatterOutput;
}
/**
* Sets whether items in collection and array returns
* should be emitted as individual output tuples.
*/
public void setScatterOutput(boolean value) {
scatterOutput = value;
}
@Override
public Number getParallelism() {
return parallelism;
}
/**
* Sets the Storm parallelism hint.
*/
public void setParallelism(Number value) {
parallelism = value;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String value) {
id = value;
}
@Override
public void setApplicationContext(ApplicationContext value) {
spring = value;
} | [
"public",
"void",
"setOutputBinding",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"value",
")",
"{",
"outputBinding",
".",
"clear",
"(",
")",
";",
"outputBindingDefinitions",
".",
"clear",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",... | Sets expressions per field.
@see #putOutputBinding(String, String) | [
"Sets",
"expressions",
"per",
"field",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/SpringComponent.java#L210-L284 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.createClientGSSContext | @Function
public static GSSContext createClientGSSContext(String server) {
try {
GSSManager manager = GSSManager.getInstance();
GSSName serverName = manager.createName(server, null);
GSSContext context = manager.createContext(serverName,
krb5Oid,
null,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true); // Mutual authentication
context.requestConf(true); // Will use encryption later
context.requestInteg(true); // Will use integrity later
return context;
} catch (GSSException ex) {
throw new RuntimeException("Exception creating client GSSContext", ex);
}
} | java | @Function
public static GSSContext createClientGSSContext(String server) {
try {
GSSManager manager = GSSManager.getInstance();
GSSName serverName = manager.createName(server, null);
GSSContext context = manager.createContext(serverName,
krb5Oid,
null,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true); // Mutual authentication
context.requestConf(true); // Will use encryption later
context.requestInteg(true); // Will use integrity later
return context;
} catch (GSSException ex) {
throw new RuntimeException("Exception creating client GSSContext", ex);
}
} | [
"@",
"Function",
"public",
"static",
"GSSContext",
"createClientGSSContext",
"(",
"String",
"server",
")",
"{",
"try",
"{",
"GSSManager",
"manager",
"=",
"GSSManager",
".",
"getInstance",
"(",
")",
";",
"GSSName",
"serverName",
"=",
"manager",
".",
"createName",... | Create a GSS Context from a clients point of view.
@param server the name of the host for which the GSS Context is being created
@return the GSS Context that a client can use to exchange security tokens for
a secure channel, then wrap()/unpack() messages. | [
"Create",
"a",
"GSS",
"Context",
"from",
"a",
"clients",
"point",
"of",
"view",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L67-L86 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.getClientToken | @Function
public static byte[] getClientToken(GSSContext context) {
byte[] initialToken = new byte[0];
if (!context.isEstablished()) {
try {
// token is ignored on the first call
initialToken = context.initSecContext(initialToken, 0, initialToken.length);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception getting client token", ex);
}
}
return null;
} | java | @Function
public static byte[] getClientToken(GSSContext context) {
byte[] initialToken = new byte[0];
if (!context.isEstablished()) {
try {
// token is ignored on the first call
initialToken = context.initSecContext(initialToken, 0, initialToken.length);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception getting client token", ex);
}
}
return null;
} | [
"@",
"Function",
"public",
"static",
"byte",
"[",
"]",
"getClientToken",
"(",
"GSSContext",
"context",
")",
"{",
"byte",
"[",
"]",
"initialToken",
"=",
"new",
"byte",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"context",
".",
"isEstablished",
"(",
")",
")",
... | Create a token, from a clients point of view, for establishing a secure
communication channel. This is a client side token so it needs to bootstrap
the token creation.
@param context GSSContext for which a connection has been established to the remote peer
@return a byte[] that represents the token a client can send to a server for
establishing a secure communication channel. | [
"Create",
"a",
"token",
"from",
"a",
"clients",
"point",
"of",
"view",
"for",
"establishing",
"a",
"secure",
"communication",
"channel",
".",
"This",
"is",
"a",
"client",
"side",
"token",
"so",
"it",
"needs",
"to",
"bootstrap",
"the",
"token",
"creation",
... | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L96-L113 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.verifyMIC | @Function
public static boolean verifyMIC(GSSContext context, MessageProp prop, byte[] message, byte[] mic) {
try {
context.verifyMIC(mic, 0, mic.length,
message, 0, message.length,
prop);
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception verifying mic", ex);
}
} | java | @Function
public static boolean verifyMIC(GSSContext context, MessageProp prop, byte[] message, byte[] mic) {
try {
context.verifyMIC(mic, 0, mic.length,
message, 0, message.length,
prop);
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception verifying mic", ex);
}
} | [
"@",
"Function",
"public",
"static",
"boolean",
"verifyMIC",
"(",
"GSSContext",
"context",
",",
"MessageProp",
"prop",
",",
"byte",
"[",
"]",
"message",
",",
"byte",
"[",
"]",
"mic",
")",
"{",
"try",
"{",
"context",
".",
"verifyMIC",
"(",
"mic",
",",
"... | Verify a message integrity check sent by a peer. If the MIC correctly identifies the
message then the peer knows that the remote peer correctly received the message.
@param context GSSContext for which a connection has been established to the remote peer
@param prop the MessageProp that was used to wrap the original message
@param message the bytes of the original message
@param mic the bytes received from the remote peer that represent the MIC (like a checksum)
@return a boolean whether or not the MIC was correctly verified | [
"Verify",
"a",
"message",
"integrity",
"check",
"sent",
"by",
"a",
"peer",
".",
"If",
"the",
"MIC",
"correctly",
"identifies",
"the",
"message",
"then",
"the",
"peer",
"knows",
"that",
"the",
"remote",
"peer",
"correctly",
"received",
"the",
"message",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L157-L168 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.createServerGSSContext | @Function
public static GSSContext createServerGSSContext() {
System.out.println("createServerGSSContext()...");
try {
final GSSManager manager = GSSManager.getInstance();
//
// Create server credentials to accept kerberos tokens. This should
// make use of the sun.security.krb5.principal system property to
// authenticate with the KDC.
//
GSSCredential serverCreds;
try {
serverCreds = Subject.doAs(new Subject(), new PrivilegedExceptionAction<GSSCredential>() {
public GSSCredential run() throws GSSException {
return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid,
GSSCredential.ACCEPT_ONLY);
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException("Exception creating server credentials", e);
}
//
// Create the GSSContext used to process requests from clients. The client
// requets should use Kerberos since the server credentials are Kerberos
// based.
//
GSSContext retVal = manager.createContext(serverCreds);
System.out.println("createServerGSSContext(), context: " + retVal);
return retVal;
} catch (GSSException ex) {
System.out.println("createServerGSSContext(), finished with exception");
throw new RuntimeException("Exception creating server GSSContext", ex);
}
} | java | @Function
public static GSSContext createServerGSSContext() {
System.out.println("createServerGSSContext()...");
try {
final GSSManager manager = GSSManager.getInstance();
//
// Create server credentials to accept kerberos tokens. This should
// make use of the sun.security.krb5.principal system property to
// authenticate with the KDC.
//
GSSCredential serverCreds;
try {
serverCreds = Subject.doAs(new Subject(), new PrivilegedExceptionAction<GSSCredential>() {
public GSSCredential run() throws GSSException {
return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid,
GSSCredential.ACCEPT_ONLY);
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException("Exception creating server credentials", e);
}
//
// Create the GSSContext used to process requests from clients. The client
// requets should use Kerberos since the server credentials are Kerberos
// based.
//
GSSContext retVal = manager.createContext(serverCreds);
System.out.println("createServerGSSContext(), context: " + retVal);
return retVal;
} catch (GSSException ex) {
System.out.println("createServerGSSContext(), finished with exception");
throw new RuntimeException("Exception creating server GSSContext", ex);
}
} | [
"@",
"Function",
"public",
"static",
"GSSContext",
"createServerGSSContext",
"(",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"createServerGSSContext()...\"",
")",
";",
"try",
"{",
"final",
"GSSManager",
"manager",
"=",
"GSSManager",
".",
"getInstance",... | Create a GSS Context not tied to any server name. Peers acting as a server
create their context this way.
@return the newly created GSS Context | [
"Create",
"a",
"GSS",
"Context",
"not",
"tied",
"to",
"any",
"server",
"name",
".",
"Peers",
"acting",
"as",
"a",
"server",
"create",
"their",
"context",
"this",
"way",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L175-L210 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.acceptClientToken | @Function
public static boolean acceptClientToken(GSSContext context, byte[] token) {
try {
if (!context.isEstablished()) {
byte[] nextToken = context.acceptSecContext(token, 0, token.length);
return nextToken == null;
}
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception accepting client token", ex);
}
} | java | @Function
public static boolean acceptClientToken(GSSContext context, byte[] token) {
try {
if (!context.isEstablished()) {
byte[] nextToken = context.acceptSecContext(token, 0, token.length);
return nextToken == null;
}
return true;
} catch (GSSException ex) {
throw new RuntimeException("Exception accepting client token", ex);
}
} | [
"@",
"Function",
"public",
"static",
"boolean",
"acceptClientToken",
"(",
"GSSContext",
"context",
",",
"byte",
"[",
"]",
"token",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"context",
".",
"isEstablished",
"(",
")",
")",
"{",
"byte",
"[",
"]",
"nextToken",
... | Accept a client token to establish a secure communication channel.
@param context GSSContext for which a connection has been established to the remote peer
@param token the client side token (client side, as in the token had
to be bootstrapped by the client and this peer uses that token
to update the GSSContext)
@return a boolean to indicate whether the token was used to successfully
establish a communication channel | [
"Accept",
"a",
"client",
"token",
"to",
"establish",
"a",
"secure",
"communication",
"channel",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L221-L232 | train |
k3po/k3po | specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java | Functions.generateMIC | @Function
public static byte[] generateMIC(GSSContext context, MessageProp prop, byte[] message) {
try {
// Ensure the default Quality-of-Protection is applied.
prop.setQOP(0);
byte[] initialToken = context.getMIC(message, 0, message.length, prop);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception generating MIC for message", ex);
}
} | java | @Function
public static byte[] generateMIC(GSSContext context, MessageProp prop, byte[] message) {
try {
// Ensure the default Quality-of-Protection is applied.
prop.setQOP(0);
byte[] initialToken = context.getMIC(message, 0, message.length, prop);
return getTokenWithLengthPrefix(initialToken);
} catch (GSSException ex) {
throw new RuntimeException("Exception generating MIC for message", ex);
}
} | [
"@",
"Function",
"public",
"static",
"byte",
"[",
"]",
"generateMIC",
"(",
"GSSContext",
"context",
",",
"MessageProp",
"prop",
",",
"byte",
"[",
"]",
"message",
")",
"{",
"try",
"{",
"// Ensure the default Quality-of-Protection is applied.",
"prop",
".",
"setQOP"... | Generate a message integrity check for a given received message.
@param context GSSContext for which a connection has been established to the remote peer
@param prop the MessageProp used for exchanging messages
@param message the bytes of the received message
@return the bytes of the message integrity check (like a checksum) that is
sent to a peer for verifying that the message was received correctly | [
"Generate",
"a",
"message",
"integrity",
"check",
"for",
"a",
"given",
"received",
"message",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L242-L254 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java | Parser.getNextPacket | public Packet getNextPacket() {
Packet parsedPacket = parseNextPacketFromPdml();
if ( parsedPacket == null ) { // All packets have been read
return null;
}
parsedPacket = addTcpdumpInfoToPacket(parsedPacket);
return parsedPacket;
} | java | public Packet getNextPacket() {
Packet parsedPacket = parseNextPacketFromPdml();
if ( parsedPacket == null ) { // All packets have been read
return null;
}
parsedPacket = addTcpdumpInfoToPacket(parsedPacket);
return parsedPacket;
} | [
"public",
"Packet",
"getNextPacket",
"(",
")",
"{",
"Packet",
"parsedPacket",
"=",
"parseNextPacketFromPdml",
"(",
")",
";",
"if",
"(",
"parsedPacket",
"==",
"null",
")",
"{",
"// All packets have been read",
"return",
"null",
";",
"}",
"parsedPacket",
"=",
"add... | Returns the next Packet that can be parsed, or null if all packets have been read
@return Packet | [
"Returns",
"the",
"next",
"Packet",
"that",
"can",
"be",
"parsed",
"or",
"null",
"if",
"all",
"packets",
"have",
"been",
"read"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java#L86-L96 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java | Parser.addTcpdumpInfoToPacket | private Packet addTcpdumpInfoToPacket(Packet parsedPacket){
int packetSize = parsedPacket.getPacketSize();
tcpdumpReader.readNewPacket(packetSize);
// Get Tcp Payload
if ( parsedPacket.isTcp() ) {
int payloadSize = parsedPacket.getTcpPayloadSize();
int payloadStart = parsedPacket.getTcpPayloadStart();
parsedPacket.setTcpPayload(tcpdumpReader.getPayload(payloadStart, payloadSize));
}
tcpdumpReader.packetReadComplete();
return parsedPacket;
} | java | private Packet addTcpdumpInfoToPacket(Packet parsedPacket){
int packetSize = parsedPacket.getPacketSize();
tcpdumpReader.readNewPacket(packetSize);
// Get Tcp Payload
if ( parsedPacket.isTcp() ) {
int payloadSize = parsedPacket.getTcpPayloadSize();
int payloadStart = parsedPacket.getTcpPayloadStart();
parsedPacket.setTcpPayload(tcpdumpReader.getPayload(payloadStart, payloadSize));
}
tcpdumpReader.packetReadComplete();
return parsedPacket;
} | [
"private",
"Packet",
"addTcpdumpInfoToPacket",
"(",
"Packet",
"parsedPacket",
")",
"{",
"int",
"packetSize",
"=",
"parsedPacket",
".",
"getPacketSize",
"(",
")",
";",
"tcpdumpReader",
".",
"readNewPacket",
"(",
"packetSize",
")",
";",
"// Get Tcp Payload",
"if",
"... | Adds tcpdump info onto packet parsed from pdml i.e. adds the packet payload for various protocols
@param parsedPacket
@return | [
"Adds",
"tcpdump",
"info",
"onto",
"packet",
"parsed",
"from",
"pdml",
"i",
".",
"e",
".",
"adds",
"the",
"packet",
"payload",
"for",
"various",
"protocols"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java#L103-L119 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java | Parser.parseNextPacketFromPdml | private Packet parseNextPacketFromPdml() {
Packet currentPacket = null;
int eventType;
fieldStack.empty();
try {
eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
if ( parser.getRawName().contains("packet") ) { // At packet tag
currentPacket = setPacketProperties(xppFactory.newStartTag());
}
else if ( parser.getRawName().contains("proto") ) {
currentPacket = setProtoProperties(xppFactory.newStartTag(), currentPacket);
}
else if ( parser.getRawName().contains("field") ) {
fieldStack.push("field");
// Added http after all others
if (protoStack.peek().equals("http") && currentPacket.isTcp()){
currentPacket = setHttpFieldProperties(xppFactory.newStartTag(), currentPacket);
}
else{
currentPacket = setFieldProperties(xppFactory.newStartTag(), currentPacket);
}
}
else {
;
}
break;
case XmlPullParser.END_TAG:
if ( parser.getRawName().contains("packet") ) {
eventType = parser.next();
return currentPacket;
}
else if ( parser.getRawName().contains("proto") ) {
protoStack.pop();
}
else if ( parser.getRawName().contains("field") ) {
fieldStack.pop();
}
default:
}
eventType = parser.next();
}
return null; // Returned if at end of pdml
}
catch (XmlPullParserException e) {
e.printStackTrace();
throw new ParserFailureException("Failed parsing pmdl " + e);
}
catch (IOException e) {
e.printStackTrace();
throw new ParserFailureException("Failed reading parser.next " + e);
}
} | java | private Packet parseNextPacketFromPdml() {
Packet currentPacket = null;
int eventType;
fieldStack.empty();
try {
eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
if ( parser.getRawName().contains("packet") ) { // At packet tag
currentPacket = setPacketProperties(xppFactory.newStartTag());
}
else if ( parser.getRawName().contains("proto") ) {
currentPacket = setProtoProperties(xppFactory.newStartTag(), currentPacket);
}
else if ( parser.getRawName().contains("field") ) {
fieldStack.push("field");
// Added http after all others
if (protoStack.peek().equals("http") && currentPacket.isTcp()){
currentPacket = setHttpFieldProperties(xppFactory.newStartTag(), currentPacket);
}
else{
currentPacket = setFieldProperties(xppFactory.newStartTag(), currentPacket);
}
}
else {
;
}
break;
case XmlPullParser.END_TAG:
if ( parser.getRawName().contains("packet") ) {
eventType = parser.next();
return currentPacket;
}
else if ( parser.getRawName().contains("proto") ) {
protoStack.pop();
}
else if ( parser.getRawName().contains("field") ) {
fieldStack.pop();
}
default:
}
eventType = parser.next();
}
return null; // Returned if at end of pdml
}
catch (XmlPullParserException e) {
e.printStackTrace();
throw new ParserFailureException("Failed parsing pmdl " + e);
}
catch (IOException e) {
e.printStackTrace();
throw new ParserFailureException("Failed reading parser.next " + e);
}
} | [
"private",
"Packet",
"parseNextPacketFromPdml",
"(",
")",
"{",
"Packet",
"currentPacket",
"=",
"null",
";",
"int",
"eventType",
";",
"fieldStack",
".",
"empty",
"(",
")",
";",
"try",
"{",
"eventType",
"=",
"parser",
".",
"getEventType",
"(",
")",
";",
"whi... | Returns the Packet set with all properties that can be read from the pdml
@return | [
"Returns",
"the",
"Packet",
"set",
"with",
"all",
"properties",
"that",
"can",
"be",
"read",
"from",
"the",
"pdml"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/Parser.java#L125-L179 | train |
k3po/k3po | control/src/main/java/org/kaazing/k3po/control/internal/Control.java | Control.connect | public void connect() throws Exception {
// connection must be null if the connection failed
URLConnection newConnection = location.openConnection();
newConnection.connect();
connection = newConnection;
InputStream bytesIn = connection.getInputStream();
CharsetDecoder decoder = UTF_8.newDecoder();
textIn = new BufferedReader(new InputStreamReader(bytesIn, decoder));
} | java | public void connect() throws Exception {
// connection must be null if the connection failed
URLConnection newConnection = location.openConnection();
newConnection.connect();
connection = newConnection;
InputStream bytesIn = connection.getInputStream();
CharsetDecoder decoder = UTF_8.newDecoder();
textIn = new BufferedReader(new InputStreamReader(bytesIn, decoder));
} | [
"public",
"void",
"connect",
"(",
")",
"throws",
"Exception",
"{",
"// connection must be null if the connection failed",
"URLConnection",
"newConnection",
"=",
"location",
".",
"openConnection",
"(",
")",
";",
"newConnection",
".",
"connect",
"(",
")",
";",
"connecti... | Connects to the k3po server.
@throws Exception if fails to connect. | [
"Connects",
"to",
"the",
"k3po",
"server",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/control/src/main/java/org/kaazing/k3po/control/internal/Control.java#L86-L95 | train |
k3po/k3po | control/src/main/java/org/kaazing/k3po/control/internal/Control.java | Control.disconnect | public void disconnect() throws Exception {
if (connection != null) {
try {
if (connection instanceof Closeable) {
((Closeable) connection).close();
} else {
try {
connection.getInputStream().close();
} catch (IOException e) {
// ignore
}
try {
connection.getOutputStream().close();
} catch (IOException e) {
// ignore
}
}
} finally {
connection = null;
}
}
} | java | public void disconnect() throws Exception {
if (connection != null) {
try {
if (connection instanceof Closeable) {
((Closeable) connection).close();
} else {
try {
connection.getInputStream().close();
} catch (IOException e) {
// ignore
}
try {
connection.getOutputStream().close();
} catch (IOException e) {
// ignore
}
}
} finally {
connection = null;
}
}
} | [
"public",
"void",
"disconnect",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"connection",
"!=",
"null",
")",
"{",
"try",
"{",
"if",
"(",
"connection",
"instanceof",
"Closeable",
")",
"{",
"(",
"(",
"Closeable",
")",
"connection",
")",
".",
"close",
... | Discoonects from the k3po server.
@throws Exception if error in closing the connection. | [
"Discoonects",
"from",
"the",
"k3po",
"server",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/control/src/main/java/org/kaazing/k3po/control/internal/Control.java#L101-L124 | train |
k3po/k3po | control/src/main/java/org/kaazing/k3po/control/internal/Control.java | Control.writeCommand | public void writeCommand(Command command) throws Exception {
checkConnected();
switch (command.getKind()) {
case PREPARE:
writeCommand((PrepareCommand) command);
break;
case START:
writeCommand((StartCommand) command);
break;
case ABORT:
writeCommand((AbortCommand) command);
break;
case AWAIT:
writeCommand((AwaitCommand) command);
break;
case NOTIFY:
writeCommand((NotifyCommand) command);
break;
case CLOSE:
writeCommand((CloseCommand) command);
break;
default:
throw new IllegalArgumentException("Urecognized command kind: " + command.getKind());
}
} | java | public void writeCommand(Command command) throws Exception {
checkConnected();
switch (command.getKind()) {
case PREPARE:
writeCommand((PrepareCommand) command);
break;
case START:
writeCommand((StartCommand) command);
break;
case ABORT:
writeCommand((AbortCommand) command);
break;
case AWAIT:
writeCommand((AwaitCommand) command);
break;
case NOTIFY:
writeCommand((NotifyCommand) command);
break;
case CLOSE:
writeCommand((CloseCommand) command);
break;
default:
throw new IllegalArgumentException("Urecognized command kind: " + command.getKind());
}
} | [
"public",
"void",
"writeCommand",
"(",
"Command",
"command",
")",
"throws",
"Exception",
"{",
"checkConnected",
"(",
")",
";",
"switch",
"(",
"command",
".",
"getKind",
"(",
")",
")",
"{",
"case",
"PREPARE",
":",
"writeCommand",
"(",
"(",
"PrepareCommand",
... | Writes a command to the wire.
@param command to write to the wire
@throws Exception if the command is not recognized | [
"Writes",
"a",
"command",
"to",
"the",
"wire",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/control/src/main/java/org/kaazing/k3po/control/internal/Control.java#L131-L157 | train |
k3po/k3po | control/src/main/java/org/kaazing/k3po/control/internal/Control.java | Control.readEvent | public CommandEvent readEvent(int timeout, TimeUnit unit) throws Exception {
checkConnected();
connection.setReadTimeout((int) unit.toMillis(timeout));
CommandEvent event = null;
String eventType = textIn.readLine();
if (Thread.interrupted())
{
throw new InterruptedException("thread interrupted during blocking read");
}
if (eventType != null) {
switch (eventType) {
case PREPARED_EVENT:
event = readPreparedEvent();
break;
case STARTED_EVENT:
event = readStartedEvent();
break;
case ERROR_EVENT:
event = readErrorEvent();
break;
case FINISHED_EVENT:
event = readFinishedEvent();
break;
case NOTIFIED_EVENT:
event = readNotifiedEvent();
break;
default:
throw new IllegalStateException("Invalid protocol frame: " + eventType);
}
}
return event;
} | java | public CommandEvent readEvent(int timeout, TimeUnit unit) throws Exception {
checkConnected();
connection.setReadTimeout((int) unit.toMillis(timeout));
CommandEvent event = null;
String eventType = textIn.readLine();
if (Thread.interrupted())
{
throw new InterruptedException("thread interrupted during blocking read");
}
if (eventType != null) {
switch (eventType) {
case PREPARED_EVENT:
event = readPreparedEvent();
break;
case STARTED_EVENT:
event = readStartedEvent();
break;
case ERROR_EVENT:
event = readErrorEvent();
break;
case FINISHED_EVENT:
event = readFinishedEvent();
break;
case NOTIFIED_EVENT:
event = readNotifiedEvent();
break;
default:
throw new IllegalStateException("Invalid protocol frame: " + eventType);
}
}
return event;
} | [
"public",
"CommandEvent",
"readEvent",
"(",
"int",
"timeout",
",",
"TimeUnit",
"unit",
")",
"throws",
"Exception",
"{",
"checkConnected",
"(",
")",
";",
"connection",
".",
"setReadTimeout",
"(",
"(",
"int",
")",
"unit",
".",
"toMillis",
"(",
"timeout",
")",
... | Reads a command event from the wire.
@param timeout is the time to read from the connection.
@param unit of time for the timeout.
@return the CommandEvent read from the wire.
@throws Exception if no event is read before the timeout. | [
"Reads",
"a",
"command",
"event",
"from",
"the",
"wire",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/control/src/main/java/org/kaazing/k3po/control/internal/Control.java#L176-L213 | train |
k3po/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/control/handler/ControlServerHandler.java | ControlServerHandler.writeEvent | private void writeEvent(final ChannelHandlerContext ctx, final Object message) {
if (isFinishedSent)
return;
if (message instanceof FinishedMessage)
isFinishedSent = true;
Channels.write(ctx, Channels.future(null), message);
} | java | private void writeEvent(final ChannelHandlerContext ctx, final Object message) {
if (isFinishedSent)
return;
if (message instanceof FinishedMessage)
isFinishedSent = true;
Channels.write(ctx, Channels.future(null), message);
} | [
"private",
"void",
"writeEvent",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"final",
"Object",
"message",
")",
"{",
"if",
"(",
"isFinishedSent",
")",
"return",
";",
"if",
"(",
"message",
"instanceof",
"FinishedMessage",
")",
"isFinishedSent",
"=",
"true"... | will send no message after the FINISHED | [
"will",
"send",
"no",
"message",
"after",
"the",
"FINISHED"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/driver/src/main/java/org/kaazing/k3po/driver/internal/control/handler/ControlServerHandler.java#L430-L438 | train |
k3po/k3po | launcher/src/main/java/org/kaazing/k3po/launcher/Launcher.java | Launcher.main | public static void main(String... args) throws Exception {
Options options = createOptions();
try {
Parser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("version")) {
System.out.println("Version: " + Launcher.class.getPackage().getImplementationVersion());
}
String scriptPathEntries = cmd.getOptionValue("scriptpath", "src/test/scripts");
String[] scriptPathEntryArray = scriptPathEntries.split(";");
List<URL> scriptUrls = new ArrayList<>();
for (String scriptPathEntry : scriptPathEntryArray) {
File scriptEntryFilePath = new File(scriptPathEntry);
scriptUrls.add(scriptEntryFilePath.toURI().toURL());
}
String controlURI = cmd.getOptionValue("control");
if (controlURI == null) {
controlURI = "tcp://localhost:11642";
}
boolean verbose = cmd.hasOption("verbose");
URLClassLoader scriptLoader = new URLClassLoader(scriptUrls.toArray(new URL[0]));
RobotServer server = new RobotServer(URI.create(controlURI), verbose, scriptLoader);
server.start();
server.join();
} catch (ParseException ex) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(Launcher.class.getSimpleName(), options, true);
}
} | java | public static void main(String... args) throws Exception {
Options options = createOptions();
try {
Parser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("version")) {
System.out.println("Version: " + Launcher.class.getPackage().getImplementationVersion());
}
String scriptPathEntries = cmd.getOptionValue("scriptpath", "src/test/scripts");
String[] scriptPathEntryArray = scriptPathEntries.split(";");
List<URL> scriptUrls = new ArrayList<>();
for (String scriptPathEntry : scriptPathEntryArray) {
File scriptEntryFilePath = new File(scriptPathEntry);
scriptUrls.add(scriptEntryFilePath.toURI().toURL());
}
String controlURI = cmd.getOptionValue("control");
if (controlURI == null) {
controlURI = "tcp://localhost:11642";
}
boolean verbose = cmd.hasOption("verbose");
URLClassLoader scriptLoader = new URLClassLoader(scriptUrls.toArray(new URL[0]));
RobotServer server = new RobotServer(URI.create(controlURI), verbose, scriptLoader);
server.start();
server.join();
} catch (ParseException ex) {
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp(Launcher.class.getSimpleName(), options, true);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"...",
"args",
")",
"throws",
"Exception",
"{",
"Options",
"options",
"=",
"createOptions",
"(",
")",
";",
"try",
"{",
"Parser",
"parser",
"=",
"new",
"PosixParser",
"(",
")",
";",
"CommandLine",
"cmd",
... | Main entry point to running K3PO.
@param args to run with
@throws Exception if fails to run | [
"Main",
"entry",
"point",
"to",
"running",
"K3PO",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/launcher/src/main/java/org/kaazing/k3po/launcher/Launcher.java#L49-L85 | train |
k3po/k3po | lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java | FunctionMapper.newFunctionMapper | public static FunctionMapper newFunctionMapper() {
ServiceLoader<FunctionMapperSpi> loader = loadFunctionMapperSpi();
// load FunctionMapperSpi instances
ConcurrentMap<String, FunctionMapperSpi> functionMappers = new ConcurrentHashMap<>();
for (FunctionMapperSpi functionMapperSpi : loader) {
String prefixName = functionMapperSpi.getPrefixName();
FunctionMapperSpi oldFunctionMapperSpi = functionMappers.putIfAbsent(prefixName, functionMapperSpi);
if (oldFunctionMapperSpi != null) {
throw new ELException(String.format("Duplicate prefix function mapper: %s", prefixName));
}
}
return new FunctionMapper(functionMappers);
} | java | public static FunctionMapper newFunctionMapper() {
ServiceLoader<FunctionMapperSpi> loader = loadFunctionMapperSpi();
// load FunctionMapperSpi instances
ConcurrentMap<String, FunctionMapperSpi> functionMappers = new ConcurrentHashMap<>();
for (FunctionMapperSpi functionMapperSpi : loader) {
String prefixName = functionMapperSpi.getPrefixName();
FunctionMapperSpi oldFunctionMapperSpi = functionMappers.putIfAbsent(prefixName, functionMapperSpi);
if (oldFunctionMapperSpi != null) {
throw new ELException(String.format("Duplicate prefix function mapper: %s", prefixName));
}
}
return new FunctionMapper(functionMappers);
} | [
"public",
"static",
"FunctionMapper",
"newFunctionMapper",
"(",
")",
"{",
"ServiceLoader",
"<",
"FunctionMapperSpi",
">",
"loader",
"=",
"loadFunctionMapperSpi",
"(",
")",
";",
"// load FunctionMapperSpi instances",
"ConcurrentMap",
"<",
"String",
",",
"FunctionMapperSpi"... | Creates a new Function Mapper.
@return returns an instance of the FunctionMapper | [
"Creates",
"a",
"new",
"Function",
"Mapper",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java#L44-L58 | train |
k3po/k3po | lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java | FunctionMapper.resolveFunction | public Method resolveFunction(String prefix, String localName) {
FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi(prefix);
return functionMapperSpi.resolveFunction(localName);
} | java | public Method resolveFunction(String prefix, String localName) {
FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi(prefix);
return functionMapperSpi.resolveFunction(localName);
} | [
"public",
"Method",
"resolveFunction",
"(",
"String",
"prefix",
",",
"String",
"localName",
")",
"{",
"FunctionMapperSpi",
"functionMapperSpi",
"=",
"findFunctionMapperSpi",
"(",
"prefix",
")",
";",
"return",
"functionMapperSpi",
".",
"resolveFunction",
"(",
"localNam... | Resolves a Function via prefix and local name.
@param prefix of the function
@param localName of the function
@return an instance of a Method | [
"Resolves",
"a",
"Function",
"via",
"prefix",
"and",
"local",
"name",
"."
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java#L66-L69 | train |
k3po/k3po | k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/TcpdumpReader.java | TcpdumpReader.getPayload | public byte[] getPayload(int payloadStart, int payloadSize) {
byte[] payloadBuffer = new byte[payloadSize];
System.arraycopy(currentBuffer, payloadStart, payloadBuffer, 0, payloadSize);
return payloadBuffer;
} | java | public byte[] getPayload(int payloadStart, int payloadSize) {
byte[] payloadBuffer = new byte[payloadSize];
System.arraycopy(currentBuffer, payloadStart, payloadBuffer, 0, payloadSize);
return payloadBuffer;
} | [
"public",
"byte",
"[",
"]",
"getPayload",
"(",
"int",
"payloadStart",
",",
"int",
"payloadSize",
")",
"{",
"byte",
"[",
"]",
"payloadBuffer",
"=",
"new",
"byte",
"[",
"payloadSize",
"]",
";",
"System",
".",
"arraycopy",
"(",
"currentBuffer",
",",
"payloadS... | Returns a portion of the internal buffer
@param payloadStart
@param payloadSize
@return | [
"Returns",
"a",
"portion",
"of",
"the",
"internal",
"buffer"
] | 3ca4fd31ab4a397893aa640c62ada0e485c8bbd4 | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/k3po.pcap.converter/src/main/java/org/kaazing/k3po/pcap/converter/internal/parser/TcpdumpReader.java#L103-L107 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/namespace/TopologyStarter.java | TopologyStarter.stormConfig | public static Config stormConfig(Properties source) {
Config result = new Config();
logger.debug("Mapping declared types for Storm properties...");
for (Field field : result.getClass().getDeclaredFields()) {
if (field.getType() != String.class) continue;
if (field.getName().endsWith(CONFIGURATION_TYPE_FIELD_SUFFIX)) continue;
try {
String key = field.get(result).toString();
String entry = source.getProperty(key);
if (entry == null) continue;
String typeFieldName = field.getName() + CONFIGURATION_TYPE_FIELD_SUFFIX;
Field typeField = result.getClass().getDeclaredField(typeFieldName);
Object type = typeField.get(result);
logger.trace("Detected key '{}' as: {}", key, field);
Object value = null;
if (type == String.class)
value = entry;
if (type == ConfigValidation.IntegerValidator.class || type == ConfigValidation.PowerOf2Validator.class)
value = Integer.valueOf(entry);
if (type == Boolean.class)
value = Boolean.valueOf(entry);
if (type == ConfigValidation.StringOrStringListValidator.class)
value = asList(entry.split(LIST_CONTINUATION_PATTERN));
if (value == null) {
logger.warn("No parser for key '{}' type: {}", key, typeField);
value = entry;
}
result.put(key, value);
} catch (ReflectiveOperationException e) {
logger.debug("Interpretation failure on {}: {}", field, e);
}
}
// Copy remaining
for (Map.Entry<Object,Object> e : source.entrySet()) {
String key = e.getKey().toString();
if (result.containsKey(key)) continue;
result.put(key, e.getValue());
}
return result;
} | java | public static Config stormConfig(Properties source) {
Config result = new Config();
logger.debug("Mapping declared types for Storm properties...");
for (Field field : result.getClass().getDeclaredFields()) {
if (field.getType() != String.class) continue;
if (field.getName().endsWith(CONFIGURATION_TYPE_FIELD_SUFFIX)) continue;
try {
String key = field.get(result).toString();
String entry = source.getProperty(key);
if (entry == null) continue;
String typeFieldName = field.getName() + CONFIGURATION_TYPE_FIELD_SUFFIX;
Field typeField = result.getClass().getDeclaredField(typeFieldName);
Object type = typeField.get(result);
logger.trace("Detected key '{}' as: {}", key, field);
Object value = null;
if (type == String.class)
value = entry;
if (type == ConfigValidation.IntegerValidator.class || type == ConfigValidation.PowerOf2Validator.class)
value = Integer.valueOf(entry);
if (type == Boolean.class)
value = Boolean.valueOf(entry);
if (type == ConfigValidation.StringOrStringListValidator.class)
value = asList(entry.split(LIST_CONTINUATION_PATTERN));
if (value == null) {
logger.warn("No parser for key '{}' type: {}", key, typeField);
value = entry;
}
result.put(key, value);
} catch (ReflectiveOperationException e) {
logger.debug("Interpretation failure on {}: {}", field, e);
}
}
// Copy remaining
for (Map.Entry<Object,Object> e : source.entrySet()) {
String key = e.getKey().toString();
if (result.containsKey(key)) continue;
result.put(key, e.getValue());
}
return result;
} | [
"public",
"static",
"Config",
"stormConfig",
"(",
"Properties",
"source",
")",
"{",
"Config",
"result",
"=",
"new",
"Config",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Mapping declared types for Storm properties...\"",
")",
";",
"for",
"(",
"Field",
"field"... | Applies type conversion where needed.
@return a copy of source ready for Storm.
@see <a href="https://issues.apache.org/jira/browse/STORM-173">Strom issue 173</a> | [
"Applies",
"type",
"conversion",
"where",
"needed",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/namespace/TopologyStarter.java#L123-L169 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/FunctionSignature.java | FunctionSignature.valueOf | public static FunctionSignature valueOf(String serial) {
int paramStart = serial.indexOf("(");
int paramEnd = serial.indexOf(")");
if (paramStart < 0 || paramEnd != serial.length() - 1)
throw new IllegalArgumentException("Malformed method signature: " + serial);
String function = serial.substring(0, paramStart).trim();
String arguments = serial.substring(paramStart + 1, paramEnd);
StringTokenizer tokenizer = new StringTokenizer(arguments, ", ");
String[] names = new String[tokenizer.countTokens()];
for (int i = 0; i < names.length; ++i)
names[i] = tokenizer.nextToken();
return new FunctionSignature(function, names);
} | java | public static FunctionSignature valueOf(String serial) {
int paramStart = serial.indexOf("(");
int paramEnd = serial.indexOf(")");
if (paramStart < 0 || paramEnd != serial.length() - 1)
throw new IllegalArgumentException("Malformed method signature: " + serial);
String function = serial.substring(0, paramStart).trim();
String arguments = serial.substring(paramStart + 1, paramEnd);
StringTokenizer tokenizer = new StringTokenizer(arguments, ", ");
String[] names = new String[tokenizer.countTokens()];
for (int i = 0; i < names.length; ++i)
names[i] = tokenizer.nextToken();
return new FunctionSignature(function, names);
} | [
"public",
"static",
"FunctionSignature",
"valueOf",
"(",
"String",
"serial",
")",
"{",
"int",
"paramStart",
"=",
"serial",
".",
"indexOf",
"(",
"\"(\"",
")",
";",
"int",
"paramEnd",
"=",
"serial",
".",
"indexOf",
"(",
"\")\"",
")",
";",
"if",
"(",
"param... | Parses a signature. | [
"Parses",
"a",
"signature",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/FunctionSignature.java#L32-L47 | train |
politie/breeze | src/main/java/eu/icolumbo/breeze/FunctionSignature.java | FunctionSignature.findMethod | public Method findMethod(Class<?> type) throws ReflectiveOperationException {
Method match = null;
for (Method option : type.getDeclaredMethods()) {
if (! getFunction().equals(option.getName())) continue;
Class<?>[] parameters = option.getParameterTypes();
if (parameters.length != getArguments().length) continue;
if (match != null) {
if (refines(option, match)) continue;
if (! refines(match, option))
throw ambiguity(match, option);
}
match = option;
}
Class<?>[] parents = { type.getSuperclass() };
if (type.isInterface())
parents = type.getInterfaces();
for (Class<?> parent : parents) {
if (parent == null) continue;
try {
Method superMatch = findMethod(parent);
if (match == null) {
match = superMatch;
continue;
}
if (! refines(superMatch, match))
throw ambiguity(match, superMatch);
} catch (NoSuchMethodException ignored) {
}
}
if (match == null) {
String fmt = "No method %s#%s with %d parameters";
String msg = format(fmt, type, getFunction(), getArguments().length);
throw new NoSuchMethodException(msg);
}
match.setAccessible(true);
return match;
} | java | public Method findMethod(Class<?> type) throws ReflectiveOperationException {
Method match = null;
for (Method option : type.getDeclaredMethods()) {
if (! getFunction().equals(option.getName())) continue;
Class<?>[] parameters = option.getParameterTypes();
if (parameters.length != getArguments().length) continue;
if (match != null) {
if (refines(option, match)) continue;
if (! refines(match, option))
throw ambiguity(match, option);
}
match = option;
}
Class<?>[] parents = { type.getSuperclass() };
if (type.isInterface())
parents = type.getInterfaces();
for (Class<?> parent : parents) {
if (parent == null) continue;
try {
Method superMatch = findMethod(parent);
if (match == null) {
match = superMatch;
continue;
}
if (! refines(superMatch, match))
throw ambiguity(match, superMatch);
} catch (NoSuchMethodException ignored) {
}
}
if (match == null) {
String fmt = "No method %s#%s with %d parameters";
String msg = format(fmt, type, getFunction(), getArguments().length);
throw new NoSuchMethodException(msg);
}
match.setAccessible(true);
return match;
} | [
"public",
"Method",
"findMethod",
"(",
"Class",
"<",
"?",
">",
"type",
")",
"throws",
"ReflectiveOperationException",
"{",
"Method",
"match",
"=",
"null",
";",
"for",
"(",
"Method",
"option",
":",
"type",
".",
"getDeclaredMethods",
"(",
")",
")",
"{",
"if"... | Gets a method match. | [
"Gets",
"a",
"method",
"match",
"."
] | 73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1 | https://github.com/politie/breeze/blob/73cb3c7b99d6f9cc3cf9afb4b8e903fbfd6ad9a1/src/main/java/eu/icolumbo/breeze/FunctionSignature.java#L66-L105 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/Modifiers.java | Modifiers.getInstance | public static Modifiers getInstance(int bitmask) {
switch (bitmask) {
case 0:
return NONE;
case Modifier.PUBLIC:
return PUBLIC;
case Modifier.PUBLIC | Modifier.ABSTRACT:
return PUBLIC_ABSTRACT;
case Modifier.PUBLIC | Modifier.STATIC:
return PUBLIC_STATIC;
case Modifier.PROTECTED:
return PROTECTED;
case Modifier.PRIVATE:
return PRIVATE;
}
return new Modifiers(bitmask);
} | java | public static Modifiers getInstance(int bitmask) {
switch (bitmask) {
case 0:
return NONE;
case Modifier.PUBLIC:
return PUBLIC;
case Modifier.PUBLIC | Modifier.ABSTRACT:
return PUBLIC_ABSTRACT;
case Modifier.PUBLIC | Modifier.STATIC:
return PUBLIC_STATIC;
case Modifier.PROTECTED:
return PROTECTED;
case Modifier.PRIVATE:
return PRIVATE;
}
return new Modifiers(bitmask);
} | [
"public",
"static",
"Modifiers",
"getInstance",
"(",
"int",
"bitmask",
")",
"{",
"switch",
"(",
"bitmask",
")",
"{",
"case",
"0",
":",
"return",
"NONE",
";",
"case",
"Modifier",
".",
"PUBLIC",
":",
"return",
"PUBLIC",
";",
"case",
"Modifier",
".",
"PUBLI... | Returns a Modifiers object with the given bitmask. | [
"Returns",
"a",
"Modifiers",
"object",
"with",
"the",
"given",
"bitmask",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/Modifiers.java#L49-L66 | train |
cojen/Cojen | src/main/java/org/cojen/util/PatternMatcher.java | PatternMatcher.getMatches | public Result<V>[] getMatches(String lookup, int limit) {
int strLen = lookup.length();
char[] chars = new char[strLen + 1];
lookup.getChars(0, strLen, chars, 0);
chars[strLen] = '\uffff';
List resultList = new ArrayList();
fillMatchResults(chars, limit, resultList);
return (Result[])resultList.toArray(new Result[resultList.size()]);
} | java | public Result<V>[] getMatches(String lookup, int limit) {
int strLen = lookup.length();
char[] chars = new char[strLen + 1];
lookup.getChars(0, strLen, chars, 0);
chars[strLen] = '\uffff';
List resultList = new ArrayList();
fillMatchResults(chars, limit, resultList);
return (Result[])resultList.toArray(new Result[resultList.size()]);
} | [
"public",
"Result",
"<",
"V",
">",
"[",
"]",
"getMatches",
"(",
"String",
"lookup",
",",
"int",
"limit",
")",
"{",
"int",
"strLen",
"=",
"lookup",
".",
"length",
"(",
")",
";",
"char",
"[",
"]",
"chars",
"=",
"new",
"char",
"[",
"strLen",
"+",
"1... | Returns an empty array if no matches.
@param limit maximum number of results to return | [
"Returns",
"an",
"empty",
"array",
"if",
"no",
"matches",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/PatternMatcher.java#L108-L118 | train |
cojen/Cojen | src/main/java/org/cojen/util/WeakCanonicalSet.java | WeakCanonicalSet.put | public synchronized <U extends T> U put(U obj) {
if (obj == null) {
return null;
}
Entry<T>[] entries = mEntries;
int hash = hashCode(obj);
int index = (hash & 0x7fffffff) % entries.length;
for (Entry<T> e = entries[index], prev = null; e != null; e = e.mNext) {
T iobj = e.get();
if (iobj == null) {
// Clean up after a cleared Reference.
if (prev == null) {
entries[index] = e.mNext;
} else {
prev.mNext = e.mNext;
}
mSize--;
} else if (e.mHash == hash && obj.getClass() == iobj.getClass() && equals(obj, iobj)) {
// Found canonical instance.
return (U) iobj;
} else {
prev = e;
}
}
if (mSize >= mThreshold) {
cleanup();
if (mSize >= mThreshold) {
rehash();
entries = mEntries;
index = (hash & 0x7fffffff) % entries.length;
}
}
entries[index] = new Entry<T>(this, obj, hash, entries[index]);
mSize++;
return obj;
} | java | public synchronized <U extends T> U put(U obj) {
if (obj == null) {
return null;
}
Entry<T>[] entries = mEntries;
int hash = hashCode(obj);
int index = (hash & 0x7fffffff) % entries.length;
for (Entry<T> e = entries[index], prev = null; e != null; e = e.mNext) {
T iobj = e.get();
if (iobj == null) {
// Clean up after a cleared Reference.
if (prev == null) {
entries[index] = e.mNext;
} else {
prev.mNext = e.mNext;
}
mSize--;
} else if (e.mHash == hash && obj.getClass() == iobj.getClass() && equals(obj, iobj)) {
// Found canonical instance.
return (U) iobj;
} else {
prev = e;
}
}
if (mSize >= mThreshold) {
cleanup();
if (mSize >= mThreshold) {
rehash();
entries = mEntries;
index = (hash & 0x7fffffff) % entries.length;
}
}
entries[index] = new Entry<T>(this, obj, hash, entries[index]);
mSize++;
return obj;
} | [
"public",
"synchronized",
"<",
"U",
"extends",
"T",
">",
"U",
"put",
"(",
"U",
"obj",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Entry",
"<",
"T",
">",
"[",
"]",
"entries",
"=",
"mEntries",
";",
"int",
"has... | Pass in a candidate canonical object and get a unique instance from this
set. The returned object will always be of the same type as that passed
in. If the object passed in does not equal any object currently in the
set, it will be added to the set, becoming canonical.
@param obj candidate canonical object; null is also accepted | [
"Pass",
"in",
"a",
"candidate",
"canonical",
"object",
"and",
"get",
"a",
"unique",
"instance",
"from",
"this",
"set",
".",
"The",
"returned",
"object",
"will",
"always",
"be",
"of",
"the",
"same",
"type",
"as",
"that",
"passed",
"in",
".",
"If",
"the",
... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/WeakCanonicalSet.java#L58-L96 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fire | public static void fire(Throwable t) {
if (t != null) {
// Don't need to do anything special for unchecked exceptions.
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
ThrowUnchecked impl = cImpl;
if (impl == null) {
synchronized (ThrowUnchecked.class) {
impl = cImpl;
if (impl == null) {
cImpl = impl =
AccessController.doPrivileged(new PrivilegedAction<ThrowUnchecked>() {
public ThrowUnchecked run() {
return generateImpl();
}
});
}
}
}
impl.doFire(t);
}
} | java | public static void fire(Throwable t) {
if (t != null) {
// Don't need to do anything special for unchecked exceptions.
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
ThrowUnchecked impl = cImpl;
if (impl == null) {
synchronized (ThrowUnchecked.class) {
impl = cImpl;
if (impl == null) {
cImpl = impl =
AccessController.doPrivileged(new PrivilegedAction<ThrowUnchecked>() {
public ThrowUnchecked run() {
return generateImpl();
}
});
}
}
}
impl.doFire(t);
}
} | [
"public",
"static",
"void",
"fire",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"// Don't need to do anything special for unchecked exceptions.",
"if",
"(",
"t",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeExcepti... | Throws the given exception, even though it may be checked. This method
only returns normally if the exception is null.
@param t exception to throw | [
"Throws",
"the",
"given",
"exception",
"even",
"though",
"it",
"may",
"be",
"checked",
".",
"This",
"method",
"only",
"returns",
"normally",
"if",
"the",
"exception",
"is",
"null",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L83-L110 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireFirstDeclared | public static void fireFirstDeclared(Throwable t, Class... declaredTypes) {
Throwable cause = t;
while (cause != null) {
cause = cause.getCause();
if (cause == null) {
break;
}
if (declaredTypes != null) {
for (Class declaredType : declaredTypes) {
if (declaredType.isInstance(cause)) {
fire(cause);
}
}
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
}
throw new UndeclaredThrowableException(t);
} | java | public static void fireFirstDeclared(Throwable t, Class... declaredTypes) {
Throwable cause = t;
while (cause != null) {
cause = cause.getCause();
if (cause == null) {
break;
}
if (declaredTypes != null) {
for (Class declaredType : declaredTypes) {
if (declaredType.isInstance(cause)) {
fire(cause);
}
}
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
}
throw new UndeclaredThrowableException(t);
} | [
"public",
"static",
"void",
"fireFirstDeclared",
"(",
"Throwable",
"t",
",",
"Class",
"...",
"declaredTypes",
")",
"{",
"Throwable",
"cause",
"=",
"t",
";",
"while",
"(",
"cause",
"!=",
"null",
")",
"{",
"cause",
"=",
"cause",
".",
"getCause",
"(",
")",
... | Throws the either the original exception or the first found cause if it
matches one of the given declared types or is unchecked. Otherwise, the
original exception is thrown as an UndeclaredThrowableException. This
method only returns normally if the exception is null.
@param t exception whose cause is to be thrown
@param declaredTypes if exception is checked and is not an instance of
any of these types, then it is thrown as an
UndeclaredThrowableException. | [
"Throws",
"the",
"either",
"the",
"original",
"exception",
"or",
"the",
"first",
"found",
"cause",
"if",
"it",
"matches",
"one",
"of",
"the",
"given",
"declared",
"types",
"or",
"is",
"unchecked",
".",
"Otherwise",
"the",
"original",
"exception",
"is",
"thro... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L153-L175 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireCause | public static void fireCause(Throwable t) {
if (t != null) {
Throwable cause = t.getCause();
if (cause == null) {
cause = t;
}
fire(cause);
}
} | java | public static void fireCause(Throwable t) {
if (t != null) {
Throwable cause = t.getCause();
if (cause == null) {
cause = t;
}
fire(cause);
}
} | [
"public",
"static",
"void",
"fireCause",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"Throwable",
"cause",
"=",
"t",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"==",
"null",
")",
"{",
"cause",
"=",
"t",
";",
... | Throws the cause of the given exception, even though it may be
checked. If the cause is null, then the original exception is
thrown. This method only returns normally if the exception is null.
@param t exception whose cause is to be thrown | [
"Throws",
"the",
"cause",
"of",
"the",
"given",
"exception",
"even",
"though",
"it",
"may",
"be",
"checked",
".",
"If",
"the",
"cause",
"is",
"null",
"then",
"the",
"original",
"exception",
"is",
"thrown",
".",
"This",
"method",
"only",
"returns",
"normall... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L184-L192 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireDeclaredCause | public static void fireDeclaredCause(Throwable t, Class... declaredTypes) {
if (t != null) {
Throwable cause = t.getCause();
if (cause == null) {
cause = t;
}
fireDeclared(cause, declaredTypes);
}
} | java | public static void fireDeclaredCause(Throwable t, Class... declaredTypes) {
if (t != null) {
Throwable cause = t.getCause();
if (cause == null) {
cause = t;
}
fireDeclared(cause, declaredTypes);
}
} | [
"public",
"static",
"void",
"fireDeclaredCause",
"(",
"Throwable",
"t",
",",
"Class",
"...",
"declaredTypes",
")",
"{",
"if",
"(",
"t",
"!=",
"null",
")",
"{",
"Throwable",
"cause",
"=",
"t",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"==",
... | Throws the cause of the given exception if it is unchecked or an
instance of any of the given declared types. Otherwise, it is thrown as
an UndeclaredThrowableException. If the cause is null, then the original
exception is thrown. This method only returns normally if the exception
is null.
@param t exception whose cause is to be thrown
@param declaredTypes if exception is checked and is not an instance of
any of these types, then it is thrown as an
UndeclaredThrowableException. | [
"Throws",
"the",
"cause",
"of",
"the",
"given",
"exception",
"if",
"it",
"is",
"unchecked",
"or",
"an",
"instance",
"of",
"any",
"of",
"the",
"given",
"declared",
"types",
".",
"Otherwise",
"it",
"is",
"thrown",
"as",
"an",
"UndeclaredThrowableException",
".... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L206-L214 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireFirstDeclaredCause | public static void fireFirstDeclaredCause(Throwable t, Class... declaredTypes) {
Throwable cause = t;
while (cause != null) {
cause = cause.getCause();
if (cause == null) {
break;
}
if (declaredTypes != null) {
for (Class declaredType : declaredTypes) {
if (declaredType.isInstance(cause)) {
fire(cause);
}
}
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
}
fireDeclaredCause(t, declaredTypes);
} | java | public static void fireFirstDeclaredCause(Throwable t, Class... declaredTypes) {
Throwable cause = t;
while (cause != null) {
cause = cause.getCause();
if (cause == null) {
break;
}
if (declaredTypes != null) {
for (Class declaredType : declaredTypes) {
if (declaredType.isInstance(cause)) {
fire(cause);
}
}
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
}
fireDeclaredCause(t, declaredTypes);
} | [
"public",
"static",
"void",
"fireFirstDeclaredCause",
"(",
"Throwable",
"t",
",",
"Class",
"...",
"declaredTypes",
")",
"{",
"Throwable",
"cause",
"=",
"t",
";",
"while",
"(",
"cause",
"!=",
"null",
")",
"{",
"cause",
"=",
"cause",
".",
"getCause",
"(",
... | Throws the first found cause that matches one of the given declared
types or is unchecked. Otherwise, the immediate cause is thrown as an
UndeclaredThrowableException. If the immediate cause is null, then the
original exception is thrown. This method only returns normally if the
exception is null.
@param t exception whose cause is to be thrown
@param declaredTypes if exception is checked and is not an instance of
any of these types, then it is thrown as an
UndeclaredThrowableException. | [
"Throws",
"the",
"first",
"found",
"cause",
"that",
"matches",
"one",
"of",
"the",
"given",
"declared",
"types",
"or",
"is",
"unchecked",
".",
"Otherwise",
"the",
"immediate",
"cause",
"is",
"thrown",
"as",
"an",
"UndeclaredThrowableException",
".",
"If",
"the... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L228-L250 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireRootCause | public static void fireRootCause(Throwable t) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fire(root);
} | java | public static void fireRootCause(Throwable t) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fire(root);
} | [
"public",
"static",
"void",
"fireRootCause",
"(",
"Throwable",
"t",
")",
"{",
"Throwable",
"root",
"=",
"t",
";",
"while",
"(",
"root",
"!=",
"null",
")",
"{",
"Throwable",
"cause",
"=",
"root",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"==... | Throws the root cause of the given exception, even though it may be
checked. If the root cause is null, then the original exception is
thrown. This method only returns normally if the exception is null.
@param t exception whose root cause is to be thrown | [
"Throws",
"the",
"root",
"cause",
"of",
"the",
"given",
"exception",
"even",
"though",
"it",
"may",
"be",
"checked",
".",
"If",
"the",
"root",
"cause",
"is",
"null",
"then",
"the",
"original",
"exception",
"is",
"thrown",
".",
"This",
"method",
"only",
"... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L259-L269 | train |
cojen/Cojen | src/main/java/org/cojen/util/ThrowUnchecked.java | ThrowUnchecked.fireDeclaredRootCause | public static void fireDeclaredRootCause(Throwable t, Class... declaredTypes) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fireDeclared(root, declaredTypes);
} | java | public static void fireDeclaredRootCause(Throwable t, Class... declaredTypes) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fireDeclared(root, declaredTypes);
} | [
"public",
"static",
"void",
"fireDeclaredRootCause",
"(",
"Throwable",
"t",
",",
"Class",
"...",
"declaredTypes",
")",
"{",
"Throwable",
"root",
"=",
"t",
";",
"while",
"(",
"root",
"!=",
"null",
")",
"{",
"Throwable",
"cause",
"=",
"root",
".",
"getCause"... | Throws the root cause of the given exception if it is unchecked or an
instance of any of the given declared types. Otherwise, it is thrown as
an UndeclaredThrowableException. If the root cause is null, then the
original exception is thrown. This method only returns normally if the
exception is null.
@param t exception whose root cause is to be thrown
@param declaredTypes if exception is checked and is not an instance of
any of these types, then it is thrown as an
UndeclaredThrowableException. | [
"Throws",
"the",
"root",
"cause",
"of",
"the",
"given",
"exception",
"if",
"it",
"is",
"unchecked",
"or",
"an",
"instance",
"of",
"any",
"of",
"the",
"given",
"declared",
"types",
".",
"Otherwise",
"it",
"is",
"thrown",
"as",
"an",
"UndeclaredThrowableExcept... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/ThrowUnchecked.java#L283-L293 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/attribute/CodeAttr.java | CodeAttr.setCodeBuffer | public void setCodeBuffer(CodeBuffer code) {
mCodeBuffer = code;
mOldLineNumberTable = mLineNumberTable;
mOldLocalVariableTable = mLocalVariableTable;
mOldStackMapTable = mStackMapTable;
mAttributes.remove(mLineNumberTable);
mAttributes.remove(mLocalVariableTable);
mAttributes.remove(mStackMapTable);
mLineNumberTable = null;
mLocalVariableTable = null;
mStackMapTable = null;
} | java | public void setCodeBuffer(CodeBuffer code) {
mCodeBuffer = code;
mOldLineNumberTable = mLineNumberTable;
mOldLocalVariableTable = mLocalVariableTable;
mOldStackMapTable = mStackMapTable;
mAttributes.remove(mLineNumberTable);
mAttributes.remove(mLocalVariableTable);
mAttributes.remove(mStackMapTable);
mLineNumberTable = null;
mLocalVariableTable = null;
mStackMapTable = null;
} | [
"public",
"void",
"setCodeBuffer",
"(",
"CodeBuffer",
"code",
")",
"{",
"mCodeBuffer",
"=",
"code",
";",
"mOldLineNumberTable",
"=",
"mLineNumberTable",
";",
"mOldLocalVariableTable",
"=",
"mLocalVariableTable",
";",
"mOldStackMapTable",
"=",
"mStackMapTable",
";",
"m... | As a side effect of calling this method, new line number and local
variable tables are created. | [
"As",
"a",
"side",
"effect",
"of",
"calling",
"this",
"method",
"new",
"line",
"number",
"and",
"local",
"variable",
"tables",
"are",
"created",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/attribute/CodeAttr.java#L119-L130 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/attribute/CodeAttr.java | CodeAttr.localVariableUse | public void localVariableUse(LocalVariable localVar) {
if (mLocalVariableTable == null) {
addAttribute(new LocalVariableTableAttr(getConstantPool()));
}
mLocalVariableTable.addEntry(localVar);
} | java | public void localVariableUse(LocalVariable localVar) {
if (mLocalVariableTable == null) {
addAttribute(new LocalVariableTableAttr(getConstantPool()));
}
mLocalVariableTable.addEntry(localVar);
} | [
"public",
"void",
"localVariableUse",
"(",
"LocalVariable",
"localVar",
")",
"{",
"if",
"(",
"mLocalVariableTable",
"==",
"null",
")",
"{",
"addAttribute",
"(",
"new",
"LocalVariableTableAttr",
"(",
"getConstantPool",
"(",
")",
")",
")",
";",
"}",
"mLocalVariabl... | Indicate a local variable's use information be recorded in the
ClassFile as a debugging aid. If the LocalVariable doesn't provide
both a start and end location, then its information is not recorded.
This method should be called at most once per LocalVariable instance. | [
"Indicate",
"a",
"local",
"variable",
"s",
"use",
"information",
"be",
"recorded",
"in",
"the",
"ClassFile",
"as",
"a",
"debugging",
"aid",
".",
"If",
"the",
"LocalVariable",
"doesn",
"t",
"provide",
"both",
"a",
"start",
"and",
"end",
"location",
"then",
... | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/attribute/CodeAttr.java#L200-L205 | train |
cojen/Cojen | src/example/org/cojen/example/HelloWorld.java | HelloWorld.createClassFile | private static RuntimeClassFile createClassFile() {
// Create a ClassFile with the super class of Object.
RuntimeClassFile cf = new RuntimeClassFile();
// Default constructor works only if super class has an accessible
// no-arg constructor.
cf.addDefaultConstructor();
// Add the main method, and construct a CodeBuilder for defining the
// bytecode.
TypeDesc[] params = new TypeDesc[] {TypeDesc.STRING.toArrayType()};
MethodInfo mi = cf.addMethod(Modifiers.PUBLIC_STATIC, "main", null, params);
CodeBuilder b = new CodeBuilder(mi);
// Create some types which will be needed later.
TypeDesc bufferedReader = TypeDesc.forClass("java.io.BufferedReader");
TypeDesc inputStreamReader = TypeDesc.forClass("java.io.InputStreamReader");
TypeDesc inputStream = TypeDesc.forClass("java.io.InputStream");
TypeDesc reader = TypeDesc.forClass("java.io.Reader");
TypeDesc stringBuffer = TypeDesc.forClass("java.lang.StringBuffer");
TypeDesc printStream = TypeDesc.forClass("java.io.PrintStream");
// Declare local variables to be used.
LocalVariable in = b.createLocalVariable("in", bufferedReader);
LocalVariable name = b.createLocalVariable("name", TypeDesc.STRING);
// Create the first line of code, corresponding to
// in = new BufferedReader(new InputStreamReader(System.in));
b.newObject(bufferedReader);
b.dup();
b.newObject(inputStreamReader);
b.dup();
b.loadStaticField("java.lang.System", "in", inputStream);
params = new TypeDesc[] {inputStream};
b.invokeConstructor(inputStreamReader.getRootName(), params);
params = new TypeDesc[] {reader};
b.invokeConstructor(bufferedReader.getRootName(), params);
b.storeLocal(in);
// Create and locate a label for the start of the "try" block.
Label tryStart = b.createLabel().setLocation();
// Create input prompt.
b.loadStaticField("java.lang.System", "out", printStream);
b.loadConstant("Please enter your name> ");
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeVirtual(printStream, "print", null, params);
// Read a line from the reader, and store it in the "name" variable.
b.loadLocal(in);
b.invokeVirtual(bufferedReader, "readLine", TypeDesc.STRING, null);
b.storeLocal(name);
// If no exception is thrown, branch to a label to print the
// response. The location of the label has not yet been set.
Label printResponse = b.createLabel();
b.branch(printResponse);
// Create and locate a label for the end of the "try" block.
Label tryEnd = b.createLabel().setLocation();
// Create the "catch" block.
b.exceptionHandler(tryStart, tryEnd, "java.io.IOException");
b.returnVoid();
// If no exception, then branch to this location to print the response.
printResponse.setLocation();
// Create the line of code, corresponding to
// System.out.println("Hello, " + name);
b.loadStaticField("java.lang.System", "out", printStream);
b.newObject(stringBuffer);
b.dup();
b.loadConstant("Hello, ");
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeConstructor(stringBuffer, params);
b.loadLocal(name);
b.invokeVirtual(stringBuffer, "append", stringBuffer, params);
b.invokeVirtual(stringBuffer, "toString", TypeDesc.STRING, null);
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeVirtual(printStream, "println", null, params);
// The last instruction reached must be a return or else the class
// verifier will complain.
b.returnVoid();
return cf;
} | java | private static RuntimeClassFile createClassFile() {
// Create a ClassFile with the super class of Object.
RuntimeClassFile cf = new RuntimeClassFile();
// Default constructor works only if super class has an accessible
// no-arg constructor.
cf.addDefaultConstructor();
// Add the main method, and construct a CodeBuilder for defining the
// bytecode.
TypeDesc[] params = new TypeDesc[] {TypeDesc.STRING.toArrayType()};
MethodInfo mi = cf.addMethod(Modifiers.PUBLIC_STATIC, "main", null, params);
CodeBuilder b = new CodeBuilder(mi);
// Create some types which will be needed later.
TypeDesc bufferedReader = TypeDesc.forClass("java.io.BufferedReader");
TypeDesc inputStreamReader = TypeDesc.forClass("java.io.InputStreamReader");
TypeDesc inputStream = TypeDesc.forClass("java.io.InputStream");
TypeDesc reader = TypeDesc.forClass("java.io.Reader");
TypeDesc stringBuffer = TypeDesc.forClass("java.lang.StringBuffer");
TypeDesc printStream = TypeDesc.forClass("java.io.PrintStream");
// Declare local variables to be used.
LocalVariable in = b.createLocalVariable("in", bufferedReader);
LocalVariable name = b.createLocalVariable("name", TypeDesc.STRING);
// Create the first line of code, corresponding to
// in = new BufferedReader(new InputStreamReader(System.in));
b.newObject(bufferedReader);
b.dup();
b.newObject(inputStreamReader);
b.dup();
b.loadStaticField("java.lang.System", "in", inputStream);
params = new TypeDesc[] {inputStream};
b.invokeConstructor(inputStreamReader.getRootName(), params);
params = new TypeDesc[] {reader};
b.invokeConstructor(bufferedReader.getRootName(), params);
b.storeLocal(in);
// Create and locate a label for the start of the "try" block.
Label tryStart = b.createLabel().setLocation();
// Create input prompt.
b.loadStaticField("java.lang.System", "out", printStream);
b.loadConstant("Please enter your name> ");
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeVirtual(printStream, "print", null, params);
// Read a line from the reader, and store it in the "name" variable.
b.loadLocal(in);
b.invokeVirtual(bufferedReader, "readLine", TypeDesc.STRING, null);
b.storeLocal(name);
// If no exception is thrown, branch to a label to print the
// response. The location of the label has not yet been set.
Label printResponse = b.createLabel();
b.branch(printResponse);
// Create and locate a label for the end of the "try" block.
Label tryEnd = b.createLabel().setLocation();
// Create the "catch" block.
b.exceptionHandler(tryStart, tryEnd, "java.io.IOException");
b.returnVoid();
// If no exception, then branch to this location to print the response.
printResponse.setLocation();
// Create the line of code, corresponding to
// System.out.println("Hello, " + name);
b.loadStaticField("java.lang.System", "out", printStream);
b.newObject(stringBuffer);
b.dup();
b.loadConstant("Hello, ");
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeConstructor(stringBuffer, params);
b.loadLocal(name);
b.invokeVirtual(stringBuffer, "append", stringBuffer, params);
b.invokeVirtual(stringBuffer, "toString", TypeDesc.STRING, null);
params = new TypeDesc[] {TypeDesc.STRING};
b.invokeVirtual(printStream, "println", null, params);
// The last instruction reached must be a return or else the class
// verifier will complain.
b.returnVoid();
return cf;
} | [
"private",
"static",
"RuntimeClassFile",
"createClassFile",
"(",
")",
"{",
"// Create a ClassFile with the super class of Object.",
"RuntimeClassFile",
"cf",
"=",
"new",
"RuntimeClassFile",
"(",
")",
";",
"// Default constructor works only if super class has an accessible",
"// no-... | Creates a ClassFile which defines a simple interactive HelloWorld class.
@param className name given to class | [
"Creates",
"a",
"ClassFile",
"which",
"defines",
"a",
"simple",
"interactive",
"HelloWorld",
"class",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/example/org/cojen/example/HelloWorld.java#L71-L159 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/ConstantPool.java | ConstantPool.addConstantClass | public ConstantClassInfo addConstantClass(String className, int dim) {
return (ConstantClassInfo)addConstant(new ConstantClassInfo(this, className, dim));
} | java | public ConstantClassInfo addConstantClass(String className, int dim) {
return (ConstantClassInfo)addConstant(new ConstantClassInfo(this, className, dim));
} | [
"public",
"ConstantClassInfo",
"addConstantClass",
"(",
"String",
"className",
",",
"int",
"dim",
")",
"{",
"return",
"(",
"ConstantClassInfo",
")",
"addConstant",
"(",
"new",
"ConstantClassInfo",
"(",
"this",
",",
"className",
",",
"dim",
")",
")",
";",
"}"
] | Get or create a constant from the constant pool representing an array
class.
@param dim Number of array dimensions. | [
"Get",
"or",
"create",
"a",
"constant",
"from",
"the",
"constant",
"pool",
"representing",
"an",
"array",
"class",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/ConstantPool.java#L128-L130 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/localization/DefaultResourceBundleFactory.java | DefaultResourceBundleFactory.init | public void init(Configuration configuration)
throws Exception
{
String baseName = configuration.getBootstrapPropertyResolver().getProperty("ResourceBundleFactory.Bundle");
if (baseName != null)
{
this.baseName = baseName;
}
} | java | public void init(Configuration configuration)
throws Exception
{
String baseName = configuration.getBootstrapPropertyResolver().getProperty("ResourceBundleFactory.Bundle");
if (baseName != null)
{
this.baseName = baseName;
}
} | [
"public",
"void",
"init",
"(",
"Configuration",
"configuration",
")",
"throws",
"Exception",
"{",
"String",
"baseName",
"=",
"configuration",
".",
"getBootstrapPropertyResolver",
"(",
")",
".",
"getProperty",
"(",
"\"ResourceBundleFactory.Bundle\"",
")",
";",
"if",
... | Initialize the bundle factory.
@param configuration the current configuration
@throws Exception when the factory cannot be initialized | [
"Initialize",
"the",
"bundle",
"factory",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/localization/DefaultResourceBundleFactory.java#L36-L44 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/localization/DefaultResourceBundleFactory.java | DefaultResourceBundleFactory.getDefaultBundle | public ResourceBundle getDefaultBundle(Locale locale)
throws MissingResourceException
{
ResourceBundle bundle;
if (locale == null)
{
bundle = ResourceBundle.getBundle(baseName);
}
else
{
bundle = ResourceBundle.getBundle(baseName, locale);
}
return bundle;
} | java | public ResourceBundle getDefaultBundle(Locale locale)
throws MissingResourceException
{
ResourceBundle bundle;
if (locale == null)
{
bundle = ResourceBundle.getBundle(baseName);
}
else
{
bundle = ResourceBundle.getBundle(baseName, locale);
}
return bundle;
} | [
"public",
"ResourceBundle",
"getDefaultBundle",
"(",
"Locale",
"locale",
")",
"throws",
"MissingResourceException",
"{",
"ResourceBundle",
"bundle",
";",
"if",
"(",
"locale",
"==",
"null",
")",
"{",
"bundle",
"=",
"ResourceBundle",
".",
"getBundle",
"(",
"baseName... | Returns the ResourceBundle from which to messages for the specified locale by default.
@param locale the locale that is in use for the current request
@return the default resource bundle
@throws java.util.MissingResourceException
when a bundle that is expected to be present cannot be located | [
"Returns",
"the",
"ResourceBundle",
"from",
"which",
"to",
"messages",
"for",
"the",
"specified",
"locale",
"by",
"default",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/localization/DefaultResourceBundleFactory.java#L55-L69 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanPropertyMapFactory.java | BeanPropertyMapFactory.forClass | public static <B> BeanPropertyMapFactory<B> forClass(Class<B> clazz) {
synchronized (cFactories) {
BeanPropertyMapFactory factory;
SoftReference<BeanPropertyMapFactory> ref = cFactories.get(clazz);
if (ref != null) {
factory = ref.get();
if (factory != null) {
return factory;
}
}
final Map<String, BeanProperty> properties = BeanIntrospector.getAllProperties(clazz);
Map<String, BeanProperty> supportedProperties = properties;
// Determine which properties are to be excluded.
for (Map.Entry<String, BeanProperty> entry : properties.entrySet()) {
BeanProperty property = entry.getValue();
if (property.getReadMethod() == null ||
property.getWriteMethod() == null ||
BeanPropertyAccessor.throwsCheckedException(property.getReadMethod()) ||
BeanPropertyAccessor.throwsCheckedException(property.getWriteMethod()))
{
// Exclude property.
if (supportedProperties == properties) {
supportedProperties = new HashMap<String, BeanProperty>(properties);
}
supportedProperties.remove(entry.getKey());
}
}
if (supportedProperties.size() == 0) {
factory = Empty.INSTANCE;
} else {
factory = new Standard<B>
(BeanPropertyAccessor.forClass
(clazz, BeanPropertyAccessor.PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS),
supportedProperties);
}
cFactories.put(clazz, new SoftReference<BeanPropertyMapFactory>(factory));
return factory;
}
} | java | public static <B> BeanPropertyMapFactory<B> forClass(Class<B> clazz) {
synchronized (cFactories) {
BeanPropertyMapFactory factory;
SoftReference<BeanPropertyMapFactory> ref = cFactories.get(clazz);
if (ref != null) {
factory = ref.get();
if (factory != null) {
return factory;
}
}
final Map<String, BeanProperty> properties = BeanIntrospector.getAllProperties(clazz);
Map<String, BeanProperty> supportedProperties = properties;
// Determine which properties are to be excluded.
for (Map.Entry<String, BeanProperty> entry : properties.entrySet()) {
BeanProperty property = entry.getValue();
if (property.getReadMethod() == null ||
property.getWriteMethod() == null ||
BeanPropertyAccessor.throwsCheckedException(property.getReadMethod()) ||
BeanPropertyAccessor.throwsCheckedException(property.getWriteMethod()))
{
// Exclude property.
if (supportedProperties == properties) {
supportedProperties = new HashMap<String, BeanProperty>(properties);
}
supportedProperties.remove(entry.getKey());
}
}
if (supportedProperties.size() == 0) {
factory = Empty.INSTANCE;
} else {
factory = new Standard<B>
(BeanPropertyAccessor.forClass
(clazz, BeanPropertyAccessor.PropertySet.READ_WRITE_UNCHECKED_EXCEPTIONS),
supportedProperties);
}
cFactories.put(clazz, new SoftReference<BeanPropertyMapFactory>(factory));
return factory;
}
} | [
"public",
"static",
"<",
"B",
">",
"BeanPropertyMapFactory",
"<",
"B",
">",
"forClass",
"(",
"Class",
"<",
"B",
">",
"clazz",
")",
"{",
"synchronized",
"(",
"cFactories",
")",
"{",
"BeanPropertyMapFactory",
"factory",
";",
"SoftReference",
"<",
"BeanPropertyMa... | Returns a new or cached BeanPropertyMapFactory for the given class. | [
"Returns",
"a",
"new",
"or",
"cached",
"BeanPropertyMapFactory",
"for",
"the",
"given",
"class",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyMapFactory.java#L54-L96 | train |
cojen/Cojen | src/main/java/org/cojen/util/BeanPropertyMapFactory.java | BeanPropertyMapFactory.asMap | public static SortedMap<String, Object> asMap(Object bean) {
if (bean == null) {
throw new IllegalArgumentException();
}
BeanPropertyMapFactory factory = forClass(bean.getClass());
return factory.createMap(bean);
} | java | public static SortedMap<String, Object> asMap(Object bean) {
if (bean == null) {
throw new IllegalArgumentException();
}
BeanPropertyMapFactory factory = forClass(bean.getClass());
return factory.createMap(bean);
} | [
"public",
"static",
"SortedMap",
"<",
"String",
",",
"Object",
">",
"asMap",
"(",
"Object",
"bean",
")",
"{",
"if",
"(",
"bean",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"BeanPropertyMapFactory",
"factory",
"=... | Returns a fixed-size map backed by the given bean. Map remove operations
are unsupported, as is access to excluded properties.
@throws IllegalArgumentException if bean is null | [
"Returns",
"a",
"fixed",
"-",
"size",
"map",
"backed",
"by",
"the",
"given",
"bean",
".",
"Map",
"remove",
"operations",
"are",
"unsupported",
"as",
"is",
"access",
"to",
"excluded",
"properties",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/BeanPropertyMapFactory.java#L104-L110 | train |
cojen/Cojen | src/main/java/org/cojen/classfile/MethodInfo.java | MethodInfo.getExceptions | public TypeDesc[] getExceptions() {
if (mExceptions == null) {
return new TypeDesc[0];
}
ConstantClassInfo[] classes = mExceptions.getExceptions();
TypeDesc[] types = new TypeDesc[classes.length];
for (int i=0; i<types.length; i++) {
types[i] = classes[i].getType();
}
return types;
} | java | public TypeDesc[] getExceptions() {
if (mExceptions == null) {
return new TypeDesc[0];
}
ConstantClassInfo[] classes = mExceptions.getExceptions();
TypeDesc[] types = new TypeDesc[classes.length];
for (int i=0; i<types.length; i++) {
types[i] = classes[i].getType();
}
return types;
} | [
"public",
"TypeDesc",
"[",
"]",
"getExceptions",
"(",
")",
"{",
"if",
"(",
"mExceptions",
"==",
"null",
")",
"{",
"return",
"new",
"TypeDesc",
"[",
"0",
"]",
";",
"}",
"ConstantClassInfo",
"[",
"]",
"classes",
"=",
"mExceptions",
".",
"getExceptions",
"(... | Returns the exceptions that this method is declared to throw. | [
"Returns",
"the",
"exceptions",
"that",
"this",
"method",
"is",
"declared",
"to",
"throw",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/classfile/MethodInfo.java#L177-L189 | train |
Faylixe/googlecodejam-client | src/main/java/fr/faylixe/googlecodejam/client/executor/Request.java | Request.createBoundary | public static final String createBoundary() {
final StringBuilder builder = new StringBuilder(BOUNDARY_PREFIX);
builder.append((int) System.currentTimeMillis());
return builder.toString();
} | java | public static final String createBoundary() {
final StringBuilder builder = new StringBuilder(BOUNDARY_PREFIX);
builder.append((int) System.currentTimeMillis());
return builder.toString();
} | [
"public",
"static",
"final",
"String",
"createBoundary",
"(",
")",
"{",
"final",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"BOUNDARY_PREFIX",
")",
";",
"builder",
".",
"append",
"(",
"(",
"int",
")",
"System",
".",
"currentTimeMillis",
"(",... | Creates and returns a boundary for multipart request.
@return Created boundary. | [
"Creates",
"and",
"returns",
"a",
"boundary",
"for",
"multipart",
"request",
"."
] | 84a5fed4e049dca48994dc3f70213976aaff4bd3 | https://github.com/Faylixe/googlecodejam-client/blob/84a5fed4e049dca48994dc3f70213976aaff4bd3/src/main/java/fr/faylixe/googlecodejam/client/executor/Request.java#L119-L123 | train |
cojen/Cojen | src/main/java/org/cojen/util/AnnotationVisitor.java | AnnotationVisitor.visit | public R visit(String name, int pos, String value, P param) {
return null;
} | java | public R visit(String name, int pos, String value, P param) {
return null;
} | [
"public",
"R",
"visit",
"(",
"String",
"name",
",",
"int",
"pos",
",",
"String",
"value",
",",
"P",
"param",
")",
"{",
"return",
"null",
";",
"}"
] | Override to visit Strings.
@param name member name, or null if array member
@param pos position of member in list or array
@param value String visited
@param param custom parameter
@return custom result, null by default | [
"Override",
"to",
"visit",
"Strings",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/AnnotationVisitor.java#L290-L292 | train |
cojen/Cojen | src/main/java/org/cojen/util/AnnotationVisitor.java | AnnotationVisitor.visit | public R visit(String name, int pos, Annotation[] value, P param) {
for (int i=0; i<value.length; i++) {
visit(null, i, value[i], param);
}
return null;
} | java | public R visit(String name, int pos, Annotation[] value, P param) {
for (int i=0; i<value.length; i++) {
visit(null, i, value[i], param);
}
return null;
} | [
"public",
"R",
"visit",
"(",
"String",
"name",
",",
"int",
"pos",
",",
"Annotation",
"[",
"]",
"value",
",",
"P",
"param",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"visit",
"... | Visits each array element.
@param name member name, or null if array member
@param pos position of member in list or array
@param value Annotation array visited
@param param custom parameter
@return custom result, null by default | [
"Visits",
"each",
"array",
"element",
"."
] | ddee9a0fde83870b97e0ed04c58270aa665f3a62 | https://github.com/cojen/Cojen/blob/ddee9a0fde83870b97e0ed04c58270aa665f3a62/src/main/java/org/cojen/util/AnnotationVisitor.java#L329-L334 | train |
StripesFramework/stripes-stuff | src/main/java/org/stripesstuff/plugin/security/AllowedTag.java | AllowedTag.doStartTag | @Override
public int doStartTag()
throws JspException
{
// Retrieve the action bean and event handler to secure.
ActionBean actionBean;
if (bean == null)
{
// Search in page, request, session (if valid) and application scopes, in that order.
actionBean = (ActionBean)pageContext.findAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN);
LOG.debug("Determining access for the action bean of the form: ", actionBean);
}
else
{
// Search in page, request, session (if valid) and application scopes, in that order.
actionBean = (ActionBean)pageContext.findAttribute(bean);
LOG.debug("Determining access for action bean \"", bean, "\": ", actionBean);
}
if (actionBean == null)
{
throw new StripesJspException(
"Could not find the action bean. This means that either you specified the name \n" +
"of a bean that doesn't exist, or this tag is not used inside a Stripes Form.");
}
Method handler;
try
{
if (event == null)
{
handler = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(actionBean.getClass());
LOG.debug("Found a handler for the default event: ", handler);
}
else
{
handler = StripesFilter.getConfiguration().getActionResolver().getHandler(actionBean.getClass(), event);
LOG.debug("Found a handler for event \"", event, "\": %s", handler);
}
}
catch (StripesServletException e)
{
throw new StripesJspException("Failed to get the handler for the event.", e);
}
// Get the judgement of the security manager.
SecurityManager securityManager = (SecurityManager)pageContext.getAttribute(
SecurityInterceptor.SECURITY_MANAGER, PageContext.REQUEST_SCOPE);
boolean haveSecurityManager = securityManager != null;
boolean eventAllowed;
if (haveSecurityManager)
{
LOG.debug("Determining access using this security manager: ", securityManager);
eventAllowed = Boolean.TRUE.equals(securityManager.getAccessAllowed(actionBean, handler));
}
else
{
LOG.debug("There is no security manager; allowing access");
eventAllowed = true;
}
// Show the tag's content (or not) based on this
//noinspection deprecation
if (haveSecurityManager && negate)
{
LOG.debug("This tag negates the decision of the security manager.");
eventAllowed = !eventAllowed;
}
LOG.debug("Access is ", eventAllowed ? "allowed" : "denied", '.');
return eventAllowed ? EVAL_BODY_INCLUDE : SKIP_BODY;
} | java | @Override
public int doStartTag()
throws JspException
{
// Retrieve the action bean and event handler to secure.
ActionBean actionBean;
if (bean == null)
{
// Search in page, request, session (if valid) and application scopes, in that order.
actionBean = (ActionBean)pageContext.findAttribute(StripesConstants.REQ_ATTR_ACTION_BEAN);
LOG.debug("Determining access for the action bean of the form: ", actionBean);
}
else
{
// Search in page, request, session (if valid) and application scopes, in that order.
actionBean = (ActionBean)pageContext.findAttribute(bean);
LOG.debug("Determining access for action bean \"", bean, "\": ", actionBean);
}
if (actionBean == null)
{
throw new StripesJspException(
"Could not find the action bean. This means that either you specified the name \n" +
"of a bean that doesn't exist, or this tag is not used inside a Stripes Form.");
}
Method handler;
try
{
if (event == null)
{
handler = StripesFilter.getConfiguration().getActionResolver().getDefaultHandler(actionBean.getClass());
LOG.debug("Found a handler for the default event: ", handler);
}
else
{
handler = StripesFilter.getConfiguration().getActionResolver().getHandler(actionBean.getClass(), event);
LOG.debug("Found a handler for event \"", event, "\": %s", handler);
}
}
catch (StripesServletException e)
{
throw new StripesJspException("Failed to get the handler for the event.", e);
}
// Get the judgement of the security manager.
SecurityManager securityManager = (SecurityManager)pageContext.getAttribute(
SecurityInterceptor.SECURITY_MANAGER, PageContext.REQUEST_SCOPE);
boolean haveSecurityManager = securityManager != null;
boolean eventAllowed;
if (haveSecurityManager)
{
LOG.debug("Determining access using this security manager: ", securityManager);
eventAllowed = Boolean.TRUE.equals(securityManager.getAccessAllowed(actionBean, handler));
}
else
{
LOG.debug("There is no security manager; allowing access");
eventAllowed = true;
}
// Show the tag's content (or not) based on this
//noinspection deprecation
if (haveSecurityManager && negate)
{
LOG.debug("This tag negates the decision of the security manager.");
eventAllowed = !eventAllowed;
}
LOG.debug("Access is ", eventAllowed ? "allowed" : "denied", '.');
return eventAllowed ? EVAL_BODY_INCLUDE : SKIP_BODY;
} | [
"@",
"Override",
"public",
"int",
"doStartTag",
"(",
")",
"throws",
"JspException",
"{",
"// Retrieve the action bean and event handler to secure.",
"ActionBean",
"actionBean",
";",
"if",
"(",
"bean",
"==",
"null",
")",
"{",
"// Search in page, request, session (if valid) a... | Determine if the body should be evaluated or not.
@return EVAL_BODY_INCLUDE if the body should be included, or SKIP_BODY
@throws JspException when the tag cannot (decide if to) write the body content | [
"Determine",
"if",
"the",
"body",
"should",
"be",
"evaluated",
"or",
"not",
"."
] | 51ad92b4bd5862ba34d7c18c5829fb00ea3a3811 | https://github.com/StripesFramework/stripes-stuff/blob/51ad92b4bd5862ba34d7c18c5829fb00ea3a3811/src/main/java/org/stripesstuff/plugin/security/AllowedTag.java#L89-L162 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.