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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java | SimpleAuthenticator.getPasswordAuthentication | protected PasswordAuthentication getPasswordAuthentication() {
// Don't worry, this is just a hack to figure out if we were able
// to set this Authenticator through the setDefault method.
if (!sInitialized && MAGIC.equals(getRequestingScheme()) && getRequestingPort() == FOURTYTWO) {
return new PasswordAuthentication(MAGIC, ("" + FOURTYTWO).toCharArray());
}
/*
System.err.println("getPasswordAuthentication");
System.err.println(getRequestingSite());
System.err.println(getRequestingPort());
System.err.println(getRequestingProtocol());
System.err.println(getRequestingPrompt());
System.err.println(getRequestingScheme());
*/
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(getRequestingSite(),
// getRequestingPort(),
// getRequestingProtocol(),
// getRequestingPrompt(),
// getRequestingScheme());
return passwordAuthentications.get(new AuthKey(getRequestingSite(),
getRequestingPort(),
getRequestingProtocol(),
getRequestingPrompt(),
getRequestingScheme()));
} | java | protected PasswordAuthentication getPasswordAuthentication() {
// Don't worry, this is just a hack to figure out if we were able
// to set this Authenticator through the setDefault method.
if (!sInitialized && MAGIC.equals(getRequestingScheme()) && getRequestingPort() == FOURTYTWO) {
return new PasswordAuthentication(MAGIC, ("" + FOURTYTWO).toCharArray());
}
/*
System.err.println("getPasswordAuthentication");
System.err.println(getRequestingSite());
System.err.println(getRequestingPort());
System.err.println(getRequestingProtocol());
System.err.println(getRequestingPrompt());
System.err.println(getRequestingScheme());
*/
// TODO:
// Look for a more specific PasswordAuthenticatior before using
// Default:
//
// if (...)
// return pa.requestPasswordAuthentication(getRequestingSite(),
// getRequestingPort(),
// getRequestingProtocol(),
// getRequestingPrompt(),
// getRequestingScheme());
return passwordAuthentications.get(new AuthKey(getRequestingSite(),
getRequestingPort(),
getRequestingProtocol(),
getRequestingPrompt(),
getRequestingScheme()));
} | [
"protected",
"PasswordAuthentication",
"getPasswordAuthentication",
"(",
")",
"{",
"// Don't worry, this is just a hack to figure out if we were able",
"// to set this Authenticator through the setDefault method.",
"if",
"(",
"!",
"sInitialized",
"&&",
"MAGIC",
".",
"equals",
"(",
... | Gets the PasswordAuthentication for the request. Called when password
authorization is needed.
@return The PasswordAuthentication collected from the user, or null if
none is provided. | [
"Gets",
"the",
"PasswordAuthentication",
"for",
"the",
"request",
".",
"Called",
"when",
"password",
"authorization",
"is",
"needed",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java#L120-L151 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java | SimpleAuthenticator.registerPasswordAuthentication | public PasswordAuthentication registerPasswordAuthentication(URL pURL, PasswordAuthentication pPA) {
return registerPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null, // Prompt/Realm
BASIC,
pPA);
} | java | public PasswordAuthentication registerPasswordAuthentication(URL pURL, PasswordAuthentication pPA) {
return registerPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null, // Prompt/Realm
BASIC,
pPA);
} | [
"public",
"PasswordAuthentication",
"registerPasswordAuthentication",
"(",
"URL",
"pURL",
",",
"PasswordAuthentication",
"pPA",
")",
"{",
"return",
"registerPasswordAuthentication",
"(",
"NetUtil",
".",
"createInetAddressFromURL",
"(",
"pURL",
")",
",",
"pURL",
".",
"ge... | Registers a PasswordAuthentication with a given URL address. | [
"Registers",
"a",
"PasswordAuthentication",
"with",
"a",
"given",
"URL",
"address",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java#L154-L161 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java | SimpleAuthenticator.registerPasswordAuthentication | public PasswordAuthentication registerPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme, PasswordAuthentication pPA) {
/*
System.err.println("registerPasswordAuthentication");
System.err.println(pAddress);
System.err.println(pPort);
System.err.println(pProtocol);
System.err.println(pPrompt);
System.err.println(pScheme);
*/
return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
} | java | public PasswordAuthentication registerPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme, PasswordAuthentication pPA) {
/*
System.err.println("registerPasswordAuthentication");
System.err.println(pAddress);
System.err.println(pPort);
System.err.println(pProtocol);
System.err.println(pPrompt);
System.err.println(pScheme);
*/
return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
} | [
"public",
"PasswordAuthentication",
"registerPasswordAuthentication",
"(",
"InetAddress",
"pAddress",
",",
"int",
"pPort",
",",
"String",
"pProtocol",
",",
"String",
"pPrompt",
",",
"String",
"pScheme",
",",
"PasswordAuthentication",
"pPA",
")",
"{",
"/*\n Syste... | Registers a PasswordAuthentication with a given net address. | [
"Registers",
"a",
"PasswordAuthentication",
"with",
"a",
"given",
"net",
"address",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java#L164-L175 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java | SimpleAuthenticator.unregisterPasswordAuthentication | public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
return unregisterPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), pURL.getPort(), pURL.getProtocol(), null, BASIC);
} | java | public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
return unregisterPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), pURL.getPort(), pURL.getProtocol(), null, BASIC);
} | [
"public",
"PasswordAuthentication",
"unregisterPasswordAuthentication",
"(",
"URL",
"pURL",
")",
"{",
"return",
"unregisterPasswordAuthentication",
"(",
"NetUtil",
".",
"createInetAddressFromURL",
"(",
"pURL",
")",
",",
"pURL",
".",
"getPort",
"(",
")",
",",
"pURL",
... | Unregisters a PasswordAuthentication with a given URL address. | [
"Unregisters",
"a",
"PasswordAuthentication",
"with",
"a",
"given",
"URL",
"address",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java#L178-L180 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java | SimpleAuthenticator.unregisterPasswordAuthentication | public PasswordAuthentication unregisterPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
return passwordAuthentications.remove(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme));
} | java | public PasswordAuthentication unregisterPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
return passwordAuthentications.remove(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme));
} | [
"public",
"PasswordAuthentication",
"unregisterPasswordAuthentication",
"(",
"InetAddress",
"pAddress",
",",
"int",
"pPort",
",",
"String",
"pProtocol",
",",
"String",
"pPrompt",
",",
"String",
"pScheme",
")",
"{",
"return",
"passwordAuthentications",
".",
"remove",
"... | Unregisters a PasswordAuthentication with a given net address. | [
"Unregisters",
"a",
"PasswordAuthentication",
"with",
"a",
"given",
"net",
"address",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/SimpleAuthenticator.java#L183-L185 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/BrowserHelperFilter.java | BrowserHelperFilter.setAcceptMappingsFile | @InitParam(name = "accept-mappings-file")
public void setAcceptMappingsFile(String pPropertiesFile) throws ServletConfigException {
// NOTE: Format is:
// <agent-name>=<reg-exp>
// <agent-name>.accept=<http-accept-header>
Properties mappings = new Properties();
try {
log("Reading Accept-mappings properties file: " + pPropertiesFile);
mappings.load(getServletContext().getResourceAsStream(pPropertiesFile));
//System.out.println("--> Loaded file: " + pPropertiesFile);
}
catch (IOException e) {
throw new ServletConfigException("Could not read Accept-mappings properties file: " + pPropertiesFile, e);
}
parseMappings(mappings);
} | java | @InitParam(name = "accept-mappings-file")
public void setAcceptMappingsFile(String pPropertiesFile) throws ServletConfigException {
// NOTE: Format is:
// <agent-name>=<reg-exp>
// <agent-name>.accept=<http-accept-header>
Properties mappings = new Properties();
try {
log("Reading Accept-mappings properties file: " + pPropertiesFile);
mappings.load(getServletContext().getResourceAsStream(pPropertiesFile));
//System.out.println("--> Loaded file: " + pPropertiesFile);
}
catch (IOException e) {
throw new ServletConfigException("Could not read Accept-mappings properties file: " + pPropertiesFile, e);
}
parseMappings(mappings);
} | [
"@",
"InitParam",
"(",
"name",
"=",
"\"accept-mappings-file\"",
")",
"public",
"void",
"setAcceptMappingsFile",
"(",
"String",
"pPropertiesFile",
")",
"throws",
"ServletConfigException",
"{",
"// NOTE: Format is:",
"// <agent-name>=<reg-exp>",
"// <agent-name>.accept=<http-acce... | Sets the accept-mappings for this filter
@param pPropertiesFile name of accept-mappings properties files
@throws ServletConfigException if the accept-mappings properties
file cannot be read. | [
"Sets",
"the",
"accept",
"-",
"mappings",
"for",
"this",
"filter"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/BrowserHelperFilter.java#L68-L87 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/TrimWhiteSpaceTag.java | TrimWhiteSpaceTag.doEndTag | public int doEndTag() throws JspException {
// Trim
String trimmed = truncateWS(bodyContent.getString());
try {
// Print trimmed content
//pageContext.getOut().print("<!--TWS-->\n");
pageContext.getOut().print(trimmed);
//pageContext.getOut().print("\n<!--/TWS-->");
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
} | java | public int doEndTag() throws JspException {
// Trim
String trimmed = truncateWS(bodyContent.getString());
try {
// Print trimmed content
//pageContext.getOut().print("<!--TWS-->\n");
pageContext.getOut().print(trimmed);
//pageContext.getOut().print("\n<!--/TWS-->");
}
catch (IOException ioe) {
throw new JspException(ioe);
}
return super.doEndTag();
} | [
"public",
"int",
"doEndTag",
"(",
")",
"throws",
"JspException",
"{",
"// Trim\r",
"String",
"trimmed",
"=",
"truncateWS",
"(",
"bodyContent",
".",
"getString",
"(",
")",
")",
";",
"try",
"{",
"// Print trimmed content\r",
"//pageContext.getOut().print(\"<!--TWS-->\\n... | doEndTag implementation, truncates all whitespace.
@return {@code super.doEndTag()} | [
"doEndTag",
"implementation",
"truncates",
"all",
"whitespace",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/TrimWhiteSpaceTag.java#L36-L50 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/TrimWhiteSpaceTag.java | TrimWhiteSpaceTag.truncateWS | private static String truncateWS(String pStr) {
char[] chars = pStr.toCharArray();
int count = 0;
boolean lastWasWS = true; // Avoids leading WS
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i])) {
// if char is not WS, just store
chars[count++] = chars[i];
lastWasWS = false;
}
else {
// else, if char is WS, store first, skip the rest
if (!lastWasWS) {
if (chars[i] == 0x0d) {
chars[count++] = 0x0a; //Always new line
}
else {
chars[count++] = chars[i];
}
}
lastWasWS = true;
}
}
// Return the trucated string
return new String(chars, 0, count);
} | java | private static String truncateWS(String pStr) {
char[] chars = pStr.toCharArray();
int count = 0;
boolean lastWasWS = true; // Avoids leading WS
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i])) {
// if char is not WS, just store
chars[count++] = chars[i];
lastWasWS = false;
}
else {
// else, if char is WS, store first, skip the rest
if (!lastWasWS) {
if (chars[i] == 0x0d) {
chars[count++] = 0x0a; //Always new line
}
else {
chars[count++] = chars[i];
}
}
lastWasWS = true;
}
}
// Return the trucated string
return new String(chars, 0, count);
} | [
"private",
"static",
"String",
"truncateWS",
"(",
"String",
"pStr",
")",
"{",
"char",
"[",
"]",
"chars",
"=",
"pStr",
".",
"toCharArray",
"(",
")",
";",
"int",
"count",
"=",
"0",
";",
"boolean",
"lastWasWS",
"=",
"true",
";",
"// Avoids leading WS\r",
"f... | Truncates whitespace from the given string.
@todo Candidate for StringUtil? | [
"Truncates",
"whitespace",
"from",
"the",
"given",
"string",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/TrimWhiteSpaceTag.java#L58-L85 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageFilter.java | ImageFilter.createImageServletResponse | private ImageServletResponse createImageServletResponse(final ServletRequest pRequest, final ServletResponse pResponse) {
if (pResponse instanceof ImageServletResponseImpl) {
ImageServletResponseImpl response = (ImageServletResponseImpl) pResponse;
// response.setRequest(pRequest);
return response;
}
return new ImageServletResponseImpl(pRequest, pResponse, getServletContext());
} | java | private ImageServletResponse createImageServletResponse(final ServletRequest pRequest, final ServletResponse pResponse) {
if (pResponse instanceof ImageServletResponseImpl) {
ImageServletResponseImpl response = (ImageServletResponseImpl) pResponse;
// response.setRequest(pRequest);
return response;
}
return new ImageServletResponseImpl(pRequest, pResponse, getServletContext());
} | [
"private",
"ImageServletResponse",
"createImageServletResponse",
"(",
"final",
"ServletRequest",
"pRequest",
",",
"final",
"ServletResponse",
"pResponse",
")",
"{",
"if",
"(",
"pResponse",
"instanceof",
"ImageServletResponseImpl",
")",
"{",
"ImageServletResponseImpl",
"resp... | Creates the image servlet response for this response.
@param pResponse the original response
@param pRequest the original request
@return the new response, or {@code pResponse} if the response is already wrapped
@see com.twelvemonkeys.servlet.image.ImageServletResponseWrapper | [
"Creates",
"the",
"image",
"servlet",
"response",
"for",
"this",
"response",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageFilter.java#L151-L159 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java | RotateFilter.doFilter | protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get angle
double ang = getAngle(pRequest);
// Get bounds
Rectangle2D rect = getBounds(pRequest, pImage, ang);
int width = (int) rect.getWidth();
int height = (int) rect.getHeight();
// Create result image
BufferedImage res = ImageUtil.createTransparent(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = res.createGraphics();
// Get background color and clear
String str = pRequest.getParameter(PARAM_BGCOLOR);
if (!StringUtil.isEmpty(str)) {
Color bgcolor = StringUtil.toColor(str);
g.setBackground(bgcolor);
g.clearRect(0, 0, width, height);
}
// Set mHints (why do I always get jagged edgdes?)
RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
g.setRenderingHints(hints);
// Rotate around center
AffineTransform at = AffineTransform
.getRotateInstance(ang, width / 2.0, height / 2.0);
// Move to center
at.translate(width / 2.0 - pImage.getWidth() / 2.0,
height / 2.0 - pImage.getHeight() / 2.0);
// Draw it, centered
g.drawImage(pImage, at, null);
return res;
} | java | protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get angle
double ang = getAngle(pRequest);
// Get bounds
Rectangle2D rect = getBounds(pRequest, pImage, ang);
int width = (int) rect.getWidth();
int height = (int) rect.getHeight();
// Create result image
BufferedImage res = ImageUtil.createTransparent(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = res.createGraphics();
// Get background color and clear
String str = pRequest.getParameter(PARAM_BGCOLOR);
if (!StringUtil.isEmpty(str)) {
Color bgcolor = StringUtil.toColor(str);
g.setBackground(bgcolor);
g.clearRect(0, 0, width, height);
}
// Set mHints (why do I always get jagged edgdes?)
RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
g.setRenderingHints(hints);
// Rotate around center
AffineTransform at = AffineTransform
.getRotateInstance(ang, width / 2.0, height / 2.0);
// Move to center
at.translate(width / 2.0 - pImage.getWidth() / 2.0,
height / 2.0 - pImage.getHeight() / 2.0);
// Draw it, centered
g.drawImage(pImage, at, null);
return res;
} | [
"protected",
"RenderedImage",
"doFilter",
"(",
"BufferedImage",
"pImage",
",",
"ServletRequest",
"pRequest",
",",
"ImageServletResponse",
"pResponse",
")",
"{",
"// Get angle\r",
"double",
"ang",
"=",
"getAngle",
"(",
"pRequest",
")",
";",
"// Get bounds\r",
"Rectangl... | Reads the image from the requested URL, rotates it, and returns
it in the
Servlet stream. See above for details on parameters. | [
"Reads",
"the",
"image",
"from",
"the",
"requested",
"URL",
"rotates",
"it",
"and",
"returns",
"it",
"in",
"the",
"Servlet",
"stream",
".",
"See",
"above",
"for",
"details",
"on",
"parameters",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java#L106-L147 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java | RotateFilter.getAngle | private double getAngle(ServletRequest pReq) {
double angle = 0.0;
String str = pReq.getParameter(PARAM_ANGLE);
if (!StringUtil.isEmpty(str)) {
angle = Double.parseDouble(str);
// Convert to radians, if needed
str = pReq.getParameter(PARAM_ANGLE_UNITS);
if (!StringUtil.isEmpty(str)
&& ANGLE_DEGREES.equalsIgnoreCase(str)) {
angle = Math.toRadians(angle);
}
}
return angle;
} | java | private double getAngle(ServletRequest pReq) {
double angle = 0.0;
String str = pReq.getParameter(PARAM_ANGLE);
if (!StringUtil.isEmpty(str)) {
angle = Double.parseDouble(str);
// Convert to radians, if needed
str = pReq.getParameter(PARAM_ANGLE_UNITS);
if (!StringUtil.isEmpty(str)
&& ANGLE_DEGREES.equalsIgnoreCase(str)) {
angle = Math.toRadians(angle);
}
}
return angle;
} | [
"private",
"double",
"getAngle",
"(",
"ServletRequest",
"pReq",
")",
"{",
"double",
"angle",
"=",
"0.0",
";",
"String",
"str",
"=",
"pReq",
".",
"getParameter",
"(",
"PARAM_ANGLE",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isEmpty",
"(",
"str",
")",
... | Gets the angle of rotation. | [
"Gets",
"the",
"angle",
"of",
"rotation",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java#L153-L168 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java | RotateFilter.getBounds | private Rectangle2D getBounds(ServletRequest pReq, BufferedImage pImage,
double pAng) {
// Get dimensions of original image
int width = pImage.getWidth(); // loads the image
int height = pImage.getHeight();
// Test if we want to crop image (default)
// if true
// - find the largest bounding box INSIDE the rotated image,
// that matches the original proportions (nearest 90deg)
// (scale up to fit dimensions?)
// else
// - find the smallest bounding box OUTSIDE the rotated image.
// - that matches the original proportions (nearest 90deg) ?
// (scale down to fit dimensions?)
AffineTransform at =
AffineTransform.getRotateInstance(pAng, width / 2.0, height / 2.0);
Rectangle2D orig = new Rectangle(width, height);
Shape rotated = at.createTransformedShape(orig);
if (ServletUtil.getBooleanParameter(pReq, PARAM_CROP, false)) {
// TODO: Inside box
return rotated.getBounds2D();
}
else {
return rotated.getBounds2D();
}
} | java | private Rectangle2D getBounds(ServletRequest pReq, BufferedImage pImage,
double pAng) {
// Get dimensions of original image
int width = pImage.getWidth(); // loads the image
int height = pImage.getHeight();
// Test if we want to crop image (default)
// if true
// - find the largest bounding box INSIDE the rotated image,
// that matches the original proportions (nearest 90deg)
// (scale up to fit dimensions?)
// else
// - find the smallest bounding box OUTSIDE the rotated image.
// - that matches the original proportions (nearest 90deg) ?
// (scale down to fit dimensions?)
AffineTransform at =
AffineTransform.getRotateInstance(pAng, width / 2.0, height / 2.0);
Rectangle2D orig = new Rectangle(width, height);
Shape rotated = at.createTransformedShape(orig);
if (ServletUtil.getBooleanParameter(pReq, PARAM_CROP, false)) {
// TODO: Inside box
return rotated.getBounds2D();
}
else {
return rotated.getBounds2D();
}
} | [
"private",
"Rectangle2D",
"getBounds",
"(",
"ServletRequest",
"pReq",
",",
"BufferedImage",
"pImage",
",",
"double",
"pAng",
")",
"{",
"// Get dimensions of original image\r",
"int",
"width",
"=",
"pImage",
".",
"getWidth",
"(",
")",
";",
"// loads the image\r",
"in... | Get the bounding rectangle of the rotated image. | [
"Get",
"the",
"bounding",
"rectangle",
"of",
"the",
"rotated",
"image",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/RotateFilter.java#L174-L202 | train |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/InverseColorMap.java | InverseColorMap.initIRGB | void initIRGB(int[] pTemp) {
final int x = (1 << TRUNCBITS); // 8 the size of 1 Dimension of each quantized cell
final int xsqr = 1 << (TRUNCBITS * 2); // 64 - twice the smallest step size vale of quantized colors
final int xsqr2 = xsqr + xsqr;
for (int i = 0; i < numColors; ++i) {
if (i == transparentIndex) {
// Skip the transparent pixel
continue;
}
int red, r, rdist, rinc, rxx;
int green, g, gdist, ginc, gxx;
int blue, b, bdist, binc, bxx;
// HaraldK 20040801: Added support for int[]
if (rgbMapByte != null) {
red = rgbMapByte[i * 4] & 0xFF;
green = rgbMapByte[i * 4 + 1] & 0xFF;
blue = rgbMapByte[i * 4 + 2] & 0xFF;
}
else if (rgbMapInt != null) {
red = (rgbMapInt[i] >> 16) & 0xFF;
green = (rgbMapInt[i] >> 8) & 0xFF;
blue = rgbMapInt[i] & 0xFF;
}
else {
throw new IllegalStateException("colormap == null");
}
rdist = red - x / 2; // distance of red to center of current cell
gdist = green - x / 2; // green
bdist = blue - x / 2; // blue
rdist = rdist * rdist + gdist * gdist + bdist * bdist;
rinc = 2 * (xsqr - (red << TRUNCBITS));
ginc = 2 * (xsqr - (green << TRUNCBITS));
binc = 2 * (xsqr - (blue << TRUNCBITS));
int rgbI = 0;
for (r = 0, rxx = rinc; r < MAXQUANTVAL; rdist += rxx, ++r, rxx += xsqr2) {
for (g = 0, gdist = rdist, gxx = ginc; g < MAXQUANTVAL; gdist += gxx, ++g, gxx += xsqr2) {
for (b = 0, bdist = gdist, bxx = binc; b < MAXQUANTVAL; bdist += bxx, ++b, ++rgbI, bxx += xsqr2) {
if (i == 0 || pTemp[rgbI] > bdist) {
pTemp[rgbI] = bdist;
inverseRGB[rgbI] = (byte) i;
}
}
}
}
}
} | java | void initIRGB(int[] pTemp) {
final int x = (1 << TRUNCBITS); // 8 the size of 1 Dimension of each quantized cell
final int xsqr = 1 << (TRUNCBITS * 2); // 64 - twice the smallest step size vale of quantized colors
final int xsqr2 = xsqr + xsqr;
for (int i = 0; i < numColors; ++i) {
if (i == transparentIndex) {
// Skip the transparent pixel
continue;
}
int red, r, rdist, rinc, rxx;
int green, g, gdist, ginc, gxx;
int blue, b, bdist, binc, bxx;
// HaraldK 20040801: Added support for int[]
if (rgbMapByte != null) {
red = rgbMapByte[i * 4] & 0xFF;
green = rgbMapByte[i * 4 + 1] & 0xFF;
blue = rgbMapByte[i * 4 + 2] & 0xFF;
}
else if (rgbMapInt != null) {
red = (rgbMapInt[i] >> 16) & 0xFF;
green = (rgbMapInt[i] >> 8) & 0xFF;
blue = rgbMapInt[i] & 0xFF;
}
else {
throw new IllegalStateException("colormap == null");
}
rdist = red - x / 2; // distance of red to center of current cell
gdist = green - x / 2; // green
bdist = blue - x / 2; // blue
rdist = rdist * rdist + gdist * gdist + bdist * bdist;
rinc = 2 * (xsqr - (red << TRUNCBITS));
ginc = 2 * (xsqr - (green << TRUNCBITS));
binc = 2 * (xsqr - (blue << TRUNCBITS));
int rgbI = 0;
for (r = 0, rxx = rinc; r < MAXQUANTVAL; rdist += rxx, ++r, rxx += xsqr2) {
for (g = 0, gdist = rdist, gxx = ginc; g < MAXQUANTVAL; gdist += gxx, ++g, gxx += xsqr2) {
for (b = 0, bdist = gdist, bxx = binc; b < MAXQUANTVAL; bdist += bxx, ++b, ++rgbI, bxx += xsqr2) {
if (i == 0 || pTemp[rgbI] > bdist) {
pTemp[rgbI] = bdist;
inverseRGB[rgbI] = (byte) i;
}
}
}
}
}
} | [
"void",
"initIRGB",
"(",
"int",
"[",
"]",
"pTemp",
")",
"{",
"final",
"int",
"x",
"=",
"(",
"1",
"<<",
"TRUNCBITS",
")",
";",
"// 8 the size of 1 Dimension of each quantized cell\r",
"final",
"int",
"xsqr",
"=",
"1",
"<<",
"(",
"TRUNCBITS",
"*",
"2",
")",
... | Simple inverse color table creation method.
@param pTemp temp array | [
"Simple",
"inverse",
"color",
"table",
"creation",
"method",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/InverseColorMap.java#L130-L181 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/ReflectUtil.java | ReflectUtil.unwrapType | public static Class unwrapType(Class pType) {
if (pType == Boolean.class) {
return Boolean.TYPE;
}
else if (pType == Byte.class) {
return Byte.TYPE;
}
else if (pType == Character.class) {
return Character.TYPE;
}
else if (pType == Double.class) {
return Double.TYPE;
}
else if (pType == Float.class) {
return Float.TYPE;
}
else if (pType == Integer.class) {
return Integer.TYPE;
}
else if (pType == Long.class) {
return Long.TYPE;
}
else if (pType == Short.class) {
return Short.TYPE;
}
throw new IllegalArgumentException("Not a primitive wrapper: " + pType);
} | java | public static Class unwrapType(Class pType) {
if (pType == Boolean.class) {
return Boolean.TYPE;
}
else if (pType == Byte.class) {
return Byte.TYPE;
}
else if (pType == Character.class) {
return Character.TYPE;
}
else if (pType == Double.class) {
return Double.TYPE;
}
else if (pType == Float.class) {
return Float.TYPE;
}
else if (pType == Integer.class) {
return Integer.TYPE;
}
else if (pType == Long.class) {
return Long.TYPE;
}
else if (pType == Short.class) {
return Short.TYPE;
}
throw new IllegalArgumentException("Not a primitive wrapper: " + pType);
} | [
"public",
"static",
"Class",
"unwrapType",
"(",
"Class",
"pType",
")",
"{",
"if",
"(",
"pType",
"==",
"Boolean",
".",
"class",
")",
"{",
"return",
"Boolean",
".",
"TYPE",
";",
"}",
"else",
"if",
"(",
"pType",
"==",
"Byte",
".",
"class",
")",
"{",
"... | Returns the primitive type for the given wrapper type.
@param pType the wrapper type
@return the primitive type
@throws IllegalArgumentException if {@code pType} is not a primitive
wrapper | [
"Returns",
"the",
"primitive",
"type",
"for",
"the",
"given",
"wrapper",
"type",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/ReflectUtil.java#L57-L84 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java | CompoundDocument.canRead | private static boolean canRead(final DataInput pInput, final boolean pReset) {
long pos = FREE_SID;
if (pReset) {
try {
if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
((InputStream) pInput).mark(8);
}
else if (pInput instanceof ImageInputStream) {
((ImageInputStream) pInput).mark();
}
else if (pInput instanceof RandomAccessFile) {
pos = ((RandomAccessFile) pInput).getFilePointer();
}
else if (pInput instanceof LittleEndianRandomAccessFile) {
pos = ((LittleEndianRandomAccessFile) pInput).getFilePointer();
}
else {
return false;
}
}
catch (IOException ignore) {
return false;
}
}
try {
byte[] magic = new byte[8];
pInput.readFully(magic);
return Arrays.equals(magic, MAGIC);
}
catch (IOException ignore) {
// Ignore
}
finally {
if (pReset) {
try {
if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
((InputStream) pInput).reset();
}
else if (pInput instanceof ImageInputStream) {
((ImageInputStream) pInput).reset();
}
else if (pInput instanceof RandomAccessFile) {
((RandomAccessFile) pInput).seek(pos);
}
else if (pInput instanceof LittleEndianRandomAccessFile) {
((LittleEndianRandomAccessFile) pInput).seek(pos);
}
}
catch (IOException e) {
// TODO: This isn't actually good enough...
// Means something fucked up, and will fail...
e.printStackTrace();
}
}
}
return false;
} | java | private static boolean canRead(final DataInput pInput, final boolean pReset) {
long pos = FREE_SID;
if (pReset) {
try {
if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
((InputStream) pInput).mark(8);
}
else if (pInput instanceof ImageInputStream) {
((ImageInputStream) pInput).mark();
}
else if (pInput instanceof RandomAccessFile) {
pos = ((RandomAccessFile) pInput).getFilePointer();
}
else if (pInput instanceof LittleEndianRandomAccessFile) {
pos = ((LittleEndianRandomAccessFile) pInput).getFilePointer();
}
else {
return false;
}
}
catch (IOException ignore) {
return false;
}
}
try {
byte[] magic = new byte[8];
pInput.readFully(magic);
return Arrays.equals(magic, MAGIC);
}
catch (IOException ignore) {
// Ignore
}
finally {
if (pReset) {
try {
if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
((InputStream) pInput).reset();
}
else if (pInput instanceof ImageInputStream) {
((ImageInputStream) pInput).reset();
}
else if (pInput instanceof RandomAccessFile) {
((RandomAccessFile) pInput).seek(pos);
}
else if (pInput instanceof LittleEndianRandomAccessFile) {
((LittleEndianRandomAccessFile) pInput).seek(pos);
}
}
catch (IOException e) {
// TODO: This isn't actually good enough...
// Means something fucked up, and will fail...
e.printStackTrace();
}
}
}
return false;
} | [
"private",
"static",
"boolean",
"canRead",
"(",
"final",
"DataInput",
"pInput",
",",
"final",
"boolean",
"pReset",
")",
"{",
"long",
"pos",
"=",
"FREE_SID",
";",
"if",
"(",
"pReset",
")",
"{",
"try",
"{",
"if",
"(",
"pInput",
"instanceof",
"InputStream",
... | It's probably safer to create one version for InputStream and one for File | [
"It",
"s",
"probably",
"safer",
"to",
"create",
"one",
"version",
"for",
"InputStream",
"and",
"one",
"for",
"File"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java#L189-L247 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java | CompoundDocument.getSIdChain | private SIdChain getSIdChain(final int pSId, final long pStreamSize) throws IOException {
SIdChain chain = new SIdChain();
int[] sat = isShortStream(pStreamSize) ? shortSAT : SAT;
int sid = pSId;
while (sid != END_OF_CHAIN_SID && sid != FREE_SID) {
chain.addSID(sid);
sid = sat[sid];
}
return chain;
} | java | private SIdChain getSIdChain(final int pSId, final long pStreamSize) throws IOException {
SIdChain chain = new SIdChain();
int[] sat = isShortStream(pStreamSize) ? shortSAT : SAT;
int sid = pSId;
while (sid != END_OF_CHAIN_SID && sid != FREE_SID) {
chain.addSID(sid);
sid = sat[sid];
}
return chain;
} | [
"private",
"SIdChain",
"getSIdChain",
"(",
"final",
"int",
"pSId",
",",
"final",
"long",
"pStreamSize",
")",
"throws",
"IOException",
"{",
"SIdChain",
"chain",
"=",
"new",
"SIdChain",
"(",
")",
";",
"int",
"[",
"]",
"sat",
"=",
"isShortStream",
"(",
"pStre... | Gets the SIdChain for the given stream Id
@param pSId the stream Id
@param pStreamSize the size of the stream, or -1 for system control streams
@return the SIdChain for the given stream Id
@throws IOException if an I/O exception occurs | [
"Gets",
"the",
"SIdChain",
"for",
"the",
"given",
"stream",
"Id"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java#L414-L426 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java | CompoundDocument.seekToSId | private void seekToSId(final int pSId, final long pStreamSize) throws IOException {
long pos;
if (isShortStream(pStreamSize)) {
// The short stream is not continuous...
Entry root = getRootEntry();
if (shortStreamSIdChain == null) {
shortStreamSIdChain = getSIdChain(root.startSId, root.streamSize);
}
// System.err.println("pSId: " + pSId);
int shortPerSId = sectorSize / shortSectorSize;
// System.err.println("shortPerSId: " + shortPerSId);
int offset = pSId / shortPerSId;
// System.err.println("offset: " + offset);
int shortOffset = pSId - (offset * shortPerSId);
// System.err.println("shortOffset: " + shortOffset);
// System.err.println("shortStreamSIdChain.offset: " + shortStreamSIdChain.get(offset));
pos = HEADER_SIZE
+ (shortStreamSIdChain.get(offset) * (long) sectorSize)
+ (shortOffset * (long) shortSectorSize);
// System.err.println("pos: " + pos);
}
else {
pos = HEADER_SIZE + pSId * (long) sectorSize;
}
if (input instanceof LittleEndianRandomAccessFile) {
((LittleEndianRandomAccessFile) input).seek(pos);
}
else if (input instanceof ImageInputStream) {
((ImageInputStream) input).seek(pos);
}
else {
((SeekableLittleEndianDataInputStream) input).seek(pos);
}
} | java | private void seekToSId(final int pSId, final long pStreamSize) throws IOException {
long pos;
if (isShortStream(pStreamSize)) {
// The short stream is not continuous...
Entry root = getRootEntry();
if (shortStreamSIdChain == null) {
shortStreamSIdChain = getSIdChain(root.startSId, root.streamSize);
}
// System.err.println("pSId: " + pSId);
int shortPerSId = sectorSize / shortSectorSize;
// System.err.println("shortPerSId: " + shortPerSId);
int offset = pSId / shortPerSId;
// System.err.println("offset: " + offset);
int shortOffset = pSId - (offset * shortPerSId);
// System.err.println("shortOffset: " + shortOffset);
// System.err.println("shortStreamSIdChain.offset: " + shortStreamSIdChain.get(offset));
pos = HEADER_SIZE
+ (shortStreamSIdChain.get(offset) * (long) sectorSize)
+ (shortOffset * (long) shortSectorSize);
// System.err.println("pos: " + pos);
}
else {
pos = HEADER_SIZE + pSId * (long) sectorSize;
}
if (input instanceof LittleEndianRandomAccessFile) {
((LittleEndianRandomAccessFile) input).seek(pos);
}
else if (input instanceof ImageInputStream) {
((ImageInputStream) input).seek(pos);
}
else {
((SeekableLittleEndianDataInputStream) input).seek(pos);
}
} | [
"private",
"void",
"seekToSId",
"(",
"final",
"int",
"pSId",
",",
"final",
"long",
"pStreamSize",
")",
"throws",
"IOException",
"{",
"long",
"pos",
";",
"if",
"(",
"isShortStream",
"(",
"pStreamSize",
")",
")",
"{",
"// The short stream is not continuous...\r",
... | Seeks to the start pos for the given stream Id
@param pSId the stream Id
@param pStreamSize the size of the stream, or -1 for system control streams
@throws IOException if an I/O exception occurs | [
"Seeks",
"to",
"the",
"start",
"pos",
"for",
"the",
"given",
"stream",
"Id"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/CompoundDocument.java#L439-L476 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java | XMLProperties.initPropertyValue | protected Object initPropertyValue(String pValue, String pType, String pFormat) throws ClassNotFoundException {
// System.out.println("pValue=" + pValue + " pType=" + pType
// + " pFormat=" + pFormat);
// No value to convert
if (pValue == null) {
return null;
}
// No conversion needed for Strings
if ((pType == null) || pType.equals("String") || pType.equals("java.lang.String")) {
return pValue;
}
Object value;
if (pType.equals("Date") || pType.equals("java.util.Date")) {
// Special parser needed
try {
// Parse date through StringUtil
if (pFormat == null) {
value = StringUtil.toDate(pValue, sDefaultFormat);
} else {
value = StringUtil.toDate(pValue, new SimpleDateFormat(pFormat));
}
} catch (IllegalArgumentException e) {
// Not parseable...
throw e;
}
// Return
return value;
} else if (pType.equals("java.sql.Timestamp")) {
// Special parser needed
try {
// Parse timestamp through StringUtil
value = StringUtil.toTimestamp(pValue);
} catch (IllegalArgumentException e) {
// Not parseable...
throw new RuntimeException(e.getMessage());
}
// Return
return value;
} else {
int dot = pType.indexOf(".");
if (dot < 0) {
pType = "java.lang." + pType;
}
// Get class
Class cl = Class.forName(pType);
// Try to create instance from <Constructor>(String)
value = createInstance(cl, pValue);
if (value == null) {
// createInstance failed for some reason
// Try to invoke the static method valueof(String)
value = invokeStaticMethod(cl, "valueOf", pValue);
// If the value is still null, well, then I cannot help...
}
}
// Return
return value;
} | java | protected Object initPropertyValue(String pValue, String pType, String pFormat) throws ClassNotFoundException {
// System.out.println("pValue=" + pValue + " pType=" + pType
// + " pFormat=" + pFormat);
// No value to convert
if (pValue == null) {
return null;
}
// No conversion needed for Strings
if ((pType == null) || pType.equals("String") || pType.equals("java.lang.String")) {
return pValue;
}
Object value;
if (pType.equals("Date") || pType.equals("java.util.Date")) {
// Special parser needed
try {
// Parse date through StringUtil
if (pFormat == null) {
value = StringUtil.toDate(pValue, sDefaultFormat);
} else {
value = StringUtil.toDate(pValue, new SimpleDateFormat(pFormat));
}
} catch (IllegalArgumentException e) {
// Not parseable...
throw e;
}
// Return
return value;
} else if (pType.equals("java.sql.Timestamp")) {
// Special parser needed
try {
// Parse timestamp through StringUtil
value = StringUtil.toTimestamp(pValue);
} catch (IllegalArgumentException e) {
// Not parseable...
throw new RuntimeException(e.getMessage());
}
// Return
return value;
} else {
int dot = pType.indexOf(".");
if (dot < 0) {
pType = "java.lang." + pType;
}
// Get class
Class cl = Class.forName(pType);
// Try to create instance from <Constructor>(String)
value = createInstance(cl, pValue);
if (value == null) {
// createInstance failed for some reason
// Try to invoke the static method valueof(String)
value = invokeStaticMethod(cl, "valueOf", pValue);
// If the value is still null, well, then I cannot help...
}
}
// Return
return value;
} | [
"protected",
"Object",
"initPropertyValue",
"(",
"String",
"pValue",
",",
"String",
"pType",
",",
"String",
"pFormat",
")",
"throws",
"ClassNotFoundException",
"{",
"// System.out.println(\"pValue=\" + pValue + \" pType=\" + pType\r",
"// + \" pFormat=\" + pFormat);... | Initializes the value of a property.
@todo move init code to the parser?
@throws ClassNotFoundException if there is no class found for the given
type
@throws IllegalArgumentException if the value given, is not parseable
as the given type | [
"Initializes",
"the",
"value",
"of",
"a",
"property",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L331-L404 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java | XMLProperties.createInstance | private Object createInstance(Class pClass, Object pParam) {
Object value;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get constructor
Constructor constructor = pClass.getDeclaredConstructor(param);
// Invoke and create instance
value = constructor.newInstance(arg);
} catch (Exception e) {
return null;
}
return value;
} | java | private Object createInstance(Class pClass, Object pParam) {
Object value;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get constructor
Constructor constructor = pClass.getDeclaredConstructor(param);
// Invoke and create instance
value = constructor.newInstance(arg);
} catch (Exception e) {
return null;
}
return value;
} | [
"private",
"Object",
"createInstance",
"(",
"Class",
"pClass",
",",
"Object",
"pParam",
")",
"{",
"Object",
"value",
";",
"try",
"{",
"// Create param and argument arrays\r",
"Class",
"[",
"]",
"param",
"=",
"{",
"pParam",
".",
"getClass",
"(",
")",
"}",
";"... | Creates an object from the given class' single argument constructor.
@return The object created from the constructor.
If the constructor could not be invoked for any reason, null is
returned. | [
"Creates",
"an",
"object",
"from",
"the",
"given",
"class",
"single",
"argument",
"constructor",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L413-L431 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java | XMLProperties.invokeStaticMethod | private Object invokeStaticMethod(Class pClass, String pMethod, Object pParam) {
Object value = null;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get method
// *** If more than one such method is found in the class, and one
// of these methods has a RETURN TYPE that is more specific than
// any of the others, that method is reflected; otherwise one of
// the methods is chosen ARBITRARILY.
// java/lang/Class.html#getMethod(java.lang.String, java.lang.Class[])
java.lang.reflect.Method method = pClass.getMethod(pMethod, param);
// Invoke public static method
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) {
value = method.invoke(null, arg);
}
} catch (Exception e) {
return null;
}
return value;
} | java | private Object invokeStaticMethod(Class pClass, String pMethod, Object pParam) {
Object value = null;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get method
// *** If more than one such method is found in the class, and one
// of these methods has a RETURN TYPE that is more specific than
// any of the others, that method is reflected; otherwise one of
// the methods is chosen ARBITRARILY.
// java/lang/Class.html#getMethod(java.lang.String, java.lang.Class[])
java.lang.reflect.Method method = pClass.getMethod(pMethod, param);
// Invoke public static method
if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) {
value = method.invoke(null, arg);
}
} catch (Exception e) {
return null;
}
return value;
} | [
"private",
"Object",
"invokeStaticMethod",
"(",
"Class",
"pClass",
",",
"String",
"pMethod",
",",
"Object",
"pParam",
")",
"{",
"Object",
"value",
"=",
"null",
";",
"try",
"{",
"// Create param and argument arrays\r",
"Class",
"[",
"]",
"param",
"=",
"{",
"pPa... | Creates an object from any given static method, given the parameter
@return The object returned by the static method.
If the return type of the method is a primitive type, it is wrapped in
the corresponding wrapper object (int is wrapped in an Integer).
If the return type of the method is void, null is returned.
If the method could not be invoked for any reason, null is returned. | [
"Creates",
"an",
"object",
"from",
"any",
"given",
"static",
"method",
"given",
"the",
"parameter"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L442-L467 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java | XMLProperties.setPropertyFormat | public synchronized String setPropertyFormat(String pKey, String pFormat) {
// Insert format
return StringUtil.valueOf(mFormats.put(pKey, pFormat));
} | java | public synchronized String setPropertyFormat(String pKey, String pFormat) {
// Insert format
return StringUtil.valueOf(mFormats.put(pKey, pFormat));
} | [
"public",
"synchronized",
"String",
"setPropertyFormat",
"(",
"String",
"pKey",
",",
"String",
"pFormat",
")",
"{",
"// Insert format\r",
"return",
"StringUtil",
".",
"valueOf",
"(",
"mFormats",
".",
"put",
"(",
"pKey",
",",
"pFormat",
")",
")",
";",
"}"
] | Sets the format of a property. This value is used for formatting the
value before it is stored as xml.
@param pKey a key in this hashtable.
@param pFormat a string representation of the format.
@return the previous format for the specified key or null if it did not
have one. | [
"Sets",
"the",
"format",
"of",
"a",
"property",
".",
"This",
"value",
"is",
"used",
"for",
"formatting",
"the",
"value",
"before",
"it",
"is",
"stored",
"as",
"xml",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L494-L498 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java | XMLProperties.insertElement | private static void insertElement(Document pDocument, String pName, Object pValue, String pFormat) {
// Get names of all elements we need
String[] names = StringUtil.toStringArray(pName, ".");
// Get value formatted as string
String value = null;
if (pValue != null) {
// ---
if (pValue instanceof Date) {
// Special threatment of Date
if (pFormat != null) {
value = new SimpleDateFormat(pFormat).format(pValue);
}
else {
value = sDefaultFormat.format(pValue);
}
}
else {
value = String.valueOf(pValue);
}
// ---
}
// Loop through document from root, and insert parents as needed
Element element = pDocument.getDocumentElement();
for (int i = 0; i < names.length; i++) {
boolean found = false;
// Get children
NodeList children = element.getElementsByTagName(PROPERTY);
Element child = null;
// Search for correct name
for (int j = 0; j < children.getLength(); j++) {
child = (Element) children.item(j);
if (names[i].equals(child.getAttribute(PROPERTY_NAME))) {
// Found
found = true;
element = child;
break; // Next name
}
}
// Test if the node was not found, otherwise we need to insert
if (!found) {
// Not found
child = pDocument.createElement(PROPERTY);
child.setAttribute(PROPERTY_NAME, names[i]);
// Insert it
element.appendChild(child);
element = child;
}
// If it's the destination node, set the value
if ((i + 1) == names.length) {
// If the value string contains special data,
// use a CDATA block instead of the "value" attribute
if (StringUtil.contains(value, "\n") || StringUtil.contains(value, "\t") || StringUtil.contains(value, "\"")
|| StringUtil.contains(value, "&") || StringUtil.contains(value, "<") || StringUtil.contains(value, ">")) {
// Create value element
Element valueElement = pDocument.createElement(PROPERTY_VALUE);
// Set type attribute
String className = pValue.getClass().getName();
className = StringUtil.replace(className, "java.lang.", "");
if (!DEFAULT_TYPE.equals(className)) {
valueElement.setAttribute(PROPERTY_TYPE, className);
}
// Set format attribute
if (pFormat != null) {
valueElement.setAttribute(PROPERTY_FORMAT, pFormat);
}
// Crate cdata section
CDATASection cdata = pDocument.createCDATASection(value);
// Append to document tree
valueElement.appendChild(cdata);
child.appendChild(valueElement);
}
else {
// Just set normal attribute value
child.setAttribute(PROPERTY_VALUE, value);
// Set type attribute
String className = pValue.getClass().getName();
className = StringUtil.replace(className, "java.lang.", "");
if (!DEFAULT_TYPE.equals(className)) {
child.setAttribute(PROPERTY_TYPE, className);
}
// If format is set, store in attribute
if (pFormat != null) {
child.setAttribute(PROPERTY_FORMAT, pFormat);
}
}
}
}
} | java | private static void insertElement(Document pDocument, String pName, Object pValue, String pFormat) {
// Get names of all elements we need
String[] names = StringUtil.toStringArray(pName, ".");
// Get value formatted as string
String value = null;
if (pValue != null) {
// ---
if (pValue instanceof Date) {
// Special threatment of Date
if (pFormat != null) {
value = new SimpleDateFormat(pFormat).format(pValue);
}
else {
value = sDefaultFormat.format(pValue);
}
}
else {
value = String.valueOf(pValue);
}
// ---
}
// Loop through document from root, and insert parents as needed
Element element = pDocument.getDocumentElement();
for (int i = 0; i < names.length; i++) {
boolean found = false;
// Get children
NodeList children = element.getElementsByTagName(PROPERTY);
Element child = null;
// Search for correct name
for (int j = 0; j < children.getLength(); j++) {
child = (Element) children.item(j);
if (names[i].equals(child.getAttribute(PROPERTY_NAME))) {
// Found
found = true;
element = child;
break; // Next name
}
}
// Test if the node was not found, otherwise we need to insert
if (!found) {
// Not found
child = pDocument.createElement(PROPERTY);
child.setAttribute(PROPERTY_NAME, names[i]);
// Insert it
element.appendChild(child);
element = child;
}
// If it's the destination node, set the value
if ((i + 1) == names.length) {
// If the value string contains special data,
// use a CDATA block instead of the "value" attribute
if (StringUtil.contains(value, "\n") || StringUtil.contains(value, "\t") || StringUtil.contains(value, "\"")
|| StringUtil.contains(value, "&") || StringUtil.contains(value, "<") || StringUtil.contains(value, ">")) {
// Create value element
Element valueElement = pDocument.createElement(PROPERTY_VALUE);
// Set type attribute
String className = pValue.getClass().getName();
className = StringUtil.replace(className, "java.lang.", "");
if (!DEFAULT_TYPE.equals(className)) {
valueElement.setAttribute(PROPERTY_TYPE, className);
}
// Set format attribute
if (pFormat != null) {
valueElement.setAttribute(PROPERTY_FORMAT, pFormat);
}
// Crate cdata section
CDATASection cdata = pDocument.createCDATASection(value);
// Append to document tree
valueElement.appendChild(cdata);
child.appendChild(valueElement);
}
else {
// Just set normal attribute value
child.setAttribute(PROPERTY_VALUE, value);
// Set type attribute
String className = pValue.getClass().getName();
className = StringUtil.replace(className, "java.lang.", "");
if (!DEFAULT_TYPE.equals(className)) {
child.setAttribute(PROPERTY_TYPE, className);
}
// If format is set, store in attribute
if (pFormat != null) {
child.setAttribute(PROPERTY_FORMAT, pFormat);
}
}
}
}
} | [
"private",
"static",
"void",
"insertElement",
"(",
"Document",
"pDocument",
",",
"String",
"pName",
",",
"Object",
"pValue",
",",
"String",
"pFormat",
")",
"{",
"// Get names of all elements we need\r",
"String",
"[",
"]",
"names",
"=",
"StringUtil",
".",
"toStrin... | Inserts elements to the given document one by one, and creates all its
parents if needed.
@param pDocument the document to insert to.
@param pName the name of the property element.
@param pValue the value of the property element.
@param pFormat
@todo I guess this implementation could use some optimisaztion, as
we do a lot of unneccessary looping. | [
"Inserts",
"elements",
"to",
"the",
"given",
"document",
"one",
"by",
"one",
"and",
"creates",
"all",
"its",
"parents",
"if",
"needed",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/XMLProperties.java#L791-L900 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java | XMLTransformTag.doEndTag | public int doEndTag() throws JspException {
// Get body content (trim is CRUCIAL, as some XML parsers are picky...)
String body = bodyContent.getString().trim();
// Do transformation
transform(new StreamSource(new ByteArrayInputStream(body.getBytes())));
return super.doEndTag();
} | java | public int doEndTag() throws JspException {
// Get body content (trim is CRUCIAL, as some XML parsers are picky...)
String body = bodyContent.getString().trim();
// Do transformation
transform(new StreamSource(new ByteArrayInputStream(body.getBytes())));
return super.doEndTag();
} | [
"public",
"int",
"doEndTag",
"(",
")",
"throws",
"JspException",
"{",
"// Get body content (trim is CRUCIAL, as some XML parsers are picky...)\r",
"String",
"body",
"=",
"bodyContent",
".",
"getString",
"(",
")",
".",
"trim",
"(",
")",
";",
"// Do transformation\r",
"tr... | doEndTag implementation, that will perform XML Transformation on the
body content.
@return super.doEndTag() | [
"doEndTag",
"implementation",
"that",
"will",
"perform",
"XML",
"Transformation",
"on",
"the",
"body",
"content",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java#L99-L107 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java | XMLTransformTag.transform | public void transform(Source pIn) throws JspException {
try {
// Create transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(getSource(mStylesheetURI));
// Store temporary output in a bytearray, as the transformer will
// usually try to flush the stream (illegal operation from a custom
// tag).
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult out = new StreamResult(os);
// Perform the transformation
transformer.transform(pIn, out);
// Write the result back to the JSP writer
pageContext.getOut().print(os.toString());
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
catch (TransformerException te) {
throw new JspException("XSLT Trandformation failed: " + te.getMessage(), te);
}
} | java | public void transform(Source pIn) throws JspException {
try {
// Create transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(getSource(mStylesheetURI));
// Store temporary output in a bytearray, as the transformer will
// usually try to flush the stream (illegal operation from a custom
// tag).
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult out = new StreamResult(os);
// Perform the transformation
transformer.transform(pIn, out);
// Write the result back to the JSP writer
pageContext.getOut().print(os.toString());
}
catch (MalformedURLException murle) {
throw new JspException(murle.getMessage(), murle);
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage(), ioe);
}
catch (TransformerException te) {
throw new JspException("XSLT Trandformation failed: " + te.getMessage(), te);
}
} | [
"public",
"void",
"transform",
"(",
"Source",
"pIn",
")",
"throws",
"JspException",
"{",
"try",
"{",
"// Create transformer\r",
"Transformer",
"transformer",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
".",
"newTransformer",
"(",
"getSource",
"(",
"mS... | Performs the transformation and writes the result to the JSP writer.
@param in the source document to transform. | [
"Performs",
"the",
"transformation",
"and",
"writes",
"the",
"result",
"to",
"the",
"JSP",
"writer",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java#L115-L142 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java | XMLTransformTag.getSource | private StreamSource getSource(String pURI)
throws IOException, MalformedURLException {
if (pURI != null && pURI.indexOf("://") < 0) {
// If local, get as stream
return new StreamSource(getResourceAsStream(pURI));
}
// ...else, create from URI string
return new StreamSource(pURI);
} | java | private StreamSource getSource(String pURI)
throws IOException, MalformedURLException {
if (pURI != null && pURI.indexOf("://") < 0) {
// If local, get as stream
return new StreamSource(getResourceAsStream(pURI));
}
// ...else, create from URI string
return new StreamSource(pURI);
} | [
"private",
"StreamSource",
"getSource",
"(",
"String",
"pURI",
")",
"throws",
"IOException",
",",
"MalformedURLException",
"{",
"if",
"(",
"pURI",
"!=",
"null",
"&&",
"pURI",
".",
"indexOf",
"(",
"\"://\"",
")",
"<",
"0",
")",
"{",
"// If local, get as stream\... | Returns a StreamSource object, for the given URI | [
"Returns",
"a",
"StreamSource",
"object",
"for",
"the",
"given",
"URI"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/jsp/taglib/XMLTransformTag.java#L148-L157 | train |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java | IndexImage.createSolid | private static BufferedImage createSolid(BufferedImage pOriginal, Color pBackground) {
// Create a temporary image of same dimension and type
BufferedImage solid = new BufferedImage(pOriginal.getColorModel(), pOriginal.copyData(null), pOriginal.isAlphaPremultiplied(), null);
Graphics2D g = solid.createGraphics();
try {
// Clear in background color
g.setColor(pBackground);
g.setComposite(AlphaComposite.DstOver);// Paint "underneath"
g.fillRect(0, 0, pOriginal.getWidth(), pOriginal.getHeight());
}
finally {
g.dispose();
}
return solid;
} | java | private static BufferedImage createSolid(BufferedImage pOriginal, Color pBackground) {
// Create a temporary image of same dimension and type
BufferedImage solid = new BufferedImage(pOriginal.getColorModel(), pOriginal.copyData(null), pOriginal.isAlphaPremultiplied(), null);
Graphics2D g = solid.createGraphics();
try {
// Clear in background color
g.setColor(pBackground);
g.setComposite(AlphaComposite.DstOver);// Paint "underneath"
g.fillRect(0, 0, pOriginal.getWidth(), pOriginal.getHeight());
}
finally {
g.dispose();
}
return solid;
} | [
"private",
"static",
"BufferedImage",
"createSolid",
"(",
"BufferedImage",
"pOriginal",
",",
"Color",
"pBackground",
")",
"{",
"// Create a temporary image of same dimension and type\r",
"BufferedImage",
"solid",
"=",
"new",
"BufferedImage",
"(",
"pOriginal",
".",
"getColor... | Creates a copy of the given image, with a solid background
@param pOriginal the original image
@param pBackground the background color
@return a new {@code BufferedImage} | [
"Creates",
"a",
"copy",
"of",
"the",
"given",
"image",
"with",
"a",
"solid",
"background"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1164-L1180 | train |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java | IndexImage.applyAlpha | private static void applyAlpha(BufferedImage pImage, BufferedImage pAlpha) {
// Apply alpha as transparency, using threshold of 25%
for (int y = 0; y < pAlpha.getHeight(); y++) {
for (int x = 0; x < pAlpha.getWidth(); x++) {
// Get alpha component of pixel, if less than 25% opaque
// (0x40 = 64 => 25% of 256), the pixel will be transparent
if (((pAlpha.getRGB(x, y) >> 24) & 0xFF) < 0x40) {
pImage.setRGB(x, y, 0x00FFFFFF); // 100% transparent
}
}
}
} | java | private static void applyAlpha(BufferedImage pImage, BufferedImage pAlpha) {
// Apply alpha as transparency, using threshold of 25%
for (int y = 0; y < pAlpha.getHeight(); y++) {
for (int x = 0; x < pAlpha.getWidth(); x++) {
// Get alpha component of pixel, if less than 25% opaque
// (0x40 = 64 => 25% of 256), the pixel will be transparent
if (((pAlpha.getRGB(x, y) >> 24) & 0xFF) < 0x40) {
pImage.setRGB(x, y, 0x00FFFFFF); // 100% transparent
}
}
}
} | [
"private",
"static",
"void",
"applyAlpha",
"(",
"BufferedImage",
"pImage",
",",
"BufferedImage",
"pAlpha",
")",
"{",
"// Apply alpha as transparency, using threshold of 25%\r",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"pAlpha",
".",
"getHeight",
"(",
")",
... | Applies the alpha-component of the alpha image to the given image.
The given image is modified in place.
@param pImage the image to apply alpha to
@param pAlpha the image containing the alpha | [
"Applies",
"the",
"alpha",
"-",
"component",
"of",
"the",
"alpha",
"image",
"to",
"the",
"given",
"image",
".",
"The",
"given",
"image",
"is",
"modified",
"in",
"place",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1189-L1201 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/FastByteArrayOutputStream.java | FastByteArrayOutputStream.toByteArray | @Override
public byte[] toByteArray() {
byte newBuf[] = new byte[count];
System.arraycopy(buf, 0, newBuf, 0, count);
return newBuf;
} | java | @Override
public byte[] toByteArray() {
byte newBuf[] = new byte[count];
System.arraycopy(buf, 0, newBuf, 0, count);
return newBuf;
} | [
"@",
"Override",
"public",
"byte",
"[",
"]",
"toByteArray",
"(",
")",
"{",
"byte",
"newBuf",
"[",
"]",
"=",
"new",
"byte",
"[",
"count",
"]",
";",
"System",
".",
"arraycopy",
"(",
"buf",
",",
"0",
",",
"newBuf",
",",
"0",
",",
"count",
")",
";",
... | Non-synchronized version of toByteArray | [
"Non",
"-",
"synchronized",
"version",
"of",
"toByteArray"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/FastByteArrayOutputStream.java#L114-L120 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java | CachedResponseImpl.writeHeadersTo | public void writeHeadersTo(final CacheResponse pResponse) {
String[] headers = getHeaderNames();
for (String header : headers) {
// HACK...
// Strip away internal headers
if (HTTPCache.HEADER_CACHED_TIME.equals(header)) {
continue;
}
// TODO: Replace Last-Modified with X-Cached-At? See CachedEntityImpl
String[] headerValues = getHeaderValues(header);
for (int i = 0; i < headerValues.length; i++) {
String headerValue = headerValues[i];
if (i == 0) {
pResponse.setHeader(header, headerValue);
}
else {
pResponse.addHeader(header, headerValue);
}
}
}
} | java | public void writeHeadersTo(final CacheResponse pResponse) {
String[] headers = getHeaderNames();
for (String header : headers) {
// HACK...
// Strip away internal headers
if (HTTPCache.HEADER_CACHED_TIME.equals(header)) {
continue;
}
// TODO: Replace Last-Modified with X-Cached-At? See CachedEntityImpl
String[] headerValues = getHeaderValues(header);
for (int i = 0; i < headerValues.length; i++) {
String headerValue = headerValues[i];
if (i == 0) {
pResponse.setHeader(header, headerValue);
}
else {
pResponse.addHeader(header, headerValue);
}
}
}
} | [
"public",
"void",
"writeHeadersTo",
"(",
"final",
"CacheResponse",
"pResponse",
")",
"{",
"String",
"[",
"]",
"headers",
"=",
"getHeaderNames",
"(",
")",
";",
"for",
"(",
"String",
"header",
":",
"headers",
")",
"{",
"// HACK...\r",
"// Strip away internal heade... | Writes the cached headers to the response
@param pResponse the response | [
"Writes",
"the",
"cached",
"headers",
"to",
"the",
"response"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java#L74-L98 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java | CachedResponseImpl.writeContentsTo | public void writeContentsTo(final OutputStream pStream) throws IOException {
if (content == null) {
throw new IOException("Cache is null, no content to write.");
}
content.writeTo(pStream);
} | java | public void writeContentsTo(final OutputStream pStream) throws IOException {
if (content == null) {
throw new IOException("Cache is null, no content to write.");
}
content.writeTo(pStream);
} | [
"public",
"void",
"writeContentsTo",
"(",
"final",
"OutputStream",
"pStream",
")",
"throws",
"IOException",
"{",
"if",
"(",
"content",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Cache is null, no content to write.\"",
")",
";",
"}",
"content",
... | Writes the cached content to the response
@param pStream the response stream
@throws java.io.IOException | [
"Writes",
"the",
"cached",
"content",
"to",
"the",
"response"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java#L106-L112 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java | CachedResponseImpl.getHeaderNames | public String[] getHeaderNames() {
Set<String> headers = this.headers.keySet();
return headers.toArray(new String[headers.size()]);
} | java | public String[] getHeaderNames() {
Set<String> headers = this.headers.keySet();
return headers.toArray(new String[headers.size()]);
} | [
"public",
"String",
"[",
"]",
"getHeaderNames",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"headers",
"=",
"this",
".",
"headers",
".",
"keySet",
"(",
")",
";",
"return",
"headers",
".",
"toArray",
"(",
"new",
"String",
"[",
"headers",
".",
"size",
"(... | Gets the header names of all headers set in this response.
@return an array of {@code String}s | [
"Gets",
"the",
"header",
"names",
"of",
"all",
"headers",
"set",
"in",
"this",
"response",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/cache/CachedResponseImpl.java#L119-L123 | train |
haraldk/TwelveMonkeys | imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/AdobePathBuilder.java | AdobePathBuilder.path | public Path2D path() throws IOException {
List<List<AdobePathSegment>> subPaths = new ArrayList<List<AdobePathSegment>>();
List<AdobePathSegment> currentPath = null;
int currentPathLength = 0;
AdobePathSegment segment;
while ((segment = nextSegment()) != null) {
if (DEBUG) {
System.out.println(segment);
}
if (segment.selector == AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD || segment.selector == AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD) {
if (currentPath != null) {
if (currentPathLength != currentPath.size()) {
throw new IIOException(String.format("Bad path, expected %d segments, found only %d", currentPathLength, currentPath.size()));
}
subPaths.add(currentPath);
}
currentPath = new ArrayList<AdobePathSegment>(segment.length);
currentPathLength = segment.length;
}
else if (segment.selector == AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED
|| segment.selector == AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED
|| segment.selector == AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED
|| segment.selector == AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED) {
if (currentPath == null) {
throw new IIOException("Bad path, missing subpath length record");
}
if (currentPath.size() >= currentPathLength) {
throw new IIOException(String.format("Bad path, expected %d segments, found%d", currentPathLength, currentPath.size()));
}
currentPath.add(segment);
}
}
// now add the last one
if (currentPath != null) {
if (currentPathLength != currentPath.size()) {
throw new IIOException(String.format("Bad path, expected %d segments, found only %d", currentPathLength, currentPath.size()));
}
subPaths.add(currentPath);
}
// now we have collected the PathPoints now create a Shape.
return pathToShape(subPaths);
} | java | public Path2D path() throws IOException {
List<List<AdobePathSegment>> subPaths = new ArrayList<List<AdobePathSegment>>();
List<AdobePathSegment> currentPath = null;
int currentPathLength = 0;
AdobePathSegment segment;
while ((segment = nextSegment()) != null) {
if (DEBUG) {
System.out.println(segment);
}
if (segment.selector == AdobePathSegment.OPEN_SUBPATH_LENGTH_RECORD || segment.selector == AdobePathSegment.CLOSED_SUBPATH_LENGTH_RECORD) {
if (currentPath != null) {
if (currentPathLength != currentPath.size()) {
throw new IIOException(String.format("Bad path, expected %d segments, found only %d", currentPathLength, currentPath.size()));
}
subPaths.add(currentPath);
}
currentPath = new ArrayList<AdobePathSegment>(segment.length);
currentPathLength = segment.length;
}
else if (segment.selector == AdobePathSegment.OPEN_SUBPATH_BEZIER_LINKED
|| segment.selector == AdobePathSegment.OPEN_SUBPATH_BEZIER_UNLINKED
|| segment.selector == AdobePathSegment.CLOSED_SUBPATH_BEZIER_LINKED
|| segment.selector == AdobePathSegment.CLOSED_SUBPATH_BEZIER_UNLINKED) {
if (currentPath == null) {
throw new IIOException("Bad path, missing subpath length record");
}
if (currentPath.size() >= currentPathLength) {
throw new IIOException(String.format("Bad path, expected %d segments, found%d", currentPathLength, currentPath.size()));
}
currentPath.add(segment);
}
}
// now add the last one
if (currentPath != null) {
if (currentPathLength != currentPath.size()) {
throw new IIOException(String.format("Bad path, expected %d segments, found only %d", currentPathLength, currentPath.size()));
}
subPaths.add(currentPath);
}
// now we have collected the PathPoints now create a Shape.
return pathToShape(subPaths);
} | [
"public",
"Path2D",
"path",
"(",
")",
"throws",
"IOException",
"{",
"List",
"<",
"List",
"<",
"AdobePathSegment",
">>",
"subPaths",
"=",
"new",
"ArrayList",
"<",
"List",
"<",
"AdobePathSegment",
">",
">",
"(",
")",
";",
"List",
"<",
"AdobePathSegment",
">"... | Builds the path.
@return the path
@throws javax.imageio.IIOException if the input contains a bad path data.
@throws IOException if a general I/O exception occurs during reading. | [
"Builds",
"the",
"path",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/AdobePathBuilder.java#L93-L142 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/image/TextRenderer.java | TextRenderer.getFontStyle | private int getFontStyle(String pStyle) {
if (pStyle == null || StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_PLAIN)) {
return Font.PLAIN;
}
// Try to find bold/italic
int style = Font.PLAIN;
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_BOLD)) {
style |= Font.BOLD;
}
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_ITALIC)) {
style |= Font.ITALIC;
}
return style;
} | java | private int getFontStyle(String pStyle) {
if (pStyle == null || StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_PLAIN)) {
return Font.PLAIN;
}
// Try to find bold/italic
int style = Font.PLAIN;
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_BOLD)) {
style |= Font.BOLD;
}
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_ITALIC)) {
style |= Font.ITALIC;
}
return style;
} | [
"private",
"int",
"getFontStyle",
"(",
"String",
"pStyle",
")",
"{",
"if",
"(",
"pStyle",
"==",
"null",
"||",
"StringUtil",
".",
"containsIgnoreCase",
"(",
"pStyle",
",",
"FONT_STYLE_PLAIN",
")",
")",
"{",
"return",
"Font",
".",
"PLAIN",
";",
"}",
"// Try ... | Returns the font style constant.
@param pStyle a string containing either the word {@code "plain"} or one
or more of {@code "bold"} and {@code italic}.
@return the font style constant as defined in {@link Font}.
@see Font#PLAIN
@see Font#BOLD
@see Font#ITALIC | [
"Returns",
"the",
"font",
"style",
"constant",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/image/TextRenderer.java#L301-L316 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/image/TextRenderer.java | TextRenderer.getAngle | private double getAngle(ServletRequest pRequest) {
// Get angle
double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0);
// Convert to radians, if needed
String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS);
if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) {
angle = Math.toRadians(angle);
}
return angle;
} | java | private double getAngle(ServletRequest pRequest) {
// Get angle
double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0);
// Convert to radians, if needed
String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS);
if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) {
angle = Math.toRadians(angle);
}
return angle;
} | [
"private",
"double",
"getAngle",
"(",
"ServletRequest",
"pRequest",
")",
"{",
"// Get angle\r",
"double",
"angle",
"=",
"ServletUtil",
".",
"getDoubleParameter",
"(",
"pRequest",
",",
"PARAM_TEXT_ROTATION",
",",
"0.0",
")",
";",
"// Convert to radians, if needed\r",
"... | Gets the angle of rotation from the request.
@param pRequest the servlet request to get parameters from
@return the angle in radians. | [
"Gets",
"the",
"angle",
"of",
"rotation",
"from",
"the",
"request",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-servlet/src/main/java/com/twelvemonkeys/servlet/image/TextRenderer.java#L324-L335 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/ServletConfigMapAdapter.java | ServletConfigMapAdapter.getName | public final String getName() {
switch (type) {
case ServletConfig:
return servletConfig.getServletName();
case FilterConfig:
return filterConfig.getFilterName();
case ServletContext:
return servletContext.getServletContextName();
default:
throw new IllegalStateException();
}
} | java | public final String getName() {
switch (type) {
case ServletConfig:
return servletConfig.getServletName();
case FilterConfig:
return filterConfig.getFilterName();
case ServletContext:
return servletContext.getServletContextName();
default:
throw new IllegalStateException();
}
} | [
"public",
"final",
"String",
"getName",
"(",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"ServletConfig",
":",
"return",
"servletConfig",
".",
"getServletName",
"(",
")",
";",
"case",
"FilterConfig",
":",
"return",
"filterConfig",
".",
"getFilterName",
... | Gets the servlet or filter name from the config.
@return the servlet or filter name | [
"Gets",
"the",
"servlet",
"or",
"filter",
"name",
"from",
"the",
"config",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ServletConfigMapAdapter.java#L111-L122 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/ServletConfigMapAdapter.java | ServletConfigMapAdapter.getServletContext | public final ServletContext getServletContext() {
switch (type) {
case ServletConfig:
return servletConfig.getServletContext();
case FilterConfig:
return filterConfig.getServletContext();
case ServletContext:
return servletContext;
default:
throw new IllegalStateException();
}
} | java | public final ServletContext getServletContext() {
switch (type) {
case ServletConfig:
return servletConfig.getServletContext();
case FilterConfig:
return filterConfig.getServletContext();
case ServletContext:
return servletContext;
default:
throw new IllegalStateException();
}
} | [
"public",
"final",
"ServletContext",
"getServletContext",
"(",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"ServletConfig",
":",
"return",
"servletConfig",
".",
"getServletContext",
"(",
")",
";",
"case",
"FilterConfig",
":",
"return",
"filterConfig",
"."... | Gets the servlet context from the config.
@return the servlet context | [
"Gets",
"the",
"servlet",
"context",
"from",
"the",
"config",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ServletConfigMapAdapter.java#L129-L140 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/enc/DecoderStream.java | DecoderStream.fill | protected int fill() throws IOException {
buffer.clear();
int read = decoder.decode(in, buffer);
// TODO: Enforce this in test case, leave here to aid debugging
if (read > buffer.capacity()) {
throw new AssertionError(
String.format(
"Decode beyond buffer (%d): %d (using %s decoder)",
buffer.capacity(), read, decoder.getClass().getName()
)
);
}
buffer.flip();
if (read == 0) {
return -1;
}
return read;
} | java | protected int fill() throws IOException {
buffer.clear();
int read = decoder.decode(in, buffer);
// TODO: Enforce this in test case, leave here to aid debugging
if (read > buffer.capacity()) {
throw new AssertionError(
String.format(
"Decode beyond buffer (%d): %d (using %s decoder)",
buffer.capacity(), read, decoder.getClass().getName()
)
);
}
buffer.flip();
if (read == 0) {
return -1;
}
return read;
} | [
"protected",
"int",
"fill",
"(",
")",
"throws",
"IOException",
"{",
"buffer",
".",
"clear",
"(",
")",
";",
"int",
"read",
"=",
"decoder",
".",
"decode",
"(",
"in",
",",
"buffer",
")",
";",
"// TODO: Enforce this in test case, leave here to aid debugging\r",
"if"... | Fills the buffer, by decoding data from the underlying input stream.
@return the number of bytes decoded, or {@code -1} if the end of the
file is reached
@throws IOException if an I/O error occurs | [
"Fills",
"the",
"buffer",
"by",
"decoding",
"data",
"from",
"the",
"underlying",
"input",
"stream",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/enc/DecoderStream.java#L178-L199 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.logDebug | public void logDebug(String message, Exception exception) {
if (!(logDebug || globalLog.logDebug))
return;
if (debugLog != null)
log(debugLog, "DEBUG", owner, message, exception);
else
log(globalLog.debugLog, "DEBUG", owner, message, exception);
} | java | public void logDebug(String message, Exception exception) {
if (!(logDebug || globalLog.logDebug))
return;
if (debugLog != null)
log(debugLog, "DEBUG", owner, message, exception);
else
log(globalLog.debugLog, "DEBUG", owner, message, exception);
} | [
"public",
"void",
"logDebug",
"(",
"String",
"message",
",",
"Exception",
"exception",
")",
"{",
"if",
"(",
"!",
"(",
"logDebug",
"||",
"globalLog",
".",
"logDebug",
")",
")",
"return",
";",
"if",
"(",
"debugLog",
"!=",
"null",
")",
"log",
"(",
"debugL... | Prints debug info to the current debugLog
@param message The message to log
@param exception An Exception | [
"Prints",
"debug",
"info",
"to",
"the",
"current",
"debugLog"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L281-L289 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.logWarning | public void logWarning(String message, Exception exception) {
if (!(logWarning || globalLog.logWarning))
return;
if (warningLog != null)
log(warningLog, "WARNING", owner, message, exception);
else
log(globalLog.warningLog, "WARNING", owner, message, exception);
} | java | public void logWarning(String message, Exception exception) {
if (!(logWarning || globalLog.logWarning))
return;
if (warningLog != null)
log(warningLog, "WARNING", owner, message, exception);
else
log(globalLog.warningLog, "WARNING", owner, message, exception);
} | [
"public",
"void",
"logWarning",
"(",
"String",
"message",
",",
"Exception",
"exception",
")",
"{",
"if",
"(",
"!",
"(",
"logWarning",
"||",
"globalLog",
".",
"logWarning",
")",
")",
"return",
";",
"if",
"(",
"warningLog",
"!=",
"null",
")",
"log",
"(",
... | Prints warning info to the current warningLog
@param message The message to log
@param exception An Exception | [
"Prints",
"warning",
"info",
"to",
"the",
"current",
"warningLog"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L385-L393 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.logError | public void logError(String message, Exception exception) {
if (!(logError || globalLog.logError))
return;
if (errorLog != null)
log(errorLog, "ERROR", owner, message, exception);
else
log(globalLog.errorLog, "ERROR", owner, message, exception);
} | java | public void logError(String message, Exception exception) {
if (!(logError || globalLog.logError))
return;
if (errorLog != null)
log(errorLog, "ERROR", owner, message, exception);
else
log(globalLog.errorLog, "ERROR", owner, message, exception);
} | [
"public",
"void",
"logError",
"(",
"String",
"message",
",",
"Exception",
"exception",
")",
"{",
"if",
"(",
"!",
"(",
"logError",
"||",
"globalLog",
".",
"logError",
")",
")",
"return",
";",
"if",
"(",
"errorLog",
"!=",
"null",
")",
"log",
"(",
"errorL... | Prints error info to the current errorLog
@param message The message to log
@param exception An Exception | [
"Prints",
"error",
"info",
"to",
"the",
"current",
"errorLog"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L488-L496 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.logInfo | public void logInfo(String message, Exception exception) {
if (!(logInfo || globalLog.logInfo))
return;
if (infoLog != null)
log(infoLog, "INFO", owner, message, exception);
else
log(globalLog.infoLog, "INFO", owner, message, exception);
} | java | public void logInfo(String message, Exception exception) {
if (!(logInfo || globalLog.logInfo))
return;
if (infoLog != null)
log(infoLog, "INFO", owner, message, exception);
else
log(globalLog.infoLog, "INFO", owner, message, exception);
} | [
"public",
"void",
"logInfo",
"(",
"String",
"message",
",",
"Exception",
"exception",
")",
"{",
"if",
"(",
"!",
"(",
"logInfo",
"||",
"globalLog",
".",
"logInfo",
")",
")",
"return",
";",
"if",
"(",
"infoLog",
"!=",
"null",
")",
"log",
"(",
"infoLog",
... | Prints info info to the current infoLog
@param message The message to log
@param exception An Exception | [
"Prints",
"info",
"info",
"to",
"the",
"current",
"infoLog"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L591-L599 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.getStream | private static OutputStream getStream(String name) throws IOException {
OutputStream os = null;
synchronized (streamCache) {
if ((os = (OutputStream) streamCache.get(name)) != null)
return os;
os = new FileOutputStream(name, true);
streamCache.put(name, os);
}
return os;
} | java | private static OutputStream getStream(String name) throws IOException {
OutputStream os = null;
synchronized (streamCache) {
if ((os = (OutputStream) streamCache.get(name)) != null)
return os;
os = new FileOutputStream(name, true);
streamCache.put(name, os);
}
return os;
} | [
"private",
"static",
"OutputStream",
"getStream",
"(",
"String",
"name",
")",
"throws",
"IOException",
"{",
"OutputStream",
"os",
"=",
"null",
";",
"synchronized",
"(",
"streamCache",
")",
"{",
"if",
"(",
"(",
"os",
"=",
"(",
"OutputStream",
")",
"streamCach... | Internal method to get a named stream | [
"Internal",
"method",
"to",
"get",
"a",
"named",
"stream"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L607-L619 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java | Log.log | private static void log(PrintStream ps, String header,
String owner, String message, Exception ex) {
// Only allow one instance to print to the given stream.
synchronized (ps) {
// Create output stream for logging
LogStream logStream = new LogStream(ps);
logStream.time = new Date(System.currentTimeMillis());
logStream.header = header;
logStream.owner = owner;
if (message != null)
logStream.println(message);
if (ex != null) {
logStream.println(ex.getMessage());
ex.printStackTrace(logStream);
}
}
} | java | private static void log(PrintStream ps, String header,
String owner, String message, Exception ex) {
// Only allow one instance to print to the given stream.
synchronized (ps) {
// Create output stream for logging
LogStream logStream = new LogStream(ps);
logStream.time = new Date(System.currentTimeMillis());
logStream.header = header;
logStream.owner = owner;
if (message != null)
logStream.println(message);
if (ex != null) {
logStream.println(ex.getMessage());
ex.printStackTrace(logStream);
}
}
} | [
"private",
"static",
"void",
"log",
"(",
"PrintStream",
"ps",
",",
"String",
"header",
",",
"String",
"owner",
",",
"String",
"message",
",",
"Exception",
"ex",
")",
"{",
"// Only allow one instance to print to the given stream.\r",
"synchronized",
"(",
"ps",
")",
... | Internal log method | [
"Internal",
"log",
"method"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/Log.java#L625-L644 | train |
haraldk/TwelveMonkeys | imageio/imageio-bmp/src/main/java/com/twelvemonkeys/imageio/plugins/bmp/CURImageReader.java | CURImageReader.getHotSpot | public final Point getHotSpot(final int pImageIndex) throws IOException {
DirectoryEntry.CUREntry entry = (DirectoryEntry.CUREntry) getEntry(pImageIndex);
return entry.getHotspot();
} | java | public final Point getHotSpot(final int pImageIndex) throws IOException {
DirectoryEntry.CUREntry entry = (DirectoryEntry.CUREntry) getEntry(pImageIndex);
return entry.getHotspot();
} | [
"public",
"final",
"Point",
"getHotSpot",
"(",
"final",
"int",
"pImageIndex",
")",
"throws",
"IOException",
"{",
"DirectoryEntry",
".",
"CUREntry",
"entry",
"=",
"(",
"DirectoryEntry",
".",
"CUREntry",
")",
"getEntry",
"(",
"pImageIndex",
")",
";",
"return",
"... | Returns the hot spot location for the cursor.
@param pImageIndex the index of the cursor in the current input.
@return the hot spot location for the cursor
@throws java.io.IOException if an I/O exception occurs during reading of image meta data
@throws IndexOutOfBoundsException if {@code pImageIndex} is less than {@code 0} or greater than/equal to
the number of cursors in the file | [
"Returns",
"the",
"hot",
"spot",
"location",
"for",
"the",
"cursor",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-bmp/src/main/java/com/twelvemonkeys/imageio/plugins/bmp/CURImageReader.java#L65-L68 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/convert/TimeConverter.java | TimeConverter.toObject | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (StringUtil.isEmpty(pString))
return null;
TimeFormat format;
try {
if (pFormat == null) {
// Use system default format
format = TimeFormat.getInstance();
}
else {
// Get format from cache
format = getTimeFormat(pFormat);
}
return format.parse(pString);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | java | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (StringUtil.isEmpty(pString))
return null;
TimeFormat format;
try {
if (pFormat == null) {
// Use system default format
format = TimeFormat.getInstance();
}
else {
// Get format from cache
format = getTimeFormat(pFormat);
}
return format.parse(pString);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | [
"public",
"Object",
"toObject",
"(",
"String",
"pString",
",",
"Class",
"pType",
",",
"String",
"pFormat",
")",
"throws",
"ConversionException",
"{",
"if",
"(",
"StringUtil",
".",
"isEmpty",
"(",
"pString",
")",
")",
"return",
"null",
";",
"TimeFormat",
"for... | Converts the string to a time, using the given format for parsing.
@param pString the string to convert.
@param pType the type to convert to. PropertyConverter
implementations may choose to ignore this parameter.
@param pFormat the format used for parsing. PropertyConverter
implementations may choose to ignore this parameter. Also,
implementations that require a parser format, should provide a default
format, and allow {@code null} as the format argument.
@return the object created from the given string. May safely be typecast
to {@code com.twelvemonkeys.util.Time}
@see com.twelvemonkeys.util.Time
@see com.twelvemonkeys.util.TimeFormat
@throws ConversionException | [
"Converts",
"the",
"string",
"to",
"a",
"time",
"using",
"the",
"given",
"format",
"for",
"parsing",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/convert/TimeConverter.java#L71-L94 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/Entry.java | Entry.readEntry | static Entry readEntry(final DataInput pInput) throws IOException {
Entry p = new Entry();
p.read(pInput);
return p;
} | java | static Entry readEntry(final DataInput pInput) throws IOException {
Entry p = new Entry();
p.read(pInput);
return p;
} | [
"static",
"Entry",
"readEntry",
"(",
"final",
"DataInput",
"pInput",
")",
"throws",
"IOException",
"{",
"Entry",
"p",
"=",
"new",
"Entry",
"(",
")",
";",
"p",
".",
"read",
"(",
"pInput",
")",
";",
"return",
"p",
";",
"}"
] | Reads an entry from the input.
@param pInput the input data
@return the {@code Entry} read from the input data
@throws IOException if an i/o exception occurs during reading | [
"Reads",
"an",
"entry",
"from",
"the",
"input",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/Entry.java#L92-L96 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/ole2/Entry.java | Entry.read | private void read(final DataInput pInput) throws IOException {
byte[] bytes = new byte[64];
pInput.readFully(bytes);
// NOTE: Length is in bytes, including the null-terminator...
int nameLength = pInput.readShort();
name = new String(bytes, 0, nameLength - 2, Charset.forName("UTF-16LE"));
// System.out.println("name: " + name);
type = pInput.readByte();
// System.out.println("type: " + type);
nodeColor = pInput.readByte();
// System.out.println("nodeColor: " + nodeColor);
prevDId = pInput.readInt();
// System.out.println("prevDId: " + prevDId);
nextDId = pInput.readInt();
// System.out.println("nextDId: " + nextDId);
rootNodeDId = pInput.readInt();
// System.out.println("rootNodeDId: " + rootNodeDId);
// UID (16) + user flags (4), ignored
if (pInput.skipBytes(20) != 20) {
throw new CorruptDocumentException();
}
createdTimestamp = CompoundDocument.toJavaTimeInMillis(pInput.readLong());
modifiedTimestamp = CompoundDocument.toJavaTimeInMillis(pInput.readLong());
startSId = pInput.readInt();
// System.out.println("startSId: " + startSId);
streamSize = pInput.readInt();
// System.out.println("streamSize: " + streamSize);
// Reserved
pInput.readInt();
} | java | private void read(final DataInput pInput) throws IOException {
byte[] bytes = new byte[64];
pInput.readFully(bytes);
// NOTE: Length is in bytes, including the null-terminator...
int nameLength = pInput.readShort();
name = new String(bytes, 0, nameLength - 2, Charset.forName("UTF-16LE"));
// System.out.println("name: " + name);
type = pInput.readByte();
// System.out.println("type: " + type);
nodeColor = pInput.readByte();
// System.out.println("nodeColor: " + nodeColor);
prevDId = pInput.readInt();
// System.out.println("prevDId: " + prevDId);
nextDId = pInput.readInt();
// System.out.println("nextDId: " + nextDId);
rootNodeDId = pInput.readInt();
// System.out.println("rootNodeDId: " + rootNodeDId);
// UID (16) + user flags (4), ignored
if (pInput.skipBytes(20) != 20) {
throw new CorruptDocumentException();
}
createdTimestamp = CompoundDocument.toJavaTimeInMillis(pInput.readLong());
modifiedTimestamp = CompoundDocument.toJavaTimeInMillis(pInput.readLong());
startSId = pInput.readInt();
// System.out.println("startSId: " + startSId);
streamSize = pInput.readInt();
// System.out.println("streamSize: " + streamSize);
// Reserved
pInput.readInt();
} | [
"private",
"void",
"read",
"(",
"final",
"DataInput",
"pInput",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"64",
"]",
";",
"pInput",
".",
"readFully",
"(",
"bytes",
")",
";",
"// NOTE: Length is in bytes, including... | Reads this entry
@param pInput the input data
@throws IOException if an i/o exception occurs during reading | [
"Reads",
"this",
"entry"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/ole2/Entry.java#L104-L141 | train |
haraldk/TwelveMonkeys | imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java | Paths.readPath | public static Path2D readPath(final ImageInputStream stream) throws IOException {
notNull(stream, "stream");
int magic = readMagic(stream);
if (magic == PSD.RESOURCE_TYPE) {
// This is a PSD Image Resource Block, we can parse directly
return buildPathFromPhotoshopResources(stream);
}
else if (magic == PSD.SIGNATURE_8BPS) {
// PSD version
// 4 byte magic, 2 byte version, 6 bytes reserved, 2 byte channels,
// 4 byte height, 4 byte width, 2 byte bit depth, 2 byte mode
stream.skipBytes(26);
// 4 byte color mode data length + n byte color mode data
long colorModeLen = stream.readUnsignedInt();
stream.skipBytes(colorModeLen);
// 4 byte image resources length
long imageResourcesLen = stream.readUnsignedInt();
// Image resources
return buildPathFromPhotoshopResources(new SubImageInputStream(stream, imageResourcesLen));
}
else if (magic >>> 16 == JPEG.SOI && (magic & 0xff00) == 0xff00) {
// JPEG version
Map<Integer, java.util.List<String>> segmentIdentifiers = new LinkedHashMap<>();
segmentIdentifiers.put(JPEG.APP13, singletonList("Photoshop 3.0"));
List<JPEGSegment> photoshop = JPEGSegmentUtil.readSegments(stream, segmentIdentifiers);
if (!photoshop.isEmpty()) {
return buildPathFromPhotoshopResources(new MemoryCacheImageInputStream(photoshop.get(0).data()));
}
}
else if (magic >>> 16 == TIFF.BYTE_ORDER_MARK_BIG_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC
|| magic >>> 16 == TIFF.BYTE_ORDER_MARK_LITTLE_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC << 8) {
// TIFF version
CompoundDirectory IFDs = (CompoundDirectory) new TIFFReader().read(stream);
Directory directory = IFDs.getDirectory(0);
Entry photoshop = directory.getEntryById(TIFF.TAG_PHOTOSHOP);
if (photoshop != null) {
return buildPathFromPhotoshopResources(new ByteArrayImageInputStream((byte[]) photoshop.getValue()));
}
}
// Unknown file format, or no path found
return null;
} | java | public static Path2D readPath(final ImageInputStream stream) throws IOException {
notNull(stream, "stream");
int magic = readMagic(stream);
if (magic == PSD.RESOURCE_TYPE) {
// This is a PSD Image Resource Block, we can parse directly
return buildPathFromPhotoshopResources(stream);
}
else if (magic == PSD.SIGNATURE_8BPS) {
// PSD version
// 4 byte magic, 2 byte version, 6 bytes reserved, 2 byte channels,
// 4 byte height, 4 byte width, 2 byte bit depth, 2 byte mode
stream.skipBytes(26);
// 4 byte color mode data length + n byte color mode data
long colorModeLen = stream.readUnsignedInt();
stream.skipBytes(colorModeLen);
// 4 byte image resources length
long imageResourcesLen = stream.readUnsignedInt();
// Image resources
return buildPathFromPhotoshopResources(new SubImageInputStream(stream, imageResourcesLen));
}
else if (magic >>> 16 == JPEG.SOI && (magic & 0xff00) == 0xff00) {
// JPEG version
Map<Integer, java.util.List<String>> segmentIdentifiers = new LinkedHashMap<>();
segmentIdentifiers.put(JPEG.APP13, singletonList("Photoshop 3.0"));
List<JPEGSegment> photoshop = JPEGSegmentUtil.readSegments(stream, segmentIdentifiers);
if (!photoshop.isEmpty()) {
return buildPathFromPhotoshopResources(new MemoryCacheImageInputStream(photoshop.get(0).data()));
}
}
else if (magic >>> 16 == TIFF.BYTE_ORDER_MARK_BIG_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC
|| magic >>> 16 == TIFF.BYTE_ORDER_MARK_LITTLE_ENDIAN && (magic & 0xffff) == TIFF.TIFF_MAGIC << 8) {
// TIFF version
CompoundDirectory IFDs = (CompoundDirectory) new TIFFReader().read(stream);
Directory directory = IFDs.getDirectory(0);
Entry photoshop = directory.getEntryById(TIFF.TAG_PHOTOSHOP);
if (photoshop != null) {
return buildPathFromPhotoshopResources(new ByteArrayImageInputStream((byte[]) photoshop.getValue()));
}
}
// Unknown file format, or no path found
return null;
} | [
"public",
"static",
"Path2D",
"readPath",
"(",
"final",
"ImageInputStream",
"stream",
")",
"throws",
"IOException",
"{",
"notNull",
"(",
"stream",
",",
"\"stream\"",
")",
";",
"int",
"magic",
"=",
"readMagic",
"(",
"stream",
")",
";",
"if",
"(",
"magic",
"... | Reads the clipping path from the given input stream, if any.
Supports PSD, JPEG and TIFF as container formats for Photoshop resources,
or a "bare" PSD Image Resource Block.
@param stream the input stream to read from, not {@code null}.
@return the path, or {@code null} if no path is found
@throws IOException if a general I/O exception occurs during reading.
@throws javax.imageio.IIOException if the input contains a bad path data.
@throws java.lang.IllegalArgumentException is {@code stream} is {@code null}.
@see com.twelvemonkeys.imageio.path.AdobePathBuilder | [
"Reads",
"the",
"clipping",
"path",
"from",
"the",
"given",
"input",
"stream",
"if",
"any",
".",
"Supports",
"PSD",
"JPEG",
"and",
"TIFF",
"as",
"container",
"formats",
"for",
"Photoshop",
"resources",
"or",
"a",
"bare",
"PSD",
"Image",
"Resource",
"Block",
... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java#L95-L146 | train |
haraldk/TwelveMonkeys | imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java | Paths.applyClippingPath | public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image) {
return applyClippingPath(clip, notNull(image, "image"), new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB));
} | java | public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image) {
return applyClippingPath(clip, notNull(image, "image"), new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB));
} | [
"public",
"static",
"BufferedImage",
"applyClippingPath",
"(",
"final",
"Shape",
"clip",
",",
"final",
"BufferedImage",
"image",
")",
"{",
"return",
"applyClippingPath",
"(",
"clip",
",",
"notNull",
"(",
"image",
",",
"\"image\"",
")",
",",
"new",
"BufferedImage... | Applies the clipping path to the given image.
All pixels outside the path will be transparent.
@param clip the clipping path, not {@code null}
@param image the image to clip, not {@code null}
@return the clipped image.
@throws java.lang.IllegalArgumentException if {@code clip} or {@code image} is {@code null}. | [
"Applies",
"the",
"clipping",
"path",
"to",
"the",
"given",
"image",
".",
"All",
"pixels",
"outside",
"the",
"path",
"will",
"be",
"transparent",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java#L185-L187 | train |
haraldk/TwelveMonkeys | imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java | Paths.readClipped | public static BufferedImage readClipped(final ImageInputStream stream) throws IOException {
Shape clip = readPath(stream);
stream.seek(0);
BufferedImage image = ImageIO.read(stream);
if (clip == null) {
return image;
}
return applyClippingPath(clip, image);
} | java | public static BufferedImage readClipped(final ImageInputStream stream) throws IOException {
Shape clip = readPath(stream);
stream.seek(0);
BufferedImage image = ImageIO.read(stream);
if (clip == null) {
return image;
}
return applyClippingPath(clip, image);
} | [
"public",
"static",
"BufferedImage",
"readClipped",
"(",
"final",
"ImageInputStream",
"stream",
")",
"throws",
"IOException",
"{",
"Shape",
"clip",
"=",
"readPath",
"(",
"stream",
")",
";",
"stream",
".",
"seek",
"(",
"0",
")",
";",
"BufferedImage",
"image",
... | Reads the clipping path from the given input stream, if any,
and applies it to the first image in the stream.
If no path was found, the image is returned without any clipping.
Supports PSD, JPEG and TIFF as container formats for Photoshop resources.
@param stream the stream to read from, not {@code null}
@return the clipped image
@throws IOException if a general I/O exception occurs during reading.
@throws javax.imageio.IIOException if the input contains a bad image or path data.
@throws java.lang.IllegalArgumentException is {@code stream} is {@code null}. | [
"Reads",
"the",
"clipping",
"path",
"from",
"the",
"given",
"input",
"stream",
"if",
"any",
"and",
"applies",
"it",
"to",
"the",
"first",
"image",
"in",
"the",
"stream",
".",
"If",
"no",
"path",
"was",
"found",
"the",
"image",
"is",
"returned",
"without"... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-clippath/src/main/java/com/twelvemonkeys/imageio/path/Paths.java#L244-L255 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/ProxyServlet.java | ProxyServlet.service | protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
// Sanity check configuration
if (remoteServer == null) {
log(MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
pResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
return;
}
HttpURLConnection remoteConnection = null;
try {
// Recreate request URI for remote request
String requestURI = createRemoteRequestURI(pRequest);
URL remoteURL = new URL(pRequest.getScheme(), remoteServer, remotePort, requestURI);
// Get connection, with method from original request
// NOTE: The actual connection is not done before we ask for streams...
// NOTE: The HttpURLConnection is supposed to handle multiple
// requests to the same server internally
String method = pRequest.getMethod();
remoteConnection = (HttpURLConnection) remoteURL.openConnection();
remoteConnection.setRequestMethod(method);
// Copy header fields
copyHeadersFromClient(pRequest, remoteConnection);
// Do proxy specifc stuff?
// TODO: Read up the specs from RFC 2616 (HTTP) on proxy behaviour
// TODO: RFC 2616 says "[a] proxy server MUST NOT establish an HTTP/1.1
// persistent connection with an HTTP/1.0 client"
// Copy message body from client to remote server
copyBodyFromClient(pRequest, remoteConnection);
// Set response status code from remote server to client
int responseCode = remoteConnection.getResponseCode();
pResponse.setStatus(responseCode);
//System.out.println("Response is: " + responseCode + " " + remoteConnection.getResponseMessage());
// Copy header fields back
copyHeadersToClient(remoteConnection, pResponse);
// More proxy specific stuff?
// Copy message body from remote server to client
copyBodyToClient(remoteConnection, pResponse);
}
catch (ConnectException e) {
// In case we could not connecto to the remote server
log("Could not connect to remote server.", e);
pResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY, e.getMessage());
}
finally {
// Disconnect from server
// TODO: Should we actually do this?
if (remoteConnection != null) {
remoteConnection.disconnect();
}
}
} | java | protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
// Sanity check configuration
if (remoteServer == null) {
log(MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
pResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
return;
}
HttpURLConnection remoteConnection = null;
try {
// Recreate request URI for remote request
String requestURI = createRemoteRequestURI(pRequest);
URL remoteURL = new URL(pRequest.getScheme(), remoteServer, remotePort, requestURI);
// Get connection, with method from original request
// NOTE: The actual connection is not done before we ask for streams...
// NOTE: The HttpURLConnection is supposed to handle multiple
// requests to the same server internally
String method = pRequest.getMethod();
remoteConnection = (HttpURLConnection) remoteURL.openConnection();
remoteConnection.setRequestMethod(method);
// Copy header fields
copyHeadersFromClient(pRequest, remoteConnection);
// Do proxy specifc stuff?
// TODO: Read up the specs from RFC 2616 (HTTP) on proxy behaviour
// TODO: RFC 2616 says "[a] proxy server MUST NOT establish an HTTP/1.1
// persistent connection with an HTTP/1.0 client"
// Copy message body from client to remote server
copyBodyFromClient(pRequest, remoteConnection);
// Set response status code from remote server to client
int responseCode = remoteConnection.getResponseCode();
pResponse.setStatus(responseCode);
//System.out.println("Response is: " + responseCode + " " + remoteConnection.getResponseMessage());
// Copy header fields back
copyHeadersToClient(remoteConnection, pResponse);
// More proxy specific stuff?
// Copy message body from remote server to client
copyBodyToClient(remoteConnection, pResponse);
}
catch (ConnectException e) {
// In case we could not connecto to the remote server
log("Could not connect to remote server.", e);
pResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY, e.getMessage());
}
finally {
// Disconnect from server
// TODO: Should we actually do this?
if (remoteConnection != null) {
remoteConnection.disconnect();
}
}
} | [
"protected",
"void",
"service",
"(",
"HttpServletRequest",
"pRequest",
",",
"HttpServletResponse",
"pResponse",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"// Sanity check configuration\r",
"if",
"(",
"remoteServer",
"==",
"null",
")",
"{",
"log",
"("... | Services a single request.
Supports HTTP and HTTPS.
@param pRequest
@param pResponse
@throws ServletException
@throws IOException
@see ProxyServlet Class descrition | [
"Services",
"a",
"single",
"request",
".",
"Supports",
"HTTP",
"and",
"HTTPS",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ProxyServlet.java#L156-L215 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/ProxyServlet.java | ProxyServlet.createRemoteRequestURI | private String createRemoteRequestURI(HttpServletRequest pRequest) {
StringBuilder requestURI = new StringBuilder(remotePath);
requestURI.append(pRequest.getPathInfo());
if (!StringUtil.isEmpty(pRequest.getQueryString())) {
requestURI.append("?");
requestURI.append(pRequest.getQueryString());
}
return requestURI.toString();
} | java | private String createRemoteRequestURI(HttpServletRequest pRequest) {
StringBuilder requestURI = new StringBuilder(remotePath);
requestURI.append(pRequest.getPathInfo());
if (!StringUtil.isEmpty(pRequest.getQueryString())) {
requestURI.append("?");
requestURI.append(pRequest.getQueryString());
}
return requestURI.toString();
} | [
"private",
"String",
"createRemoteRequestURI",
"(",
"HttpServletRequest",
"pRequest",
")",
"{",
"StringBuilder",
"requestURI",
"=",
"new",
"StringBuilder",
"(",
"remotePath",
")",
";",
"requestURI",
".",
"append",
"(",
"pRequest",
".",
"getPathInfo",
"(",
")",
")"... | Creates the remote request URI based on the incoming request.
The URI will include any query strings etc.
@param pRequest
@return a {@code String} representing the remote request URI | [
"Creates",
"the",
"remote",
"request",
"URI",
"based",
"on",
"the",
"incoming",
"request",
".",
"The",
"URI",
"will",
"include",
"any",
"query",
"strings",
"etc",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ProxyServlet.java#L323-L333 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/TimeoutMap.java | TimeoutMap.setExpiryTime | public void setExpiryTime(long pExpiryTime) {
long oldEexpiryTime = expiryTime;
expiryTime = pExpiryTime;
if (expiryTime < oldEexpiryTime) {
// Expire now
nextExpiryTime = 0;
removeExpiredEntries();
}
} | java | public void setExpiryTime(long pExpiryTime) {
long oldEexpiryTime = expiryTime;
expiryTime = pExpiryTime;
if (expiryTime < oldEexpiryTime) {
// Expire now
nextExpiryTime = 0;
removeExpiredEntries();
}
} | [
"public",
"void",
"setExpiryTime",
"(",
"long",
"pExpiryTime",
")",
"{",
"long",
"oldEexpiryTime",
"=",
"expiryTime",
";",
"expiryTime",
"=",
"pExpiryTime",
";",
"if",
"(",
"expiryTime",
"<",
"oldEexpiryTime",
")",
"{",
"// Expire now\r",
"nextExpiryTime",
"=",
... | Sets the maximum time any value will be kept in the map, before it expires.
Removes any items that are older than the specified time.
@param pExpiryTime the expiry time (time to live) for elements in this map | [
"Sets",
"the",
"maximum",
"time",
"any",
"value",
"will",
"be",
"kept",
"in",
"the",
"map",
"before",
"it",
"expires",
".",
"Removes",
"any",
"items",
"that",
"are",
"older",
"than",
"the",
"specified",
"time",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/TimeoutMap.java#L148-L158 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/TimeoutMap.java | TimeoutMap.removeExpiredEntriesSynced | private synchronized void removeExpiredEntriesSynced(long pTime) {
if (pTime > nextExpiryTime) {
////
long next = Long.MAX_VALUE;
nextExpiryTime = next; // Avoid multiple runs...
for (Iterator<Entry<K, V>> iterator = new EntryIterator(); iterator.hasNext();) {
TimedEntry<K, V> entry = (TimedEntry<K, V>) iterator.next();
////
long expires = entry.expires();
if (expires < next) {
next = expires;
}
////
}
////
nextExpiryTime = next;
}
} | java | private synchronized void removeExpiredEntriesSynced(long pTime) {
if (pTime > nextExpiryTime) {
////
long next = Long.MAX_VALUE;
nextExpiryTime = next; // Avoid multiple runs...
for (Iterator<Entry<K, V>> iterator = new EntryIterator(); iterator.hasNext();) {
TimedEntry<K, V> entry = (TimedEntry<K, V>) iterator.next();
////
long expires = entry.expires();
if (expires < next) {
next = expires;
}
////
}
////
nextExpiryTime = next;
}
} | [
"private",
"synchronized",
"void",
"removeExpiredEntriesSynced",
"(",
"long",
"pTime",
")",
"{",
"if",
"(",
"pTime",
">",
"nextExpiryTime",
")",
"{",
"////\r",
"long",
"next",
"=",
"Long",
".",
"MAX_VALUE",
";",
"nextExpiryTime",
"=",
"next",
";",
"// Avoid mu... | Okay, I guess this do resemble DCL...
@todo Write some exhausting multi-threaded unit-tests.
@param pTime now | [
"Okay",
"I",
"guess",
"this",
"do",
"resemble",
"DCL",
"..."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/TimeoutMap.java#L307-L324 | train |
haraldk/TwelveMonkeys | imageio/imageio-pcx/src/main/java/com/twelvemonkeys/imageio/plugins/pcx/BitRotator.java | BitRotator.bitRotateCW | static void bitRotateCW(final byte[] pSrc, int pSrcPos, int pSrcStep,
final byte[] pDst, int pDstPos, int pDstStep) {
int idx = pSrcPos;
int lonyb;
int hinyb;
long lo = 0;
long hi = 0;
for (int i = 0; i < 8; i++) {
lonyb = pSrc[idx] & 0xF;
hinyb = (pSrc[idx] >> 4) & 0xF;
lo |= RTABLE[i][lonyb];
hi |= RTABLE[i][hinyb];
idx += pSrcStep;
}
idx = pDstPos;
pDst[idx] = (byte)((hi >> 24) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((hi >> 16) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((hi >> 8) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)(hi & 0xFF);
idx += pDstStep;
}
}
}
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 24) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 16) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 8) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)(lo & 0xFF);
}
}
}
}
} | java | static void bitRotateCW(final byte[] pSrc, int pSrcPos, int pSrcStep,
final byte[] pDst, int pDstPos, int pDstStep) {
int idx = pSrcPos;
int lonyb;
int hinyb;
long lo = 0;
long hi = 0;
for (int i = 0; i < 8; i++) {
lonyb = pSrc[idx] & 0xF;
hinyb = (pSrc[idx] >> 4) & 0xF;
lo |= RTABLE[i][lonyb];
hi |= RTABLE[i][hinyb];
idx += pSrcStep;
}
idx = pDstPos;
pDst[idx] = (byte)((hi >> 24) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((hi >> 16) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((hi >> 8) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)(hi & 0xFF);
idx += pDstStep;
}
}
}
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 24) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 16) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)((lo >> 8) & 0xFF);
idx += pDstStep;
if (idx < pDst.length) {
pDst[idx] = (byte)(lo & 0xFF);
}
}
}
}
} | [
"static",
"void",
"bitRotateCW",
"(",
"final",
"byte",
"[",
"]",
"pSrc",
",",
"int",
"pSrcPos",
",",
"int",
"pSrcStep",
",",
"final",
"byte",
"[",
"]",
"pDst",
",",
"int",
"pDstPos",
",",
"int",
"pDstStep",
")",
"{",
"int",
"idx",
"=",
"pSrcPos",
";"... | Rotate bits clockwise.
The IFFImageReader uses this to convert pixel bits from planar to chunky.
Bits from the source are rotated 90 degrees clockwise written to the
destination.
@param pSrc source pixel data
@param pSrcPos starting index of 8 x 8 bit source tile
@param pSrcStep byte offset between adjacent rows in source
@param pDst destination pixel data
@param pDstPos starting index of 8 x 8 bit destination tile
@param pDstStep byte offset between adjacent rows in destination | [
"Rotate",
"bits",
"clockwise",
".",
"The",
"IFFImageReader",
"uses",
"this",
"to",
"convert",
"pixel",
"bits",
"from",
"planar",
"to",
"chunky",
".",
"Bits",
"from",
"the",
"source",
"are",
"rotated",
"90",
"degrees",
"clockwise",
"written",
"to",
"the",
"de... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pcx/src/main/java/com/twelvemonkeys/imageio/plugins/pcx/BitRotator.java#L79-L128 | train |
haraldk/TwelveMonkeys | imageio/imageio-hdr/src/main/java/com/twelvemonkeys/imageio/plugins/hdr/RGBE.java | RGBE.readPixels | public static void readPixels(DataInput in, float[] data, int numpixels) throws IOException {
byte[] rgbe = new byte[4];
float[] rgb = new float[3];
int offset = 0;
while (numpixels-- > 0) {
in.readFully(rgbe);
rgbe2float(rgb, rgbe, 0);
data[offset++] = rgb[0];
data[offset++] = rgb[1];
data[offset++] = rgb[2];
}
} | java | public static void readPixels(DataInput in, float[] data, int numpixels) throws IOException {
byte[] rgbe = new byte[4];
float[] rgb = new float[3];
int offset = 0;
while (numpixels-- > 0) {
in.readFully(rgbe);
rgbe2float(rgb, rgbe, 0);
data[offset++] = rgb[0];
data[offset++] = rgb[1];
data[offset++] = rgb[2];
}
} | [
"public",
"static",
"void",
"readPixels",
"(",
"DataInput",
"in",
",",
"float",
"[",
"]",
"data",
",",
"int",
"numpixels",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"rgbe",
"=",
"new",
"byte",
"[",
"4",
"]",
";",
"float",
"[",
"]",
"rgb",
... | Simple read routine. Will not correctly handle run length encoding. | [
"Simple",
"read",
"routine",
".",
"Will",
"not",
"correctly",
"handle",
"run",
"length",
"encoding",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-hdr/src/main/java/com/twelvemonkeys/imageio/plugins/hdr/RGBE.java#L189-L203 | train |
haraldk/TwelveMonkeys | imageio/imageio-hdr/src/main/java/com/twelvemonkeys/imageio/plugins/hdr/RGBE.java | RGBE.float2rgbe | public static void float2rgbe(byte[] rgbe, float red, float green, float blue) {
float v;
int e;
v = red;
if (green > v) {
v = green;
}
if (blue > v) {
v = blue;
}
if (v < 1e-32f) {
rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
}
else {
FracExp fe = frexp(v);
v = (float) (fe.getFraction() * 256.0 / v);
rgbe[0] = (byte) (red * v);
rgbe[1] = (byte) (green * v);
rgbe[2] = (byte) (blue * v);
rgbe[3] = (byte) (fe.getExponent() + 128);
}
} | java | public static void float2rgbe(byte[] rgbe, float red, float green, float blue) {
float v;
int e;
v = red;
if (green > v) {
v = green;
}
if (blue > v) {
v = blue;
}
if (v < 1e-32f) {
rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;
}
else {
FracExp fe = frexp(v);
v = (float) (fe.getFraction() * 256.0 / v);
rgbe[0] = (byte) (red * v);
rgbe[1] = (byte) (green * v);
rgbe[2] = (byte) (blue * v);
rgbe[3] = (byte) (fe.getExponent() + 128);
}
} | [
"public",
"static",
"void",
"float2rgbe",
"(",
"byte",
"[",
"]",
"rgbe",
",",
"float",
"red",
",",
"float",
"green",
",",
"float",
"blue",
")",
"{",
"float",
"v",
";",
"int",
"e",
";",
"v",
"=",
"red",
";",
"if",
"(",
"green",
">",
"v",
")",
"{... | Standard conversion from float pixels to rgbe pixels. | [
"Standard",
"conversion",
"from",
"float",
"pixels",
"to",
"rgbe",
"pixels",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-hdr/src/main/java/com/twelvemonkeys/imageio/plugins/hdr/RGBE.java#L291-L313 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/CropFilter.java | CropFilter.doFilter | protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get crop coordinates
int x = ServletUtil.getIntParameter(pRequest, PARAM_CROP_X, -1);
int y = ServletUtil.getIntParameter(pRequest, PARAM_CROP_Y, -1);
int width = ServletUtil.getIntParameter(pRequest, PARAM_CROP_WIDTH, -1);
int height = ServletUtil.getIntParameter(pRequest, PARAM_CROP_HEIGHT, -1);
boolean uniform =
ServletUtil.getBooleanParameter(pRequest, PARAM_CROP_UNIFORM, false);
int units = getUnits(ServletUtil.getParameter(pRequest, PARAM_CROP_UNITS, null));
// Get crop bounds
Rectangle bounds =
getBounds(x, y, width, height, units, uniform, pImage);
// Return cropped version
return pImage.getSubimage((int) bounds.getX(), (int) bounds.getY(),
(int) bounds.getWidth(),
(int) bounds.getHeight());
//return scaled.getSubimage(x, y, width, height);
} | java | protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get crop coordinates
int x = ServletUtil.getIntParameter(pRequest, PARAM_CROP_X, -1);
int y = ServletUtil.getIntParameter(pRequest, PARAM_CROP_Y, -1);
int width = ServletUtil.getIntParameter(pRequest, PARAM_CROP_WIDTH, -1);
int height = ServletUtil.getIntParameter(pRequest, PARAM_CROP_HEIGHT, -1);
boolean uniform =
ServletUtil.getBooleanParameter(pRequest, PARAM_CROP_UNIFORM, false);
int units = getUnits(ServletUtil.getParameter(pRequest, PARAM_CROP_UNITS, null));
// Get crop bounds
Rectangle bounds =
getBounds(x, y, width, height, units, uniform, pImage);
// Return cropped version
return pImage.getSubimage((int) bounds.getX(), (int) bounds.getY(),
(int) bounds.getWidth(),
(int) bounds.getHeight());
//return scaled.getSubimage(x, y, width, height);
} | [
"protected",
"RenderedImage",
"doFilter",
"(",
"BufferedImage",
"pImage",
",",
"ServletRequest",
"pRequest",
",",
"ImageServletResponse",
"pResponse",
")",
"{",
"// Get crop coordinates\r",
"int",
"x",
"=",
"ServletUtil",
".",
"getIntParameter",
"(",
"pRequest",
",",
... | Reads the image from the requested URL, scales it, crops it, and returns
it in the
Servlet stream. See above for details on parameters. | [
"Reads",
"the",
"image",
"from",
"the",
"requested",
"URL",
"scales",
"it",
"crops",
"it",
"and",
"returns",
"it",
"in",
"the",
"Servlet",
"stream",
".",
"See",
"above",
"for",
"details",
"on",
"parameters",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/CropFilter.java#L117-L138 | train |
mpetazzoni/ttorrent | common/src/main/java/com/turn/ttorrent/common/TorrentCreator.java | TorrentCreator.hashFile | private static String hashFile(final File file, final int pieceSize)
throws InterruptedException, IOException {
return hashFiles(Collections.singletonList(file), pieceSize);
} | java | private static String hashFile(final File file, final int pieceSize)
throws InterruptedException, IOException {
return hashFiles(Collections.singletonList(file), pieceSize);
} | [
"private",
"static",
"String",
"hashFile",
"(",
"final",
"File",
"file",
",",
"final",
"int",
"pieceSize",
")",
"throws",
"InterruptedException",
",",
"IOException",
"{",
"return",
"hashFiles",
"(",
"Collections",
".",
"singletonList",
"(",
"file",
")",
",",
"... | Return the concatenation of the SHA-1 hashes of a file's pieces.
<p>
Hashes the given file piece by piece using the default Torrent piece
length (see {@link #DEFAULT_PIECE_LENGTH}) and returns the concatenation of
these hashes, as a string.
</p>
<p>
This is used for creating Torrent meta-info structures from a file.
</p>
@param file The file to hash. | [
"Return",
"the",
"concatenation",
"of",
"the",
"SHA",
"-",
"1",
"hashes",
"of",
"a",
"file",
"s",
"pieces",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/TorrentCreator.java#L252-L255 | train |
mpetazzoni/ttorrent | common/src/main/java/com/turn/ttorrent/common/protocol/PeerMessage.java | PeerMessage.parse | public static PeerMessage parse(ByteBuffer buffer, TorrentInfo torrent)
throws ParseException {
int length = buffer.getInt();
if (length == 0) {
return KeepAliveMessage.parse(buffer, torrent);
} else if (length != buffer.remaining()) {
throw new ParseException("Message size did not match announced " +
"size!", 0);
}
Type type = Type.get(buffer.get());
if (type == null) {
throw new ParseException("Unknown message ID!",
buffer.position() - 1);
}
switch (type) {
case CHOKE:
return ChokeMessage.parse(buffer.slice(), torrent);
case UNCHOKE:
return UnchokeMessage.parse(buffer.slice(), torrent);
case INTERESTED:
return InterestedMessage.parse(buffer.slice(), torrent);
case NOT_INTERESTED:
return NotInterestedMessage.parse(buffer.slice(), torrent);
case HAVE:
return HaveMessage.parse(buffer.slice(), torrent);
case BITFIELD:
return BitfieldMessage.parse(buffer.slice(), torrent);
case REQUEST:
return RequestMessage.parse(buffer.slice(), torrent);
case PIECE:
return PieceMessage.parse(buffer.slice(), torrent);
case CANCEL:
return CancelMessage.parse(buffer.slice(), torrent);
default:
throw new IllegalStateException("Message type should have " +
"been properly defined by now.");
}
} | java | public static PeerMessage parse(ByteBuffer buffer, TorrentInfo torrent)
throws ParseException {
int length = buffer.getInt();
if (length == 0) {
return KeepAliveMessage.parse(buffer, torrent);
} else if (length != buffer.remaining()) {
throw new ParseException("Message size did not match announced " +
"size!", 0);
}
Type type = Type.get(buffer.get());
if (type == null) {
throw new ParseException("Unknown message ID!",
buffer.position() - 1);
}
switch (type) {
case CHOKE:
return ChokeMessage.parse(buffer.slice(), torrent);
case UNCHOKE:
return UnchokeMessage.parse(buffer.slice(), torrent);
case INTERESTED:
return InterestedMessage.parse(buffer.slice(), torrent);
case NOT_INTERESTED:
return NotInterestedMessage.parse(buffer.slice(), torrent);
case HAVE:
return HaveMessage.parse(buffer.slice(), torrent);
case BITFIELD:
return BitfieldMessage.parse(buffer.slice(), torrent);
case REQUEST:
return RequestMessage.parse(buffer.slice(), torrent);
case PIECE:
return PieceMessage.parse(buffer.slice(), torrent);
case CANCEL:
return CancelMessage.parse(buffer.slice(), torrent);
default:
throw new IllegalStateException("Message type should have " +
"been properly defined by now.");
}
} | [
"public",
"static",
"PeerMessage",
"parse",
"(",
"ByteBuffer",
"buffer",
",",
"TorrentInfo",
"torrent",
")",
"throws",
"ParseException",
"{",
"int",
"length",
"=",
"buffer",
".",
"getInt",
"(",
")",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"return",
... | Parse the given buffer into a peer protocol message.
<p>
Parses the provided byte array and builds the corresponding PeerMessage
subclass object.
</p>
@param buffer The byte buffer containing the message data.
@param torrent The torrent this message is about.
@return A PeerMessage subclass instance.
@throws ParseException When the message is invalid, can't be parsed or
does not match the protocol requirements. | [
"Parse",
"the",
"given",
"buffer",
"into",
"a",
"peer",
"protocol",
"message",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/protocol/PeerMessage.java#L150-L189 | train |
mpetazzoni/ttorrent | ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java | TrackerRequestProcessor.serveError | private void serveError(Status status, String error, RequestHandler requestHandler) throws IOException {
this.serveError(status, HTTPTrackerErrorMessage.craft(error), requestHandler);
} | java | private void serveError(Status status, String error, RequestHandler requestHandler) throws IOException {
this.serveError(status, HTTPTrackerErrorMessage.craft(error), requestHandler);
} | [
"private",
"void",
"serveError",
"(",
"Status",
"status",
",",
"String",
"error",
",",
"RequestHandler",
"requestHandler",
")",
"throws",
"IOException",
"{",
"this",
".",
"serveError",
"(",
"status",
",",
"HTTPTrackerErrorMessage",
".",
"craft",
"(",
"error",
")... | Write an error message to the response with the given HTTP status code.
@param status The HTTP status code to return.
@param error The error message reported by the tracker. | [
"Write",
"an",
"error",
"message",
"to",
"the",
"response",
"with",
"the",
"given",
"HTTP",
"status",
"code",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java#L300-L302 | train |
mpetazzoni/ttorrent | ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java | TrackerRequestProcessor.serveError | private void serveError(Status status, ErrorMessage.FailureReason reason, RequestHandler requestHandler) throws IOException {
this.serveError(status, reason.getMessage(), requestHandler);
} | java | private void serveError(Status status, ErrorMessage.FailureReason reason, RequestHandler requestHandler) throws IOException {
this.serveError(status, reason.getMessage(), requestHandler);
} | [
"private",
"void",
"serveError",
"(",
"Status",
"status",
",",
"ErrorMessage",
".",
"FailureReason",
"reason",
",",
"RequestHandler",
"requestHandler",
")",
"throws",
"IOException",
"{",
"this",
".",
"serveError",
"(",
"status",
",",
"reason",
".",
"getMessage",
... | Write a tracker failure reason code to the response with the given HTTP
status code.
@param status The HTTP status code to return.
@param reason The failure reason reported by the tracker. | [
"Write",
"a",
"tracker",
"failure",
"reason",
"code",
"to",
"the",
"response",
"with",
"the",
"given",
"HTTP",
"status",
"code",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/TrackerRequestProcessor.java#L311-L313 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | TrackerClient.formatAnnounceEvent | protected String formatAnnounceEvent(
AnnounceRequestMessage.RequestEvent event) {
return AnnounceRequestMessage.RequestEvent.NONE.equals(event)
? ""
: String.format(" %s", event.name());
} | java | protected String formatAnnounceEvent(
AnnounceRequestMessage.RequestEvent event) {
return AnnounceRequestMessage.RequestEvent.NONE.equals(event)
? ""
: String.format(" %s", event.name());
} | [
"protected",
"String",
"formatAnnounceEvent",
"(",
"AnnounceRequestMessage",
".",
"RequestEvent",
"event",
")",
"{",
"return",
"AnnounceRequestMessage",
".",
"RequestEvent",
".",
"NONE",
".",
"equals",
"(",
"event",
")",
"?",
"\"\"",
":",
"String",
".",
"format",
... | Formats an announce event into a usable string. | [
"Formats",
"an",
"announce",
"event",
"into",
"a",
"usable",
"string",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java#L141-L146 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | TrackerClient.handleTrackerAnnounceResponse | protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
if (message instanceof ErrorMessage) {
ErrorMessage error = (ErrorMessage) message;
throw new AnnounceException(error.getReason());
}
if (!(message instanceof AnnounceResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
AnnounceResponseMessage response =
(AnnounceResponseMessage) message;
this.fireAnnounceResponseEvent(
response.getComplete(),
response.getIncomplete(),
response.getInterval(),
hexInfoHash);
if (inhibitEvents) {
return;
}
this.fireDiscoveredPeersEvent(
response.getPeers(),
hexInfoHash);
} | java | protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
if (message instanceof ErrorMessage) {
ErrorMessage error = (ErrorMessage) message;
throw new AnnounceException(error.getReason());
}
if (!(message instanceof AnnounceResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
AnnounceResponseMessage response =
(AnnounceResponseMessage) message;
this.fireAnnounceResponseEvent(
response.getComplete(),
response.getIncomplete(),
response.getInterval(),
hexInfoHash);
if (inhibitEvents) {
return;
}
this.fireDiscoveredPeersEvent(
response.getPeers(),
hexInfoHash);
} | [
"protected",
"void",
"handleTrackerAnnounceResponse",
"(",
"TrackerMessage",
"message",
",",
"boolean",
"inhibitEvents",
",",
"String",
"hexInfoHash",
")",
"throws",
"AnnounceException",
"{",
"if",
"(",
"message",
"instanceof",
"ErrorMessage",
")",
"{",
"ErrorMessage",
... | Handle the announce response from the tracker.
<p>
Analyzes the response from the tracker and acts on it. If the response
is an error, it is logged. Otherwise, the announce response is used
to fire the corresponding announce and peer events to all announce
listeners.
</p>
@param message The incoming {@link TrackerMessage}.
@param inhibitEvents Whether or not to prevent events from being fired. | [
"Handle",
"the",
"announce",
"response",
"from",
"the",
"tracker",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java#L161-L190 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | TrackerClient.fireAnnounceResponseEvent | protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash);
}
} | java | protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash);
}
} | [
"protected",
"void",
"fireAnnounceResponseEvent",
"(",
"int",
"complete",
",",
"int",
"incomplete",
",",
"int",
"interval",
",",
"String",
"hexInfoHash",
")",
"{",
"for",
"(",
"AnnounceResponseListener",
"listener",
":",
"this",
".",
"listeners",
")",
"{",
"list... | Fire the announce response event to all listeners.
@param complete The number of seeders on this torrent.
@param incomplete The number of leechers on this torrent.
@param interval The announce interval requested by the tracker. | [
"Fire",
"the",
"announce",
"response",
"event",
"to",
"all",
"listeners",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java#L199-L203 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | TrackerClient.fireDiscoveredPeersEvent | protected void fireDiscoveredPeersEvent(List<Peer> peers, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleDiscoveredPeers(peers, hexInfoHash);
}
} | java | protected void fireDiscoveredPeersEvent(List<Peer> peers, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleDiscoveredPeers(peers, hexInfoHash);
}
} | [
"protected",
"void",
"fireDiscoveredPeersEvent",
"(",
"List",
"<",
"Peer",
">",
"peers",
",",
"String",
"hexInfoHash",
")",
"{",
"for",
"(",
"AnnounceResponseListener",
"listener",
":",
"this",
".",
"listeners",
")",
"{",
"listener",
".",
"handleDiscoveredPeers",
... | Fire the new peer discovery event to all listeners.
@param peers The list of peers discovered. | [
"Fire",
"the",
"new",
"peer",
"discovery",
"event",
"to",
"all",
"listeners",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java#L210-L214 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/storage/FileStorage.java | FileStorage.finish | @Override
public void finish() throws IOException {
try {
myLock.writeLock().lock();
logger.debug("Closing file channel to " + this.current.getName() +
" (download complete).");
if (this.channel.isOpen()) {
this.channel.force(true);
}
// Nothing more to do if we're already on the target file.
if (this.isFinished()) {
return;
}
try {
FileUtils.deleteQuietly(this.target);
this.raf.close();
FileUtils.moveFile(this.current, this.target);
} catch (Exception ex) {
logger.error("An error occurred while moving file to its final location", ex);
if (this.target.exists()) {
throw new IOException("Was unable to delete existing file " + target.getAbsolutePath(), ex);
}
FileUtils.copyFile(this.current, this.target);
}
this.current = this.target;
FileUtils.deleteQuietly(this.partial);
myIsOpen = false;
logger.debug("Moved torrent data from {} to {}.",
this.partial.getName(),
this.target.getName());
} finally {
myLock.writeLock().unlock();
}
} | java | @Override
public void finish() throws IOException {
try {
myLock.writeLock().lock();
logger.debug("Closing file channel to " + this.current.getName() +
" (download complete).");
if (this.channel.isOpen()) {
this.channel.force(true);
}
// Nothing more to do if we're already on the target file.
if (this.isFinished()) {
return;
}
try {
FileUtils.deleteQuietly(this.target);
this.raf.close();
FileUtils.moveFile(this.current, this.target);
} catch (Exception ex) {
logger.error("An error occurred while moving file to its final location", ex);
if (this.target.exists()) {
throw new IOException("Was unable to delete existing file " + target.getAbsolutePath(), ex);
}
FileUtils.copyFile(this.current, this.target);
}
this.current = this.target;
FileUtils.deleteQuietly(this.partial);
myIsOpen = false;
logger.debug("Moved torrent data from {} to {}.",
this.partial.getName(),
this.target.getName());
} finally {
myLock.writeLock().unlock();
}
} | [
"@",
"Override",
"public",
"void",
"finish",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"myLock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Closing file channel to \"",
"+",
"this",
".",
"current",
"... | Move the partial file to its final location. | [
"Move",
"the",
"partial",
"file",
"to",
"its",
"final",
"location",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/storage/FileStorage.java#L182-L219 | train |
mpetazzoni/ttorrent | common/src/main/java/com/turn/ttorrent/common/protocol/http/HTTPAnnounceResponseMessage.java | HTTPAnnounceResponseMessage.craft | public static HTTPAnnounceResponseMessage craft(int interval,
int complete, int incomplete,
List<Peer> peers, String hexInfoHash) throws IOException, UnsupportedEncodingException {
Map<String, BEValue> response = new HashMap<String, BEValue>();
response.put("interval", new BEValue(interval));
response.put("complete", new BEValue(complete));
response.put("incomplete", new BEValue(incomplete));
if (hexInfoHash != null) {
response.put("torrentIdentifier", new BEValue(hexInfoHash));
}
ByteBuffer data = ByteBuffer.allocate(peers.size() * 6);
for (Peer peer : peers) {
byte[] ip = peer.getRawIp();
if (ip == null || ip.length != 4) {
continue;
}
data.put(ip);
data.putShort((short) peer.getPort());
}
response.put("peers", new BEValue(Arrays.copyOf(data.array(), data.position())));
return new HTTPAnnounceResponseMessage(
BEncoder.bencode(response),
interval, complete, incomplete, peers, hexInfoHash);
} | java | public static HTTPAnnounceResponseMessage craft(int interval,
int complete, int incomplete,
List<Peer> peers, String hexInfoHash) throws IOException, UnsupportedEncodingException {
Map<String, BEValue> response = new HashMap<String, BEValue>();
response.put("interval", new BEValue(interval));
response.put("complete", new BEValue(complete));
response.put("incomplete", new BEValue(incomplete));
if (hexInfoHash != null) {
response.put("torrentIdentifier", new BEValue(hexInfoHash));
}
ByteBuffer data = ByteBuffer.allocate(peers.size() * 6);
for (Peer peer : peers) {
byte[] ip = peer.getRawIp();
if (ip == null || ip.length != 4) {
continue;
}
data.put(ip);
data.putShort((short) peer.getPort());
}
response.put("peers", new BEValue(Arrays.copyOf(data.array(), data.position())));
return new HTTPAnnounceResponseMessage(
BEncoder.bencode(response),
interval, complete, incomplete, peers, hexInfoHash);
} | [
"public",
"static",
"HTTPAnnounceResponseMessage",
"craft",
"(",
"int",
"interval",
",",
"int",
"complete",
",",
"int",
"incomplete",
",",
"List",
"<",
"Peer",
">",
"peers",
",",
"String",
"hexInfoHash",
")",
"throws",
"IOException",
",",
"UnsupportedEncodingExcep... | Craft a compact announce response message with a torrent identifier.
@param interval
@param complete
@param incomplete
@param peers | [
"Craft",
"a",
"compact",
"announce",
"response",
"message",
"with",
"a",
"torrent",
"identifier",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/protocol/http/HTTPAnnounceResponseMessage.java#L198-L223 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/storage/FileCollectionStorage.java | FileCollectionStorage.select | private List<FileOffset> select(long offset, long length) {
if (offset + length > this.size) {
throw new IllegalArgumentException("Buffer overrun (" +
offset + " + " + length + " > " + this.size + ") !");
}
List<FileOffset> selected = new LinkedList<FileOffset>();
long bytes = 0;
for (FileStorage file : this.files) {
if (file.offset() >= offset + length) {
break;
}
if (file.offset() + file.size() < offset) {
continue;
}
long position = offset - file.offset();
position = position > 0 ? position : 0;
long size = Math.min(
file.size() - position,
length - bytes);
selected.add(new FileOffset(file, position, size));
bytes += size;
}
if (selected.size() == 0 || bytes < length) {
throw new IllegalStateException("Buffer underrun (only got " +
bytes + " out of " + length + " byte(s) requested)!");
}
return selected;
} | java | private List<FileOffset> select(long offset, long length) {
if (offset + length > this.size) {
throw new IllegalArgumentException("Buffer overrun (" +
offset + " + " + length + " > " + this.size + ") !");
}
List<FileOffset> selected = new LinkedList<FileOffset>();
long bytes = 0;
for (FileStorage file : this.files) {
if (file.offset() >= offset + length) {
break;
}
if (file.offset() + file.size() < offset) {
continue;
}
long position = offset - file.offset();
position = position > 0 ? position : 0;
long size = Math.min(
file.size() - position,
length - bytes);
selected.add(new FileOffset(file, position, size));
bytes += size;
}
if (selected.size() == 0 || bytes < length) {
throw new IllegalStateException("Buffer underrun (only got " +
bytes + " out of " + length + " byte(s) requested)!");
}
return selected;
} | [
"private",
"List",
"<",
"FileOffset",
">",
"select",
"(",
"long",
"offset",
",",
"long",
"length",
")",
"{",
"if",
"(",
"offset",
"+",
"length",
">",
"this",
".",
"size",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Buffer overrun (\"",
"+... | Select the group of files impacted by an operation.
<p>
This function selects which files are impacted by a read or write
operation, with their respective relative offset and chunk length.
</p>
@param offset The offset of the operation, in bytes, relative to the
complete byte storage.
@param length The number of bytes to read or write.
@return A list of {@link FileOffset} objects representing the {@link
FileStorage}s impacted by the operation, bundled with their
respective relative offset and number of bytes to read or write.
@throws IllegalArgumentException If the offset and length go over the
byte storage size.
@throws IllegalStateException If the files registered with this byte
storage can't accommodate the request (should not happen, really). | [
"Select",
"the",
"group",
"of",
"files",
"impacted",
"by",
"an",
"operation",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/storage/FileCollectionStorage.java#L215-L248 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.handleTrackerAnnounceResponse | @Override
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
this.validateTrackerResponse(message);
super.handleTrackerAnnounceResponse(message, inhibitEvents, hexInfoHash);
} | java | @Override
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
this.validateTrackerResponse(message);
super.handleTrackerAnnounceResponse(message, inhibitEvents, hexInfoHash);
} | [
"@",
"Override",
"protected",
"void",
"handleTrackerAnnounceResponse",
"(",
"TrackerMessage",
"message",
",",
"boolean",
"inhibitEvents",
",",
"String",
"hexInfoHash",
")",
"throws",
"AnnounceException",
"{",
"this",
".",
"validateTrackerResponse",
"(",
"message",
")",
... | Handles the tracker announce response message.
<p>
Verifies the transaction ID of the message before passing it over to
{@link Announce#()}.
</p>
@param message The message received from the tracker in response to the
announce request. | [
"Handles",
"the",
"tracker",
"announce",
"response",
"message",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L248-L253 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.close | @Override
protected void close() {
this.stop = true;
// Close the socket to force blocking operations to return.
if (this.socket != null && !this.socket.isClosed()) {
this.socket.close();
}
} | java | @Override
protected void close() {
this.stop = true;
// Close the socket to force blocking operations to return.
if (this.socket != null && !this.socket.isClosed()) {
this.socket.close();
}
} | [
"@",
"Override",
"protected",
"void",
"close",
"(",
")",
"{",
"this",
".",
"stop",
"=",
"true",
";",
"// Close the socket to force blocking operations to return.",
"if",
"(",
"this",
".",
"socket",
"!=",
"null",
"&&",
"!",
"this",
".",
"socket",
".",
"isClosed... | Close this announce connection. | [
"Close",
"this",
"announce",
"connection",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L258-L266 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.validateTrackerResponse | private void validateTrackerResponse(TrackerMessage message)
throws AnnounceException {
if (message instanceof ErrorMessage) {
throw new AnnounceException(((ErrorMessage) message).getReason());
}
if (message instanceof UDPTrackerMessage &&
(((UDPTrackerMessage) message).getTransactionId() != this.transactionId)) {
throw new AnnounceException("Invalid transaction ID!");
}
} | java | private void validateTrackerResponse(TrackerMessage message)
throws AnnounceException {
if (message instanceof ErrorMessage) {
throw new AnnounceException(((ErrorMessage) message).getReason());
}
if (message instanceof UDPTrackerMessage &&
(((UDPTrackerMessage) message).getTransactionId() != this.transactionId)) {
throw new AnnounceException("Invalid transaction ID!");
}
} | [
"private",
"void",
"validateTrackerResponse",
"(",
"TrackerMessage",
"message",
")",
"throws",
"AnnounceException",
"{",
"if",
"(",
"message",
"instanceof",
"ErrorMessage",
")",
"{",
"throw",
"new",
"AnnounceException",
"(",
"(",
"(",
"ErrorMessage",
")",
"message",... | Validates an incoming tracker message.
<p>
Verifies that the message is not an error message (throws an exception
with the error message if it is) and that the transaction ID matches the
current one.
</p>
@param message The incoming tracker message. | [
"Validates",
"an",
"incoming",
"tracker",
"message",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L296-L306 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.handleTrackerConnectResponse | private void handleTrackerConnectResponse(TrackerMessage message)
throws AnnounceException {
this.validateTrackerResponse(message);
if (!(message instanceof ConnectionResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
UDPConnectResponseMessage connectResponse =
(UDPConnectResponseMessage) message;
this.connectionId = connectResponse.getConnectionId();
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, 1);
this.connectionExpiration = now.getTime();
} | java | private void handleTrackerConnectResponse(TrackerMessage message)
throws AnnounceException {
this.validateTrackerResponse(message);
if (!(message instanceof ConnectionResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
UDPConnectResponseMessage connectResponse =
(UDPConnectResponseMessage) message;
this.connectionId = connectResponse.getConnectionId();
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, 1);
this.connectionExpiration = now.getTime();
} | [
"private",
"void",
"handleTrackerConnectResponse",
"(",
"TrackerMessage",
"message",
")",
"throws",
"AnnounceException",
"{",
"this",
".",
"validateTrackerResponse",
"(",
"message",
")",
";",
"if",
"(",
"!",
"(",
"message",
"instanceof",
"ConnectionResponseMessage",
"... | Handles the tracker connect response message.
@param message The message received from the tracker in response to the
connection request. | [
"Handles",
"the",
"tracker",
"connect",
"response",
"message",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L314-L330 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.send | private void send(ByteBuffer data) {
try {
this.socket.send(new DatagramPacket(
data.array(),
data.capacity(),
this.address));
} catch (IOException ioe) {
logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
}
} | java | private void send(ByteBuffer data) {
try {
this.socket.send(new DatagramPacket(
data.array(),
data.capacity(),
this.address));
} catch (IOException ioe) {
logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
}
} | [
"private",
"void",
"send",
"(",
"ByteBuffer",
"data",
")",
"{",
"try",
"{",
"this",
".",
"socket",
".",
"send",
"(",
"new",
"DatagramPacket",
"(",
"data",
".",
"array",
"(",
")",
",",
"data",
".",
"capacity",
"(",
")",
",",
"this",
".",
"address",
... | Send a UDP packet to the tracker.
@param data The {@link ByteBuffer} to send in a datagram packet to the
tracker. | [
"Send",
"a",
"UDP",
"packet",
"to",
"the",
"tracker",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L338-L347 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java | UDPTrackerClient.recv | private ByteBuffer recv(int attempt)
throws IOException, SocketException, SocketTimeoutException {
int timeout = UDP_BASE_TIMEOUT_SECONDS * (int) Math.pow(2, attempt);
logger.trace("Setting receive timeout to {}s for attempt {}...",
timeout, attempt);
this.socket.setSoTimeout(timeout * 1000);
try {
DatagramPacket p = new DatagramPacket(
new byte[UDP_PACKET_LENGTH],
UDP_PACKET_LENGTH);
this.socket.receive(p);
return ByteBuffer.wrap(p.getData(), 0, p.getLength());
} catch (SocketTimeoutException ste) {
throw ste;
}
} | java | private ByteBuffer recv(int attempt)
throws IOException, SocketException, SocketTimeoutException {
int timeout = UDP_BASE_TIMEOUT_SECONDS * (int) Math.pow(2, attempt);
logger.trace("Setting receive timeout to {}s for attempt {}...",
timeout, attempt);
this.socket.setSoTimeout(timeout * 1000);
try {
DatagramPacket p = new DatagramPacket(
new byte[UDP_PACKET_LENGTH],
UDP_PACKET_LENGTH);
this.socket.receive(p);
return ByteBuffer.wrap(p.getData(), 0, p.getLength());
} catch (SocketTimeoutException ste) {
throw ste;
}
} | [
"private",
"ByteBuffer",
"recv",
"(",
"int",
"attempt",
")",
"throws",
"IOException",
",",
"SocketException",
",",
"SocketTimeoutException",
"{",
"int",
"timeout",
"=",
"UDP_BASE_TIMEOUT_SECONDS",
"*",
"(",
"int",
")",
"Math",
".",
"pow",
"(",
"2",
",",
"attem... | Receive a UDP packet from the tracker.
@param attempt The attempt number, used to calculate the timeout for the
receive operation.
@retun Returns a {@link ByteBuffer} containing the packet data. | [
"Receive",
"a",
"UDP",
"packet",
"from",
"the",
"tracker",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/UDPTrackerClient.java#L356-L372 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java | BEValue.getString | public String getString(String encoding) throws InvalidBEncodingException {
try {
return new String(this.getBytes(), encoding);
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
} catch (UnsupportedEncodingException uee) {
throw new InternalError(uee.toString());
}
} | java | public String getString(String encoding) throws InvalidBEncodingException {
try {
return new String(this.getBytes(), encoding);
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
} catch (UnsupportedEncodingException uee) {
throw new InternalError(uee.toString());
}
} | [
"public",
"String",
"getString",
"(",
"String",
"encoding",
")",
"throws",
"InvalidBEncodingException",
"{",
"try",
"{",
"return",
"new",
"String",
"(",
"this",
".",
"getBytes",
"(",
")",
",",
"encoding",
")",
";",
"}",
"catch",
"(",
"ClassCastException",
"c... | Returns this BEValue as a String, interpreted with the specified
encoding.
@param encoding The encoding to interpret the bytes as when converting
them into a {@link String}.
@throws InvalidBEncodingException If the value is not a byte[]. | [
"Returns",
"this",
"BEValue",
"as",
"a",
"String",
"interpreted",
"with",
"the",
"specified",
"encoding",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java#L92-L100 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java | BEValue.getNumber | public Number getNumber() throws InvalidBEncodingException {
try {
return (Number) this.value;
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
}
} | java | public Number getNumber() throws InvalidBEncodingException {
try {
return (Number) this.value;
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
}
} | [
"public",
"Number",
"getNumber",
"(",
")",
"throws",
"InvalidBEncodingException",
"{",
"try",
"{",
"return",
"(",
"Number",
")",
"this",
".",
"value",
";",
"}",
"catch",
"(",
"ClassCastException",
"cce",
")",
"{",
"throw",
"new",
"InvalidBEncodingException",
"... | Returns this BEValue as a Number.
@throws InvalidBEncodingException If the value is not a {@link Number}. | [
"Returns",
"this",
"BEValue",
"as",
"a",
"Number",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java#L120-L126 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java | BEValue.getList | @SuppressWarnings("unchecked")
public List<BEValue> getList() throws InvalidBEncodingException {
if (this.value instanceof ArrayList) {
return (ArrayList<BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Excepted List<BEvalue> !");
}
} | java | @SuppressWarnings("unchecked")
public List<BEValue> getList() throws InvalidBEncodingException {
if (this.value instanceof ArrayList) {
return (ArrayList<BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Excepted List<BEvalue> !");
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"List",
"<",
"BEValue",
">",
"getList",
"(",
")",
"throws",
"InvalidBEncodingException",
"{",
"if",
"(",
"this",
".",
"value",
"instanceof",
"ArrayList",
")",
"{",
"return",
"(",
"ArrayList",
"<",
... | Returns this BEValue as a List of BEValues.
@throws InvalidBEncodingException If the value is not an
{@link ArrayList}. | [
"Returns",
"this",
"BEValue",
"as",
"a",
"List",
"of",
"BEValues",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java#L161-L168 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java | BEValue.getMap | @SuppressWarnings("unchecked")
public Map<String, BEValue> getMap() throws InvalidBEncodingException {
if (this.value instanceof HashMap) {
return (Map<String, BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Expected Map<String, BEValue> !");
}
} | java | @SuppressWarnings("unchecked")
public Map<String, BEValue> getMap() throws InvalidBEncodingException {
if (this.value instanceof HashMap) {
return (Map<String, BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Expected Map<String, BEValue> !");
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"Map",
"<",
"String",
",",
"BEValue",
">",
"getMap",
"(",
")",
"throws",
"InvalidBEncodingException",
"{",
"if",
"(",
"this",
".",
"value",
"instanceof",
"HashMap",
")",
"{",
"return",
"(",
"Map",... | Returns this BEValue as a Map of String keys and BEValue values.
@throws InvalidBEncodingException If the value is not a {@link HashMap}. | [
"Returns",
"this",
"BEValue",
"as",
"a",
"Map",
"of",
"String",
"keys",
"and",
"BEValue",
"values",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BEValue.java#L175-L182 | train |
mpetazzoni/ttorrent | ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/Tracker.java | Tracker.start | public void start(final boolean startPeerCleaningThread) throws IOException {
logger.info("Starting BitTorrent tracker on {}...",
getAnnounceUrl());
connection = new SocketConnection(new ContainerServer(myTrackerServiceContainer));
List<SocketAddress> tries = new ArrayList<SocketAddress>() {{
try {
add(new InetSocketAddress(InetAddress.getByAddress(new byte[4]), myPort));
} catch (Exception ex) {
}
try {
add(new InetSocketAddress(InetAddress.getLocalHost(), myPort));
} catch (Exception ex) {
}
try {
add(new InetSocketAddress(InetAddress.getByName(new URL(getAnnounceUrl()).getHost()), myPort));
} catch (Exception ex) {
}
}};
boolean started = false;
for (SocketAddress address : tries) {
try {
if ((myBoundAddress = connection.connect(address)) != null) {
logger.info("Started torrent tracker on {}", address);
started = true;
break;
}
} catch (IOException ioe) {
logger.info("Can't start the tracker using address{} : ", address.toString(), ioe.getMessage());
}
}
if (!started) {
logger.error("Cannot start tracker on port {}. Stopping now...", myPort);
stop();
return;
}
if (startPeerCleaningThread) {
if (myPeerCollectorThread == null || !myPeerCollectorThread.isAlive() || myPeerCollectorThread.getState() != Thread.State.NEW) {
myPeerCollectorThread = new PeerCollectorThread(myTorrentsRepository);
}
myPeerCollectorThread.setName("peer-peerCollectorThread:" + myPort);
myPeerCollectorThread.start();
}
} | java | public void start(final boolean startPeerCleaningThread) throws IOException {
logger.info("Starting BitTorrent tracker on {}...",
getAnnounceUrl());
connection = new SocketConnection(new ContainerServer(myTrackerServiceContainer));
List<SocketAddress> tries = new ArrayList<SocketAddress>() {{
try {
add(new InetSocketAddress(InetAddress.getByAddress(new byte[4]), myPort));
} catch (Exception ex) {
}
try {
add(new InetSocketAddress(InetAddress.getLocalHost(), myPort));
} catch (Exception ex) {
}
try {
add(new InetSocketAddress(InetAddress.getByName(new URL(getAnnounceUrl()).getHost()), myPort));
} catch (Exception ex) {
}
}};
boolean started = false;
for (SocketAddress address : tries) {
try {
if ((myBoundAddress = connection.connect(address)) != null) {
logger.info("Started torrent tracker on {}", address);
started = true;
break;
}
} catch (IOException ioe) {
logger.info("Can't start the tracker using address{} : ", address.toString(), ioe.getMessage());
}
}
if (!started) {
logger.error("Cannot start tracker on port {}. Stopping now...", myPort);
stop();
return;
}
if (startPeerCleaningThread) {
if (myPeerCollectorThread == null || !myPeerCollectorThread.isAlive() || myPeerCollectorThread.getState() != Thread.State.NEW) {
myPeerCollectorThread = new PeerCollectorThread(myTorrentsRepository);
}
myPeerCollectorThread.setName("peer-peerCollectorThread:" + myPort);
myPeerCollectorThread.start();
}
} | [
"public",
"void",
"start",
"(",
"final",
"boolean",
"startPeerCleaningThread",
")",
"throws",
"IOException",
"{",
"logger",
".",
"info",
"(",
"\"Starting BitTorrent tracker on {}...\"",
",",
"getAnnounceUrl",
"(",
")",
")",
";",
"connection",
"=",
"new",
"SocketConn... | Start the tracker thread. | [
"Start",
"the",
"tracker",
"thread",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-tracker/src/main/java/com/turn/ttorrent/tracker/Tracker.java#L148-L193 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/HTTPTrackerClient.java | HTTPTrackerClient.announce | public void announce(final AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, final AnnounceableInformation torrentInfo, final List<Peer> adresses) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
final List<HTTPTrackerMessage> trackerResponses = new ArrayList<HTTPTrackerMessage>();
for (final Peer address : adresses) {
final URL target = encodeAnnounceToURL(event, torrentInfo, address);
try {
sendAnnounce(target, "GET", new ResponseParser() {
@Override
public void parse(InputStream inputStream, int responseCode) throws IOException, MessageValidationException {
if (responseCode != 200) {
logger.info("received not http 200 code from tracker for request " + target);
return;
}
trackerResponses.add(HTTPTrackerMessage.parse(inputStream));
}
});
} catch (ConnectException e) {
throw new AnnounceException(e.getMessage(), e);
}
}
// we process only first request:
if (trackerResponses.size() > 0) {
final HTTPTrackerMessage message = trackerResponses.get(0);
this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash());
}
} | java | public void announce(final AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, final AnnounceableInformation torrentInfo, final List<Peer> adresses) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
final List<HTTPTrackerMessage> trackerResponses = new ArrayList<HTTPTrackerMessage>();
for (final Peer address : adresses) {
final URL target = encodeAnnounceToURL(event, torrentInfo, address);
try {
sendAnnounce(target, "GET", new ResponseParser() {
@Override
public void parse(InputStream inputStream, int responseCode) throws IOException, MessageValidationException {
if (responseCode != 200) {
logger.info("received not http 200 code from tracker for request " + target);
return;
}
trackerResponses.add(HTTPTrackerMessage.parse(inputStream));
}
});
} catch (ConnectException e) {
throw new AnnounceException(e.getMessage(), e);
}
}
// we process only first request:
if (trackerResponses.size() > 0) {
final HTTPTrackerMessage message = trackerResponses.get(0);
this.handleTrackerAnnounceResponse(message, inhibitEvents, torrentInfo.getHexInfoHash());
}
} | [
"public",
"void",
"announce",
"(",
"final",
"AnnounceRequestMessage",
".",
"RequestEvent",
"event",
",",
"boolean",
"inhibitEvents",
",",
"final",
"AnnounceableInformation",
"torrentInfo",
",",
"final",
"List",
"<",
"Peer",
">",
"adresses",
")",
"throws",
"AnnounceE... | Build, send and process a tracker announce request.
<p>
This function first builds an announce request for the specified event
with all the required parameters. Then, the request is made to the
tracker and the response analyzed.
</p>
<p>
All registered {@link AnnounceResponseListener} objects are then fired
with the decoded payload.
</p>
@param event The announce event type (can be AnnounceEvent.NONE for
periodic updates).
@param inhibitEvents Prevent event listeners from being notified.
@param torrentInfo | [
"Build",
"send",
"and",
"process",
"a",
"tracker",
"announce",
"request",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/HTTPTrackerClient.java#L77-L104 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/HTTPTrackerClient.java | HTTPTrackerClient.buildAnnounceRequest | private HTTPAnnounceRequestMessage buildAnnounceRequest(
AnnounceRequestMessage.RequestEvent event, AnnounceableInformation torrentInfo, Peer peer)
throws IOException,
MessageValidationException {
// Build announce request message
final long uploaded = torrentInfo.getUploaded();
final long downloaded = torrentInfo.getDownloaded();
final long left = torrentInfo.getLeft();
return HTTPAnnounceRequestMessage.craft(
torrentInfo.getInfoHash(),
peer.getPeerIdArray(),
peer.getPort(),
uploaded,
downloaded,
left,
true, false, event,
peer.getIp(),
AnnounceRequestMessage.DEFAULT_NUM_WANT);
} | java | private HTTPAnnounceRequestMessage buildAnnounceRequest(
AnnounceRequestMessage.RequestEvent event, AnnounceableInformation torrentInfo, Peer peer)
throws IOException,
MessageValidationException {
// Build announce request message
final long uploaded = torrentInfo.getUploaded();
final long downloaded = torrentInfo.getDownloaded();
final long left = torrentInfo.getLeft();
return HTTPAnnounceRequestMessage.craft(
torrentInfo.getInfoHash(),
peer.getPeerIdArray(),
peer.getPort(),
uploaded,
downloaded,
left,
true, false, event,
peer.getIp(),
AnnounceRequestMessage.DEFAULT_NUM_WANT);
} | [
"private",
"HTTPAnnounceRequestMessage",
"buildAnnounceRequest",
"(",
"AnnounceRequestMessage",
".",
"RequestEvent",
"event",
",",
"AnnounceableInformation",
"torrentInfo",
",",
"Peer",
"peer",
")",
"throws",
"IOException",
",",
"MessageValidationException",
"{",
"// Build an... | Build the announce request tracker message.
@param event The announce event (can be <tt>NONE</tt> or <em>null</em>)
@return Returns an instance of a {@link HTTPAnnounceRequestMessage}
that can be used to generate the fully qualified announce URL, with
parameters, to make the announce request.
@throws UnsupportedEncodingException
@throws IOException
@throws MessageValidationException | [
"Build",
"the",
"announce",
"request",
"tracker",
"message",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/HTTPTrackerClient.java#L309-L327 | train |
mpetazzoni/ttorrent | common/src/main/java/com/turn/ttorrent/common/protocol/http/HTTPAnnounceRequestMessage.java | HTTPAnnounceRequestMessage.buildAnnounceURL | public URL buildAnnounceURL(URL trackerAnnounceURL)
throws UnsupportedEncodingException, MalformedURLException {
String base = trackerAnnounceURL.toString();
StringBuilder url = new StringBuilder(base);
url.append(base.contains("?") ? "&" : "?")
.append("info_hash=")
.append(URLEncoder.encode(
new String(this.getInfoHash(), Constants.BYTE_ENCODING),
Constants.BYTE_ENCODING))
.append("&peer_id=")
.append(URLEncoder.encode(
new String(this.getPeerId(), Constants.BYTE_ENCODING),
Constants.BYTE_ENCODING))
.append("&port=").append(this.getPort())
.append("&uploaded=").append(this.getUploaded())
.append("&downloaded=").append(this.getDownloaded())
.append("&left=").append(this.getLeft())
.append("&compact=").append(this.isCompact() ? 1 : 0)
.append("&no_peer_id=").append(this.canOmitPeerId() ? 1 : 0);
if (this.getEvent() != null &&
!RequestEvent.NONE.equals(this.getEvent())) {
url.append("&event=").append(this.getEvent().getEventName());
}
if (this.getIp() != null) {
url.append("&ip=").append(this.getIp());
}
return new URL(url.toString());
} | java | public URL buildAnnounceURL(URL trackerAnnounceURL)
throws UnsupportedEncodingException, MalformedURLException {
String base = trackerAnnounceURL.toString();
StringBuilder url = new StringBuilder(base);
url.append(base.contains("?") ? "&" : "?")
.append("info_hash=")
.append(URLEncoder.encode(
new String(this.getInfoHash(), Constants.BYTE_ENCODING),
Constants.BYTE_ENCODING))
.append("&peer_id=")
.append(URLEncoder.encode(
new String(this.getPeerId(), Constants.BYTE_ENCODING),
Constants.BYTE_ENCODING))
.append("&port=").append(this.getPort())
.append("&uploaded=").append(this.getUploaded())
.append("&downloaded=").append(this.getDownloaded())
.append("&left=").append(this.getLeft())
.append("&compact=").append(this.isCompact() ? 1 : 0)
.append("&no_peer_id=").append(this.canOmitPeerId() ? 1 : 0);
if (this.getEvent() != null &&
!RequestEvent.NONE.equals(this.getEvent())) {
url.append("&event=").append(this.getEvent().getEventName());
}
if (this.getIp() != null) {
url.append("&ip=").append(this.getIp());
}
return new URL(url.toString());
} | [
"public",
"URL",
"buildAnnounceURL",
"(",
"URL",
"trackerAnnounceURL",
")",
"throws",
"UnsupportedEncodingException",
",",
"MalformedURLException",
"{",
"String",
"base",
"=",
"trackerAnnounceURL",
".",
"toString",
"(",
")",
";",
"StringBuilder",
"url",
"=",
"new",
... | Build the announce request URL for the given tracker announce URL.
@param trackerAnnounceURL The tracker's announce URL.
@return The URL object representing the announce request URL. | [
"Build",
"the",
"announce",
"request",
"URL",
"for",
"the",
"given",
"tracker",
"announce",
"URL",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/protocol/http/HTTPAnnounceRequestMessage.java#L158-L188 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/peer/Rate.java | Rate.add | public synchronized void add(long count) {
this.bytes += count;
if (this.reset == 0) {
this.reset = System.currentTimeMillis();
}
this.last = System.currentTimeMillis();
} | java | public synchronized void add(long count) {
this.bytes += count;
if (this.reset == 0) {
this.reset = System.currentTimeMillis();
}
this.last = System.currentTimeMillis();
} | [
"public",
"synchronized",
"void",
"add",
"(",
"long",
"count",
")",
"{",
"this",
".",
"bytes",
"+=",
"count",
";",
"if",
"(",
"this",
".",
"reset",
"==",
"0",
")",
"{",
"this",
".",
"reset",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"... | Add a byte count to the current measurement.
@param count The number of bytes exchanged since the last reset. | [
"Add",
"a",
"byte",
"count",
"to",
"the",
"current",
"measurement",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/peer/Rate.java#L47-L53 | train |
mpetazzoni/ttorrent | common/src/main/java/com/turn/ttorrent/common/Peer.java | Peer.getRawIp | public byte[] getRawIp() {
final InetAddress address = this.address.getAddress();
if (address == null) return null;
return address.getAddress();
} | java | public byte[] getRawIp() {
final InetAddress address = this.address.getAddress();
if (address == null) return null;
return address.getAddress();
} | [
"public",
"byte",
"[",
"]",
"getRawIp",
"(",
")",
"{",
"final",
"InetAddress",
"address",
"=",
"this",
".",
"address",
".",
"getAddress",
"(",
")",
";",
"if",
"(",
"address",
"==",
"null",
")",
"return",
"null",
";",
"return",
"address",
".",
"getAddre... | Returns a binary representation of the peer's IP. | [
"Returns",
"a",
"binary",
"representation",
"of",
"the",
"peer",
"s",
"IP",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/common/src/main/java/com/turn/ttorrent/common/Peer.java#L181-L185 | train |
mpetazzoni/ttorrent | cli/src/main/java/com/turn/ttorrent/cli/TrackerMain.java | TrackerMain.main | public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option port = parser.addIntegerOption('p', "port");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException oe) {
System.err.println(oe.getMessage());
usage(System.err);
System.exit(1);
}
// Display help and exit if requested
if (Boolean.TRUE.equals((Boolean)parser.getOptionValue(help))) {
usage(System.out);
System.exit(0);
}
Integer portValue = (Integer)parser.getOptionValue(port,
Integer.valueOf(Tracker.DEFAULT_TRACKER_PORT));
String[] otherArgs = parser.getRemainingArgs();
if (otherArgs.length > 1) {
usage(System.err);
System.exit(1);
}
// Get directory from command-line argument or default to current
// directory
String directory = otherArgs.length > 0
? otherArgs[0]
: ".";
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".torrent");
}
};
try {
Tracker t = new Tracker(portValue);
File parent = new File(directory);
for (File f : parent.listFiles(filter)) {
logger.info("Loading torrent from " + f.getName());
t.announce(TrackedTorrent.load(f));
}
logger.info("Starting tracker with {} announced torrents...",
t.getTrackedTorrents().size());
t.start(true);
} catch (Exception e) {
logger.error("{}", e.getMessage(), e);
System.exit(2);
}
} | java | public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option port = parser.addIntegerOption('p', "port");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException oe) {
System.err.println(oe.getMessage());
usage(System.err);
System.exit(1);
}
// Display help and exit if requested
if (Boolean.TRUE.equals((Boolean)parser.getOptionValue(help))) {
usage(System.out);
System.exit(0);
}
Integer portValue = (Integer)parser.getOptionValue(port,
Integer.valueOf(Tracker.DEFAULT_TRACKER_PORT));
String[] otherArgs = parser.getRemainingArgs();
if (otherArgs.length > 1) {
usage(System.err);
System.exit(1);
}
// Get directory from command-line argument or default to current
// directory
String directory = otherArgs.length > 0
? otherArgs[0]
: ".";
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".torrent");
}
};
try {
Tracker t = new Tracker(portValue);
File parent = new File(directory);
for (File f : parent.listFiles(filter)) {
logger.info("Loading torrent from " + f.getName());
t.announce(TrackedTorrent.load(f));
}
logger.info("Starting tracker with {} announced torrents...",
t.getTrackedTorrents().size());
t.start(true);
} catch (Exception e) {
logger.error("{}", e.getMessage(), e);
System.exit(2);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"BasicConfigurator",
".",
"configure",
"(",
"new",
"ConsoleAppender",
"(",
"new",
"PatternLayout",
"(",
"\"%d [%-25t] %-5p: %m%n\"",
")",
")",
")",
";",
"CmdLineParser",
"parser",
"... | Main function to start a tracker. | [
"Main",
"function",
"to",
"start",
"a",
"tracker",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/cli/src/main/java/com/turn/ttorrent/cli/TrackerMain.java#L56-L117 | train |
mpetazzoni/ttorrent | cli/src/main/java/com/turn/ttorrent/cli/ClientMain.java | ClientMain.main | public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option output = parser.addStringOption('o', "output");
CmdLineParser.Option iface = parser.addStringOption('i', "iface");
CmdLineParser.Option seedTime = parser.addIntegerOption('s', "seed");
CmdLineParser.Option maxUpload = parser.addDoubleOption('u', "max-upload");
CmdLineParser.Option maxDownload = parser.addDoubleOption('d', "max-download");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException oe) {
System.err.println(oe.getMessage());
usage(System.err);
System.exit(1);
}
// Display help and exit if requested
if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
usage(System.out);
System.exit(0);
}
String outputValue = (String) parser.getOptionValue(output,
DEFAULT_OUTPUT_DIRECTORY);
String ifaceValue = (String) parser.getOptionValue(iface);
int seedTimeValue = (Integer) parser.getOptionValue(seedTime, -1);
String[] otherArgs = parser.getRemainingArgs();
if (otherArgs.length != 1) {
usage(System.err);
System.exit(1);
}
SimpleClient client = new SimpleClient();
try {
Inet4Address iPv4Address = getIPv4Address(ifaceValue);
File torrentFile = new File(otherArgs[0]);
File outputFile = new File(outputValue);
client.downloadTorrent(
torrentFile.getAbsolutePath(),
outputFile.getAbsolutePath(),
iPv4Address);
if (seedTimeValue > 0) {
Thread.sleep(seedTimeValue * 1000);
}
} catch (Exception e) {
logger.error("Fatal error: {}", e.getMessage(), e);
System.exit(2);
} finally {
client.stop();
}
} | java | public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option output = parser.addStringOption('o', "output");
CmdLineParser.Option iface = parser.addStringOption('i', "iface");
CmdLineParser.Option seedTime = parser.addIntegerOption('s', "seed");
CmdLineParser.Option maxUpload = parser.addDoubleOption('u', "max-upload");
CmdLineParser.Option maxDownload = parser.addDoubleOption('d', "max-download");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException oe) {
System.err.println(oe.getMessage());
usage(System.err);
System.exit(1);
}
// Display help and exit if requested
if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
usage(System.out);
System.exit(0);
}
String outputValue = (String) parser.getOptionValue(output,
DEFAULT_OUTPUT_DIRECTORY);
String ifaceValue = (String) parser.getOptionValue(iface);
int seedTimeValue = (Integer) parser.getOptionValue(seedTime, -1);
String[] otherArgs = parser.getRemainingArgs();
if (otherArgs.length != 1) {
usage(System.err);
System.exit(1);
}
SimpleClient client = new SimpleClient();
try {
Inet4Address iPv4Address = getIPv4Address(ifaceValue);
File torrentFile = new File(otherArgs[0]);
File outputFile = new File(outputValue);
client.downloadTorrent(
torrentFile.getAbsolutePath(),
outputFile.getAbsolutePath(),
iPv4Address);
if (seedTimeValue > 0) {
Thread.sleep(seedTimeValue * 1000);
}
} catch (Exception e) {
logger.error("Fatal error: {}", e.getMessage(), e);
System.exit(2);
} finally {
client.stop();
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"BasicConfigurator",
".",
"configure",
"(",
"new",
"ConsoleAppender",
"(",
"new",
"PatternLayout",
"(",
"\"%d [%-25t] %-5p: %m%n\"",
")",
")",
")",
";",
"CmdLineParser",
"parser",
"... | Main client entry point for stand-alone operation. | [
"Main",
"client",
"entry",
"point",
"for",
"stand",
"-",
"alone",
"operation",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/cli/src/main/java/com/turn/ttorrent/cli/ClientMain.java#L107-L164 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/SharedTorrent.java | SharedTorrent.getPiece | public Piece getPiece(int index) {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
if (index >= this.pieces.length) {
throw new IllegalArgumentException("Invalid piece index!");
}
return this.pieces[index];
} | java | public Piece getPiece(int index) {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
if (index >= this.pieces.length) {
throw new IllegalArgumentException("Invalid piece index!");
}
return this.pieces[index];
} | [
"public",
"Piece",
"getPiece",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"this",
".",
"pieces",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Torrent not initialized yet.\"",
")",
";",
"}",
"if",
"(",
"index",
">=",
"this",
".",
... | Retrieve a piece object by index.
@param index The index of the piece in this torrent. | [
"Retrieve",
"a",
"piece",
"object",
"by",
"index",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/SharedTorrent.java#L297-L307 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/SharedTorrent.java | SharedTorrent.markCompleted | public synchronized void markCompleted(Piece piece) {
if (this.completedPieces.get(piece.getIndex())) {
return;
}
// A completed piece means that's that much data left to download for
// this torrent.
myTorrentStatistic.addLeft(-piece.size());
this.completedPieces.set(piece.getIndex());
if (completedPieces.cardinality() == getPiecesCount()) {
logger.info("all pieces are received for torrent {}. Validating...", this);
}
} | java | public synchronized void markCompleted(Piece piece) {
if (this.completedPieces.get(piece.getIndex())) {
return;
}
// A completed piece means that's that much data left to download for
// this torrent.
myTorrentStatistic.addLeft(-piece.size());
this.completedPieces.set(piece.getIndex());
if (completedPieces.cardinality() == getPiecesCount()) {
logger.info("all pieces are received for torrent {}. Validating...", this);
}
} | [
"public",
"synchronized",
"void",
"markCompleted",
"(",
"Piece",
"piece",
")",
"{",
"if",
"(",
"this",
".",
"completedPieces",
".",
"get",
"(",
"piece",
".",
"getIndex",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"// A completed piece means that's that much ... | Mark a piece as completed, decrementing the piece size in bytes from our
left bytes to download counter. | [
"Mark",
"a",
"piece",
"as",
"completed",
"decrementing",
"the",
"piece",
"size",
"in",
"bytes",
"from",
"our",
"left",
"bytes",
"to",
"download",
"counter",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/SharedTorrent.java#L395-L407 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java | Announce.start | public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
myAnnounceInterval = announceInterval;
myPeers.addAll(Arrays.asList(peers));
if (defaultTrackerURI != null) {
try {
myDefaultTracker = myTrackerClientFactory.createTrackerClient(myPeers, defaultTrackerURI);
myDefaultTracker.register(listener);
this.clients.put(defaultTrackerURI.toString(), myDefaultTracker);
} catch (Exception e) {
}
} else {
myDefaultTracker = null;
}
this.stop = false;
this.forceStop = false;
if (this.thread == null || !this.thread.isAlive()) {
this.thread = new Thread(this);
this.thread.setName("torrent tracker announce thread");
this.thread.start();
}
} | java | public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
myAnnounceInterval = announceInterval;
myPeers.addAll(Arrays.asList(peers));
if (defaultTrackerURI != null) {
try {
myDefaultTracker = myTrackerClientFactory.createTrackerClient(myPeers, defaultTrackerURI);
myDefaultTracker.register(listener);
this.clients.put(defaultTrackerURI.toString(), myDefaultTracker);
} catch (Exception e) {
}
} else {
myDefaultTracker = null;
}
this.stop = false;
this.forceStop = false;
if (this.thread == null || !this.thread.isAlive()) {
this.thread = new Thread(this);
this.thread.setName("torrent tracker announce thread");
this.thread.start();
}
} | [
"public",
"void",
"start",
"(",
"final",
"URI",
"defaultTrackerURI",
",",
"final",
"AnnounceResponseListener",
"listener",
",",
"final",
"Peer",
"[",
"]",
"peers",
",",
"final",
"int",
"announceInterval",
")",
"{",
"myAnnounceInterval",
"=",
"announceInterval",
";... | Start the announce request thread. | [
"Start",
"the",
"announce",
"request",
"thread",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java#L109-L131 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java | Announce.setAnnounceInterval | public void setAnnounceInterval(int announceInterval) {
if (announceInterval <= 0) {
this.stop(true);
return;
}
if (this.myAnnounceInterval == announceInterval) {
return;
}
logger.trace("Setting announce interval to {}s per tracker request.",
announceInterval);
this.myAnnounceInterval = announceInterval;
} | java | public void setAnnounceInterval(int announceInterval) {
if (announceInterval <= 0) {
this.stop(true);
return;
}
if (this.myAnnounceInterval == announceInterval) {
return;
}
logger.trace("Setting announce interval to {}s per tracker request.",
announceInterval);
this.myAnnounceInterval = announceInterval;
} | [
"public",
"void",
"setAnnounceInterval",
"(",
"int",
"announceInterval",
")",
"{",
"if",
"(",
"announceInterval",
"<=",
"0",
")",
"{",
"this",
".",
"stop",
"(",
"true",
")",
";",
"return",
";",
"}",
"if",
"(",
"this",
".",
"myAnnounceInterval",
"==",
"an... | Set the announce interval. | [
"Set",
"the",
"announce",
"interval",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java#L136-L149 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java | Announce.getCurrentTrackerClient | public TrackerClient getCurrentTrackerClient(AnnounceableInformation torrent) {
final URI uri = getURIForTorrent(torrent);
if (uri == null) return null;
return this.clients.get(uri.toString());
} | java | public TrackerClient getCurrentTrackerClient(AnnounceableInformation torrent) {
final URI uri = getURIForTorrent(torrent);
if (uri == null) return null;
return this.clients.get(uri.toString());
} | [
"public",
"TrackerClient",
"getCurrentTrackerClient",
"(",
"AnnounceableInformation",
"torrent",
")",
"{",
"final",
"URI",
"uri",
"=",
"getURIForTorrent",
"(",
"torrent",
")",
";",
"if",
"(",
"uri",
"==",
"null",
")",
"return",
"null",
";",
"return",
"this",
"... | Returns the current tracker client used for announces. | [
"Returns",
"the",
"current",
"tracker",
"client",
"used",
"for",
"announces",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/announce/Announce.java#L284-L288 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java | BDecoder.bdecode | public static BEValue bdecode(ByteBuffer data) throws IOException {
return BDecoder.bdecode(new ByteArrayInputStream(data.array()));
} | java | public static BEValue bdecode(ByteBuffer data) throws IOException {
return BDecoder.bdecode(new ByteArrayInputStream(data.array()));
} | [
"public",
"static",
"BEValue",
"bdecode",
"(",
"ByteBuffer",
"data",
")",
"throws",
"IOException",
"{",
"return",
"BDecoder",
".",
"bdecode",
"(",
"new",
"ByteArrayInputStream",
"(",
"data",
".",
"array",
"(",
")",
")",
")",
";",
"}"
] | Decode a B-encoded byte buffer.
<p>
Automatically instantiates a new BDecoder for the provided buffer and
decodes its root member.
</p>
@param data The {@link ByteBuffer} to read from. | [
"Decode",
"a",
"B",
"-",
"encoded",
"byte",
"buffer",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java#L99-L101 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java | BDecoder.bdecode | public BEValue bdecode() throws IOException {
if (this.getNextIndicator() == -1)
return null;
if (this.indicator >= '0' && this.indicator <= '9')
return this.bdecodeBytes();
else if (this.indicator == 'i')
return this.bdecodeNumber();
else if (this.indicator == 'l')
return this.bdecodeList();
else if (this.indicator == 'd')
return this.bdecodeMap();
else
throw new InvalidBEncodingException
("Unknown indicator '" + this.indicator + "'");
} | java | public BEValue bdecode() throws IOException {
if (this.getNextIndicator() == -1)
return null;
if (this.indicator >= '0' && this.indicator <= '9')
return this.bdecodeBytes();
else if (this.indicator == 'i')
return this.bdecodeNumber();
else if (this.indicator == 'l')
return this.bdecodeList();
else if (this.indicator == 'd')
return this.bdecodeMap();
else
throw new InvalidBEncodingException
("Unknown indicator '" + this.indicator + "'");
} | [
"public",
"BEValue",
"bdecode",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"getNextIndicator",
"(",
")",
"==",
"-",
"1",
")",
"return",
"null",
";",
"if",
"(",
"this",
".",
"indicator",
">=",
"'",
"'",
"&&",
"this",
".",
"indicat... | Gets the next indicator and returns either null when the stream
has ended or b-decodes the rest of the stream and returns the
appropriate BEValue encoded object. | [
"Gets",
"the",
"next",
"indicator",
"and",
"returns",
"either",
"null",
"when",
"the",
"stream",
"has",
"ended",
"or",
"b",
"-",
"decodes",
"the",
"rest",
"of",
"the",
"stream",
"and",
"returns",
"the",
"appropriate",
"BEValue",
"encoded",
"object",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java#L126-L141 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java | BDecoder.bdecodeBytes | public BEValue bdecodeBytes() throws IOException {
int c = this.getNextIndicator();
int num = c - '0';
if (num < 0 || num > 9)
throw new InvalidBEncodingException("Number expected, not '"
+ (char) c + "'");
this.indicator = 0;
c = this.read();
int i = c - '0';
while (i >= 0 && i <= 9) {
// This can overflow!
num = num * 10 + i;
c = this.read();
i = c - '0';
}
if (c != ':') {
throw new InvalidBEncodingException("Colon expected, not '" +
(char) c + "'");
}
return new BEValue(read(num));
} | java | public BEValue bdecodeBytes() throws IOException {
int c = this.getNextIndicator();
int num = c - '0';
if (num < 0 || num > 9)
throw new InvalidBEncodingException("Number expected, not '"
+ (char) c + "'");
this.indicator = 0;
c = this.read();
int i = c - '0';
while (i >= 0 && i <= 9) {
// This can overflow!
num = num * 10 + i;
c = this.read();
i = c - '0';
}
if (c != ':') {
throw new InvalidBEncodingException("Colon expected, not '" +
(char) c + "'");
}
return new BEValue(read(num));
} | [
"public",
"BEValue",
"bdecodeBytes",
"(",
")",
"throws",
"IOException",
"{",
"int",
"c",
"=",
"this",
".",
"getNextIndicator",
"(",
")",
";",
"int",
"num",
"=",
"c",
"-",
"'",
"'",
";",
"if",
"(",
"num",
"<",
"0",
"||",
"num",
">",
"9",
")",
"thr... | Returns the next b-encoded value on the stream and makes sure it is a
byte array.
@throws InvalidBEncodingException If it is not a b-encoded byte array. | [
"Returns",
"the",
"next",
"b",
"-",
"encoded",
"value",
"on",
"the",
"stream",
"and",
"makes",
"sure",
"it",
"is",
"a",
"byte",
"array",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java#L149-L172 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java | BDecoder.bdecodeNumber | public BEValue bdecodeNumber() throws IOException {
int c = this.getNextIndicator();
if (c != 'i') {
throw new InvalidBEncodingException("Expected 'i', not '" +
(char) c + "'");
}
this.indicator = 0;
c = this.read();
if (c == '0') {
c = this.read();
if (c == 'e')
return new BEValue(BigInteger.ZERO);
else
throw new InvalidBEncodingException("'e' expected after zero," +
" not '" + (char) c + "'");
}
// We don't support more the 255 char big integers
char[] chars = new char[256];
int off = 0;
if (c == '-') {
c = this.read();
if (c == '0')
throw new InvalidBEncodingException("Negative zero not allowed");
chars[off] = '-';
off++;
}
if (c < '1' || c > '9')
throw new InvalidBEncodingException("Invalid Integer start '"
+ (char) c + "'");
chars[off] = (char) c;
off++;
c = this.read();
int i = c - '0';
while (i >= 0 && i <= 9) {
chars[off] = (char) c;
off++;
c = read();
i = c - '0';
}
if (c != 'e')
throw new InvalidBEncodingException("Integer should end with 'e'");
String s = new String(chars, 0, off);
return new BEValue(new BigInteger(s));
} | java | public BEValue bdecodeNumber() throws IOException {
int c = this.getNextIndicator();
if (c != 'i') {
throw new InvalidBEncodingException("Expected 'i', not '" +
(char) c + "'");
}
this.indicator = 0;
c = this.read();
if (c == '0') {
c = this.read();
if (c == 'e')
return new BEValue(BigInteger.ZERO);
else
throw new InvalidBEncodingException("'e' expected after zero," +
" not '" + (char) c + "'");
}
// We don't support more the 255 char big integers
char[] chars = new char[256];
int off = 0;
if (c == '-') {
c = this.read();
if (c == '0')
throw new InvalidBEncodingException("Negative zero not allowed");
chars[off] = '-';
off++;
}
if (c < '1' || c > '9')
throw new InvalidBEncodingException("Invalid Integer start '"
+ (char) c + "'");
chars[off] = (char) c;
off++;
c = this.read();
int i = c - '0';
while (i >= 0 && i <= 9) {
chars[off] = (char) c;
off++;
c = read();
i = c - '0';
}
if (c != 'e')
throw new InvalidBEncodingException("Integer should end with 'e'");
String s = new String(chars, 0, off);
return new BEValue(new BigInteger(s));
} | [
"public",
"BEValue",
"bdecodeNumber",
"(",
")",
"throws",
"IOException",
"{",
"int",
"c",
"=",
"this",
".",
"getNextIndicator",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"{",
"throw",
"new",
"InvalidBEncodingException",
"(",
"\"Expected 'i', not '\... | Returns the next b-encoded value on the stream and makes sure it is a
number.
@throws InvalidBEncodingException If it is not a number. | [
"Returns",
"the",
"next",
"b",
"-",
"encoded",
"value",
"on",
"the",
"stream",
"and",
"makes",
"sure",
"it",
"is",
"a",
"number",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java#L180-L230 | train |
mpetazzoni/ttorrent | bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java | BDecoder.bdecodeList | public BEValue bdecodeList() throws IOException {
int c = this.getNextIndicator();
if (c != 'l') {
throw new InvalidBEncodingException("Expected 'l', not '" +
(char) c + "'");
}
this.indicator = 0;
List<BEValue> result = new ArrayList<BEValue>();
c = this.getNextIndicator();
while (c != 'e') {
result.add(this.bdecode());
c = this.getNextIndicator();
}
this.indicator = 0;
return new BEValue(result);
} | java | public BEValue bdecodeList() throws IOException {
int c = this.getNextIndicator();
if (c != 'l') {
throw new InvalidBEncodingException("Expected 'l', not '" +
(char) c + "'");
}
this.indicator = 0;
List<BEValue> result = new ArrayList<BEValue>();
c = this.getNextIndicator();
while (c != 'e') {
result.add(this.bdecode());
c = this.getNextIndicator();
}
this.indicator = 0;
return new BEValue(result);
} | [
"public",
"BEValue",
"bdecodeList",
"(",
")",
"throws",
"IOException",
"{",
"int",
"c",
"=",
"this",
".",
"getNextIndicator",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"{",
"throw",
"new",
"InvalidBEncodingException",
"(",
"\"Expected 'l', not '\""... | Returns the next b-encoded value on the stream and makes sure it is a
list.
@throws InvalidBEncodingException If it is not a list. | [
"Returns",
"the",
"next",
"b",
"-",
"encoded",
"value",
"on",
"the",
"stream",
"and",
"makes",
"sure",
"it",
"is",
"a",
"list",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/bencoding/src/main/java/com/turn/ttorrent/bcodec/BDecoder.java#L238-L255 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java | Piece.validate | public boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
logger.trace("Validating {}...", this);
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
byte[] pieceBytes = data.array();
final byte[] calculatedHash = TorrentUtils.calculateSha1Hash(pieceBytes);
this.valid = Arrays.equals(calculatedHash, this.hash);
logger.trace("validating result of piece {} is {}", this.index, this.valid);
return this.isValid();
} | java | public boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
logger.trace("Validating {}...", this);
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
byte[] pieceBytes = data.array();
final byte[] calculatedHash = TorrentUtils.calculateSha1Hash(pieceBytes);
this.valid = Arrays.equals(calculatedHash, this.hash);
logger.trace("validating result of piece {} is {}", this.index, this.valid);
return this.isValid();
} | [
"public",
"boolean",
"validate",
"(",
"SharedTorrent",
"torrent",
",",
"Piece",
"piece",
")",
"throws",
"IOException",
"{",
"logger",
".",
"trace",
"(",
"\"Validating {}...\"",
",",
"this",
")",
";",
"// TODO: remove cast to int when large ByteBuffer support is",
"// im... | Validates this piece.
@return Returns true if this piece, as stored in the underlying byte
storage, is valid, i.e. its SHA1 sum matches the one from the torrent
meta-info. | [
"Validates",
"this",
"piece",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java#L150-L162 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java | Piece._read | private ByteBuffer _read(long offset, long length, ByteBuffer buffer) throws IOException {
if (offset + length > this.length) {
throw new IllegalArgumentException("Piece#" + this.index +
" overrun (" + offset + " + " + length + " > " +
this.length + ") !");
}
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
int position = buffer.position();
byte[] bytes = this.pieceStorage.readPiecePart(this.index, (int)offset, (int)length);
buffer.put(bytes);
buffer.rewind();
buffer.limit(bytes.length + position);
return buffer;
} | java | private ByteBuffer _read(long offset, long length, ByteBuffer buffer) throws IOException {
if (offset + length > this.length) {
throw new IllegalArgumentException("Piece#" + this.index +
" overrun (" + offset + " + " + length + " > " +
this.length + ") !");
}
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
int position = buffer.position();
byte[] bytes = this.pieceStorage.readPiecePart(this.index, (int)offset, (int)length);
buffer.put(bytes);
buffer.rewind();
buffer.limit(bytes.length + position);
return buffer;
} | [
"private",
"ByteBuffer",
"_read",
"(",
"long",
"offset",
",",
"long",
"length",
",",
"ByteBuffer",
"buffer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"offset",
"+",
"length",
">",
"this",
".",
"length",
")",
"{",
"throw",
"new",
"IllegalArgumentExceptio... | Internal piece data read function.
<p>
This function will read the piece data without checking if the piece has
been validated. It is simply meant at factoring-in the common read code
from the validate and read functions.
</p>
@param offset Offset inside this piece where to start reading.
@param length Number of bytes to read from the piece.
@return A byte buffer containing the piece data.
@throws IllegalArgumentException If <em>offset + length</em> goes over
the piece boundary.
@throws IOException If the read can't be completed (I/O error, or EOF
reached, which can happen if the piece is not complete). | [
"Internal",
"piece",
"data",
"read",
"function",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java#L181-L196 | train |
mpetazzoni/ttorrent | ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java | Piece.read | public ByteBuffer read(long offset, int length, ByteBuffer block)
throws IllegalArgumentException, IllegalStateException, IOException {
if (!this.valid) {
throw new IllegalStateException("Attempting to read an " +
"known-to-be invalid piece!");
}
return this._read(offset, length, block);
} | java | public ByteBuffer read(long offset, int length, ByteBuffer block)
throws IllegalArgumentException, IllegalStateException, IOException {
if (!this.valid) {
throw new IllegalStateException("Attempting to read an " +
"known-to-be invalid piece!");
}
return this._read(offset, length, block);
} | [
"public",
"ByteBuffer",
"read",
"(",
"long",
"offset",
",",
"int",
"length",
",",
"ByteBuffer",
"block",
")",
"throws",
"IllegalArgumentException",
",",
"IllegalStateException",
",",
"IOException",
"{",
"if",
"(",
"!",
"this",
".",
"valid",
")",
"{",
"throw",
... | Read a piece block from the underlying byte storage.
<p>
This is the public method for reading this piece's data, and it will
only succeed if the piece is complete and valid on disk, thus ensuring
any data that comes out of this function is valid piece data we can send
to other peers.
</p>
@param offset Offset inside this piece where to start reading.
@param length Number of bytes to read from the piece.
@return A byte buffer containing the piece data.
@throws IllegalArgumentException If <em>offset + length</em> goes over
the piece boundary.
@throws IllegalStateException If the piece is not valid when attempting
to read it.
@throws IOException If the read can't be completed (I/O error, or EOF
reached, which can happen if the piece is not complete). | [
"Read",
"a",
"piece",
"block",
"from",
"the",
"underlying",
"byte",
"storage",
"."
] | ecd0e6caf853b63393c4ab63cfd8f20114f73f70 | https://github.com/mpetazzoni/ttorrent/blob/ecd0e6caf853b63393c4ab63cfd8f20114f73f70/ttorrent-client/src/main/java/com/turn/ttorrent/client/Piece.java#L218-L226 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.