_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q178100
|
JspCServletContext.getResource
|
test
|
public URL getResource(String path) throws MalformedURLException {
if (!path.startsWith("/"))
throw new MalformedURLException("Path '" + path +
"' does not start with '/'");
URL url = new URL(myResourceBaseURL, path.substring(1));
InputStream is = null;
try {
is = url.openStream();
} catch (Throwable t) {
url = null;
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable t2) {
// Ignore
}
}
}
return url;
}
|
java
|
{
"resource": ""
}
|
q178101
|
JspCServletContext.getResourceAsStream
|
test
|
public InputStream getResourceAsStream(String path) {
try {
return (getResource(path).openStream());
} catch (Throwable t) {
return (null);
}
}
|
java
|
{
"resource": ""
}
|
q178102
|
JspCServletContext.getResourcePaths
|
test
|
public Set<String> getResourcePaths(String path) {
Set<String> thePaths = new HashSet<String>();
if (!path.endsWith("/"))
path += "/";
String basePath = getRealPath(path);
if (basePath == null)
return (thePaths);
File theBaseDir = new File(basePath);
if (!theBaseDir.exists() || !theBaseDir.isDirectory())
return (thePaths);
String theFiles[] = theBaseDir.list();
for (int i = 0; i < theFiles.length; i++) {
File testFile = new File(basePath + File.separator + theFiles[i]);
if (testFile.isFile())
thePaths.add(path + theFiles[i]);
else if (testFile.isDirectory())
thePaths.add(path + theFiles[i] + "/");
}
return (thePaths);
}
|
java
|
{
"resource": ""
}
|
q178103
|
JspCServletContext.log
|
test
|
public void log(String message, Throwable exception) {
myLogWriter.println(message);
exception.printStackTrace(myLogWriter);
}
|
java
|
{
"resource": ""
}
|
q178104
|
JspCServletContext.addFilter
|
test
|
public void addFilter(String filterName,
String description,
String className,
Map<String, String> initParameters) {
// Do nothing
return;
}
|
java
|
{
"resource": ""
}
|
q178105
|
LZEncoder.getBufSize
|
test
|
private static int getBufSize(
int dictSize, int extraSizeBefore, int extraSizeAfter,
int matchLenMax) {
int keepSizeBefore = extraSizeBefore + dictSize;
int keepSizeAfter = extraSizeAfter + matchLenMax;
int reserveSize = Math.min(dictSize / 2 + (256 << 10), 512 << 20);
return keepSizeBefore + keepSizeAfter + reserveSize;
}
|
java
|
{
"resource": ""
}
|
q178106
|
LZEncoder.getMemoryUsage
|
test
|
public static int getMemoryUsage(
int dictSize, int extraSizeBefore, int extraSizeAfter,
int matchLenMax, int mf) {
// Buffer size + a little extra
int m = getBufSize(dictSize, extraSizeBefore, extraSizeAfter,
matchLenMax) / 1024 + 10;
switch (mf) {
case MF_HC4:
m += HC4.getMemoryUsage(dictSize);
break;
case MF_BT4:
m += BT4.getMemoryUsage(dictSize);
break;
default:
throw new IllegalArgumentException();
}
return m;
}
|
java
|
{
"resource": ""
}
|
q178107
|
LZEncoder.setPresetDict
|
test
|
public void setPresetDict(int dictSize, byte[] presetDict) {
assert !isStarted();
assert writePos == 0;
if (presetDict != null) {
// If the preset dictionary buffer is bigger than the dictionary
// size, copy only the tail of the preset dictionary.
int copySize = Math.min(presetDict.length, dictSize);
int offset = presetDict.length - copySize;
System.arraycopy(presetDict, offset, buf, 0, copySize);
writePos += copySize;
skip(copySize);
}
}
|
java
|
{
"resource": ""
}
|
q178108
|
LZEncoder.moveWindow
|
test
|
private void moveWindow() {
// Align the move to a multiple of 16 bytes. LZMA2 needs this
// because it uses the lowest bits from readPos to get the
// alignment of the uncompressed data.
int moveOffset = (readPos + 1 - keepSizeBefore) & ~15;
int moveSize = writePos - moveOffset;
System.arraycopy(buf, moveOffset, buf, 0, moveSize);
readPos -= moveOffset;
readLimit -= moveOffset;
writePos -= moveOffset;
}
|
java
|
{
"resource": ""
}
|
q178109
|
LZEncoder.fillWindow
|
test
|
public int fillWindow(byte[] in, int off, int len) {
assert !finishing;
// Move the sliding window if needed.
if (readPos >= bufSize - keepSizeAfter)
moveWindow();
// Try to fill the dictionary buffer. If it becomes full,
// some of the input bytes may be left unused.
if (len > bufSize - writePos)
len = bufSize - writePos;
System.arraycopy(in, off, buf, writePos, len);
writePos += len;
// Set the new readLimit but only if there's enough data to allow
// encoding of at least one more byte.
if (writePos >= keepSizeAfter)
readLimit = writePos - keepSizeAfter;
processPendingBytes();
// Tell the caller how much input we actually copied into
// the dictionary.
return len;
}
|
java
|
{
"resource": ""
}
|
q178110
|
LZEncoder.processPendingBytes
|
test
|
private void processPendingBytes() {
// After flushing or setting a preset dictionary there will be
// pending data that hasn't been ran through the match finder yet.
// Run it through the match finder now if there is enough new data
// available (readPos < readLimit) that the encoder may encode at
// least one more input byte. This way we don't waste any time
// looping in the match finder (and marking the same bytes as
// pending again) if the application provides very little new data
// per write call.
if (pendingSize > 0 && readPos < readLimit) {
readPos -= pendingSize;
int oldPendingSize = pendingSize;
pendingSize = 0;
skip(oldPendingSize);
assert pendingSize < oldPendingSize;
}
}
|
java
|
{
"resource": ""
}
|
q178111
|
LZEncoder.getMatchLen
|
test
|
public int getMatchLen(int dist, int lenLimit) {
int backPos = readPos - dist - 1;
int len = 0;
while (len < lenLimit && buf[readPos + len] == buf[backPos + len])
++len;
return len;
}
|
java
|
{
"resource": ""
}
|
q178112
|
LZEncoder.getMatchLen
|
test
|
public int getMatchLen(int forward, int dist, int lenLimit) {
int curPos = readPos + forward;
int backPos = curPos - dist - 1;
int len = 0;
while (len < lenLimit && buf[curPos + len] == buf[backPos + len])
++len;
return len;
}
|
java
|
{
"resource": ""
}
|
q178113
|
LZEncoder.verifyMatches
|
test
|
public boolean verifyMatches(Matches matches) {
int lenLimit = Math.min(getAvail(), matchLenMax);
for (int i = 0; i < matches.count; ++i)
if (getMatchLen(matches.dist[i], lenLimit) != matches.len[i])
return false;
return true;
}
|
java
|
{
"resource": ""
}
|
q178114
|
LZEncoder.movePos
|
test
|
int movePos(int requiredForFlushing, int requiredForFinishing) {
assert requiredForFlushing >= requiredForFinishing;
++readPos;
int avail = writePos - readPos;
if (avail < requiredForFlushing) {
if (avail < requiredForFinishing || !finishing) {
++pendingSize;
avail = 0;
}
}
return avail;
}
|
java
|
{
"resource": ""
}
|
q178115
|
JspWriterImpl.recycle
|
test
|
void recycle() {
flushed = false;
closed = false;
out = null;
byteOut = null;
releaseCharBuffer();
response = null;
}
|
java
|
{
"resource": ""
}
|
q178116
|
JspWriterImpl.flushBuffer
|
test
|
protected final void flushBuffer() throws IOException {
if (bufferSize == 0)
return;
flushed = true;
ensureOpen();
if (buf.pos == buf.offset)
return;
initOut();
out.write(buf.buf, buf.offset, buf.pos - buf.offset);
buf.pos = buf.offset;
}
|
java
|
{
"resource": ""
}
|
q178117
|
JspWriterImpl.clear
|
test
|
public final void clear() throws IOException {
if ((bufferSize == 0) && (out != null))
// clear() is illegal after any unbuffered output (JSP.5.5)
throw new IllegalStateException(
getLocalizeMessage("jsp.error.ise_on_clear"));
if (flushed)
throw new IOException(
getLocalizeMessage("jsp.error.attempt_to_clear_flushed_buffer"));
ensureOpen();
if (buf != null)
buf.pos = buf.offset;
}
|
java
|
{
"resource": ""
}
|
q178118
|
JspWriterImpl.flush
|
test
|
public void flush() throws IOException {
flushBuffer();
if (out != null) {
out.flush();
}
// START 6426898
else {
// Set the default character encoding if there isn't any present,
// see CR 6699416
response.setCharacterEncoding(response.getCharacterEncoding());
// Cause response headers to be sent
response.flushBuffer();
}
// END 6426898
}
|
java
|
{
"resource": ""
}
|
q178119
|
JspWriterImpl.close
|
test
|
public void close() throws IOException {
if (response == null || closed)
// multiple calls to close is OK
return;
flush();
if (out != null)
out.close();
out = null;
byteOut = null;
closed = true;
}
|
java
|
{
"resource": ""
}
|
q178120
|
JspWriterImpl.write
|
test
|
public void write(boolean bytesOK, byte buf[], String str)
throws IOException {
ensureOpen();
if (bufferSize == 0 && bytesOK) {
initByteOut();
if (implementsByteWriter) {
write(buf, 0, buf.length);
return;
}
}
write(str);
}
|
java
|
{
"resource": ""
}
|
q178121
|
JspWriterImpl.allocateCharBuffer
|
test
|
private void allocateCharBuffer() {
if (bufferSize == 0) return;
if (bufferSize > MAX_BUFFER_SIZE) {
buf = new CharBuffer(new char[bufferSize], 0, bufferSize);
} else {
buf = getCharBufferThreadLocalPool().allocate(bufferSize);
}
}
|
java
|
{
"resource": ""
}
|
q178122
|
DefaultErrorHandler.javacError
|
test
|
public void javacError(String errorReport, Exception exception)
throws JasperException {
throw new JasperException(
Localizer.getMessage("jsp.error.unable.compile"), exception);
}
|
java
|
{
"resource": ""
}
|
q178123
|
Aggregator.makeKey
|
test
|
public List<String> makeKey ( final Map<MetaKey, String> metaData, final boolean requireAll )
{
final List<String> result = new ArrayList<> ( this.fields.size () );
for ( final MetaKey field : this.fields )
{
final String value = metaData.get ( field );
if ( requireAll && value == null )
{
return null;
}
result.add ( value );
}
return result;
}
|
java
|
{
"resource": ""
}
|
q178124
|
Compiler.generateClass
|
test
|
private void generateClass()
throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isLoggable(Level.FINE)) {
t1 = System.currentTimeMillis();
}
String javaFileName = ctxt.getServletJavaFileName();
setJavaCompilerOptions();
// Start java compilation
JavacErrorDetail[] javacErrors =
javaCompiler.compile(ctxt.getFullClassName(), pageNodes);
if (javacErrors != null) {
// If there are errors, always generate java files to disk.
javaCompiler.doJavaFile(true);
log.severe("Error compiling file: " + javaFileName);
errDispatcher.javacError(javacErrors);
}
if (log.isLoggable(Level.FINE)) {
long t2 = System.currentTimeMillis();
log.fine("Compiled " + javaFileName + " " + (t2-t1) + "ms");
}
// Save or delete the generated Java files, depending on the
// value of "keepgenerated" attribute
javaCompiler.doJavaFile(ctxt.keepGenerated());
// JSR45 Support
if (!ctxt.isPrototypeMode() && !options.isSmapSuppressed()) {
smapUtil.installSmap();
}
// START CR 6373479
if (jsw != null && jsw.getServletClassLastModifiedTime() <= 0) {
jsw.setServletClassLastModifiedTime(
javaCompiler.getClassLastModified());
}
// END CR 6373479
if (options.getSaveBytecode()) {
javaCompiler.saveClassFile(ctxt.getFullClassName(),
ctxt.getClassFileName());
}
// On some systems, due to file caching, the time stamp for the updated
// JSP file may actually be greater than that of the newly created byte
// codes in the cache. In such cases, adjust the cache time stamp to
// JSP page time, to avoid unnecessary recompilations.
ctxt.getRuntimeContext().adjustBytecodeTime(ctxt.getFullClassName(),
jspModTime);
}
|
java
|
{
"resource": ""
}
|
q178125
|
Compiler.compile
|
test
|
public void compile(boolean compileClass)
throws FileNotFoundException, JasperException, Exception
{
try {
// Create the output directory for the generated files
// Always try and create the directory tree, in case the generated
// directories were deleted after the server was started.
ctxt.makeOutputDir(ctxt.getOutputDir());
// If errDispatcher is nulled from a previous compilation of the
// same page, instantiate one here.
if (errDispatcher == null) {
errDispatcher = new ErrorDispatcher(jspcMode);
}
generateJava();
if (compileClass) {
generateClass();
}
else {
// If called from jspc to only compile to .java files,
// make sure that .java files are written to disk.
javaCompiler.doJavaFile(ctxt.keepGenerated());
}
} finally {
if (tfp != null) {
tfp.removeProtoTypeFiles(null);
}
javaCompiler.release();
// Make sure these object which are only used during the
// generation and compilation of the JSP page get
// dereferenced so that they can be GC'd and reduce the
// memory footprint.
tfp = null;
errDispatcher = null;
if (!jspcMode) {
pageInfo = null;
}
pageNodes = null;
if (ctxt.getWriter() != null) {
ctxt.getWriter().close();
ctxt.setWriter(null);
}
}
}
|
java
|
{
"resource": ""
}
|
q178126
|
Compiler.removeGeneratedFiles
|
test
|
public void removeGeneratedFiles() {
try {
String classFileName = ctxt.getClassFileName();
if (classFileName != null) {
File classFile = new File(classFileName);
if( log.isLoggable(Level.FINE) )
log.fine( "Deleting " + classFile );
classFile.delete();
}
} catch (Exception e) {
// Remove as much as possible, ignore possible exceptions
}
try {
String javaFileName = ctxt.getServletJavaFileName();
if (javaFileName != null) {
File javaFile = new File(javaFileName);
if( log.isLoggable(Level.FINE) )
log.fine( "Deleting " + javaFile );
javaFile.delete();
}
} catch (Exception e) {
// Remove as much as possible, ignore possible exceptions
}
}
|
java
|
{
"resource": ""
}
|
q178127
|
Compiler.initJavaCompiler
|
test
|
private void initJavaCompiler() throws JasperException {
boolean disablejsr199 = Boolean.TRUE.toString().equals(
System.getProperty("org.apache.jasper.compiler.disablejsr199"));
Double version =
Double.valueOf(System.getProperty("java.specification.version"));
if (!disablejsr199 &&
(version >= 1.6 || getClassFor("javax.tools.Tool") != null)) {
// JDK 6 or bundled with jsr199 compiler
javaCompiler = new Jsr199JavaCompiler();
} else {
Class c = getClassFor("org.eclipse.jdt.internal.compiler.Compiler");
if (c != null) {
c = getClassFor("org.apache.jasper.compiler.JDTJavaCompiler");
if (c != null) {
try {
javaCompiler = (JavaCompiler) c.newInstance();
} catch (Exception ex) {
}
}
}
}
if (javaCompiler == null) {
Class c = getClassFor("org.apache.tools.ant.taskdefs.Javac");
if (c != null) {
c = getClassFor("org.apache.jasper.compiler.AntJavaCompiler");
if (c != null) {
try {
javaCompiler = (JavaCompiler) c.newInstance();
} catch (Exception ex) {
}
}
}
}
if (javaCompiler == null) {
errDispatcher.jspError("jsp.error.nojavac");
}
javaCompiler.init(ctxt, errDispatcher, jspcMode);
}
|
java
|
{
"resource": ""
}
|
q178128
|
Compiler.systemJarInWebinf
|
test
|
private boolean systemJarInWebinf(String path) {
if (path.indexOf("/WEB-INF/") < 0) {
return false;
}
Boolean useMyFaces = (Boolean) ctxt.getServletContext().
getAttribute("com.sun.faces.useMyFaces");
if (useMyFaces == null || !useMyFaces) {
for (String jar: systemJsfJars) {
if (path.indexOf(jar) > 0) {
return true;
}
}
}
for (String jar: systemJars) {
if (path.indexOf(jar) > 0) {
return true;
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q178129
|
Generator.quote
|
test
|
static String quote(char c) {
StringBuilder b = new StringBuilder();
b.append('\'');
if (c == '\'')
b.append('\\').append('\'');
else if (c == '\\')
b.append('\\').append('\\');
else if (c == '\n')
b.append('\\').append('n');
else if (c == '\r')
b.append('\\').append('r');
else
b.append(c);
b.append('\'');
return b.toString();
}
|
java
|
{
"resource": ""
}
|
q178130
|
Generator.generateDeclarations
|
test
|
private void generateDeclarations(Node.Nodes page) throws JasperException {
class DeclarationVisitor extends Node.Visitor {
private boolean getServletInfoGenerated = false;
/*
* Generates getServletInfo() method that returns the value of the
* page directive's 'info' attribute, if present.
*
* The Validator has already ensured that if the translation unit
* contains more than one page directive with an 'info' attribute,
* their values match.
*/
public void visit(Node.PageDirective n) throws JasperException {
if (getServletInfoGenerated) {
return;
}
String info = n.getAttributeValue("info");
if (info == null)
return;
getServletInfoGenerated = true;
out.printil("public String getServletInfo() {");
out.pushIndent();
out.printin("return ");
out.print(quote(info));
out.println(";");
out.popIndent();
out.printil("}");
out.println();
}
public void visit(Node.Declaration n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printMultiLn(n.getText());
out.println();
n.setEndJavaLine(out.getJavaLine());
}
// Custom Tags may contain declarations from tag plugins.
public void visit(Node.CustomTag n) throws JasperException {
if (n.useTagPlugin()) {
if (n.getAtSTag() != null) {
n.getAtSTag().visit(this);
}
visitBody(n);
if (n.getAtETag() != null) {
n.getAtETag().visit(this);
}
} else {
visitBody(n);
}
}
}
out.println();
page.visit(new DeclarationVisitor());
}
|
java
|
{
"resource": ""
}
|
q178131
|
Generator.compileTagHandlerPoolList
|
test
|
private void compileTagHandlerPoolList(Node.Nodes page)
throws JasperException {
class TagHandlerPoolVisitor extends Node.Visitor {
private Set<String> names = new HashSet<String>();
/*
* Constructor
*
* @param v Set of tag handler pool names to populate
*/
TagHandlerPoolVisitor(Set<String> v) {
names = v;
}
/*
* Gets the name of the tag handler pool for the given custom tag
* and adds it to the list of tag handler pool names unless it is
* already contained in it.
*/
public void visit(Node.CustomTag n) throws JasperException {
if (!n.implementsSimpleTag()) {
String name =
createTagHandlerPoolName(
n.getPrefix(),
n.getLocalName(),
n.getAttributes(),
n.hasEmptyBody());
n.setTagHandlerPoolName(name);
if (!names.contains(name)) {
names.add(name);
}
}
visitBody(n);
}
/*
* Creates the name of the tag handler pool whose tag handlers may
* be (re)used to service this action.
*
* @return The name of the tag handler pool
*/
private String createTagHandlerPoolName(
String prefix,
String shortName,
Attributes attrs,
boolean hasEmptyBody) {
String poolName = null;
poolName = "_jspx_tagPool_" + prefix + "_" + shortName;
if (attrs != null) {
String[] attrNames = new String[attrs.getLength()];
for (int i = 0; i < attrNames.length; i++) {
attrNames[i] = attrs.getQName(i);
}
Arrays.sort(attrNames, Collections.reverseOrder());
for (int i = 0; i < attrNames.length; i++) {
poolName = poolName + "_" + attrNames[i];
}
}
if (hasEmptyBody) {
poolName = poolName + "_nobody";
}
return JspUtil.makeXmlJavaIdentifier(poolName);
}
}
page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames));
}
|
java
|
{
"resource": ""
}
|
q178132
|
Generator.generateXmlProlog
|
test
|
private void generateXmlProlog(Node.Nodes page) {
/*
* An XML declaration is generated under the following conditions:
*
* - 'omit-xml-declaration' attribute of <jsp:output> action is set to
* "no" or "false"
* - JSP document without a <jsp:root>
*/
String omitXmlDecl = pageInfo.getOmitXmlDecl();
if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl))
|| (omitXmlDecl == null
&& page.getRoot().isXmlSyntax()
&& !pageInfo.hasJspRoot()
&& !ctxt.isTagFile())) {
String cType = pageInfo.getContentType();
String charSet = cType.substring(cType.indexOf("charset=") + 8);
out.printil(
"out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\""
+ charSet
+ "\\\"?>\\n\");");
}
/*
* Output a DOCTYPE declaration if the doctype-root-element appears.
* If doctype-public appears:
* <!DOCTYPE name PUBLIC "doctypePublic" "doctypeSystem">
* else
* <!DOCTYPE name SYSTEM "doctypeSystem" >
*/
String doctypeName = pageInfo.getDoctypeName();
if (doctypeName != null) {
String doctypePublic = pageInfo.getDoctypePublic();
String doctypeSystem = pageInfo.getDoctypeSystem();
out.printin("out.write(\"<!DOCTYPE ");
out.print(doctypeName);
if (doctypePublic == null) {
out.print(" SYSTEM \\\"");
} else {
out.print(" PUBLIC \\\"");
out.print(doctypePublic);
out.print("\\\" \\\"");
}
out.print(doctypeSystem);
out.println("\\\">\\n\");");
}
}
|
java
|
{
"resource": ""
}
|
q178133
|
Generator.genCommonPostamble
|
test
|
private void genCommonPostamble() {
// Append any methods that were generated in the buffer.
for (int i = 0; i < methodsBuffered.size(); i++) {
GenBuffer methodBuffer = methodsBuffered.get(i);
methodBuffer.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(methodBuffer.toString());
}
// Append the helper class
if (fragmentHelperClass.isUsed()) {
fragmentHelperClass.generatePostamble();
fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(fragmentHelperClass.toString());
}
// Append char array declarations
if (arrayBuffer != null) {
out.printMultiLn(arrayBuffer.toString());
}
// Close the class definition
out.popIndent();
out.printil("}");
}
|
java
|
{
"resource": ""
}
|
q178134
|
Generator.generatePostamble
|
test
|
private void generatePostamble(Node.Nodes page) {
out.popIndent();
out.printil("} catch (Throwable t) {");
out.pushIndent();
out.printil(
"if (!(t instanceof SkipPageException)){");
out.pushIndent();
out.printil("out = _jspx_out;");
out.printil("if (out != null && out.getBufferSize() != 0)");
out.pushIndent();
out.printil("out.clearBuffer();");
out.popIndent();
out.printil(
"if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);");
out.printil("else throw new ServletException(t);");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printil(
"_jspxFactory.releasePageContext(_jspx_page_context);");
out.popIndent();
out.printil("}");
// Close the service method
out.popIndent();
out.printil("}");
// Generated methods, helper classes, etc.
genCommonPostamble();
}
|
java
|
{
"resource": ""
}
|
q178135
|
Generator.generate
|
test
|
public static void generate(
ServletWriter out,
Compiler compiler,
Node.Nodes page)
throws JasperException {
Generator gen = new Generator(out, compiler);
if (gen.isPoolingEnabled) {
gen.compileTagHandlerPoolList(page);
}
if (gen.ctxt.isTagFile()) {
JasperTagInfo tagInfo = (JasperTagInfo)gen.ctxt.getTagInfo();
gen.generateTagHandlerPreamble(tagInfo, page);
if (gen.ctxt.isPrototypeMode()) {
return;
}
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(
gen.new GenerateVisitor(
gen.ctxt.isTagFile(),
out,
gen.methodsBuffered,
gen.fragmentHelperClass));
gen.generateTagHandlerPostamble(tagInfo);
} else {
gen.generatePreamble(page);
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(
gen.new GenerateVisitor(
gen.ctxt.isTagFile(),
out,
gen.methodsBuffered,
gen.fragmentHelperClass));
gen.generatePostamble(page);
}
}
|
java
|
{
"resource": ""
}
|
q178136
|
Generator.generateTagHandlerAttributes
|
test
|
private void generateTagHandlerAttributes(TagInfo tagInfo)
throws JasperException {
if (tagInfo.hasDynamicAttributes()) {
out.printil(
"private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();");
}
// Declare attributes
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
for (int i = 0; i < attrInfos.length; i++) {
out.printin("private ");
if (attrInfos[i].isFragment()) {
out.print("javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(attrInfos[i].getName());
out.println(";");
}
out.println();
// Define attribute getter and setter methods
for (int i = 0; i < attrInfos.length; i++) {
// getter method
out.printin("public ");
if (attrInfos[i].isFragment()) {
out.print("javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(toGetterMethod(attrInfos[i].getName()));
out.println(" {");
out.pushIndent();
out.printin("return this.");
out.print(attrInfos[i].getName());
out.println(";");
out.popIndent();
out.printil("}");
out.println();
// setter method
out.printin("public void ");
out.print(toSetterMethodName(attrInfos[i].getName()));
if (attrInfos[i].isFragment()) {
out.print("(javax.servlet.jsp.tagext.JspFragment ");
} else {
out.print("(");
out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName()));
out.print(" ");
}
out.print(attrInfos[i].getName());
out.println(") {");
out.pushIndent();
out.printin("this.");
out.print(attrInfos[i].getName());
out.print(" = ");
out.print(attrInfos[i].getName());
out.println(";");
out.popIndent();
out.printil("}");
out.println();
}
}
|
java
|
{
"resource": ""
}
|
q178137
|
TransferServiceImpl.readProperties
|
test
|
private Map<MetaKey, String> readProperties ( final InputStream stream ) throws IOException
{
try
{
// wrap the input stream since we don't want the XML parser to close the stream while parsing
final Document doc = this.xmlToolsFactory.newDocumentBuilder ().parse ( new FilterInputStream ( stream ) {
@Override
public void close ()
{
// do nothing
}
} );
final Element root = doc.getDocumentElement ();
if ( !"properties".equals ( root.getNodeName () ) )
{
throw new IllegalStateException ( String.format ( "Root element must be of type '%s'", "properties" ) );
}
final Map<MetaKey, String> result = new HashMap<> ();
for ( final Element ele : XmlHelper.iterElement ( root, "property" ) )
{
final String namespace = ele.getAttribute ( "namespace" );
final String key = ele.getAttribute ( "key" );
final String value = ele.getTextContent ();
if ( namespace.isEmpty () || key.isEmpty () )
{
continue;
}
result.put ( new MetaKey ( namespace, key ), value );
}
return result;
}
catch ( final Exception e )
{
throw new IOException ( "Failed to read properties", e );
}
}
|
java
|
{
"resource": ""
}
|
q178138
|
TransferServiceImpl.exportChannel
|
test
|
private void exportChannel ( final By by, final OutputStream stream ) throws IOException
{
final ZipOutputStream zos = new ZipOutputStream ( stream );
initExportFile ( zos );
this.channelService.accessRun ( by, ReadableChannel.class, channel -> {
putDataEntry ( zos, "names", makeNames ( channel.getId () ) );
putDataEntry ( zos, "description", channel.getId ().getDescription () );
putDirEntry ( zos, "artifacts" );
putProperties ( zos, "properties.xml", channel.getContext ().getProvidedMetaData () );
putAspects ( zos, channel.getContext ().getAspectStates ().keySet () );
// the first run receives all artifacts and filters for the root elements
putArtifacts ( zos, "artifacts/", channel, channel.getArtifacts (), true );
} );
this.channelService.accessRun ( by, TriggeredChannel.class, channel -> {
putTriggers ( zos, channel );
} );
zos.finish (); // don't close stream, since there might be other channels following
}
|
java
|
{
"resource": ""
}
|
q178139
|
Validator.validateXmlView
|
test
|
private static void validateXmlView(PageData xmlView, Compiler compiler)
throws JasperException {
StringBuilder errMsg = null;
ErrorDispatcher errDisp = compiler.getErrorDispatcher();
for (Iterator<TagLibraryInfo> iter =
compiler.getPageInfo().getTaglibs().iterator();
iter.hasNext(); ) {
TagLibraryInfo o = iter.next();
if (!(o instanceof TagLibraryInfoImpl))
continue;
TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o;
ValidationMessage[] errors = tli.validate(xmlView);
if ((errors != null) && (errors.length != 0)) {
if (errMsg == null) {
errMsg = new StringBuilder();
}
errMsg.append("<h3>");
errMsg.append(Localizer.getMessage("jsp.error.tlv.invalid.page",
tli.getShortName()));
errMsg.append("</h3>");
for (int i=0; i<errors.length; i++) {
if (errors[i] != null) {
errMsg.append("<p>");
errMsg.append(errors[i].getId());
errMsg.append(": ");
errMsg.append(errors[i].getMessage());
errMsg.append("</p>");
}
}
}
}
if (errMsg != null) {
errDisp.jspError(errMsg.toString());
}
}
|
java
|
{
"resource": ""
}
|
q178140
|
TagHandlerPool.get
|
test
|
public <T extends JspTag> JspTag get(Class<T> handlerClass)
throws JspException {
synchronized( this ) {
if (current >= 0) {
return handlers[current--];
}
}
// Out of sync block - there is no need for other threads to
// wait for us to construct a tag for this thread.
JspTag tagHandler = null;
try {
if (resourceInjector != null) {
tagHandler = resourceInjector.createTagHandlerInstance(
handlerClass);
} else {
tagHandler = handlerClass.newInstance();
}
} catch (Exception e) {
throw new JspException(e.getMessage(), e);
}
return tagHandler;
}
|
java
|
{
"resource": ""
}
|
q178141
|
ELParser.parse
|
test
|
public static ELNode.Nodes parse(String expression) {
ELParser parser = new ELParser(expression);
while (parser.hasNextChar()) {
String text = parser.skipUntilEL();
if (text.length() > 0) {
parser.expr.add(new ELNode.Text(text));
}
ELNode.Nodes elexpr = parser.parseEL();
if (! elexpr.isEmpty()) {
parser.expr.add(new ELNode.Root(elexpr, parser.isDollarExpr));
}
}
return parser.expr;
}
|
java
|
{
"resource": ""
}
|
q178142
|
JspConfig.selectProperty
|
test
|
private JspPropertyGroup selectProperty(JspPropertyGroup prev,
JspPropertyGroup curr) {
if (prev == null) {
return curr;
}
if (prev.getExtension() == null) {
// exact match
return prev;
}
if (curr.getExtension() == null) {
// exact match
return curr;
}
String prevPath = prev.getPath();
String currPath = curr.getPath();
if (prevPath == null && currPath == null) {
// Both specifies a *.ext, keep the first one
return prev;
}
if (prevPath == null && currPath != null) {
return curr;
}
if (prevPath != null && currPath == null) {
return prev;
}
if (prevPath.length() >= currPath.length()) {
return prev;
}
return curr;
}
|
java
|
{
"resource": ""
}
|
q178143
|
JspConfig.isJspPage
|
test
|
public boolean isJspPage(String uri) throws JasperException {
init();
if (jspProperties == null) {
return false;
}
String uriPath = null;
int index = uri.lastIndexOf('/');
if (index >=0 ) {
uriPath = uri.substring(0, index+1);
}
String uriExtension = null;
index = uri.lastIndexOf('.');
if (index >=0) {
uriExtension = uri.substring(index+1);
}
for (JspPropertyGroup jpg: jspProperties) {
JspProperty jp = jpg.getJspProperty();
String extension = jpg.getExtension();
String path = jpg.getPath();
if (extension == null) {
if (uri.equals(path)) {
// There is an exact match
return true;
}
} else {
if ((path == null || path.equals(uriPath)) &&
(extension.equals("*") || extension.equals(uriExtension))) {
// Matches *, *.ext, /p/*, or /p/*.ext
return true;
}
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q178144
|
ServletWriter.printComment
|
test
|
public void printComment(Mark start, Mark stop, char[] chars) {
if (start != null && stop != null) {
println("// from="+start);
println("// to="+stop);
}
if (chars != null)
for(int i = 0; i < chars.length;) {
printin();
print("// ");
while (chars[i] != '\n' && i < chars.length)
writer.print(chars[i++]);
}
}
|
java
|
{
"resource": ""
}
|
q178145
|
ServletWriter.printin
|
test
|
public void printin(String s) {
writer.print(SPACES.substring(0, indent));
writer.print(s);
}
|
java
|
{
"resource": ""
}
|
q178146
|
ServletWriter.printil
|
test
|
public void printil(String s) {
javaLine++;
writer.print(SPACES.substring(0, indent));
writer.println(s);
}
|
java
|
{
"resource": ""
}
|
q178147
|
ServletWriter.printMultiLn
|
test
|
public void printMultiLn(String s) {
int index = 0;
// look for hidden newlines inside strings
while ((index=s.indexOf('\n',index)) > -1 ) {
javaLine++;
index++;
}
writer.print(s);
}
|
java
|
{
"resource": ""
}
|
q178148
|
JspUtil.getExprInXml
|
test
|
public static String getExprInXml(String expression) {
String returnString;
int length = expression.length();
if (expression.startsWith(OPEN_EXPR)
&& expression.endsWith(CLOSE_EXPR)) {
returnString = expression.substring (1, length - 1);
} else {
returnString = expression;
}
return escapeXml(returnString);
}
|
java
|
{
"resource": ""
}
|
q178149
|
JspUtil.checkScope
|
test
|
public static void checkScope(String scope, Node n, ErrorDispatcher err)
throws JasperException {
if (scope != null && !scope.equals("page") && !scope.equals("request")
&& !scope.equals("session") && !scope.equals("application")) {
err.jspError(n, "jsp.error.invalid.scope", scope);
}
}
|
java
|
{
"resource": ""
}
|
q178150
|
JspUtil.escapeXml
|
test
|
public static String escapeXml(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
sb.append("<");
} else if (c == '>') {
sb.append(">");
} else if (c == '\'') {
sb.append("'");
} else if (c == '&') {
sb.append("&");
} else if (c == '"') {
sb.append(""");
} else {
sb.append(c);
}
}
return sb.toString();
}
|
java
|
{
"resource": ""
}
|
q178151
|
JspUtil.validateExpressions
|
test
|
public static void validateExpressions(Mark where,
String expressions,
FunctionMapper functionMapper,
ErrorDispatcher err)
throws JasperException {
try {
ELContextImpl elContext = new ELContextImpl(null);
elContext.setFunctionMapper(functionMapper);
getExpressionFactory().createValueExpression(
elContext,
expressions, Object.class);
}
catch( ELException e ) {
err.jspError(where, "jsp.error.invalid.expression", expressions,
e.toString() );
}
}
|
java
|
{
"resource": ""
}
|
q178152
|
JspUtil.getTagHandlerClassName
|
test
|
public static String getTagHandlerClassName(String path,
ErrorDispatcher err)
throws JasperException {
String className = null;
int begin = 0;
int index;
index = path.lastIndexOf(".tag");
if (index == -1) {
err.jspError("jsp.error.tagfile.badSuffix", path);
}
//It's tempting to remove the ".tag" suffix here, but we can't.
//If we remove it, the fully-qualified class name of this tag
//could conflict with the package name of other tags.
//For instance, the tag file
// /WEB-INF/tags/foo.tag
//would have fully-qualified class name
// org.apache.jsp.tag.web.foo
//which would conflict with the package name of the tag file
// /WEB-INF/tags/foo/bar.tag
index = path.indexOf(WEB_INF_TAGS);
if (index != -1) {
className = "org.apache.jsp.tag.web.";
begin = index + WEB_INF_TAGS.length();
} else {
index = path.indexOf(META_INF_TAGS);
if (index != -1) {
className = "org.apache.jsp.tag.meta.";
begin = index + META_INF_TAGS.length();
} else {
err.jspError("jsp.error.tagfile.illegalPath", path);
}
}
className += makeJavaPackage(path.substring(begin));
return className;
}
|
java
|
{
"resource": ""
}
|
q178153
|
JspUtil.makeJavaPackage
|
test
|
public static final String makeJavaPackage(String path) {
String classNameComponents[] = split(path,"/");
StringBuilder legalClassNames = new StringBuilder();
for (int i = 0; i < classNameComponents.length; i++) {
legalClassNames.append(makeJavaIdentifier(classNameComponents[i]));
if (i < classNameComponents.length - 1) {
legalClassNames.append('.');
}
}
return legalClassNames.toString();
}
|
java
|
{
"resource": ""
}
|
q178154
|
JspUtil.split
|
test
|
private static final String [] split(String path, String pat) {
ArrayList<String> comps = new ArrayList<String>();
int pos = path.indexOf(pat);
int start = 0;
while( pos >= 0 ) {
if(pos > start ) {
String comp = path.substring(start,pos);
comps.add(comp);
}
start = pos + pat.length();
pos = path.indexOf(pat,start);
}
if( start < path.length()) {
comps.add(path.substring(start));
}
String [] result = new String[comps.size()];
for(int i=0; i < comps.size(); i++) {
result[i] = comps.get(i);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q178155
|
JspUtil.makeJavaIdentifier
|
test
|
public static final String makeJavaIdentifier(String identifier) {
StringBuilder modifiedIdentifier =
new StringBuilder(identifier.length());
if (!Character.isJavaIdentifierStart(identifier.charAt(0))) {
modifiedIdentifier.append('_');
}
for (int i = 0; i < identifier.length(); i++) {
char ch = identifier.charAt(i);
if (Character.isJavaIdentifierPart(ch) && ch != '_') {
modifiedIdentifier.append(ch);
} else if (ch == '.') {
modifiedIdentifier.append('_');
} else {
modifiedIdentifier.append(mangleChar(ch));
}
}
if (isJavaKeyword(modifiedIdentifier.toString())) {
modifiedIdentifier.append('_');
}
return modifiedIdentifier.toString();
}
|
java
|
{
"resource": ""
}
|
q178156
|
JspUtil.mangleChar
|
test
|
public static final String mangleChar(char ch) {
char[] result = new char[5];
result[0] = '_';
result[1] = Character.forDigit((ch >> 12) & 0xf, 16);
result[2] = Character.forDigit((ch >> 8) & 0xf, 16);
result[3] = Character.forDigit((ch >> 4) & 0xf, 16);
result[4] = Character.forDigit(ch & 0xf, 16);
return new String(result);
}
|
java
|
{
"resource": ""
}
|
q178157
|
JspUtil.isJavaKeyword
|
test
|
public static boolean isJavaKeyword(String key) {
int i = 0;
int j = javaKeywords.length;
while (i < j) {
int k = (i+j)/2;
int result = javaKeywords[k].compareTo(key);
if (result == 0) {
return true;
}
if (result < 0) {
i = k+1;
} else {
j = k;
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q178158
|
InstallableUnit.addProperty
|
test
|
private static void addProperty ( final Map<String, String> props, final String key, final String value )
{
if ( value == null )
{
return;
}
props.put ( key, value );
}
|
java
|
{
"resource": ""
}
|
q178159
|
Functions.modifier
|
test
|
public static String modifier ( final String prefix, final Modifier modifier )
{
if ( modifier == null )
{
return "";
}
String value = null;
switch ( modifier )
{
case DEFAULT:
value = "default";
break;
case PRIMARY:
value = "primary";
break;
case SUCCESS:
value = "success";
break;
case INFO:
value = "info";
break;
case WARNING:
value = "warning";
break;
case DANGER:
value = "danger";
break;
case LINK:
value = "link";
break;
}
if ( value != null && prefix != null )
{
return prefix + value;
}
else
{
return value != null ? value : "";
}
}
|
java
|
{
"resource": ""
}
|
q178160
|
Functions.metadata
|
test
|
public static SortedSet<String> metadata ( final Map<MetaKey, String> metadata, String namespace, String key )
{
final SortedSet<String> result = new TreeSet<> ();
if ( namespace.isEmpty () )
{
namespace = null;
}
if ( key.isEmpty () )
{
key = null;
}
for ( final Map.Entry<MetaKey, String> entry : metadata.entrySet () )
{
if ( namespace != null && !namespace.equals ( entry.getKey ().getNamespace () ) )
{
continue;
}
if ( key != null && !key.equals ( entry.getKey ().getKey () ) )
{
continue;
}
result.add ( entry.getValue () );
}
return result;
}
|
java
|
{
"resource": ""
}
|
q178161
|
DatabaseUserService.run
|
test
|
@Override
public void run () throws Exception
{
this.storageManager.modifyRun ( MODEL_KEY, UserWriteModel.class, users -> {
final Date timeout = new Date ( System.currentTimeMillis () - getTimeout () );
final Collection<UserEntity> updates = new LinkedList<> ();
final Collection<String> removals = new LinkedList<> ();
for ( final UserEntity user : users.asCollection () )
{
if ( user.getEmailTokenDate () == null || user.getEmailTokenDate ().after ( timeout ) )
{
continue;
}
// process timeout
if ( user.isEmailVerified () )
{
user.setEmailToken ( null );
user.setEmailTokenDate ( null );
user.setEmailTokenSalt ( null );
updates.add ( user );
}
else
{
// delete
removals.add ( user.getId () );
}
}
updates.forEach ( users::putUser );
removals.forEach ( users::removeUser );
} );
}
|
java
|
{
"resource": ""
}
|
q178162
|
FileNames.getBasename
|
test
|
public static String getBasename ( final String name )
{
if ( name == null )
{
return null;
}
final String[] toks = name.split ( "/" );
if ( toks.length < 1 )
{
return name;
}
return toks[toks.length - 1];
}
|
java
|
{
"resource": ""
}
|
q178163
|
MetadataCache.put
|
test
|
public boolean put(Locator locator, String key, String value) throws CacheException {
if (value == null) return false;
Timer.Context cachePutTimerContext = MetadataCache.cachePutTimer.time();
boolean dbWrite = false;
try {
CacheKey cacheKey = new CacheKey(locator, key);
String oldValue = cache.getIfPresent(cacheKey);
// don't care if oldValue == EMPTY.
// always put new value in the cache. it keeps reads from happening.
cache.put(cacheKey, value);
if (oldValue == null || !oldValue.equals(value)) {
dbWrite = true;
}
if (dbWrite) {
updatedMetricMeter.mark();
if (!batchedWrites) {
databasePut(locator, key, value);
} else {
databaseLazyWrite(locator, key);
}
}
return dbWrite;
} finally {
cachePutTimerContext.stop();
}
}
|
java
|
{
"resource": ""
}
|
q178164
|
MetadataCache.databaseLoad
|
test
|
private String databaseLoad(Locator locator, String key) throws CacheException {
try {
CacheKey cacheKey = new CacheKey(locator, key);
Map<String, String> metadata = io.getAllValues(locator);
if (metadata == null || metadata.isEmpty()) {
cache.put(cacheKey, NULL);
return NULL;
}
int metadataRowSize = 0;
// prepopulate all other metadata other than the key we called the method with
for (Map.Entry<String, String> meta : metadata.entrySet()) {
metadataRowSize += meta.getKey().getBytes().length + locator.toString().getBytes().length;
if (meta.getValue() != null)
metadataRowSize += meta.getValue().getBytes().length;
if (meta.getKey().equals(key)) continue;
CacheKey metaKey = new CacheKey(locator, meta.getKey());
cache.put(metaKey, meta.getValue());
}
totalMetadataSize.update(metadataRowSize);
String value = metadata.get(key);
if (value == null) {
cache.put(cacheKey, NULL);
value = NULL;
}
return value;
} catch (IOException ex) {
throw new CacheException(ex);
}
}
|
java
|
{
"resource": ""
}
|
q178165
|
PreaggregateConversions.buildMetricsCollection
|
test
|
public static Collection<IMetric> buildMetricsCollection(AggregatedPayload payload) {
Collection<IMetric> metrics = new ArrayList<IMetric>();
metrics.addAll(PreaggregateConversions.convertCounters(payload.getTenantId(), payload.getTimestamp(), payload.getFlushIntervalMillis(), payload.getCounters()));
metrics.addAll(PreaggregateConversions.convertGauges(payload.getTenantId(), payload.getTimestamp(), payload.getGauges()));
metrics.addAll(PreaggregateConversions.convertSets(payload.getTenantId(), payload.getTimestamp(), payload.getSets()));
metrics.addAll(PreaggregateConversions.convertTimers(payload.getTenantId(), payload.getTimestamp(), payload.getTimers()));
return metrics;
}
|
java
|
{
"resource": ""
}
|
q178166
|
PreaggregateConversions.resolveNumber
|
test
|
public static Number resolveNumber(Number n) {
if (n instanceof LazilyParsedNumber) {
try {
return n.longValue();
} catch (NumberFormatException ex) {
return n.doubleValue();
}
} else {
// already resolved.
return n;
}
}
|
java
|
{
"resource": ""
}
|
q178167
|
StringMetadataSerDes.writeToOutputStream
|
test
|
private static void writeToOutputStream(Object obj, CodedOutputStream out) throws IOException {
out.writeRawByte(STRING);
out.writeStringNoTag((String)obj);
}
|
java
|
{
"resource": ""
}
|
q178168
|
AbstractMetricsRW.getTtl
|
test
|
protected int getTtl(Locator locator, RollupType rollupType, Granularity granularity) {
return (int) TTL_PROVIDER.getTTL(locator.getTenantId(),
granularity,
rollupType).get().toSeconds();
}
|
java
|
{
"resource": ""
}
|
q178169
|
DLocatorIO.createPreparedStatements
|
test
|
private void createPreparedStatements() {
// create a generic select statement for retrieving from metrics_locator
Select.Where select = QueryBuilder
.select()
.all()
.from( CassandraModel.CF_METRICS_LOCATOR_NAME )
.where( eq ( KEY, bindMarker() ));
getValue = DatastaxIO.getSession().prepare( select );
// create a generic insert statement for inserting into metrics_locator
Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME)
.using(ttl(TenantTtlProvider.LOCATOR_TTL))
.value(KEY, bindMarker())
.value(COLUMN1, bindMarker())
.value(VALUE, bindMarker());
putValue = DatastaxIO.getSession()
.prepare(insert)
.setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
}
|
java
|
{
"resource": ""
}
|
q178170
|
Tracker.trackDelayedMetricsTenant
|
test
|
public void trackDelayedMetricsTenant(String tenantid, final List<Metric> delayedMetrics) {
if (isTrackingDelayedMetrics) {
String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s", tenantid);
log.info(logMessage);
// log individual delayed metrics locator and collectionTime
double delayedMinutes;
long nowMillis = System.currentTimeMillis();
for (Metric metric : delayedMetrics) {
delayedMinutes = (double)(nowMillis - metric.getCollectionTime()) / 1000 / 60;
logMessage = String.format("[TRACKER][DELAYED METRIC] %s has collectionTime %s which is delayed by %.2f minutes",
metric.getLocator().toString(),
dateFormatter.format(new Date(metric.getCollectionTime())),
delayedMinutes);
log.info(logMessage);
}
}
}
|
java
|
{
"resource": ""
}
|
q178171
|
Tracker.trackDelayedAggregatedMetricsTenant
|
test
|
public void trackDelayedAggregatedMetricsTenant(String tenantId, long collectionTimeMs, long delayTimeMs, List<String> delayedMetricNames) {
if (isTrackingDelayedMetrics) {
String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s", tenantId);
log.info(logMessage);
// log individual delayed metrics locator and collectionTime
double delayMin = delayTimeMs / 1000 / 60;
logMessage = String.format("[TRACKER][DELAYED METRIC] %s have collectionTime %s which is delayed by %.2f minutes",
StringUtils.join(delayedMetricNames, ","),
dateFormatter.format(new Date(collectionTimeMs)),
delayMin);
log.info(logMessage);
}
}
|
java
|
{
"resource": ""
}
|
q178172
|
AbstractSerDes.getUnversionedDoubleOrLong
|
test
|
protected Number getUnversionedDoubleOrLong(CodedInputStream in) throws IOException {
byte type = in.readRawByte();
if (type == Constants.B_DOUBLE)
return in.readDouble();
else
return in.readRawVarint64();
}
|
java
|
{
"resource": ""
}
|
q178173
|
AbstractSerDes.putUnversionedDoubleOrLong
|
test
|
protected void putUnversionedDoubleOrLong(Number number, CodedOutputStream out) throws IOException {
if (number instanceof Double) {
out.writeRawByte(Constants.B_DOUBLE);
out.writeDoubleNoTag(number.doubleValue());
} else {
out.writeRawByte(Constants.B_I64);
out.writeRawVarint64(number.longValue());
}
}
|
java
|
{
"resource": ""
}
|
q178174
|
Configuration.getAllProperties
|
test
|
public Map<Object, Object> getAllProperties() {
Map<Object, Object> map = new HashMap<Object, Object>();
for (Object key : defaultProps.keySet()) {
map.put(key, defaultProps.getProperty(key.toString()));
}
for (Object key : props.keySet()) {
map.put(key, props.getProperty(key.toString()));
}
return Collections.unmodifiableMap(map);
}
|
java
|
{
"resource": ""
}
|
q178175
|
CloudFilesPublisher.createContainer
|
test
|
private void createContainer() {
String containerName = CONTAINER_DATE_FORMAT.format(new Date());
blobStore.createContainerInLocation(null, containerName);
lastContainerCreated = containerName;
}
|
java
|
{
"resource": ""
}
|
q178176
|
ScheduleContext.scheduleEligibleSlots
|
test
|
void scheduleEligibleSlots(long maxAgeMillis, long rollupDelayForMetricsWithShortDelay, long rollupWaitForMetricsWithLongDelay) {
long now = scheduleTime;
ArrayList<Integer> shardKeys = new ArrayList<Integer>(shardStateManager.getManagedShards());
Collections.shuffle(shardKeys);
for (int shard : shardKeys) {
for (Granularity g : Granularity.rollupGranularities()) {
// sync on map since we do not want anything added to or taken from it while we iterate.
synchronized (scheduledSlots) { // read
synchronized (runningSlots) { // read
List<Integer> slotsToWorkOn = shardStateManager.getSlotStateManager(shard, g)
.getSlotsEligibleForRollup(now, maxAgeMillis, rollupDelayForMetricsWithShortDelay, rollupWaitForMetricsWithLongDelay);
if (slotsToWorkOn.size() == 0) {
continue;
}
if (!canWorkOnShard(shard)) {
continue;
}
for (Integer slot : slotsToWorkOn) {
SlotKey slotKey = SlotKey.of(g, slot, shard);
if (areChildKeysOrSelfKeyScheduledOrRunning(slotKey)) {
continue;
}
SlotKey key = SlotKey.of(g, slot, shard);
scheduledSlots.add(key);
orderedScheduledSlots.add(key);
recentlyScheduledShards.put(shard, scheduleTime);
}
}
}
}
}
}
|
java
|
{
"resource": ""
}
|
q178177
|
ScheduleContext.clearFromRunning
|
test
|
void clearFromRunning(SlotKey slotKey) {
synchronized (runningSlots) {
runningSlots.remove(slotKey);
UpdateStamp stamp = shardStateManager.getUpdateStamp(slotKey);
shardStateManager.setAllCoarserSlotsDirtyForSlot(slotKey);
//When state gets set to "X", before it got persisted, it might get scheduled for rollup
//again, if we get delayed metrics. To prevent this we temporarily set last rollup time with current
//time. This value wont get persisted.
long currentTimeInMillis = clock.now().getMillis();
stamp.setLastRollupTimestamp(currentTimeInMillis);
log.debug("SlotKey {} is marked in memory with last rollup time as {}", slotKey, currentTimeInMillis);
// Update the stamp to Rolled state if and only if the current state
// is running. If the current state is active, it means we received
// a delayed put which toggled the status to Active.
if (stamp.getState() == UpdateStamp.State.Running) {
stamp.setState(UpdateStamp.State.Rolled);
// Note: Rollup state will be updated to the last ACTIVE
// timestamp which caused rollup process to kick in.
stamp.setDirty(true);
}
}
}
|
java
|
{
"resource": ""
}
|
q178178
|
Emitter.on
|
test
|
public Emitter on(String event, Listener fn) {
ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event);
if (callbacks == null) {
callbacks = new ConcurrentLinkedQueue<Listener>();
ConcurrentLinkedQueue<Listener> _callbacks = this.callbacks.putIfAbsent(event, callbacks);
if (_callbacks != null) {
callbacks = _callbacks;
}
}
callbacks.add(fn);
return this;
}
|
java
|
{
"resource": ""
}
|
q178179
|
Emitter.once
|
test
|
public Emitter once(final String event, final Listener<T> fn) {
Listener on = new Listener<T>() {
@Override
public void call(T... args) {
Emitter.this.off(event, this);
fn.call(args);
}
};
this.onceCallbacks.put(fn, on);
this.on(event, on);
return this;
}
|
java
|
{
"resource": ""
}
|
q178180
|
Emitter.off
|
test
|
public Emitter off(String event) {
ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.remove(event);
if (callbacks != null) {
for (Listener fn : callbacks) {
this.onceCallbacks.remove(fn);
}
}
return this;
}
|
java
|
{
"resource": ""
}
|
q178181
|
Emitter.emit
|
test
|
public Future emit(String event, T... args) {
ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event);
if (callbacks != null) {
callbacks = new ConcurrentLinkedQueue<Listener>(callbacks);
for (Listener fn : callbacks) {
fn.call(args);
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q178182
|
Emitter.listeners
|
test
|
public List<Listener> listeners(String event) {
ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event);
return callbacks != null ?
new ArrayList<Listener>(callbacks) : new ArrayList<Listener>();
}
|
java
|
{
"resource": ""
}
|
q178183
|
RollupFile.getRemoteName
|
test
|
public String getRemoteName() {
Date time = new Date(timestamp);
String formattedTime = new SimpleDateFormat("yyyyMMdd_").format(time);
return formattedTime + System.currentTimeMillis() + "_" + Configuration.getInstance().getStringProperty(CloudfilesConfig.CLOUDFILES_HOST_UNIQUE_IDENTIFIER);
}
|
java
|
{
"resource": ""
}
|
q178184
|
RollupFile.append
|
test
|
public void append(RollupEvent rollup) throws IOException {
ensureOpen();
outputStream.write(serializer.toBytes(rollup));
outputStream.write('\n');
outputStream.flush();
}
|
java
|
{
"resource": ""
}
|
q178185
|
RollupFile.parseTimestamp
|
test
|
private static long parseTimestamp(String fileName) throws NumberFormatException {
String numberPart = fileName.substring(0, fileName.length() - 5);
return Long.parseLong(numberPart);
}
|
java
|
{
"resource": ""
}
|
q178186
|
HttpMetricsIngestionServer.startServer
|
test
|
public void startServer() throws InterruptedException {
RouteMatcher router = new RouteMatcher();
router.get("/v1.0", new DefaultHandler());
router.post("/v1.0/multitenant/experimental/metrics",
new HttpMultitenantMetricsIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v1.0/:tenantId/experimental/metrics",
new HttpMetricsIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v1.0/:tenantId/experimental/metrics/statsd",
new HttpAggregatedIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.get("/v2.0", new DefaultHandler());
router.post("/v2.0/:tenantId/ingest/multi",
new HttpMultitenantMetricsIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v2.0/:tenantId/ingest",
new HttpMetricsIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v2.0/:tenantId/ingest/aggregated",
new HttpAggregatedIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v2.0/:tenantId/ingest/aggregated/multi",
new HttpAggregatedMultiIngestionHandler(processor, timeout, ENABLE_PER_TENANT_METRICS));
router.post("/v2.0/:tenantId/events", getHttpEventsIngestionHandler());
final RouteMatcher finalRouter = router;
log.info("Starting metrics listener HTTP server on port {}", httpIngestPort);
ServerBootstrap server = new ServerBootstrap();
server.group(acceptorGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
setupPipeline(channel, finalRouter);
}
});
Channel channel = server.bind(new InetSocketAddress(httpIngestHost, httpIngestPort)).sync().channel();
allOpenChannels.add(channel);
//register the tracker MBean for JMX/jolokia
log.info("Registering tracker service");
Tracker.getInstance().register();
log.info("Token search improvements enabled: " + EXP_TOKEN_SEARCH_IMPROVEMENTS);
}
|
java
|
{
"resource": ""
}
|
q178187
|
RollupRunnable.getRollupComputer
|
test
|
public static Rollup.Type getRollupComputer(RollupType srcType, Granularity srcGran) {
switch (srcType) {
case COUNTER:
return Rollup.CounterFromCounter;
case TIMER:
return Rollup.TimerFromTimer;
case GAUGE:
return Rollup.GaugeFromGauge;
case BF_BASIC:
return srcGran == Granularity.FULL ? Rollup.BasicFromRaw : Rollup.BasicFromBasic;
case SET:
return Rollup.SetFromSet;
default:
break;
}
throw new IllegalArgumentException(String.format("Cannot compute rollups for %s from %s", srcType.name(), srcGran.shortName()));
}
|
java
|
{
"resource": ""
}
|
q178188
|
IOContainer.fromConfig
|
test
|
public static synchronized IOContainer fromConfig() {
if ( FROM_CONFIG_INSTANCE == null ) {
String driver = configuration.getStringProperty(CoreConfig.CASSANDRA_DRIVER);
LOG.info(String.format("Using driver %s", driver));
boolean isRecordingDelayedMetrics = configuration.getBooleanProperty(CoreConfig.RECORD_DELAYED_METRICS);
LOG.info(String.format("Recording delayed metrics: %s", isRecordingDelayedMetrics));
boolean isDtxIngestBatchEnabled = configuration.getBooleanProperty(CoreConfig.ENABLE_DTX_INGEST_BATCH);
LOG.info(String.format("Datastax Ingest batch enabled: %s", isDtxIngestBatchEnabled));
FROM_CONFIG_INSTANCE = new IOContainer(DriverType.getDriverType(driver),
isRecordingDelayedMetrics,
isDtxIngestBatchEnabled);
}
return FROM_CONFIG_INSTANCE;
}
|
java
|
{
"resource": ""
}
|
q178189
|
ConfigTtlProvider.put
|
test
|
private boolean put(
ImmutableTable.Builder<Granularity, RollupType, TimeValue> ttlMapBuilder,
Configuration config,
Granularity gran,
RollupType rollupType,
TtlConfig configKey) {
int value;
try {
value = config.getIntegerProperty(configKey);
if (value < 0) return false;
} catch (NumberFormatException ex) {
log.trace(String.format("No valid TTL config set for granularity: %s, rollup type: %s",
gran.name(), rollupType.name()), ex);
return false;
}
ttlMapBuilder.put(gran, rollupType, new TimeValue(value, TimeUnit.DAYS));
return true;
}
|
java
|
{
"resource": ""
}
|
q178190
|
OutputFormatter.computeMaximums
|
test
|
public static int [] computeMaximums(String[] headers, OutputFormatter... outputs) {
int[] max = new int[headers.length];
for (int i = 0; i < headers.length; i++)
max[i] = headers[i].length();
for (OutputFormatter output : outputs) {
max[0] = Math.max(output.host.length(), max[0]);
for (int i = 1; i < headers.length; i++)
max[i] = Math.max(output.results[i-1].length(), max[i]);
}
return max;
}
|
java
|
{
"resource": ""
}
|
q178191
|
OutputFormatter.formatHeader
|
test
|
public static String formatHeader(int[] maximums, String[] headers) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < headers.length; i++)
sb = sb.append(formatIn(headers[i], maximums[i], false)).append(GAP);
return sb.toString();
}
|
java
|
{
"resource": ""
}
|
q178192
|
OutputFormatter.format
|
test
|
public static String[] format(int[] maximums, OutputFormatter... outputs) {
String[] formattedStrings = new String[outputs.length];
int pos = 0;
for (OutputFormatter output : outputs) {
StringBuilder sb = new StringBuilder();
sb = sb.append(formatIn(output.host, maximums[0], false));
for (int i = 0; i < output.results.length; i++)
sb = sb.append(GAP).append(formatIn(output.results[i], maximums[i+1], true));
formattedStrings[pos++] = sb.toString();
}
return formattedStrings;
}
|
java
|
{
"resource": ""
}
|
q178193
|
ZKShardLockManager.registerMetrics
|
test
|
private void registerMetrics(final ObjectName nameObj, MetricRegistry reg) {
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Lock Disinterested Time Millis"),
new JmxAttributeGauge(nameObj, "LockDisinterestedTimeMillis"));
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Min Lock Hold Time Millis"),
new JmxAttributeGauge(nameObj, "MinLockHoldTimeMillis"));
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Seconds Since Last Scavenge"),
new JmxAttributeGauge(nameObj, "SecondsSinceLastScavenge"));
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Zk Connection Status"),
new JmxAttributeGauge(nameObj, "ZkConnectionStatus") {
@Override
public Object getValue() {
Object val = super.getValue();
if (val.equals("connected")) {
return 1;
}
return 0;
}
});
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Held Shards"),
new Gauge<Integer>() {
@Override
public Integer getValue() {
return getHeldShards().size();
}
});
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Unheld Shards"),
new Gauge<Integer>() {
@Override
public Integer getValue() {
return getUnheldShards().size();
}
});
reg.register(MetricRegistry.name(ZKShardLockManager.class, "Error Shards"),
new Gauge<Integer>() {
@Override
public Integer getValue() {
return getErrorShards().size();
}
});
}
|
java
|
{
"resource": ""
}
|
q178194
|
ThreadPoolBuilder.withName
|
test
|
public ThreadPoolBuilder withName(String name) {
// ensure we've got a spot to put the thread id.
if (!name.contains("%d")) {
name = name + "-%d";
}
nameMap.putIfAbsent(name, new AtomicInteger(0));
int id = nameMap.get(name).incrementAndGet();
this.poolName = String.format(name, id);
if (id > 1) {
this.threadNameFormat = name.replace("%d", id + "-%d");
} else {
this.threadNameFormat = name;
}
return this;
}
|
java
|
{
"resource": ""
}
|
q178195
|
MetricIndexData.add
|
test
|
public void add(String metricIndex, long docCount) {
final String[] tokens = metricIndex.split(METRIC_TOKEN_SEPARATOR_REGEX);
/**
*
* For the ES response shown in class description, for a baseLevel of 2,
* the data is classified as follows
*
* metricNamesWithNextLevelSet -> {foo.bar.baz} (Metric Names which are at base + 1 level and also have a subsequent level.)
*
* For count map, data is in the form {metricIndex, (actualDocCount, childrenTotalDocCount)}
*
* metricNameBaseLevelMap -> {foo.bar.baz -> (2, 1)} (all indexes which are of same length as baseLevel)
*
*/
switch (tokens.length - baseLevel) {
case 1:
if (baseLevel > 0) {
metricNamesWithNextLevelSet.add(metricIndex.substring(0, metricIndex.lastIndexOf(".")));
} else {
metricNamesWithNextLevelSet.add(metricIndex.substring(0, metricIndex.indexOf(".")));
}
//For foo.bar.baz, baseLevel=3 we update children doc count of foo.bar.baz
addChildrenDocCount(metricNameBaseLevelMap,
metricIndex.substring(0, metricIndex.lastIndexOf(".")),
docCount);
break;
case 0:
setActualDocCount(metricNameBaseLevelMap, metricIndex, docCount);
break;
default:
break;
}
}
|
java
|
{
"resource": ""
}
|
q178196
|
MetricIndexData.getCompleteMetricNames
|
test
|
private Set<String> getCompleteMetricNames(Map<String, MetricIndexDocCount> metricIndexMap) {
Set<String> completeMetricNames = new HashSet<String>();
for (Map.Entry<String, MetricIndexDocCount> entry : metricIndexMap.entrySet()) {
MetricIndexDocCount metricIndexDocCount = entry.getValue();
if (metricIndexDocCount != null) {
//if total doc count is greater than its children docs, its a complete metric name
if (metricIndexDocCount.actualDocCount > 0 &&
metricIndexDocCount.actualDocCount > metricIndexDocCount.childrenTotalDocCount) {
completeMetricNames.add(entry.getKey());
}
}
}
return Collections.unmodifiableSet(completeMetricNames);
}
|
java
|
{
"resource": ""
}
|
q178197
|
Token.getTokens
|
test
|
public static List<Token> getTokens(Locator locator) {
if (StringUtils.isEmpty(locator.getMetricName()) || StringUtils.isEmpty(locator.getTenantId()))
return new ArrayList<>();
String[] tokens = locator.getMetricName().split(Locator.METRIC_TOKEN_SEPARATOR_REGEX);
return IntStream.range(0, tokens.length)
.mapToObj(index -> new Token(locator, tokens, index))
.collect(toList());
}
|
java
|
{
"resource": ""
}
|
q178198
|
DAbstractMetricIO.putAsync
|
test
|
public ResultSetFuture putAsync(Locator locator, long collectionTime, Rollup rollup, Granularity granularity, int ttl) {
Session session = DatastaxIO.getSession();
// we use batch statement here in case sub classes
// override the addRollupToBatch() and provide
// multiple statements
BatchStatement batch = new BatchStatement();
addRollupToBatch(batch, locator, rollup, collectionTime, granularity, ttl);
Collection<Statement> statements = batch.getStatements();
if ( statements.size() == 1 ) {
Statement oneStatement = statements.iterator().next();
return session.executeAsync(oneStatement);
} else {
LOG.debug(String.format("Using BatchStatement for %d statements", statements.size()));
return session.executeAsync(batch);
}
}
|
java
|
{
"resource": ""
}
|
q178199
|
Granularity.granularityFromPointsInInterval
|
test
|
public static Granularity granularityFromPointsInInterval(String tenantid, long from, long to, int points, String algorithm, long assumedIntervalMillis, Clock ttlComparisonClock) {
if (from >= to) {
throw new RuntimeException("Invalid interval specified for fromPointsInInterval");
}
double requestedDuration = to - from;
if (algorithm.startsWith("GEOMETRIC"))
return granularityFromPointsGeometric(tenantid, from, to, requestedDuration, points, assumedIntervalMillis, ttlComparisonClock);
else if (algorithm.startsWith("LINEAR"))
return granularityFromPointsLinear(requestedDuration, points, assumedIntervalMillis);
else if (algorithm.startsWith("LESSTHANEQUAL"))
return granularityFromPointsLessThanEqual(requestedDuration, points, assumedIntervalMillis);
return granularityFromPointsGeometric(tenantid, from, to, requestedDuration, points, assumedIntervalMillis, ttlComparisonClock);
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.