id
int32
0
165k
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
143,000
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java
TupleHashPartitioner.partialHashCode
public int partialHashCode(ITuple tuple, int[] fields) { int result = 0; for(int field : fields) { Object o = tuple.get(field); if(o == null) { // nulls don't account for hashcode continue; } int hashCode; if(o instanceof String) { // since String.hashCode() != Utf8.hashCode() HELPER_UTF8.set((String) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof Text) { HELPER_UTF8.set((Text) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof byte[]){ hashCode = hashBytes((byte[])o,0,((byte[]) o).length); } else if(o instanceof ByteBuffer){ ByteBuffer buffer = (ByteBuffer)o; int offset = buffer.arrayOffset() + buffer.position(); int length = buffer.limit() - buffer.position(); hashCode = hashBytes(buffer.array(),offset,length); } else { hashCode = o.hashCode(); } result = result * 31 + hashCode; } return result; }
java
public int partialHashCode(ITuple tuple, int[] fields) { int result = 0; for(int field : fields) { Object o = tuple.get(field); if(o == null) { // nulls don't account for hashcode continue; } int hashCode; if(o instanceof String) { // since String.hashCode() != Utf8.hashCode() HELPER_UTF8.set((String) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof Text) { HELPER_UTF8.set((Text) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof byte[]){ hashCode = hashBytes((byte[])o,0,((byte[]) o).length); } else if(o instanceof ByteBuffer){ ByteBuffer buffer = (ByteBuffer)o; int offset = buffer.arrayOffset() + buffer.position(); int length = buffer.limit() - buffer.position(); hashCode = hashBytes(buffer.array(),offset,length); } else { hashCode = o.hashCode(); } result = result * 31 + hashCode; } return result; }
[ "public", "int", "partialHashCode", "(", "ITuple", "tuple", ",", "int", "[", "]", "fields", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "field", ":", "fields", ")", "{", "Object", "o", "=", "tuple", ".", "get", "(", "field", ")", ";", "if", "(", "o", "==", "null", ")", "{", "// nulls don't account for hashcode", "continue", ";", "}", "int", "hashCode", ";", "if", "(", "o", "instanceof", "String", ")", "{", "// since String.hashCode() != Utf8.hashCode()", "HELPER_UTF8", ".", "set", "(", "(", "String", ")", "o", ")", ";", "hashCode", "=", "HELPER_UTF8", ".", "hashCode", "(", ")", ";", "}", "else", "if", "(", "o", "instanceof", "Text", ")", "{", "HELPER_UTF8", ".", "set", "(", "(", "Text", ")", "o", ")", ";", "hashCode", "=", "HELPER_UTF8", ".", "hashCode", "(", ")", ";", "}", "else", "if", "(", "o", "instanceof", "byte", "[", "]", ")", "{", "hashCode", "=", "hashBytes", "(", "(", "byte", "[", "]", ")", "o", ",", "0", ",", "(", "(", "byte", "[", "]", ")", "o", ")", ".", "length", ")", ";", "}", "else", "if", "", "(", "o", "instanceof", "ByteBuffer", ")", "", "{", "ByteBuffer", "buffer", "=", "(", "ByteBuffer", ")", "o", ";", "int", "offset", "=", "buffer", ".", "arrayOffset", "(", ")", "+", "buffer", ".", "position", "(", ")", ";", "int", "length", "=", "buffer", ".", "limit", "(", ")", "-", "buffer", ".", "position", "(", ")", ";", "hashCode", "=", "hashBytes", "(", "buffer", ".", "array", "(", ")", ",", "offset", ",", "length", ")", ";", "}", "else", "", "{", "hashCode", "=", "o", ".", "hashCode", "(", ")", ";", "}", "result", "=", "result", "*", "31", "+", "hashCode", ";", "}", "return", "result", ";", "}" ]
Calculates a combinated hashCode using the specified number of fields.
[ "Calculates", "a", "combinated", "hashCode", "using", "the", "specified", "number", "of", "fields", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java#L87-L114
143,001
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/ErrorPageFilter.java
ErrorPageFilter.init
@Override public void init(FilterConfig config) throws ServletException { if(config.getInitParameter("ignorePrefix") != null) { ignorePath = config.getInitParameter("ignorePrefix"); } }
java
@Override public void init(FilterConfig config) throws ServletException { if(config.getInitParameter("ignorePrefix") != null) { ignorePath = config.getInitParameter("ignorePrefix"); } }
[ "@", "Override", "public", "void", "init", "(", "FilterConfig", "config", ")", "throws", "ServletException", "{", "if", "(", "config", ".", "getInitParameter", "(", "\"ignorePrefix\"", ")", "!=", "null", ")", "{", "ignorePath", "=", "config", ".", "getInitParameter", "(", "\"ignorePrefix\"", ")", ";", "}", "}" ]
Configures the ignore prefix.
[ "Configures", "the", "ignore", "prefix", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/ErrorPageFilter.java#L81-L87
143,002
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/GroupComparator.java
GroupComparator.compare
@SuppressWarnings("rawtypes") @Override public int compare(ITuple w1, ITuple w2) { int schemaId1 = tupleMRConf.getSchemaIdByName(w1.getSchema().getName()); int schemaId2 = tupleMRConf.getSchemaIdByName(w2.getSchema().getName()); int[] indexes1 = serInfo.getGroupSchemaIndexTranslation(schemaId1); int[] indexes2 = serInfo.getGroupSchemaIndexTranslation(schemaId2); Serializer[] serializers = serInfo.getGroupSchemaSerializers(); return compare(w1.getSchema(), groupCriteria, w1, indexes1, w2, indexes2,serializers); }
java
@SuppressWarnings("rawtypes") @Override public int compare(ITuple w1, ITuple w2) { int schemaId1 = tupleMRConf.getSchemaIdByName(w1.getSchema().getName()); int schemaId2 = tupleMRConf.getSchemaIdByName(w2.getSchema().getName()); int[] indexes1 = serInfo.getGroupSchemaIndexTranslation(schemaId1); int[] indexes2 = serInfo.getGroupSchemaIndexTranslation(schemaId2); Serializer[] serializers = serInfo.getGroupSchemaSerializers(); return compare(w1.getSchema(), groupCriteria, w1, indexes1, w2, indexes2,serializers); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "@", "Override", "public", "int", "compare", "(", "ITuple", "w1", ",", "ITuple", "w2", ")", "{", "int", "schemaId1", "=", "tupleMRConf", ".", "getSchemaIdByName", "(", "w1", ".", "getSchema", "(", ")", ".", "getName", "(", ")", ")", ";", "int", "schemaId2", "=", "tupleMRConf", ".", "getSchemaIdByName", "(", "w2", ".", "getSchema", "(", ")", ".", "getName", "(", ")", ")", ";", "int", "[", "]", "indexes1", "=", "serInfo", ".", "getGroupSchemaIndexTranslation", "(", "schemaId1", ")", ";", "int", "[", "]", "indexes2", "=", "serInfo", ".", "getGroupSchemaIndexTranslation", "(", "schemaId2", ")", ";", "Serializer", "[", "]", "serializers", "=", "serInfo", ".", "getGroupSchemaSerializers", "(", ")", ";", "return", "compare", "(", "w1", ".", "getSchema", "(", ")", ",", "groupCriteria", ",", "w1", ",", "indexes1", ",", "w2", ",", "indexes2", ",", "serializers", ")", ";", "}" ]
Never called in MapRed jobs. Just for completion and test purposes
[ "Never", "called", "in", "MapRed", "jobs", ".", "Just", "for", "completion", "and", "test", "purposes" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/GroupComparator.java#L45-L54
143,003
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/BitEncoderChannel.java
BitEncoderChannel.encodeNBitUnsignedInteger
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Encode negative value as unsigned integer is invalid!"); } assert (b >= 0); assert (n >= 0); ostream.writeBits(b, n); }
java
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Encode negative value as unsigned integer is invalid!"); } assert (b >= 0); assert (n >= 0); ostream.writeBits(b, n); }
[ "public", "void", "encodeNBitUnsignedInteger", "(", "int", "b", ",", "int", "n", ")", "throws", "IOException", "{", "if", "(", "b", "<", "0", "||", "n", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Encode negative value as unsigned integer is invalid!\"", ")", ";", "}", "assert", "(", "b", ">=", "0", ")", ";", "assert", "(", "n", ">=", "0", ")", ";", "ostream", ".", "writeBits", "(", "b", ",", "n", ")", ";", "}" ]
Encode n-bit unsigned integer. The n least significant bits of parameter b starting with the most significant, i.e. from left to right.
[ "Encode", "n", "-", "bit", "unsigned", "integer", ".", "The", "n", "least", "significant", "bits", "of", "parameter", "b", "starting", "with", "the", "most", "significant", "i", ".", "e", ".", "from", "left", "to", "right", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/BitEncoderChannel.java#L90-L99
143,004
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Mutator.java
Mutator.subSetOf
public static Schema subSetOf(Schema schema, String... subSetFields) { return subSetOf("subSetSchema" + (COUNTER++), schema, subSetFields); }
java
public static Schema subSetOf(Schema schema, String... subSetFields) { return subSetOf("subSetSchema" + (COUNTER++), schema, subSetFields); }
[ "public", "static", "Schema", "subSetOf", "(", "Schema", "schema", ",", "String", "...", "subSetFields", ")", "{", "return", "subSetOf", "(", "\"subSetSchema\"", "+", "(", "COUNTER", "++", ")", ",", "schema", ",", "subSetFields", ")", ";", "}" ]
Creates a subset of the input Schema exactly with the fields whose names are specified. The name of the schema is auto-generated with a static counter.
[ "Creates", "a", "subset", "of", "the", "input", "Schema", "exactly", "with", "the", "fields", "whose", "names", "are", "specified", ".", "The", "name", "of", "the", "schema", "is", "auto", "-", "generated", "with", "a", "static", "counter", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L52-L54
143,005
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Mutator.java
Mutator.subSetOf
public static Schema subSetOf(String newName, Schema schema, String... subSetFields) { List<Field> newSchema = new ArrayList<Field>(); for(String subSetField: subSetFields) { newSchema.add(schema.getField(subSetField)); } return new Schema(newName, newSchema); }
java
public static Schema subSetOf(String newName, Schema schema, String... subSetFields) { List<Field> newSchema = new ArrayList<Field>(); for(String subSetField: subSetFields) { newSchema.add(schema.getField(subSetField)); } return new Schema(newName, newSchema); }
[ "public", "static", "Schema", "subSetOf", "(", "String", "newName", ",", "Schema", "schema", ",", "String", "...", "subSetFields", ")", "{", "List", "<", "Field", ">", "newSchema", "=", "new", "ArrayList", "<", "Field", ">", "(", ")", ";", "for", "(", "String", "subSetField", ":", "subSetFields", ")", "{", "newSchema", ".", "add", "(", "schema", ".", "getField", "(", "subSetField", ")", ")", ";", "}", "return", "new", "Schema", "(", "newName", ",", "newSchema", ")", ";", "}" ]
Creates a subset of the input Schema exactly with the fields whose names are specified. The name of the schema is also specified as a parameter.
[ "Creates", "a", "subset", "of", "the", "input", "Schema", "exactly", "with", "the", "fields", "whose", "names", "are", "specified", ".", "The", "name", "of", "the", "schema", "is", "also", "specified", "as", "a", "parameter", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L60-L66
143,006
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Mutator.java
Mutator.superSetOf
public static Schema superSetOf(Schema schema, Field... newFields) { return superSetOf("superSetSchema" + (COUNTER++), schema, newFields); }
java
public static Schema superSetOf(Schema schema, Field... newFields) { return superSetOf("superSetSchema" + (COUNTER++), schema, newFields); }
[ "public", "static", "Schema", "superSetOf", "(", "Schema", "schema", ",", "Field", "...", "newFields", ")", "{", "return", "superSetOf", "(", "\"superSetSchema\"", "+", "(", "COUNTER", "++", ")", ",", "schema", ",", "newFields", ")", ";", "}" ]
Creates a superset of the input Schema, taking all the Fields in the input schema and adding some new ones. The new fields are fully specified in a Field class. The name of the schema is auto-generated with a static counter.
[ "Creates", "a", "superset", "of", "the", "input", "Schema", "taking", "all", "the", "Fields", "in", "the", "input", "schema", "and", "adding", "some", "new", "ones", ".", "The", "new", "fields", "are", "fully", "specified", "in", "a", "Field", "class", ".", "The", "name", "of", "the", "schema", "is", "auto", "-", "generated", "with", "a", "static", "counter", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L73-L75
143,007
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Mutator.java
Mutator.superSetOf
public static Schema superSetOf(String newName, Schema schema, Field... newFields) { List<Field> newSchema = new ArrayList<Field>(); newSchema.addAll(schema.getFields()); for(Field newField: newFields) { newSchema.add(newField); } return new Schema(newName, newSchema); }
java
public static Schema superSetOf(String newName, Schema schema, Field... newFields) { List<Field> newSchema = new ArrayList<Field>(); newSchema.addAll(schema.getFields()); for(Field newField: newFields) { newSchema.add(newField); } return new Schema(newName, newSchema); }
[ "public", "static", "Schema", "superSetOf", "(", "String", "newName", ",", "Schema", "schema", ",", "Field", "...", "newFields", ")", "{", "List", "<", "Field", ">", "newSchema", "=", "new", "ArrayList", "<", "Field", ">", "(", ")", ";", "newSchema", ".", "addAll", "(", "schema", ".", "getFields", "(", ")", ")", ";", "for", "(", "Field", "newField", ":", "newFields", ")", "{", "newSchema", ".", "add", "(", "newField", ")", ";", "}", "return", "new", "Schema", "(", "newName", ",", "newSchema", ")", ";", "}" ]
Creates a superset of the input Schema, taking all the Fields in the input schema and adding some new ones. The new fields are fully specified in a Field class. The name of the schema is also specified as a parameter.
[ "Creates", "a", "superset", "of", "the", "input", "Schema", "taking", "all", "the", "Fields", "in", "the", "input", "schema", "and", "adding", "some", "new", "ones", ".", "The", "new", "fields", "are", "fully", "specified", "in", "a", "Field", "class", ".", "The", "name", "of", "the", "schema", "is", "also", "specified", "as", "a", "parameter", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L82-L89
143,008
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerService.java
SchedulerService.setupScheduler
@PostConstruct public void setupScheduler() { for(SchedulerTask task : tasks) { if(task.getDelay() > 0 && task.getInterval() > 0) { executor.scheduleWithFixedDelay(task.getTask(), task.getDelay(), task.getInterval(), task.getTimeUnit()); } else if(task.isImmediate() && task.getInterval() > 0) { executor.scheduleWithFixedDelay(task.getTask(), 0l, task.getInterval(), task.getTimeUnit()); } else if(task.getDelay() > 0) { executor.schedule(task.getTask(), task.getDelay(), task.getTimeUnit()); } else { executor.execute(task.getTask()); } } }
java
@PostConstruct public void setupScheduler() { for(SchedulerTask task : tasks) { if(task.getDelay() > 0 && task.getInterval() > 0) { executor.scheduleWithFixedDelay(task.getTask(), task.getDelay(), task.getInterval(), task.getTimeUnit()); } else if(task.isImmediate() && task.getInterval() > 0) { executor.scheduleWithFixedDelay(task.getTask(), 0l, task.getInterval(), task.getTimeUnit()); } else if(task.getDelay() > 0) { executor.schedule(task.getTask(), task.getDelay(), task.getTimeUnit()); } else { executor.execute(task.getTask()); } } }
[ "@", "PostConstruct", "public", "void", "setupScheduler", "(", ")", "{", "for", "(", "SchedulerTask", "task", ":", "tasks", ")", "{", "if", "(", "task", ".", "getDelay", "(", ")", ">", "0", "&&", "task", ".", "getInterval", "(", ")", ">", "0", ")", "{", "executor", ".", "scheduleWithFixedDelay", "(", "task", ".", "getTask", "(", ")", ",", "task", ".", "getDelay", "(", ")", ",", "task", ".", "getInterval", "(", ")", ",", "task", ".", "getTimeUnit", "(", ")", ")", ";", "}", "else", "if", "(", "task", ".", "isImmediate", "(", ")", "&&", "task", ".", "getInterval", "(", ")", ">", "0", ")", "{", "executor", ".", "scheduleWithFixedDelay", "(", "task", ".", "getTask", "(", ")", ",", "0l", ",", "task", ".", "getInterval", "(", ")", ",", "task", ".", "getTimeUnit", "(", ")", ")", ";", "}", "else", "if", "(", "task", ".", "getDelay", "(", ")", ">", "0", ")", "{", "executor", ".", "schedule", "(", "task", ".", "getTask", "(", ")", ",", "task", ".", "getDelay", "(", ")", ",", "task", ".", "getTimeUnit", "(", ")", ")", ";", "}", "else", "{", "executor", ".", "execute", "(", "task", ".", "getTask", "(", ")", ")", ";", "}", "}", "}" ]
Schedules all tasks injected in by guice.
[ "Schedules", "all", "tasks", "injected", "in", "by", "guice", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerService.java#L57-L70
143,009
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/meta/AlternateContentConfigProcessor.java
AlternateContentConfigProcessor.getAlternateContentDirectory
public File getAlternateContentDirectory(String userAgent) { Configuration config = liveConfig; for(AlternateContent configuration: config.configs) { try { if(configuration.compiledPattern.matcher(userAgent).matches()) { return new File(config.metaDir, configuration.getContentDirectory()); } } catch(Exception e) { logger.warn("Failed to process config: "+ configuration.getPattern()+"->"+ configuration.getContentDirectory(), e); } } return null; }
java
public File getAlternateContentDirectory(String userAgent) { Configuration config = liveConfig; for(AlternateContent configuration: config.configs) { try { if(configuration.compiledPattern.matcher(userAgent).matches()) { return new File(config.metaDir, configuration.getContentDirectory()); } } catch(Exception e) { logger.warn("Failed to process config: "+ configuration.getPattern()+"->"+ configuration.getContentDirectory(), e); } } return null; }
[ "public", "File", "getAlternateContentDirectory", "(", "String", "userAgent", ")", "{", "Configuration", "config", "=", "liveConfig", ";", "for", "(", "AlternateContent", "configuration", ":", "config", ".", "configs", ")", "{", "try", "{", "if", "(", "configuration", ".", "compiledPattern", ".", "matcher", "(", "userAgent", ")", ".", "matches", "(", ")", ")", "{", "return", "new", "File", "(", "config", ".", "metaDir", ",", "configuration", ".", "getContentDirectory", "(", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"Failed to process config: \"", "+", "configuration", ".", "getPattern", "(", ")", "+", "\"->\"", "+", "configuration", ".", "getContentDirectory", "(", ")", ",", "e", ")", ";", "}", "}", "return", "null", ";", "}" ]
Iterates through AlternateContent objects trying to match against their pre compiled pattern. @param userAgent The userAgent request header. @return the ContentDirectory of the matched AlternateContent instance or null if none are found.
[ "Iterates", "through", "AlternateContent", "objects", "trying", "to", "match", "against", "their", "pre", "compiled", "pattern", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/meta/AlternateContentConfigProcessor.java#L75-L87
143,010
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java
TupleMRConfigBuilder.addIntermediateSchema
public void addIntermediateSchema(Schema schema) throws TupleMRException { if (schemaAlreadyExists(schema.getName())) { throw new TupleMRException("There's a schema with that name '" + schema.getName() + "'"); } schemas.add(schema); }
java
public void addIntermediateSchema(Schema schema) throws TupleMRException { if (schemaAlreadyExists(schema.getName())) { throw new TupleMRException("There's a schema with that name '" + schema.getName() + "'"); } schemas.add(schema); }
[ "public", "void", "addIntermediateSchema", "(", "Schema", "schema", ")", "throws", "TupleMRException", "{", "if", "(", "schemaAlreadyExists", "(", "schema", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"There's a schema with that name '\"", "+", "schema", ".", "getName", "(", ")", "+", "\"'\"", ")", ";", "}", "schemas", ".", "add", "(", "schema", ")", ";", "}" ]
Adds a Map-output schema. Tuples emitted by TupleMapper will use one of the schemas added by this method. Schemas added in consecutive calls to this method must be named differently.
[ "Adds", "a", "Map", "-", "output", "schema", ".", "Tuples", "emitted", "by", "TupleMapper", "will", "use", "one", "of", "the", "schemas", "added", "by", "this", "method", ".", "Schemas", "added", "in", "consecutive", "calls", "to", "this", "method", "must", "be", "named", "differently", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java#L73-L79
143,011
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java
TupleMRConfigBuilder.setOrderBy
public void setOrderBy(OrderBy ordering) throws TupleMRException { failIfNull(ordering, "OrderBy can't be null"); failIfEmpty(ordering.getElements(), "OrderBy can't be empty"); failIfEmpty(schemas, "Need to specify source schemas"); failIfEmpty(groupByFields, "Need to specify group by fields"); if (schemas.size() == 1) { if (ordering.getSchemaOrderIndex() != null) { throw new TupleMRException( "Not able to use source order when just one source specified"); } } Schema firstSchema = schemas.get(0); for (SortElement sortElement : ordering.getElements()) { if (!fieldPresentInAllSchemas(sortElement.getName())) { throw new TupleMRException("Can't sort by field '" + sortElement.getName() + "' . Not present in all sources"); } if (!fieldSameTypeInAllSources(sortElement.getName())) { throw new TupleMRException("Can't sort by field '" + sortElement.getName() + "' since its type differs among sources"); } if (sortElement.getCustomComparator() != null) { Field field = firstSchema.getField(sortElement.getName()); if (field.getType() != Type.OBJECT) { throw new TupleMRException("Not allowed to specify custom comparator for type=" + field.getType()); } } } // group by fields need to be a prefix of sort by fields for (String groupField : groupByFields) { if (!ordering.containsBeforeSchemaOrder(groupField)) { throw new TupleMRException("Group by field '" + groupField + "' is not present in common order by before source order"); } } this.commonOrderBy = ordering; }
java
public void setOrderBy(OrderBy ordering) throws TupleMRException { failIfNull(ordering, "OrderBy can't be null"); failIfEmpty(ordering.getElements(), "OrderBy can't be empty"); failIfEmpty(schemas, "Need to specify source schemas"); failIfEmpty(groupByFields, "Need to specify group by fields"); if (schemas.size() == 1) { if (ordering.getSchemaOrderIndex() != null) { throw new TupleMRException( "Not able to use source order when just one source specified"); } } Schema firstSchema = schemas.get(0); for (SortElement sortElement : ordering.getElements()) { if (!fieldPresentInAllSchemas(sortElement.getName())) { throw new TupleMRException("Can't sort by field '" + sortElement.getName() + "' . Not present in all sources"); } if (!fieldSameTypeInAllSources(sortElement.getName())) { throw new TupleMRException("Can't sort by field '" + sortElement.getName() + "' since its type differs among sources"); } if (sortElement.getCustomComparator() != null) { Field field = firstSchema.getField(sortElement.getName()); if (field.getType() != Type.OBJECT) { throw new TupleMRException("Not allowed to specify custom comparator for type=" + field.getType()); } } } // group by fields need to be a prefix of sort by fields for (String groupField : groupByFields) { if (!ordering.containsBeforeSchemaOrder(groupField)) { throw new TupleMRException("Group by field '" + groupField + "' is not present in common order by before source order"); } } this.commonOrderBy = ordering; }
[ "public", "void", "setOrderBy", "(", "OrderBy", "ordering", ")", "throws", "TupleMRException", "{", "failIfNull", "(", "ordering", ",", "\"OrderBy can't be null\"", ")", ";", "failIfEmpty", "(", "ordering", ".", "getElements", "(", ")", ",", "\"OrderBy can't be empty\"", ")", ";", "failIfEmpty", "(", "schemas", ",", "\"Need to specify source schemas\"", ")", ";", "failIfEmpty", "(", "groupByFields", ",", "\"Need to specify group by fields\"", ")", ";", "if", "(", "schemas", ".", "size", "(", ")", "==", "1", ")", "{", "if", "(", "ordering", ".", "getSchemaOrderIndex", "(", ")", "!=", "null", ")", "{", "throw", "new", "TupleMRException", "(", "\"Not able to use source order when just one source specified\"", ")", ";", "}", "}", "Schema", "firstSchema", "=", "schemas", ".", "get", "(", "0", ")", ";", "for", "(", "SortElement", "sortElement", ":", "ordering", ".", "getElements", "(", ")", ")", "{", "if", "(", "!", "fieldPresentInAllSchemas", "(", "sortElement", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Can't sort by field '\"", "+", "sortElement", ".", "getName", "(", ")", "+", "\"' . Not present in all sources\"", ")", ";", "}", "if", "(", "!", "fieldSameTypeInAllSources", "(", "sortElement", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Can't sort by field '\"", "+", "sortElement", ".", "getName", "(", ")", "+", "\"' since its type differs among sources\"", ")", ";", "}", "if", "(", "sortElement", ".", "getCustomComparator", "(", ")", "!=", "null", ")", "{", "Field", "field", "=", "firstSchema", ".", "getField", "(", "sortElement", ".", "getName", "(", ")", ")", ";", "if", "(", "field", ".", "getType", "(", ")", "!=", "Type", ".", "OBJECT", ")", "{", "throw", "new", "TupleMRException", "(", "\"Not allowed to specify custom comparator for type=\"", "+", "field", ".", "getType", "(", ")", ")", ";", "}", "}", "}", "// group by fields need to be a prefix of sort by fields", "for", "(", "String", "groupField", ":", "groupByFields", ")", "{", "if", "(", "!", "ordering", ".", "containsBeforeSchemaOrder", "(", "groupField", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Group by field '\"", "+", "groupField", "+", "\"' is not present in common order by before source order\"", ")", ";", "}", "}", "this", ".", "commonOrderBy", "=", "ordering", ";", "}" ]
Sets the criteria to sort the tuples by. In a multi-schema scenario all the fields defined in the specified ordering must be present in every intermediate schema defined. @see OrderBy
[ "Sets", "the", "criteria", "to", "sort", "the", "tuples", "by", ".", "In", "a", "multi", "-", "schema", "scenario", "all", "the", "fields", "defined", "in", "the", "specified", "ordering", "must", "be", "present", "in", "every", "intermediate", "schema", "defined", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java#L252-L291
143,012
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java
TupleMRConfigBuilder.setSpecificOrderBy
public void setSpecificOrderBy(String schemaName, OrderBy ordering) throws TupleMRException { // TODO failIfNull(schemaName, "Not able to set specific orderBy for null source"); if (!schemaAlreadyExists(schemaName)) { throw new TupleMRException("Unknown source '" + schemaName + "' in specific OrderBy"); } failIfNull(ordering, "Not able to set null criteria for source '" + schemaName + "'"); failIfEmpty(ordering.getElements(), "Can't set empty ordering"); failIfNull(commonOrderBy, "Not able to set specific order with no previous common OrderBy"); if (commonOrderBy.getSchemaOrderIndex() == null) { throw new TupleMRException( "Need to specify source order in common OrderBy when using specific OrderBy"); } if (ordering.getSchemaOrderIndex() != null) { throw new TupleMRException("Not allowed to set source order in specific order"); } Schema schema = getSchemaByName(schemaName); Map<String, String> aliases = fieldAliases.get(schema.getName()); for (SortElement e : ordering.getElements()) { if (!Schema.containsFieldUsingAlias(schema, e.getName(), aliases)) { throw new TupleMRException("Source '" + schemaName + "' doesn't contain field '" + e.getName()); } if (e.getCustomComparator() != null) { Field field = schema.getField(e.getName()); if (field == null) { field = schema.getField(aliases.get(e.getName())); } if (field.getType() != Type.OBJECT) { throw new TupleMRException("Not allowed to set custom comparator for type=" + field.getType()); } } } for (SortElement e : ordering.getElements()) { if (commonOrderBy.containsFieldName(e.getName())) { throw new TupleMRException("Common sort by already contains sorting for field '" + e.getName()); } } this.specificsOrderBy.put(schemaName, ordering); }
java
public void setSpecificOrderBy(String schemaName, OrderBy ordering) throws TupleMRException { // TODO failIfNull(schemaName, "Not able to set specific orderBy for null source"); if (!schemaAlreadyExists(schemaName)) { throw new TupleMRException("Unknown source '" + schemaName + "' in specific OrderBy"); } failIfNull(ordering, "Not able to set null criteria for source '" + schemaName + "'"); failIfEmpty(ordering.getElements(), "Can't set empty ordering"); failIfNull(commonOrderBy, "Not able to set specific order with no previous common OrderBy"); if (commonOrderBy.getSchemaOrderIndex() == null) { throw new TupleMRException( "Need to specify source order in common OrderBy when using specific OrderBy"); } if (ordering.getSchemaOrderIndex() != null) { throw new TupleMRException("Not allowed to set source order in specific order"); } Schema schema = getSchemaByName(schemaName); Map<String, String> aliases = fieldAliases.get(schema.getName()); for (SortElement e : ordering.getElements()) { if (!Schema.containsFieldUsingAlias(schema, e.getName(), aliases)) { throw new TupleMRException("Source '" + schemaName + "' doesn't contain field '" + e.getName()); } if (e.getCustomComparator() != null) { Field field = schema.getField(e.getName()); if (field == null) { field = schema.getField(aliases.get(e.getName())); } if (field.getType() != Type.OBJECT) { throw new TupleMRException("Not allowed to set custom comparator for type=" + field.getType()); } } } for (SortElement e : ordering.getElements()) { if (commonOrderBy.containsFieldName(e.getName())) { throw new TupleMRException("Common sort by already contains sorting for field '" + e.getName()); } } this.specificsOrderBy.put(schemaName, ordering); }
[ "public", "void", "setSpecificOrderBy", "(", "String", "schemaName", ",", "OrderBy", "ordering", ")", "throws", "TupleMRException", "{", "// TODO", "failIfNull", "(", "schemaName", ",", "\"Not able to set specific orderBy for null source\"", ")", ";", "if", "(", "!", "schemaAlreadyExists", "(", "schemaName", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Unknown source '\"", "+", "schemaName", "+", "\"' in specific OrderBy\"", ")", ";", "}", "failIfNull", "(", "ordering", ",", "\"Not able to set null criteria for source '\"", "+", "schemaName", "+", "\"'\"", ")", ";", "failIfEmpty", "(", "ordering", ".", "getElements", "(", ")", ",", "\"Can't set empty ordering\"", ")", ";", "failIfNull", "(", "commonOrderBy", ",", "\"Not able to set specific order with no previous common OrderBy\"", ")", ";", "if", "(", "commonOrderBy", ".", "getSchemaOrderIndex", "(", ")", "==", "null", ")", "{", "throw", "new", "TupleMRException", "(", "\"Need to specify source order in common OrderBy when using specific OrderBy\"", ")", ";", "}", "if", "(", "ordering", ".", "getSchemaOrderIndex", "(", ")", "!=", "null", ")", "{", "throw", "new", "TupleMRException", "(", "\"Not allowed to set source order in specific order\"", ")", ";", "}", "Schema", "schema", "=", "getSchemaByName", "(", "schemaName", ")", ";", "Map", "<", "String", ",", "String", ">", "aliases", "=", "fieldAliases", ".", "get", "(", "schema", ".", "getName", "(", ")", ")", ";", "for", "(", "SortElement", "e", ":", "ordering", ".", "getElements", "(", ")", ")", "{", "if", "(", "!", "Schema", ".", "containsFieldUsingAlias", "(", "schema", ",", "e", ".", "getName", "(", ")", ",", "aliases", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Source '\"", "+", "schemaName", "+", "\"' doesn't contain field '\"", "+", "e", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "e", ".", "getCustomComparator", "(", ")", "!=", "null", ")", "{", "Field", "field", "=", "schema", ".", "getField", "(", "e", ".", "getName", "(", ")", ")", ";", "if", "(", "field", "==", "null", ")", "{", "field", "=", "schema", ".", "getField", "(", "aliases", ".", "get", "(", "e", ".", "getName", "(", ")", ")", ")", ";", "}", "if", "(", "field", ".", "getType", "(", ")", "!=", "Type", ".", "OBJECT", ")", "{", "throw", "new", "TupleMRException", "(", "\"Not allowed to set custom comparator for type=\"", "+", "field", ".", "getType", "(", ")", ")", ";", "}", "}", "}", "for", "(", "SortElement", "e", ":", "ordering", ".", "getElements", "(", ")", ")", "{", "if", "(", "commonOrderBy", ".", "containsFieldName", "(", "e", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "TupleMRException", "(", "\"Common sort by already contains sorting for field '\"", "+", "e", ".", "getName", "(", ")", ")", ";", "}", "}", "this", ".", "specificsOrderBy", ".", "put", "(", "schemaName", ",", "ordering", ")", ";", "}" ]
Sets how tuples from the specific schemaName will be sorted after being sorted by commonOrderBy and schemaOrder
[ "Sets", "how", "tuples", "from", "the", "specific", "schemaName", "will", "be", "sorted", "after", "being", "sorted", "by", "commonOrderBy", "and", "schemaOrder" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/TupleMRConfigBuilder.java#L299-L343
143,013
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/RollupReducer.java
RollupReducer.initComparators
private void initComparators() { TupleMRConfigBuilder.initializeComparators(context.getHadoopContext() .getConfiguration(), tupleMRConfig); customComparators = new RawComparator<?>[maxDepth + 1]; for(int i = minDepth; i <= maxDepth; i++) { SortElement element = tupleMRConfig.getCommonCriteria().getElements().get(i); if(element.getCustomComparator() != null) { customComparators[i] = element.getCustomComparator(); } } }
java
private void initComparators() { TupleMRConfigBuilder.initializeComparators(context.getHadoopContext() .getConfiguration(), tupleMRConfig); customComparators = new RawComparator<?>[maxDepth + 1]; for(int i = minDepth; i <= maxDepth; i++) { SortElement element = tupleMRConfig.getCommonCriteria().getElements().get(i); if(element.getCustomComparator() != null) { customComparators[i] = element.getCustomComparator(); } } }
[ "private", "void", "initComparators", "(", ")", "{", "TupleMRConfigBuilder", ".", "initializeComparators", "(", "context", ".", "getHadoopContext", "(", ")", ".", "getConfiguration", "(", ")", ",", "tupleMRConfig", ")", ";", "customComparators", "=", "new", "RawComparator", "<", "?", ">", "[", "maxDepth", "+", "1", "]", ";", "for", "(", "int", "i", "=", "minDepth", ";", "i", "<=", "maxDepth", ";", "i", "++", ")", "{", "SortElement", "element", "=", "tupleMRConfig", ".", "getCommonCriteria", "(", ")", ".", "getElements", "(", ")", ".", "get", "(", "i", ")", ";", "if", "(", "element", ".", "getCustomComparator", "(", ")", "!=", "null", ")", "{", "customComparators", "[", "i", "]", "=", "element", ".", "getCustomComparator", "(", ")", ";", "}", "}", "}" ]
Initialize the custom comparators. Creates a quick access array for the custom comparators.
[ "Initialize", "the", "custom", "comparators", ".", "Creates", "a", "quick", "access", "array", "for", "the", "custom", "comparators", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/RollupReducer.java#L92-L102
143,014
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/TupleToAvroRecordConverter.java
TupleToAvroRecordConverter.toRecord
@SuppressWarnings({ "unchecked", "rawtypes" }) public Record toRecord(ITuple tuple, Record reuse) throws IOException { Record record = reuse; if (record == null){ record = new Record(avroSchema); } if (schemaValidation && !tuple.getSchema().equals(pangoolSchema)){ throw new IOException("Tuple '"+tuple + "' " + "contains schema not expected." + "Expected schema '"+ pangoolSchema + " and actual: " + tuple.getSchema()); } for(int i = 0; i < pangoolSchema.getFields().size(); i++) { Object obj = tuple.get(i); Field field = pangoolSchema.getField(i); if (obj == null){ throw new IOException("Field '" + field.getName() + "' can't be null in tuple:" + tuple); } switch(field.getType()){ case INT: case LONG: case FLOAT: case BOOLEAN: case DOUBLE: case BYTES: record.put(i, obj); //optimistic break; case OBJECT: Serializer customSer = customSerializers[i]; DataOutputBuffer buffer = buffers[i]; buffer.reset(); if (customSer != null){ customSer.open(buffer); customSer.serialize(obj); customSer.close(); //TODO is this safe ? } else { hadoopSer.ser(obj, buffer); } //TODO this byteBuffer instances should be cached and reused ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.getData(), 0,buffer.getLength()); record.put(i, byteBuffer); break; case ENUM: record.put(i,obj.toString()); break; case STRING: record.put(i,new Utf8(obj.toString())); //could be directly String ? break; default: throw new IOException("Not correspondence to Avro type from Pangool type " + field.getType()); } } return record; }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Record toRecord(ITuple tuple, Record reuse) throws IOException { Record record = reuse; if (record == null){ record = new Record(avroSchema); } if (schemaValidation && !tuple.getSchema().equals(pangoolSchema)){ throw new IOException("Tuple '"+tuple + "' " + "contains schema not expected." + "Expected schema '"+ pangoolSchema + " and actual: " + tuple.getSchema()); } for(int i = 0; i < pangoolSchema.getFields().size(); i++) { Object obj = tuple.get(i); Field field = pangoolSchema.getField(i); if (obj == null){ throw new IOException("Field '" + field.getName() + "' can't be null in tuple:" + tuple); } switch(field.getType()){ case INT: case LONG: case FLOAT: case BOOLEAN: case DOUBLE: case BYTES: record.put(i, obj); //optimistic break; case OBJECT: Serializer customSer = customSerializers[i]; DataOutputBuffer buffer = buffers[i]; buffer.reset(); if (customSer != null){ customSer.open(buffer); customSer.serialize(obj); customSer.close(); //TODO is this safe ? } else { hadoopSer.ser(obj, buffer); } //TODO this byteBuffer instances should be cached and reused ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.getData(), 0,buffer.getLength()); record.put(i, byteBuffer); break; case ENUM: record.put(i,obj.toString()); break; case STRING: record.put(i,new Utf8(obj.toString())); //could be directly String ? break; default: throw new IOException("Not correspondence to Avro type from Pangool type " + field.getType()); } } return record; }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "Record", "toRecord", "(", "ITuple", "tuple", ",", "Record", "reuse", ")", "throws", "IOException", "{", "Record", "record", "=", "reuse", ";", "if", "(", "record", "==", "null", ")", "{", "record", "=", "new", "Record", "(", "avroSchema", ")", ";", "}", "if", "(", "schemaValidation", "&&", "!", "tuple", ".", "getSchema", "(", ")", ".", "equals", "(", "pangoolSchema", ")", ")", "{", "throw", "new", "IOException", "(", "\"Tuple '\"", "+", "tuple", "+", "\"' \"", "+", "\"contains schema not expected.\"", "+", "\"Expected schema '\"", "+", "pangoolSchema", "+", "\" and actual: \"", "+", "tuple", ".", "getSchema", "(", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pangoolSchema", ".", "getFields", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Object", "obj", "=", "tuple", ".", "get", "(", "i", ")", ";", "Field", "field", "=", "pangoolSchema", ".", "getField", "(", "i", ")", ";", "if", "(", "obj", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Field '\"", "+", "field", ".", "getName", "(", ")", "+", "\"' can't be null in tuple:\"", "+", "tuple", ")", ";", "}", "switch", "(", "field", ".", "getType", "(", ")", ")", "{", "case", "INT", ":", "case", "LONG", ":", "case", "FLOAT", ":", "case", "BOOLEAN", ":", "case", "DOUBLE", ":", "case", "BYTES", ":", "record", ".", "put", "(", "i", ",", "obj", ")", ";", "//optimistic", "break", ";", "case", "OBJECT", ":", "Serializer", "customSer", "=", "customSerializers", "[", "i", "]", ";", "DataOutputBuffer", "buffer", "=", "buffers", "[", "i", "]", ";", "buffer", ".", "reset", "(", ")", ";", "if", "(", "customSer", "!=", "null", ")", "{", "customSer", ".", "open", "(", "buffer", ")", ";", "customSer", ".", "serialize", "(", "obj", ")", ";", "customSer", ".", "close", "(", ")", ";", "//TODO is this safe ?", "}", "else", "{", "hadoopSer", ".", "ser", "(", "obj", ",", "buffer", ")", ";", "}", "//TODO this byteBuffer instances should be cached and reused", "ByteBuffer", "byteBuffer", "=", "ByteBuffer", ".", "wrap", "(", "buffer", ".", "getData", "(", ")", ",", "0", ",", "buffer", ".", "getLength", "(", ")", ")", ";", "record", ".", "put", "(", "i", ",", "byteBuffer", ")", ";", "break", ";", "case", "ENUM", ":", "record", ".", "put", "(", "i", ",", "obj", ".", "toString", "(", ")", ")", ";", "break", ";", "case", "STRING", ":", "record", ".", "put", "(", "i", ",", "new", "Utf8", "(", "obj", ".", "toString", "(", ")", ")", ")", ";", "//could be directly String ?", "break", ";", "default", ":", "throw", "new", "IOException", "(", "\"Not correspondence to Avro type from Pangool type \"", "+", "field", ".", "getType", "(", ")", ")", ";", "}", "}", "return", "record", ";", "}" ]
Moves data between a Tuple and an Avro Record
[ "Moves", "data", "between", "a", "Tuple", "and", "an", "Avro", "Record" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/TupleToAvroRecordConverter.java#L75-L130
143,015
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.appendToDefaultProperties
public Properties appendToDefaultProperties(File configFile) { if(defaultProperties != null && configFile.canRead()) { defaultProperties = appendProperties(defaultProperties, configFile); } return defaultProperties; }
java
public Properties appendToDefaultProperties(File configFile) { if(defaultProperties != null && configFile.canRead()) { defaultProperties = appendProperties(defaultProperties, configFile); } return defaultProperties; }
[ "public", "Properties", "appendToDefaultProperties", "(", "File", "configFile", ")", "{", "if", "(", "defaultProperties", "!=", "null", "&&", "configFile", ".", "canRead", "(", ")", ")", "{", "defaultProperties", "=", "appendProperties", "(", "defaultProperties", ",", "configFile", ")", ";", "}", "return", "defaultProperties", ";", "}" ]
Adds properties from file to the default properties if the file exists. @param configFile @return default properties instance
[ "Adds", "properties", "from", "file", "to", "the", "default", "properties", "if", "the", "file", "exists", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L95-L103
143,016
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.appendProperties
public Properties appendProperties(Properties properties, File configFile) { if(!configFile.exists()) { return properties; } return reader.appendProperties(properties, configFile, log); }
java
public Properties appendProperties(Properties properties, File configFile) { if(!configFile.exists()) { return properties; } return reader.appendProperties(properties, configFile, log); }
[ "public", "Properties", "appendProperties", "(", "Properties", "properties", ",", "File", "configFile", ")", "{", "if", "(", "!", "configFile", ".", "exists", "(", ")", ")", "{", "return", "properties", ";", "}", "return", "reader", ".", "appendProperties", "(", "properties", ",", "configFile", ",", "log", ")", ";", "}" ]
Add new properties to an existing Properties object
[ "Add", "new", "properties", "to", "an", "existing", "Properties", "object" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L109-L117
143,017
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.getSystemProperties
public Properties getSystemProperties() { Properties properties = new Properties(); properties.putAll(System.getenv()); properties.putAll(System.getProperties()); return properties; }
java
public Properties getSystemProperties() { Properties properties = new Properties(); properties.putAll(System.getenv()); properties.putAll(System.getProperties()); return properties; }
[ "public", "Properties", "getSystemProperties", "(", ")", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "properties", ".", "putAll", "(", "System", ".", "getenv", "(", ")", ")", ";", "properties", ".", "putAll", "(", "System", ".", "getProperties", "(", ")", ")", ";", "return", "properties", ";", "}" ]
Read in The system properties
[ "Read", "in", "The", "system", "properties" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L123-L130
143,018
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.getPropertiesByContext
public Properties getPropertiesByContext(ServletContext context, String path) { return reader.getProperties(context, path, log); }
java
public Properties getPropertiesByContext(ServletContext context, String path) { return reader.getProperties(context, path, log); }
[ "public", "Properties", "getPropertiesByContext", "(", "ServletContext", "context", ",", "String", "path", ")", "{", "return", "reader", ".", "getProperties", "(", "context", ",", "path", ",", "log", ")", ";", "}" ]
Read in properties based on a ServletContext and a path to a config file
[ "Read", "in", "properties", "based", "on", "a", "ServletContext", "and", "a", "path", "to", "a", "config", "file" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L136-L139
143,019
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.persistProperties
public synchronized void persistProperties(Properties properties, File propsFile, String message) { Properties toWrite = new Properties(); for(String key : properties.stringPropertyNames()) { if(System.getProperties().containsKey(key) && !properties.getProperty(key).equals(System.getProperty(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(System.getenv().containsKey(key) && !properties.getProperty(key).equals(System.getenv(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(!System.getProperties().containsKey(key) && !System.getenv().containsKey(key)){ toWrite.setProperty(key, properties.getProperty(key)); } } writer.persistProperties(toWrite, propsFile, message, log); }
java
public synchronized void persistProperties(Properties properties, File propsFile, String message) { Properties toWrite = new Properties(); for(String key : properties.stringPropertyNames()) { if(System.getProperties().containsKey(key) && !properties.getProperty(key).equals(System.getProperty(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(System.getenv().containsKey(key) && !properties.getProperty(key).equals(System.getenv(key))) { toWrite.setProperty(key, properties.getProperty(key)); } else if(!System.getProperties().containsKey(key) && !System.getenv().containsKey(key)){ toWrite.setProperty(key, properties.getProperty(key)); } } writer.persistProperties(toWrite, propsFile, message, log); }
[ "public", "synchronized", "void", "persistProperties", "(", "Properties", "properties", ",", "File", "propsFile", ",", "String", "message", ")", "{", "Properties", "toWrite", "=", "new", "Properties", "(", ")", ";", "for", "(", "String", "key", ":", "properties", ".", "stringPropertyNames", "(", ")", ")", "{", "if", "(", "System", ".", "getProperties", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "properties", ".", "getProperty", "(", "key", ")", ".", "equals", "(", "System", ".", "getProperty", "(", "key", ")", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "else", "if", "(", "System", ".", "getenv", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "properties", ".", "getProperty", "(", "key", ")", ".", "equals", "(", "System", ".", "getenv", "(", "key", ")", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "else", "if", "(", "!", "System", ".", "getProperties", "(", ")", ".", "containsKey", "(", "key", ")", "&&", "!", "System", ".", "getenv", "(", ")", ".", "containsKey", "(", "key", ")", ")", "{", "toWrite", ".", "setProperty", "(", "key", ",", "properties", ".", "getProperty", "(", "key", ")", ")", ";", "}", "}", "writer", ".", "persistProperties", "(", "toWrite", ",", "propsFile", ",", "message", ",", "log", ")", ";", "}" ]
Persist properties that are not system env or other system properties, in a thread synchronized manner
[ "Persist", "properties", "that", "are", "not", "system", "env", "or", "other", "system", "properties", "in", "a", "thread", "synchronized", "manner" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L164-L182
143,020
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.makeConfigParserLive
public void makeConfigParserLive() { if(stagedConfigParser != null) { notifyListeners(listeners, stagedConfigParser, log); liveConfigParser = stagedConfigParser; latch.countDown(); } }
java
public void makeConfigParserLive() { if(stagedConfigParser != null) { notifyListeners(listeners, stagedConfigParser, log); liveConfigParser = stagedConfigParser; latch.countDown(); } }
[ "public", "void", "makeConfigParserLive", "(", ")", "{", "if", "(", "stagedConfigParser", "!=", "null", ")", "{", "notifyListeners", "(", "listeners", ",", "stagedConfigParser", ",", "log", ")", ";", "liveConfigParser", "=", "stagedConfigParser", ";", "latch", ".", "countDown", "(", ")", ";", "}", "}" ]
This notifies all registered listeners then make a staged configuration live.
[ "This", "notifies", "all", "registered", "listeners", "then", "make", "a", "staged", "configuration", "live", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L214-L222
143,021
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java
ConfigManager.getListenerGenericTypes
private static Class<?>[] getListenerGenericTypes(Class<?> listenerClass, Logger log) { List<Class<?>> configClasses = new ArrayList<Class<?>>(); Type[] typeVars = listenerClass.getGenericInterfaces(); if(typeVars != null) { for(Type interfaceClass : typeVars) { if(interfaceClass instanceof ParameterizedType) { if(((ParameterizedType) interfaceClass).getRawType() instanceof Class) { if(ConfigurationListener.class.isAssignableFrom((Class<?>) ((ParameterizedType) interfaceClass).getRawType())) { ParameterizedType pType = (ParameterizedType) interfaceClass; Type[] typeArgs = pType.getActualTypeArguments(); if(typeArgs != null && typeArgs.length == 1 && typeArgs[0] instanceof Class) { Class<?> type = (Class<?>) typeArgs[0]; if(type.isAnnotationPresent(CadmiumConfig.class)){ log.debug("Adding "+type+" to the configuration types interesting to "+listenerClass); configClasses.add(type); } } } } } } } return configClasses.toArray(new Class<?>[] {}); }
java
private static Class<?>[] getListenerGenericTypes(Class<?> listenerClass, Logger log) { List<Class<?>> configClasses = new ArrayList<Class<?>>(); Type[] typeVars = listenerClass.getGenericInterfaces(); if(typeVars != null) { for(Type interfaceClass : typeVars) { if(interfaceClass instanceof ParameterizedType) { if(((ParameterizedType) interfaceClass).getRawType() instanceof Class) { if(ConfigurationListener.class.isAssignableFrom((Class<?>) ((ParameterizedType) interfaceClass).getRawType())) { ParameterizedType pType = (ParameterizedType) interfaceClass; Type[] typeArgs = pType.getActualTypeArguments(); if(typeArgs != null && typeArgs.length == 1 && typeArgs[0] instanceof Class) { Class<?> type = (Class<?>) typeArgs[0]; if(type.isAnnotationPresent(CadmiumConfig.class)){ log.debug("Adding "+type+" to the configuration types interesting to "+listenerClass); configClasses.add(type); } } } } } } } return configClasses.toArray(new Class<?>[] {}); }
[ "private", "static", "Class", "<", "?", ">", "[", "]", "getListenerGenericTypes", "(", "Class", "<", "?", ">", "listenerClass", ",", "Logger", "log", ")", "{", "List", "<", "Class", "<", "?", ">", ">", "configClasses", "=", "new", "ArrayList", "<", "Class", "<", "?", ">", ">", "(", ")", ";", "Type", "[", "]", "typeVars", "=", "listenerClass", ".", "getGenericInterfaces", "(", ")", ";", "if", "(", "typeVars", "!=", "null", ")", "{", "for", "(", "Type", "interfaceClass", ":", "typeVars", ")", "{", "if", "(", "interfaceClass", "instanceof", "ParameterizedType", ")", "{", "if", "(", "(", "(", "ParameterizedType", ")", "interfaceClass", ")", ".", "getRawType", "(", ")", "instanceof", "Class", ")", "{", "if", "(", "ConfigurationListener", ".", "class", ".", "isAssignableFrom", "(", "(", "Class", "<", "?", ">", ")", "(", "(", "ParameterizedType", ")", "interfaceClass", ")", ".", "getRawType", "(", ")", ")", ")", "{", "ParameterizedType", "pType", "=", "(", "ParameterizedType", ")", "interfaceClass", ";", "Type", "[", "]", "typeArgs", "=", "pType", ".", "getActualTypeArguments", "(", ")", ";", "if", "(", "typeArgs", "!=", "null", "&&", "typeArgs", ".", "length", "==", "1", "&&", "typeArgs", "[", "0", "]", "instanceof", "Class", ")", "{", "Class", "<", "?", ">", "type", "=", "(", "Class", "<", "?", ">", ")", "typeArgs", "[", "0", "]", ";", "if", "(", "type", ".", "isAnnotationPresent", "(", "CadmiumConfig", ".", "class", ")", ")", "{", "log", ".", "debug", "(", "\"Adding \"", "+", "type", "+", "\" to the configuration types interesting to \"", "+", "listenerClass", ")", ";", "configClasses", ".", "add", "(", "type", ")", ";", "}", "}", "}", "}", "}", "}", "}", "return", "configClasses", ".", "toArray", "(", "new", "Class", "<", "?", ">", "[", "]", "{", "}", ")", ";", "}" ]
Gets a list of classes that the listenerClass is interesting in listening to. @param listenerClass @param log @return
[ "Gets", "a", "list", "of", "classes", "that", "the", "listenerClass", "is", "interesting", "in", "listening", "to", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/ConfigManager.java#L271-L294
143,022
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/helpers/DefaultEXIFactory.java
DefaultEXIFactory.doSanityCheck
protected void doSanityCheck() throws EXIException { // Self-contained elements do not work with re-ordered if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_SC) && (codingMode == CodingMode.COMPRESSION || codingMode == CodingMode.PRE_COMPRESSION)) { throw new EXIException( "(Pre-)Compression and selfContained elements cannot work together"); } if (!this.grammar.isSchemaInformed()) { this.maximumNumberOfBuiltInElementGrammars = -1; this.maximumNumberOfBuiltInProductions = -1; this.grammarLearningDisabled = false; // TODO warn user? } // blockSize in NON compression mode? Just ignore it! // canonical EXI (http://www.w3.org/TR/exi-c14n/) if (this.getEncodingOptions().isOptionEnabled( EncodingOptions.CANONICAL_EXI)) { updateFactoryAccordingCanonicalEXI(); } }
java
protected void doSanityCheck() throws EXIException { // Self-contained elements do not work with re-ordered if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_SC) && (codingMode == CodingMode.COMPRESSION || codingMode == CodingMode.PRE_COMPRESSION)) { throw new EXIException( "(Pre-)Compression and selfContained elements cannot work together"); } if (!this.grammar.isSchemaInformed()) { this.maximumNumberOfBuiltInElementGrammars = -1; this.maximumNumberOfBuiltInProductions = -1; this.grammarLearningDisabled = false; // TODO warn user? } // blockSize in NON compression mode? Just ignore it! // canonical EXI (http://www.w3.org/TR/exi-c14n/) if (this.getEncodingOptions().isOptionEnabled( EncodingOptions.CANONICAL_EXI)) { updateFactoryAccordingCanonicalEXI(); } }
[ "protected", "void", "doSanityCheck", "(", ")", "throws", "EXIException", "{", "// Self-contained elements do not work with re-ordered\r", "if", "(", "fidelityOptions", ".", "isFidelityEnabled", "(", "FidelityOptions", ".", "FEATURE_SC", ")", "&&", "(", "codingMode", "==", "CodingMode", ".", "COMPRESSION", "||", "codingMode", "==", "CodingMode", ".", "PRE_COMPRESSION", ")", ")", "{", "throw", "new", "EXIException", "(", "\"(Pre-)Compression and selfContained elements cannot work together\"", ")", ";", "}", "if", "(", "!", "this", ".", "grammar", ".", "isSchemaInformed", "(", ")", ")", "{", "this", ".", "maximumNumberOfBuiltInElementGrammars", "=", "-", "1", ";", "this", ".", "maximumNumberOfBuiltInProductions", "=", "-", "1", ";", "this", ".", "grammarLearningDisabled", "=", "false", ";", "// TODO warn user?\r", "}", "// blockSize in NON compression mode? Just ignore it!\r", "// canonical EXI (http://www.w3.org/TR/exi-c14n/)\r", "if", "(", "this", ".", "getEncodingOptions", "(", ")", ".", "isOptionEnabled", "(", "EncodingOptions", ".", "CANONICAL_EXI", ")", ")", "{", "updateFactoryAccordingCanonicalEXI", "(", ")", ";", "}", "}" ]
some consistency and sanity checks
[ "some", "consistency", "and", "sanity", "checks" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/helpers/DefaultEXIFactory.java#L399-L422
143,023
datasalt/pangool
core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java
SolrRecordWriter.zipDirectory
static public int zipDirectory(final Configuration conf, final ZipOutputStream zos, final String baseName, final String root, final Path itemToZip) throws IOException { LOG.info(String.format("zipDirectory: %s %s %s", baseName, root, itemToZip)); LocalFileSystem localFs = FileSystem.getLocal(conf); int count = 0; final FileStatus itemStatus = localFs.getFileStatus(itemToZip); if(itemStatus.isDir()) { final FileStatus[] statai = localFs.listStatus(itemToZip); // Add a directory entry to the zip file final String zipDirName = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root); final ZipEntry dirZipEntry = new ZipEntry(zipDirName + Path.SEPARATOR_CHAR); LOG.info(String.format("Adding directory %s to zip", zipDirName)); zos.putNextEntry(dirZipEntry); zos.closeEntry(); count++; if(statai == null || statai.length == 0) { LOG.info(String.format("Skipping empty directory %s", itemToZip)); return count; } for(FileStatus status : statai) { count += zipDirectory(conf, zos, baseName, root, status.getPath()); } LOG.info(String.format("Wrote %d entries for directory %s", count, itemToZip)); return count; } final String inZipPath = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root); if(inZipPath.length() == 0) { LOG.warn(String.format("Skipping empty zip file path for %s (%s %s)", itemToZip, root, baseName)); return 0; } // Take empty files in case the place holder is needed FSDataInputStream in = null; try { in = localFs.open(itemToZip); final ZipEntry ze = new ZipEntry(inZipPath); ze.setTime(itemStatus.getModificationTime()); // Comments confuse looking at the zip file // ze.setComment(itemToZip.toString()); zos.putNextEntry(ze); IOUtils.copyBytes(in, zos, conf, false); zos.closeEntry(); LOG.info(String.format("Wrote %d entries for file %s", count, itemToZip)); return 1; } finally { in.close(); } }
java
static public int zipDirectory(final Configuration conf, final ZipOutputStream zos, final String baseName, final String root, final Path itemToZip) throws IOException { LOG.info(String.format("zipDirectory: %s %s %s", baseName, root, itemToZip)); LocalFileSystem localFs = FileSystem.getLocal(conf); int count = 0; final FileStatus itemStatus = localFs.getFileStatus(itemToZip); if(itemStatus.isDir()) { final FileStatus[] statai = localFs.listStatus(itemToZip); // Add a directory entry to the zip file final String zipDirName = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root); final ZipEntry dirZipEntry = new ZipEntry(zipDirName + Path.SEPARATOR_CHAR); LOG.info(String.format("Adding directory %s to zip", zipDirName)); zos.putNextEntry(dirZipEntry); zos.closeEntry(); count++; if(statai == null || statai.length == 0) { LOG.info(String.format("Skipping empty directory %s", itemToZip)); return count; } for(FileStatus status : statai) { count += zipDirectory(conf, zos, baseName, root, status.getPath()); } LOG.info(String.format("Wrote %d entries for directory %s", count, itemToZip)); return count; } final String inZipPath = relativePathForZipEntry(itemToZip.toUri().getPath(), baseName, root); if(inZipPath.length() == 0) { LOG.warn(String.format("Skipping empty zip file path for %s (%s %s)", itemToZip, root, baseName)); return 0; } // Take empty files in case the place holder is needed FSDataInputStream in = null; try { in = localFs.open(itemToZip); final ZipEntry ze = new ZipEntry(inZipPath); ze.setTime(itemStatus.getModificationTime()); // Comments confuse looking at the zip file // ze.setComment(itemToZip.toString()); zos.putNextEntry(ze); IOUtils.copyBytes(in, zos, conf, false); zos.closeEntry(); LOG.info(String.format("Wrote %d entries for file %s", count, itemToZip)); return 1; } finally { in.close(); } }
[ "static", "public", "int", "zipDirectory", "(", "final", "Configuration", "conf", ",", "final", "ZipOutputStream", "zos", ",", "final", "String", "baseName", ",", "final", "String", "root", ",", "final", "Path", "itemToZip", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"zipDirectory: %s %s %s\"", ",", "baseName", ",", "root", ",", "itemToZip", ")", ")", ";", "LocalFileSystem", "localFs", "=", "FileSystem", ".", "getLocal", "(", "conf", ")", ";", "int", "count", "=", "0", ";", "final", "FileStatus", "itemStatus", "=", "localFs", ".", "getFileStatus", "(", "itemToZip", ")", ";", "if", "(", "itemStatus", ".", "isDir", "(", ")", ")", "{", "final", "FileStatus", "[", "]", "statai", "=", "localFs", ".", "listStatus", "(", "itemToZip", ")", ";", "// Add a directory entry to the zip file", "final", "String", "zipDirName", "=", "relativePathForZipEntry", "(", "itemToZip", ".", "toUri", "(", ")", ".", "getPath", "(", ")", ",", "baseName", ",", "root", ")", ";", "final", "ZipEntry", "dirZipEntry", "=", "new", "ZipEntry", "(", "zipDirName", "+", "Path", ".", "SEPARATOR_CHAR", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Adding directory %s to zip\"", ",", "zipDirName", ")", ")", ";", "zos", ".", "putNextEntry", "(", "dirZipEntry", ")", ";", "zos", ".", "closeEntry", "(", ")", ";", "count", "++", ";", "if", "(", "statai", "==", "null", "||", "statai", ".", "length", "==", "0", ")", "{", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Skipping empty directory %s\"", ",", "itemToZip", ")", ")", ";", "return", "count", ";", "}", "for", "(", "FileStatus", "status", ":", "statai", ")", "{", "count", "+=", "zipDirectory", "(", "conf", ",", "zos", ",", "baseName", ",", "root", ",", "status", ".", "getPath", "(", ")", ")", ";", "}", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Wrote %d entries for directory %s\"", ",", "count", ",", "itemToZip", ")", ")", ";", "return", "count", ";", "}", "final", "String", "inZipPath", "=", "relativePathForZipEntry", "(", "itemToZip", ".", "toUri", "(", ")", ".", "getPath", "(", ")", ",", "baseName", ",", "root", ")", ";", "if", "(", "inZipPath", ".", "length", "(", ")", "==", "0", ")", "{", "LOG", ".", "warn", "(", "String", ".", "format", "(", "\"Skipping empty zip file path for %s (%s %s)\"", ",", "itemToZip", ",", "root", ",", "baseName", ")", ")", ";", "return", "0", ";", "}", "// Take empty files in case the place holder is needed", "FSDataInputStream", "in", "=", "null", ";", "try", "{", "in", "=", "localFs", ".", "open", "(", "itemToZip", ")", ";", "final", "ZipEntry", "ze", "=", "new", "ZipEntry", "(", "inZipPath", ")", ";", "ze", ".", "setTime", "(", "itemStatus", ".", "getModificationTime", "(", ")", ")", ";", "// Comments confuse looking at the zip file", "// ze.setComment(itemToZip.toString());", "zos", ".", "putNextEntry", "(", "ze", ")", ";", "IOUtils", ".", "copyBytes", "(", "in", ",", "zos", ",", "conf", ",", "false", ")", ";", "zos", ".", "closeEntry", "(", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Wrote %d entries for file %s\"", ",", "count", ",", "itemToZip", ")", ")", ";", "return", "1", ";", "}", "finally", "{", "in", ".", "close", "(", ")", ";", "}", "}" ]
Write a file to a zip output stream, removing leading path name components from the actual file name when creating the zip file entry. The entry placed in the zip file is <code>baseName</code>/ <code>relativePath</code>, where <code>relativePath</code> is constructed by removing a leading <code>root</code> from the path for <code>itemToZip</code>. If <code>itemToZip</code> is an empty directory, it is ignored. If <code>itemToZip</code> is a directory, the contents of the directory are added recursively. @param zos The zip output stream @param baseName The base name to use for the file name entry in the zip file @param root The path to remove from <code>itemToZip</code> to make a relative path name @param itemToZip The path to the file to be added to the zip file @return the number of entries added @throws IOException
[ "Write", "a", "file", "to", "a", "zip", "output", "stream", "removing", "leading", "path", "name", "components", "from", "the", "actual", "file", "name", "when", "creating", "the", "zip", "file", "entry", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/solr/SolrRecordWriter.java#L432-L486
143,024
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addListener
public static void addListener(Document doc, Element root) { Element listener = doc.createElement("listener"); Element listenerClass = doc.createElement("listener-class"); listener.appendChild(listenerClass); listenerClass.appendChild(doc .createTextNode("org.apache.shiro.web.env.EnvironmentLoaderListener")); addRelativeTo(root, listener, "listener", true); }
java
public static void addListener(Document doc, Element root) { Element listener = doc.createElement("listener"); Element listenerClass = doc.createElement("listener-class"); listener.appendChild(listenerClass); listenerClass.appendChild(doc .createTextNode("org.apache.shiro.web.env.EnvironmentLoaderListener")); addRelativeTo(root, listener, "listener", true); }
[ "public", "static", "void", "addListener", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "listener", "=", "doc", ".", "createElement", "(", "\"listener\"", ")", ";", "Element", "listenerClass", "=", "doc", ".", "createElement", "(", "\"listener-class\"", ")", ";", "listener", ".", "appendChild", "(", "listenerClass", ")", ";", "listenerClass", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"org.apache.shiro.web.env.EnvironmentLoaderListener\"", ")", ")", ";", "addRelativeTo", "(", "root", ",", "listener", ",", "\"listener\"", ",", "true", ")", ";", "}" ]
Adds a shiro environment listener to load the shiro config file. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the listener to.
[ "Adds", "a", "shiro", "environment", "listener", "to", "load", "the", "shiro", "config", "file", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L261-L269
143,025
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addContextParam
public static void addContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroConfigLocations")); ctxParam.appendChild(paramName); Element paramValue = doc.createElement("param-value"); paramValue.appendChild(doc.createTextNode("file:" + new File(System .getProperty("com.meltmedia.cadmium.contentRoot"), "shiro.ini") .getAbsoluteFile().getAbsolutePath())); ctxParam.appendChild(paramValue); addRelativeTo(root, ctxParam, "listener", false); }
java
public static void addContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroConfigLocations")); ctxParam.appendChild(paramName); Element paramValue = doc.createElement("param-value"); paramValue.appendChild(doc.createTextNode("file:" + new File(System .getProperty("com.meltmedia.cadmium.contentRoot"), "shiro.ini") .getAbsoluteFile().getAbsolutePath())); ctxParam.appendChild(paramValue); addRelativeTo(root, ctxParam, "listener", false); }
[ "public", "static", "void", "addContextParam", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "ctxParam", "=", "doc", ".", "createElement", "(", "\"context-param\"", ")", ";", "Element", "paramName", "=", "doc", ".", "createElement", "(", "\"param-name\"", ")", ";", "paramName", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"shiroConfigLocations\"", ")", ")", ";", "ctxParam", ".", "appendChild", "(", "paramName", ")", ";", "Element", "paramValue", "=", "doc", ".", "createElement", "(", "\"param-value\"", ")", ";", "paramValue", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"file:\"", "+", "new", "File", "(", "System", ".", "getProperty", "(", "\"com.meltmedia.cadmium.contentRoot\"", ")", ",", "\"shiro.ini\"", ")", ".", "getAbsoluteFile", "(", ")", ".", "getAbsolutePath", "(", ")", ")", ")", ";", "ctxParam", ".", "appendChild", "(", "paramValue", ")", ";", "addRelativeTo", "(", "root", ",", "ctxParam", ",", "\"listener\"", ",", "false", ")", ";", "}" ]
Adds a context parameter to a web.xml file to override where the shiro config location is to be loaded from. The location loaded from will be represented by the "com.meltmedia.cadmium.contentRoot" system property. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the context param to.
[ "Adds", "a", "context", "parameter", "to", "a", "web", ".", "xml", "file", "to", "override", "where", "the", "shiro", "config", "location", "is", "to", "be", "loaded", "from", ".", "The", "location", "loaded", "from", "will", "be", "represented", "by", "the", "com", ".", "meltmedia", ".", "cadmium", ".", "contentRoot", "system", "property", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L277-L289
143,026
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addEnvContextParam
public static void addEnvContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroEnvironmentClass")); ctxParam.appendChild(paramName); Element paramValue = doc.createElement("param-value"); paramValue.appendChild(doc.createTextNode("com.meltmedia.cadmium.servlets.shiro.WebEnvironment")); ctxParam.appendChild(paramValue); addRelativeTo(root, ctxParam, "listener", false); }
java
public static void addEnvContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroEnvironmentClass")); ctxParam.appendChild(paramName); Element paramValue = doc.createElement("param-value"); paramValue.appendChild(doc.createTextNode("com.meltmedia.cadmium.servlets.shiro.WebEnvironment")); ctxParam.appendChild(paramValue); addRelativeTo(root, ctxParam, "listener", false); }
[ "public", "static", "void", "addEnvContextParam", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "ctxParam", "=", "doc", ".", "createElement", "(", "\"context-param\"", ")", ";", "Element", "paramName", "=", "doc", ".", "createElement", "(", "\"param-name\"", ")", ";", "paramName", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"shiroEnvironmentClass\"", ")", ")", ";", "ctxParam", ".", "appendChild", "(", "paramName", ")", ";", "Element", "paramValue", "=", "doc", ".", "createElement", "(", "\"param-value\"", ")", ";", "paramValue", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"com.meltmedia.cadmium.servlets.shiro.WebEnvironment\"", ")", ")", ";", "ctxParam", ".", "appendChild", "(", "paramValue", ")", ";", "addRelativeTo", "(", "root", ",", "ctxParam", ",", "\"listener\"", ",", "false", ")", ";", "}" ]
Adds a context parameter to a web.xml file to override where the shiro environment class. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the context param to.
[ "Adds", "a", "context", "parameter", "to", "a", "web", ".", "xml", "file", "to", "override", "where", "the", "shiro", "environment", "class", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L296-L306
143,027
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addFilter
public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc .createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }
java
public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc .createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }
[ "public", "static", "void", "addFilter", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "filter", "=", "doc", ".", "createElement", "(", "\"filter\"", ")", ";", "Element", "filterName", "=", "doc", ".", "createElement", "(", "\"filter-name\"", ")", ";", "filterName", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"ShiroFilter\"", ")", ")", ";", "filter", ".", "appendChild", "(", "filterName", ")", ";", "Element", "filterClass", "=", "doc", ".", "createElement", "(", "\"filter-class\"", ")", ";", "filterClass", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"org.apache.shiro.web.servlet.ShiroFilter\"", ")", ")", ";", "filter", ".", "appendChild", "(", "filterClass", ")", ";", "addRelativeTo", "(", "root", ",", "filter", ",", "\"filter\"", ",", "true", ")", ";", "}" ]
Adds the shiro filter to a web.xml file. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the filter to.
[ "Adds", "the", "shiro", "filter", "to", "a", "web", ".", "xml", "file", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L313-L324
143,028
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addFilterMapping
public static void addFilterMapping(Document doc, Element root) { Element filterMapping = doc.createElement("filter-mapping"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filterMapping.appendChild(filterName); Element urlPattern = doc.createElement("url-pattern"); urlPattern.appendChild(doc.createTextNode("/*")); filterMapping.appendChild(urlPattern); addDispatchers(doc, filterMapping, "REQUEST", "FORWARD", "INCLUDE", "ERROR"); addRelativeTo(root, filterMapping, "filter-mapping", true); }
java
public static void addFilterMapping(Document doc, Element root) { Element filterMapping = doc.createElement("filter-mapping"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filterMapping.appendChild(filterName); Element urlPattern = doc.createElement("url-pattern"); urlPattern.appendChild(doc.createTextNode("/*")); filterMapping.appendChild(urlPattern); addDispatchers(doc, filterMapping, "REQUEST", "FORWARD", "INCLUDE", "ERROR"); addRelativeTo(root, filterMapping, "filter-mapping", true); }
[ "public", "static", "void", "addFilterMapping", "(", "Document", "doc", ",", "Element", "root", ")", "{", "Element", "filterMapping", "=", "doc", ".", "createElement", "(", "\"filter-mapping\"", ")", ";", "Element", "filterName", "=", "doc", ".", "createElement", "(", "\"filter-name\"", ")", ";", "filterName", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"ShiroFilter\"", ")", ")", ";", "filterMapping", ".", "appendChild", "(", "filterName", ")", ";", "Element", "urlPattern", "=", "doc", ".", "createElement", "(", "\"url-pattern\"", ")", ";", "urlPattern", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "\"/*\"", ")", ")", ";", "filterMapping", ".", "appendChild", "(", "urlPattern", ")", ";", "addDispatchers", "(", "doc", ",", "filterMapping", ",", "\"REQUEST\"", ",", "\"FORWARD\"", ",", "\"INCLUDE\"", ",", "\"ERROR\"", ")", ";", "addRelativeTo", "(", "root", ",", "filterMapping", ",", "\"filter-mapping\"", ",", "true", ")", ";", "}" ]
Adds the filter mapping for the shiro filter to a web.xml file. @param doc The xml DOM document to create the new xml elements with. @param root The xml Element node to add the filter mapping to.
[ "Adds", "the", "filter", "mapping", "for", "the", "shiro", "filter", "to", "a", "web", ".", "xml", "file", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L331-L343
143,029
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.addDispatchers
public static void addDispatchers(Document doc, Element filterMapping, String... names) { if (names != null) { for (String name : names) { Element dispatcher = doc.createElement("dispatcher"); dispatcher.appendChild(doc.createTextNode(name)); filterMapping.appendChild(dispatcher); } } }
java
public static void addDispatchers(Document doc, Element filterMapping, String... names) { if (names != null) { for (String name : names) { Element dispatcher = doc.createElement("dispatcher"); dispatcher.appendChild(doc.createTextNode(name)); filterMapping.appendChild(dispatcher); } } }
[ "public", "static", "void", "addDispatchers", "(", "Document", "doc", ",", "Element", "filterMapping", ",", "String", "...", "names", ")", "{", "if", "(", "names", "!=", "null", ")", "{", "for", "(", "String", "name", ":", "names", ")", "{", "Element", "dispatcher", "=", "doc", ".", "createElement", "(", "\"dispatcher\"", ")", ";", "dispatcher", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "name", ")", ")", ";", "filterMapping", ".", "appendChild", "(", "dispatcher", ")", ";", "}", "}", "}" ]
Adds dispatchers for each item in the vargs parameter names to a filter mapping element of a web.xml file. @param doc The xml DOM document to create the new xml elements with. @param filterMapping The filter mapping element to append to from a web.xml document. @param names The names of the dispatchers to add.
[ "Adds", "dispatchers", "for", "each", "item", "in", "the", "vargs", "parameter", "names", "to", "a", "filter", "mapping", "element", "of", "a", "web", ".", "xml", "file", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L352-L361
143,030
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.storeXmlDocument
public static void storeXmlDocument(ZipOutputStream outZip, ZipEntry jbossWeb, Document doc) throws IOException, TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { jbossWeb = new ZipEntry(jbossWeb.getName()); outZip.putNextEntry(jbossWeb); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outZip); transformer.transform(source, result); outZip.closeEntry(); }
java
public static void storeXmlDocument(ZipOutputStream outZip, ZipEntry jbossWeb, Document doc) throws IOException, TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { jbossWeb = new ZipEntry(jbossWeb.getName()); outZip.putNextEntry(jbossWeb); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outZip); transformer.transform(source, result); outZip.closeEntry(); }
[ "public", "static", "void", "storeXmlDocument", "(", "ZipOutputStream", "outZip", ",", "ZipEntry", "jbossWeb", ",", "Document", "doc", ")", "throws", "IOException", ",", "TransformerFactoryConfigurationError", ",", "TransformerConfigurationException", ",", "TransformerException", "{", "jbossWeb", "=", "new", "ZipEntry", "(", "jbossWeb", ".", "getName", "(", ")", ")", ";", "outZip", ".", "putNextEntry", "(", "jbossWeb", ")", ";", "TransformerFactory", "tFactory", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", "=", "tFactory", ".", "newTransformer", "(", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "INDENT", ",", "\"yes\"", ")", ";", "transformer", ".", "setOutputProperty", "(", "\"{http://xml.apache.org/xslt}indent-amount\"", ",", "\"2\"", ")", ";", "DOMSource", "source", "=", "new", "DOMSource", "(", "doc", ")", ";", "StreamResult", "result", "=", "new", "StreamResult", "(", "outZip", ")", ";", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "outZip", ".", "closeEntry", "(", ")", ";", "}" ]
Writes a xml document to a zip file with an entry specified by the jbossWeb parameter. @param outZip The zip output stream to write to. @param jbossWeb The zip entry to add to the zip file. @param doc The xml DOM document to write to the zip file. @throws IOException @throws TransformerFactoryConfigurationError @throws TransformerConfigurationException @throws TransformerException
[ "Writes", "a", "xml", "document", "to", "a", "zip", "file", "with", "an", "entry", "specified", "by", "the", "jbossWeb", "parameter", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L411-L429
143,031
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.removeNodesByTagName
public static void removeNodesByTagName(Element doc, String tagname) { NodeList nodes = doc.getElementsByTagName(tagname); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); doc.removeChild(n); } }
java
public static void removeNodesByTagName(Element doc, String tagname) { NodeList nodes = doc.getElementsByTagName(tagname); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); doc.removeChild(n); } }
[ "public", "static", "void", "removeNodesByTagName", "(", "Element", "doc", ",", "String", "tagname", ")", "{", "NodeList", "nodes", "=", "doc", ".", "getElementsByTagName", "(", "tagname", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nodes", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "n", "=", "nodes", ".", "item", "(", "i", ")", ";", "doc", ".", "removeChild", "(", "n", ")", ";", "}", "}" ]
Removes elements by a specified tag name from the xml Element passed in. @param doc The xml Element to remove from. @param tagname The tag name to remove.
[ "Removes", "elements", "by", "a", "specified", "tag", "name", "from", "the", "xml", "Element", "passed", "in", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L436-L442
143,032
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.storeProperties
public static void storeProperties(ZipOutputStream outZip, ZipEntry cadmiumPropertiesEntry, Properties cadmiumProps, List<String> newWarNames) throws IOException { ZipEntry newCadmiumEntry = new ZipEntry(cadmiumPropertiesEntry.getName()); outZip.putNextEntry(newCadmiumEntry); cadmiumProps.store(outZip, "Initial git properties for " + newWarNames.get(0)); outZip.closeEntry(); }
java
public static void storeProperties(ZipOutputStream outZip, ZipEntry cadmiumPropertiesEntry, Properties cadmiumProps, List<String> newWarNames) throws IOException { ZipEntry newCadmiumEntry = new ZipEntry(cadmiumPropertiesEntry.getName()); outZip.putNextEntry(newCadmiumEntry); cadmiumProps.store(outZip, "Initial git properties for " + newWarNames.get(0)); outZip.closeEntry(); }
[ "public", "static", "void", "storeProperties", "(", "ZipOutputStream", "outZip", ",", "ZipEntry", "cadmiumPropertiesEntry", ",", "Properties", "cadmiumProps", ",", "List", "<", "String", ">", "newWarNames", ")", "throws", "IOException", "{", "ZipEntry", "newCadmiumEntry", "=", "new", "ZipEntry", "(", "cadmiumPropertiesEntry", ".", "getName", "(", ")", ")", ";", "outZip", ".", "putNextEntry", "(", "newCadmiumEntry", ")", ";", "cadmiumProps", ".", "store", "(", "outZip", ",", "\"Initial git properties for \"", "+", "newWarNames", ".", "get", "(", "0", ")", ")", ";", "outZip", ".", "closeEntry", "(", ")", ";", "}" ]
Adds a properties file to a war. @param outZip The zip output stream to add to. @param cadmiumPropertiesEntry The entry to add. @param cadmiumProps The properties to store in the zip file. @param newWarNames The first element of this list is used in a comment of the properties file. @throws IOException
[ "Adds", "a", "properties", "file", "to", "a", "war", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L452-L460
143,033
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java
WarUtils.getWarName
public static String getWarName( ServletContext context ) { String[] pathSegments = context.getRealPath("/WEB-INF/web.xml").split("/"); String warName = pathSegments[pathSegments.length - 3]; if(!warName.endsWith(".war")) { URL webXml = WarUtils.class.getClassLoader().getResource("/cadmium-version.properties"); if(webXml != null) { String urlString = webXml.toString().substring(0, webXml.toString().length() - "/WEB-INF/classes/cadmium-version.properties".length()); File warFile = null; if (webXml.getProtocol().equalsIgnoreCase("file")) { warFile = new File(urlString.substring(5)); } else if (webXml.getProtocol().equalsIgnoreCase("vfszip")) { warFile = new File(urlString.substring(7)); } else if (webXml.getProtocol().equalsIgnoreCase("vfsfile")) { warFile = new File(urlString.substring(8)); } else if (webXml.getProtocol().equalsIgnoreCase("vfs") && System.getProperty(JBOSS_7_DEPLOY_DIR) != null) { String path = urlString.substring("vfs:/".length()); String deployDir = System.getProperty(JBOSS_7_DEPLOY_DIR); warFile = new File(deployDir, path); } if(warFile != null) { warName = warFile.getName(); } } } return warName; }
java
public static String getWarName( ServletContext context ) { String[] pathSegments = context.getRealPath("/WEB-INF/web.xml").split("/"); String warName = pathSegments[pathSegments.length - 3]; if(!warName.endsWith(".war")) { URL webXml = WarUtils.class.getClassLoader().getResource("/cadmium-version.properties"); if(webXml != null) { String urlString = webXml.toString().substring(0, webXml.toString().length() - "/WEB-INF/classes/cadmium-version.properties".length()); File warFile = null; if (webXml.getProtocol().equalsIgnoreCase("file")) { warFile = new File(urlString.substring(5)); } else if (webXml.getProtocol().equalsIgnoreCase("vfszip")) { warFile = new File(urlString.substring(7)); } else if (webXml.getProtocol().equalsIgnoreCase("vfsfile")) { warFile = new File(urlString.substring(8)); } else if (webXml.getProtocol().equalsIgnoreCase("vfs") && System.getProperty(JBOSS_7_DEPLOY_DIR) != null) { String path = urlString.substring("vfs:/".length()); String deployDir = System.getProperty(JBOSS_7_DEPLOY_DIR); warFile = new File(deployDir, path); } if(warFile != null) { warName = warFile.getName(); } } } return warName; }
[ "public", "static", "String", "getWarName", "(", "ServletContext", "context", ")", "{", "String", "[", "]", "pathSegments", "=", "context", ".", "getRealPath", "(", "\"/WEB-INF/web.xml\"", ")", ".", "split", "(", "\"/\"", ")", ";", "String", "warName", "=", "pathSegments", "[", "pathSegments", ".", "length", "-", "3", "]", ";", "if", "(", "!", "warName", ".", "endsWith", "(", "\".war\"", ")", ")", "{", "URL", "webXml", "=", "WarUtils", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "\"/cadmium-version.properties\"", ")", ";", "if", "(", "webXml", "!=", "null", ")", "{", "String", "urlString", "=", "webXml", ".", "toString", "(", ")", ".", "substring", "(", "0", ",", "webXml", ".", "toString", "(", ")", ".", "length", "(", ")", "-", "\"/WEB-INF/classes/cadmium-version.properties\"", ".", "length", "(", ")", ")", ";", "File", "warFile", "=", "null", ";", "if", "(", "webXml", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"file\"", ")", ")", "{", "warFile", "=", "new", "File", "(", "urlString", ".", "substring", "(", "5", ")", ")", ";", "}", "else", "if", "(", "webXml", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"vfszip\"", ")", ")", "{", "warFile", "=", "new", "File", "(", "urlString", ".", "substring", "(", "7", ")", ")", ";", "}", "else", "if", "(", "webXml", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"vfsfile\"", ")", ")", "{", "warFile", "=", "new", "File", "(", "urlString", ".", "substring", "(", "8", ")", ")", ";", "}", "else", "if", "(", "webXml", ".", "getProtocol", "(", ")", ".", "equalsIgnoreCase", "(", "\"vfs\"", ")", "&&", "System", ".", "getProperty", "(", "JBOSS_7_DEPLOY_DIR", ")", "!=", "null", ")", "{", "String", "path", "=", "urlString", ".", "substring", "(", "\"vfs:/\"", ".", "length", "(", ")", ")", ";", "String", "deployDir", "=", "System", ".", "getProperty", "(", "JBOSS_7_DEPLOY_DIR", ")", ";", "warFile", "=", "new", "File", "(", "deployDir", ",", "path", ")", ";", "}", "if", "(", "warFile", "!=", "null", ")", "{", "warName", "=", "warFile", ".", "getName", "(", ")", ";", "}", "}", "}", "return", "warName", ";", "}" ]
Gets the currently deployed war file name from the ServletContext. @param context @return
[ "Gets", "the", "currently", "deployed", "war", "file", "name", "from", "the", "ServletContext", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/WarUtils.java#L779-L805
143,034
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractDecoderChannel.java
AbstractDecoderChannel.decodeUnsignedInteger
public final int decodeUnsignedInteger() throws IOException { // 0XXXXXXX ... 1XXXXXXX 1XXXXXXX int result = decode(); // < 128: just one byte, optimal case // ELSE: multiple bytes... if (result >= 128) { result = (result & 127); int mShift = 7; int b; do { // 1. Read the next octet b = decode(); // 2. Multiply the value of the unsigned number represented by // the 7 least significant // bits of the octet by the current multiplier and add the // result to the current value. result += (b & 127) << mShift; // 3. Multiply the multiplier by 128 mShift += 7; // 4. If the most significant bit of the octet was 1, go back to // step 1 } while (b >= 128); } return result; }
java
public final int decodeUnsignedInteger() throws IOException { // 0XXXXXXX ... 1XXXXXXX 1XXXXXXX int result = decode(); // < 128: just one byte, optimal case // ELSE: multiple bytes... if (result >= 128) { result = (result & 127); int mShift = 7; int b; do { // 1. Read the next octet b = decode(); // 2. Multiply the value of the unsigned number represented by // the 7 least significant // bits of the octet by the current multiplier and add the // result to the current value. result += (b & 127) << mShift; // 3. Multiply the multiplier by 128 mShift += 7; // 4. If the most significant bit of the octet was 1, go back to // step 1 } while (b >= 128); } return result; }
[ "public", "final", "int", "decodeUnsignedInteger", "(", ")", "throws", "IOException", "{", "// 0XXXXXXX ... 1XXXXXXX 1XXXXXXX", "int", "result", "=", "decode", "(", ")", ";", "// < 128: just one byte, optimal case", "// ELSE: multiple bytes...", "if", "(", "result", ">=", "128", ")", "{", "result", "=", "(", "result", "&", "127", ")", ";", "int", "mShift", "=", "7", ";", "int", "b", ";", "do", "{", "// 1. Read the next octet", "b", "=", "decode", "(", ")", ";", "// 2. Multiply the value of the unsigned number represented by", "// the 7 least significant", "// bits of the octet by the current multiplier and add the", "// result to the current value.", "result", "+=", "(", "b", "&", "127", ")", "<<", "mShift", ";", "// 3. Multiply the multiplier by 128", "mShift", "+=", "7", ";", "// 4. If the most significant bit of the octet was 1, go back to", "// step 1", "}", "while", "(", "b", ">=", "128", ")", ";", "}", "return", "result", ";", "}" ]
Decode an arbitrary precision non negative integer using a sequence of octets. The most significant bit of the last octet is set to zero to indicate sequence termination. Only seven bits per octet are used to store the integer's value.
[ "Decode", "an", "arbitrary", "precision", "non", "negative", "integer", "using", "a", "sequence", "of", "octets", ".", "The", "most", "significant", "bit", "of", "the", "last", "octet", "is", "set", "to", "zero", "to", "indicate", "sequence", "termination", ".", "Only", "seven", "bits", "per", "octet", "are", "used", "to", "store", "the", "integer", "s", "value", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractDecoderChannel.java#L129-L157
143,035
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractDecoderChannel.java
AbstractDecoderChannel.decodeDateTimeValue
public DateTimeValue decodeDateTimeValue(DateTimeType type) throws IOException { int year = 0, monthDay = 0, time = 0, fractionalSecs = 0; switch (type) { case gYear: // Year, [Time-Zone] year = decodeInteger() + DateTimeValue.YEAR_OFFSET; break; case gYearMonth: // Year, MonthDay, [TimeZone] case date: // Year, MonthDay, [TimeZone] year = decodeInteger() + DateTimeValue.YEAR_OFFSET; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); break; case dateTime: // Year, MonthDay, Time, [FractionalSecs], [TimeZone] // e.g. "0001-01-01T00:00:00.111+00:33"; year = decodeInteger() + DateTimeValue.YEAR_OFFSET; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); // Note: *no* break; case time: // Time, [FractionalSecs], [TimeZone] // e.g. "12:34:56.135" time = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_TIME); boolean presenceFractionalSecs = decodeBoolean(); fractionalSecs = presenceFractionalSecs ? decodeUnsignedInteger() : 0; break; case gMonth: // MonthDay, [TimeZone] // e.g. "--12" case gMonthDay: // MonthDay, [TimeZone] // e.g. "--01-28" case gDay: // MonthDay, [TimeZone] // "---16"; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); break; default: throw new UnsupportedOperationException(); } boolean presenceTimezone = decodeBoolean(); int timeZone = presenceTimezone ? decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_TIMEZONE) - DateTimeValue.TIMEZONE_OFFSET_IN_MINUTES : 0; return new DateTimeValue(type, year, monthDay, time, fractionalSecs, presenceTimezone, timeZone); }
java
public DateTimeValue decodeDateTimeValue(DateTimeType type) throws IOException { int year = 0, monthDay = 0, time = 0, fractionalSecs = 0; switch (type) { case gYear: // Year, [Time-Zone] year = decodeInteger() + DateTimeValue.YEAR_OFFSET; break; case gYearMonth: // Year, MonthDay, [TimeZone] case date: // Year, MonthDay, [TimeZone] year = decodeInteger() + DateTimeValue.YEAR_OFFSET; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); break; case dateTime: // Year, MonthDay, Time, [FractionalSecs], [TimeZone] // e.g. "0001-01-01T00:00:00.111+00:33"; year = decodeInteger() + DateTimeValue.YEAR_OFFSET; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); // Note: *no* break; case time: // Time, [FractionalSecs], [TimeZone] // e.g. "12:34:56.135" time = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_TIME); boolean presenceFractionalSecs = decodeBoolean(); fractionalSecs = presenceFractionalSecs ? decodeUnsignedInteger() : 0; break; case gMonth: // MonthDay, [TimeZone] // e.g. "--12" case gMonthDay: // MonthDay, [TimeZone] // e.g. "--01-28" case gDay: // MonthDay, [TimeZone] // "---16"; monthDay = decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_MONTHDAY); break; default: throw new UnsupportedOperationException(); } boolean presenceTimezone = decodeBoolean(); int timeZone = presenceTimezone ? decodeNBitUnsignedInteger(DateTimeValue.NUMBER_BITS_TIMEZONE) - DateTimeValue.TIMEZONE_OFFSET_IN_MINUTES : 0; return new DateTimeValue(type, year, monthDay, time, fractionalSecs, presenceTimezone, timeZone); }
[ "public", "DateTimeValue", "decodeDateTimeValue", "(", "DateTimeType", "type", ")", "throws", "IOException", "{", "int", "year", "=", "0", ",", "monthDay", "=", "0", ",", "time", "=", "0", ",", "fractionalSecs", "=", "0", ";", "switch", "(", "type", ")", "{", "case", "gYear", ":", "// Year, [Time-Zone]", "year", "=", "decodeInteger", "(", ")", "+", "DateTimeValue", ".", "YEAR_OFFSET", ";", "break", ";", "case", "gYearMonth", ":", "// Year, MonthDay, [TimeZone]", "case", "date", ":", "// Year, MonthDay, [TimeZone]", "year", "=", "decodeInteger", "(", ")", "+", "DateTimeValue", ".", "YEAR_OFFSET", ";", "monthDay", "=", "decodeNBitUnsignedInteger", "(", "DateTimeValue", ".", "NUMBER_BITS_MONTHDAY", ")", ";", "break", ";", "case", "dateTime", ":", "// Year, MonthDay, Time, [FractionalSecs], [TimeZone]", "// e.g. \"0001-01-01T00:00:00.111+00:33\";", "year", "=", "decodeInteger", "(", ")", "+", "DateTimeValue", ".", "YEAR_OFFSET", ";", "monthDay", "=", "decodeNBitUnsignedInteger", "(", "DateTimeValue", ".", "NUMBER_BITS_MONTHDAY", ")", ";", "// Note: *no* break;", "case", "time", ":", "// Time, [FractionalSecs], [TimeZone]", "// e.g. \"12:34:56.135\"", "time", "=", "decodeNBitUnsignedInteger", "(", "DateTimeValue", ".", "NUMBER_BITS_TIME", ")", ";", "boolean", "presenceFractionalSecs", "=", "decodeBoolean", "(", ")", ";", "fractionalSecs", "=", "presenceFractionalSecs", "?", "decodeUnsignedInteger", "(", ")", ":", "0", ";", "break", ";", "case", "gMonth", ":", "// MonthDay, [TimeZone]", "// e.g. \"--12\"", "case", "gMonthDay", ":", "// MonthDay, [TimeZone]", "// e.g. \"--01-28\"", "case", "gDay", ":", "// MonthDay, [TimeZone]", "// \"---16\";", "monthDay", "=", "decodeNBitUnsignedInteger", "(", "DateTimeValue", ".", "NUMBER_BITS_MONTHDAY", ")", ";", "break", ";", "default", ":", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "boolean", "presenceTimezone", "=", "decodeBoolean", "(", ")", ";", "int", "timeZone", "=", "presenceTimezone", "?", "decodeNBitUnsignedInteger", "(", "DateTimeValue", ".", "NUMBER_BITS_TIMEZONE", ")", "-", "DateTimeValue", ".", "TIMEZONE_OFFSET_IN_MINUTES", ":", "0", ";", "return", "new", "DateTimeValue", "(", "type", ",", "year", ",", "monthDay", ",", "time", ",", "fractionalSecs", ",", "presenceTimezone", ",", "timeZone", ")", ";", "}" ]
Decode Date-Time as sequence of values representing the individual components of the Date-Time.
[ "Decode", "Date", "-", "Time", "as", "sequence", "of", "values", "representing", "the", "individual", "components", "of", "the", "Date", "-", "Time", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractDecoderChannel.java#L329-L373
143,036
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/MultipleInputsInterface.java
MultipleInputsInterface.configureJob
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException { Set<String> instanceFiles = new HashSet<String>(); for (Map.Entry<Path, List<Input>> entry : multiInputs.entrySet()) { for (int inputId = 0; inputId < entry.getValue().size(); inputId++) { Input input = entry.getValue().get(inputId); instanceFiles.addAll(PangoolMultipleInputs.addInputPath(job, input.path, input.inputFormat, input.inputProcessor, input.specificContext, inputId)); } } return instanceFiles; }
java
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException { Set<String> instanceFiles = new HashSet<String>(); for (Map.Entry<Path, List<Input>> entry : multiInputs.entrySet()) { for (int inputId = 0; inputId < entry.getValue().size(); inputId++) { Input input = entry.getValue().get(inputId); instanceFiles.addAll(PangoolMultipleInputs.addInputPath(job, input.path, input.inputFormat, input.inputProcessor, input.specificContext, inputId)); } } return instanceFiles; }
[ "public", "Set", "<", "String", ">", "configureJob", "(", "Job", "job", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "Set", "<", "String", ">", "instanceFiles", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Path", ",", "List", "<", "Input", ">", ">", "entry", ":", "multiInputs", ".", "entrySet", "(", ")", ")", "{", "for", "(", "int", "inputId", "=", "0", ";", "inputId", "<", "entry", ".", "getValue", "(", ")", ".", "size", "(", ")", ";", "inputId", "++", ")", "{", "Input", "input", "=", "entry", ".", "getValue", "(", ")", ".", "get", "(", "inputId", ")", ";", "instanceFiles", ".", "addAll", "(", "PangoolMultipleInputs", ".", "addInputPath", "(", "job", ",", "input", ".", "path", ",", "input", ".", "inputFormat", ",", "input", ".", "inputProcessor", ",", "input", ".", "specificContext", ",", "inputId", ")", ")", ";", "}", "}", "return", "instanceFiles", ";", "}" ]
Use this method for configuring a Job instance according to the multiple input specs that has been specified. Returns the instance files created.
[ "Use", "this", "method", "for", "configuring", "a", "Job", "instance", "according", "to", "the", "multiple", "input", "specs", "that", "has", "been", "specified", ".", "Returns", "the", "instance", "files", "created", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/MultipleInputsInterface.java#L56-L66
143,037
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java
HistoryCommand.waitForToken
public static void waitForToken(String siteUri, String token, Long since, Long timeout) throws Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } siteUri += "/" + token; if(since != null) { siteUri += "/" + since; } HttpClient httpClient = httpClient(); HttpGet get = new HttpGet(siteUri); Long currentTime = System.currentTimeMillis(); Long timeoutTime = currentTime + timeout; do { currentTime = System.currentTimeMillis(); HttpResponse resp = httpClient.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String response = EntityUtils.toString(resp.getEntity()); if(response != null && response.trim().equalsIgnoreCase("true")) { return; } else { Thread.sleep(1000l); } } else { String errorResponse = EntityUtils.toString(resp.getEntity()); if(errorResponse != null) { throw new Exception(errorResponse.trim()); } else { throw new Exception("Command failed!"); } } } while(currentTime < timeoutTime); if(currentTime >= timeoutTime) { throw new Exception("Timed out waiting for command to complete!"); } }
java
public static void waitForToken(String siteUri, String token, Long since, Long timeout) throws Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } siteUri += "/" + token; if(since != null) { siteUri += "/" + since; } HttpClient httpClient = httpClient(); HttpGet get = new HttpGet(siteUri); Long currentTime = System.currentTimeMillis(); Long timeoutTime = currentTime + timeout; do { currentTime = System.currentTimeMillis(); HttpResponse resp = httpClient.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String response = EntityUtils.toString(resp.getEntity()); if(response != null && response.trim().equalsIgnoreCase("true")) { return; } else { Thread.sleep(1000l); } } else { String errorResponse = EntityUtils.toString(resp.getEntity()); if(errorResponse != null) { throw new Exception(errorResponse.trim()); } else { throw new Exception("Command failed!"); } } } while(currentTime < timeoutTime); if(currentTime >= timeoutTime) { throw new Exception("Timed out waiting for command to complete!"); } }
[ "public", "static", "void", "waitForToken", "(", "String", "siteUri", ",", "String", "token", ",", "Long", "since", ",", "Long", "timeout", ")", "throws", "Exception", "{", "if", "(", "!", "siteUri", ".", "endsWith", "(", "\"/system/history\"", ")", ")", "{", "siteUri", "+=", "\"/system/history\"", ";", "}", "siteUri", "+=", "\"/\"", "+", "token", ";", "if", "(", "since", "!=", "null", ")", "{", "siteUri", "+=", "\"/\"", "+", "since", ";", "}", "HttpClient", "httpClient", "=", "httpClient", "(", ")", ";", "HttpGet", "get", "=", "new", "HttpGet", "(", "siteUri", ")", ";", "Long", "currentTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Long", "timeoutTime", "=", "currentTime", "+", "timeout", ";", "do", "{", "currentTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "HttpResponse", "resp", "=", "httpClient", ".", "execute", "(", "get", ")", ";", "if", "(", "resp", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", "==", "HttpStatus", ".", "SC_OK", ")", "{", "String", "response", "=", "EntityUtils", ".", "toString", "(", "resp", ".", "getEntity", "(", ")", ")", ";", "if", "(", "response", "!=", "null", "&&", "response", ".", "trim", "(", ")", ".", "equalsIgnoreCase", "(", "\"true\"", ")", ")", "{", "return", ";", "}", "else", "{", "Thread", ".", "sleep", "(", "1000l", ")", ";", "}", "}", "else", "{", "String", "errorResponse", "=", "EntityUtils", ".", "toString", "(", "resp", ".", "getEntity", "(", ")", ")", ";", "if", "(", "errorResponse", "!=", "null", ")", "{", "throw", "new", "Exception", "(", "errorResponse", ".", "trim", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"Command failed!\"", ")", ";", "}", "}", "}", "while", "(", "currentTime", "<", "timeoutTime", ")", ";", "if", "(", "currentTime", ">=", "timeoutTime", ")", "{", "throw", "new", "Exception", "(", "\"Timed out waiting for command to complete!\"", ")", ";", "}", "}" ]
Waits until a timeout is reached or a token shows up in the history of a site as finished or failed. @param siteUri The uri to a cadmium site. @param token The token that represents a history event to wait for. @param since A timestamp to pass on the the cadmium site to set a limit on how far back to check the history for a token. @param timeout The timeout in milliseconds to wait for if the token never shows up or fails in the sites log. @throws Exception
[ "Waits", "until", "a", "timeout", "is", "reached", "or", "a", "token", "shows", "up", "in", "the", "history", "of", "a", "site", "as", "finished", "or", "failed", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java#L135-L172
143,038
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java
HistoryCommand.getHistory
public static List<HistoryEntry> getHistory(String siteUri, int limit, boolean filter, String token) throws URISyntaxException, IOException, ClientProtocolException, Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } List<HistoryEntry> history = null; HttpClient httpClient = httpClient(); HttpGet get = null; try { URIBuilder uriBuilder = new URIBuilder(siteUri); if(limit > 0) { uriBuilder.addParameter("limit", limit+""); } if(filter) { uriBuilder.addParameter("filter", filter+""); } URI uri = uriBuilder.build(); get = new HttpGet(uri); addAuthHeader(token, get); HttpResponse resp = httpClient.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); if(entity.getContentType().getValue().equals("application/json")) { String responseContent = EntityUtils.toString(entity); Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException { return new Date(json.getAsLong()); } }).create(); history = gson.fromJson(responseContent, new TypeToken<List<HistoryEntry>>() {}.getType()); } else { System.err.println("Invalid response content type ["+entity.getContentType().getValue()+"]"); System.exit(1); } } else { System.err.println("Request failed due to a ["+resp.getStatusLine().getStatusCode()+":"+resp.getStatusLine().getReasonPhrase()+"] response from the remote server."); System.exit(1); } } finally { if(get != null) { get.releaseConnection(); } } return history; }
java
public static List<HistoryEntry> getHistory(String siteUri, int limit, boolean filter, String token) throws URISyntaxException, IOException, ClientProtocolException, Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } List<HistoryEntry> history = null; HttpClient httpClient = httpClient(); HttpGet get = null; try { URIBuilder uriBuilder = new URIBuilder(siteUri); if(limit > 0) { uriBuilder.addParameter("limit", limit+""); } if(filter) { uriBuilder.addParameter("filter", filter+""); } URI uri = uriBuilder.build(); get = new HttpGet(uri); addAuthHeader(token, get); HttpResponse resp = httpClient.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); if(entity.getContentType().getValue().equals("application/json")) { String responseContent = EntityUtils.toString(entity); Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException { return new Date(json.getAsLong()); } }).create(); history = gson.fromJson(responseContent, new TypeToken<List<HistoryEntry>>() {}.getType()); } else { System.err.println("Invalid response content type ["+entity.getContentType().getValue()+"]"); System.exit(1); } } else { System.err.println("Request failed due to a ["+resp.getStatusLine().getStatusCode()+":"+resp.getStatusLine().getReasonPhrase()+"] response from the remote server."); System.exit(1); } } finally { if(get != null) { get.releaseConnection(); } } return history; }
[ "public", "static", "List", "<", "HistoryEntry", ">", "getHistory", "(", "String", "siteUri", ",", "int", "limit", ",", "boolean", "filter", ",", "String", "token", ")", "throws", "URISyntaxException", ",", "IOException", ",", "ClientProtocolException", ",", "Exception", "{", "if", "(", "!", "siteUri", ".", "endsWith", "(", "\"/system/history\"", ")", ")", "{", "siteUri", "+=", "\"/system/history\"", ";", "}", "List", "<", "HistoryEntry", ">", "history", "=", "null", ";", "HttpClient", "httpClient", "=", "httpClient", "(", ")", ";", "HttpGet", "get", "=", "null", ";", "try", "{", "URIBuilder", "uriBuilder", "=", "new", "URIBuilder", "(", "siteUri", ")", ";", "if", "(", "limit", ">", "0", ")", "{", "uriBuilder", ".", "addParameter", "(", "\"limit\"", ",", "limit", "+", "\"\"", ")", ";", "}", "if", "(", "filter", ")", "{", "uriBuilder", ".", "addParameter", "(", "\"filter\"", ",", "filter", "+", "\"\"", ")", ";", "}", "URI", "uri", "=", "uriBuilder", ".", "build", "(", ")", ";", "get", "=", "new", "HttpGet", "(", "uri", ")", ";", "addAuthHeader", "(", "token", ",", "get", ")", ";", "HttpResponse", "resp", "=", "httpClient", ".", "execute", "(", "get", ")", ";", "if", "(", "resp", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", "==", "HttpStatus", ".", "SC_OK", ")", "{", "HttpEntity", "entity", "=", "resp", ".", "getEntity", "(", ")", ";", "if", "(", "entity", ".", "getContentType", "(", ")", ".", "getValue", "(", ")", ".", "equals", "(", "\"application/json\"", ")", ")", "{", "String", "responseContent", "=", "EntityUtils", ".", "toString", "(", "entity", ")", ";", "Gson", "gson", "=", "new", "GsonBuilder", "(", ")", ".", "registerTypeAdapter", "(", "Date", ".", "class", ",", "new", "JsonDeserializer", "<", "Date", ">", "(", ")", "{", "@", "Override", "public", "Date", "deserialize", "(", "JsonElement", "json", ",", "Type", "typeOfT", ",", "JsonDeserializationContext", "ctx", ")", "throws", "JsonParseException", "{", "return", "new", "Date", "(", "json", ".", "getAsLong", "(", ")", ")", ";", "}", "}", ")", ".", "create", "(", ")", ";", "history", "=", "gson", ".", "fromJson", "(", "responseContent", ",", "new", "TypeToken", "<", "List", "<", "HistoryEntry", ">", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ")", ";", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"Invalid response content type [\"", "+", "entity", ".", "getContentType", "(", ")", ".", "getValue", "(", ")", "+", "\"]\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"Request failed due to a [\"", "+", "resp", ".", "getStatusLine", "(", ")", ".", "getStatusCode", "(", ")", "+", "\":\"", "+", "resp", ".", "getStatusLine", "(", ")", ".", "getReasonPhrase", "(", ")", "+", "\"] response from the remote server.\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "finally", "{", "if", "(", "get", "!=", "null", ")", "{", "get", ".", "releaseConnection", "(", ")", ";", "}", "}", "return", "history", ";", "}" ]
Retrieves the history of a Cadmium site. @param siteUri The uri of a cadmium site. @param limit The maximum number of history entries to retrieve or if set to -1 tells the site to retrieve all history. @param filter If true filters out the non revertable history entries. @param token The Github API token to pass to the Cadmium site for authentication. @return A list of {@link HistoryEntry} Objects that are populated with the history returned from the Cadmium site. @throws URISyntaxException @throws IOException @throws ClientProtocolException @throws Exception
[ "Retrieves", "the", "history", "of", "a", "Cadmium", "site", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java#L189-L241
143,039
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java
HistoryCommand.printComments
private static void printComments(String comment) { int index = 0; int nextIndex = 154; while(index < comment.length()) { nextIndex = nextIndex <= comment.length() ? nextIndex : comment.length(); String commentSegment = comment.substring(index, nextIndex); int lastSpace = commentSegment.lastIndexOf(' '); int lastNewLine = commentSegment.indexOf('\n'); char lastChar = ' '; if(nextIndex < comment.length() ) { lastChar = comment.charAt(nextIndex); } if(lastNewLine > 0) { nextIndex = index + lastNewLine; commentSegment = comment.substring(index, nextIndex); } else if(Character.isWhitespace(lastChar)) { } else if(lastSpace > 0) { nextIndex = index + lastSpace; commentSegment = comment.substring(index, nextIndex); } System.out.println(" " + commentSegment); index = nextIndex; if(lastNewLine > 0 || lastSpace > 0) { index++; } nextIndex = index + 154; } }
java
private static void printComments(String comment) { int index = 0; int nextIndex = 154; while(index < comment.length()) { nextIndex = nextIndex <= comment.length() ? nextIndex : comment.length(); String commentSegment = comment.substring(index, nextIndex); int lastSpace = commentSegment.lastIndexOf(' '); int lastNewLine = commentSegment.indexOf('\n'); char lastChar = ' '; if(nextIndex < comment.length() ) { lastChar = comment.charAt(nextIndex); } if(lastNewLine > 0) { nextIndex = index + lastNewLine; commentSegment = comment.substring(index, nextIndex); } else if(Character.isWhitespace(lastChar)) { } else if(lastSpace > 0) { nextIndex = index + lastSpace; commentSegment = comment.substring(index, nextIndex); } System.out.println(" " + commentSegment); index = nextIndex; if(lastNewLine > 0 || lastSpace > 0) { index++; } nextIndex = index + 154; } }
[ "private", "static", "void", "printComments", "(", "String", "comment", ")", "{", "int", "index", "=", "0", ";", "int", "nextIndex", "=", "154", ";", "while", "(", "index", "<", "comment", ".", "length", "(", ")", ")", "{", "nextIndex", "=", "nextIndex", "<=", "comment", ".", "length", "(", ")", "?", "nextIndex", ":", "comment", ".", "length", "(", ")", ";", "String", "commentSegment", "=", "comment", ".", "substring", "(", "index", ",", "nextIndex", ")", ";", "int", "lastSpace", "=", "commentSegment", ".", "lastIndexOf", "(", "'", "'", ")", ";", "int", "lastNewLine", "=", "commentSegment", ".", "indexOf", "(", "'", "'", ")", ";", "char", "lastChar", "=", "'", "'", ";", "if", "(", "nextIndex", "<", "comment", ".", "length", "(", ")", ")", "{", "lastChar", "=", "comment", ".", "charAt", "(", "nextIndex", ")", ";", "}", "if", "(", "lastNewLine", ">", "0", ")", "{", "nextIndex", "=", "index", "+", "lastNewLine", ";", "commentSegment", "=", "comment", ".", "substring", "(", "index", ",", "nextIndex", ")", ";", "}", "else", "if", "(", "Character", ".", "isWhitespace", "(", "lastChar", ")", ")", "{", "}", "else", "if", "(", "lastSpace", ">", "0", ")", "{", "nextIndex", "=", "index", "+", "lastSpace", ";", "commentSegment", "=", "comment", ".", "substring", "(", "index", ",", "nextIndex", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\" \"", "+", "commentSegment", ")", ";", "index", "=", "nextIndex", ";", "if", "(", "lastNewLine", ">", "0", "||", "lastSpace", ">", "0", ")", "{", "index", "++", ";", "}", "nextIndex", "=", "index", "+", "154", ";", "}", "}" ]
Helper method to format comments to standard out. @param comment
[ "Helper", "method", "to", "format", "comments", "to", "standard", "out", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java#L248-L278
143,040
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java
HistoryCommand.formatTimeLive
private static String formatTimeLive(long timeLive) { String timeString = "ms"; timeString = (timeLive % 1000) + timeString; timeLive = timeLive / 1000; if(timeLive > 0) { timeString = (timeLive % 60) + "s" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 60) + "m" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 24) + "h" + timeString; timeLive = timeLive / 24; if(timeLive > 0) { timeString = (timeLive) + "d" + timeString; } } } } return timeString; }
java
private static String formatTimeLive(long timeLive) { String timeString = "ms"; timeString = (timeLive % 1000) + timeString; timeLive = timeLive / 1000; if(timeLive > 0) { timeString = (timeLive % 60) + "s" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 60) + "m" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString = (timeLive % 24) + "h" + timeString; timeLive = timeLive / 24; if(timeLive > 0) { timeString = (timeLive) + "d" + timeString; } } } } return timeString; }
[ "private", "static", "String", "formatTimeLive", "(", "long", "timeLive", ")", "{", "String", "timeString", "=", "\"ms\"", ";", "timeString", "=", "(", "timeLive", "%", "1000", ")", "+", "timeString", ";", "timeLive", "=", "timeLive", "/", "1000", ";", "if", "(", "timeLive", ">", "0", ")", "{", "timeString", "=", "(", "timeLive", "%", "60", ")", "+", "\"s\"", "+", "timeString", ";", "timeLive", "=", "timeLive", "/", "60", ";", "if", "(", "timeLive", ">", "0", ")", "{", "timeString", "=", "(", "timeLive", "%", "60", ")", "+", "\"m\"", "+", "timeString", ";", "timeLive", "=", "timeLive", "/", "60", ";", "if", "(", "timeLive", ">", "0", ")", "{", "timeString", "=", "(", "timeLive", "%", "24", ")", "+", "\"h\"", "+", "timeString", ";", "timeLive", "=", "timeLive", "/", "24", ";", "if", "(", "timeLive", ">", "0", ")", "{", "timeString", "=", "(", "timeLive", ")", "+", "\"d\"", "+", "timeString", ";", "}", "}", "}", "}", "return", "timeString", ";", "}" ]
Helper method to format a timestamp. @param timeLive @return
[ "Helper", "method", "to", "format", "a", "timestamp", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/HistoryCommand.java#L286-L306
143,041
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java
XForwardedSecureRedirectStrategy.isSecure
@Override public boolean isSecure(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto.equalsIgnoreCase(HTTPS_PROTOCOL); return super.isSecure(request); }
java
@Override public boolean isSecure(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto.equalsIgnoreCase(HTTPS_PROTOCOL); return super.isSecure(request); }
[ "@", "Override", "public", "boolean", "isSecure", "(", "HttpServletRequest", "request", ")", "{", "String", "proto", "=", "request", ".", "getHeader", "(", "X_FORWARED_PROTO", ")", ";", "if", "(", "proto", "!=", "null", ")", "return", "proto", ".", "equalsIgnoreCase", "(", "HTTPS_PROTOCOL", ")", ";", "return", "super", ".", "isSecure", "(", "request", ")", ";", "}" ]
When the X-Forwarded-Proto header is present, this method returns true if the header equals "https", false otherwise. When the header is not present, it delegates this call to the super class.
[ "When", "the", "X", "-", "Forwarded", "-", "Proto", "header", "is", "present", "this", "method", "returns", "true", "if", "the", "header", "equals", "https", "false", "otherwise", ".", "When", "the", "header", "is", "not", "present", "it", "delegates", "this", "call", "to", "the", "super", "class", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java#L38-L43
143,042
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java
XForwardedSecureRedirectStrategy.getProtocol
@Override public String getProtocol(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto; return super.getProtocol(request); }
java
@Override public String getProtocol(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto; return super.getProtocol(request); }
[ "@", "Override", "public", "String", "getProtocol", "(", "HttpServletRequest", "request", ")", "{", "String", "proto", "=", "request", ".", "getHeader", "(", "X_FORWARED_PROTO", ")", ";", "if", "(", "proto", "!=", "null", ")", "return", "proto", ";", "return", "super", ".", "getProtocol", "(", "request", ")", ";", "}" ]
When the X-Forwarded-Proto header is present, this method returns the value of that header. When the header is not present, it delegates this call to the super class.
[ "When", "the", "X", "-", "Forwarded", "-", "Proto", "header", "is", "present", "this", "method", "returns", "the", "value", "of", "that", "header", ".", "When", "the", "header", "is", "not", "present", "it", "delegates", "this", "call", "to", "the", "super", "class", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java#L49-L54
143,043
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java
XForwardedSecureRedirectStrategy.getPort
@Override public int getPort(HttpServletRequest request) { String portValue = request.getHeader(X_FORWARED_PORT); if( portValue != null ) return Integer.parseInt(portValue); return super.getPort(request); }
java
@Override public int getPort(HttpServletRequest request) { String portValue = request.getHeader(X_FORWARED_PORT); if( portValue != null ) return Integer.parseInt(portValue); return super.getPort(request); }
[ "@", "Override", "public", "int", "getPort", "(", "HttpServletRequest", "request", ")", "{", "String", "portValue", "=", "request", ".", "getHeader", "(", "X_FORWARED_PORT", ")", ";", "if", "(", "portValue", "!=", "null", ")", "return", "Integer", ".", "parseInt", "(", "portValue", ")", ";", "return", "super", ".", "getPort", "(", "request", ")", ";", "}" ]
When the X-Forwarded-Port header is present, this method returns the value of that header. When the header is not present, it delegates this call to the super class.
[ "When", "the", "X", "-", "Forwarded", "-", "Port", "header", "is", "present", "this", "method", "returns", "the", "value", "of", "that", "header", ".", "When", "the", "header", "is", "not", "present", "it", "delegates", "this", "call", "to", "the", "super", "class", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/XForwardedSecureRedirectStrategy.java#L60-L65
143,044
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/FileServlet.java
FileServlet.contentTypeOf
public String contentTypeOf( String path ) throws IOException { File file = findFile(path); return lookupMimeType(file.getName()); }
java
public String contentTypeOf( String path ) throws IOException { File file = findFile(path); return lookupMimeType(file.getName()); }
[ "public", "String", "contentTypeOf", "(", "String", "path", ")", "throws", "IOException", "{", "File", "file", "=", "findFile", "(", "path", ")", ";", "return", "lookupMimeType", "(", "file", ".", "getName", "(", ")", ")", ";", "}" ]
Returns the content type for the specified path. @param path the path to look up. @return the content type for the path. @throws FileNotFoundException if a file (or welcome file) does not exist at path. @throws IOException if any other problem prevents the lookup of the content type.
[ "Returns", "the", "content", "type", "for", "the", "specified", "path", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/FileServlet.java#L92-L95
143,045
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/FileServlet.java
FileServlet.findFile
public File findFile( String path ) throws IOException { File base = new File(getBasePath()); File pathFile = new File(base, "."+path); if( !pathFile.exists()) throw new FileNotFoundException("No file or directory at "+pathFile.getCanonicalPath()); if( pathFile.isFile()) return pathFile; pathFile = new File(pathFile, "index.html"); if( !pathFile.exists() ) throw new FileNotFoundException("No welcome file at "+pathFile.getCanonicalPath()); return pathFile; }
java
public File findFile( String path ) throws IOException { File base = new File(getBasePath()); File pathFile = new File(base, "."+path); if( !pathFile.exists()) throw new FileNotFoundException("No file or directory at "+pathFile.getCanonicalPath()); if( pathFile.isFile()) return pathFile; pathFile = new File(pathFile, "index.html"); if( !pathFile.exists() ) throw new FileNotFoundException("No welcome file at "+pathFile.getCanonicalPath()); return pathFile; }
[ "public", "File", "findFile", "(", "String", "path", ")", "throws", "IOException", "{", "File", "base", "=", "new", "File", "(", "getBasePath", "(", ")", ")", ";", "File", "pathFile", "=", "new", "File", "(", "base", ",", "\".\"", "+", "path", ")", ";", "if", "(", "!", "pathFile", ".", "exists", "(", ")", ")", "throw", "new", "FileNotFoundException", "(", "\"No file or directory at \"", "+", "pathFile", ".", "getCanonicalPath", "(", ")", ")", ";", "if", "(", "pathFile", ".", "isFile", "(", ")", ")", "return", "pathFile", ";", "pathFile", "=", "new", "File", "(", "pathFile", ",", "\"index.html\"", ")", ";", "if", "(", "!", "pathFile", ".", "exists", "(", ")", ")", "throw", "new", "FileNotFoundException", "(", "\"No welcome file at \"", "+", "pathFile", ".", "getCanonicalPath", "(", ")", ")", ";", "return", "pathFile", ";", "}" ]
Returns the file object for the given path, including welcome file lookup. If the file cannot be found, a FileNotFoundException is returned. @param path the path to look up. @return the file object for that path. @throws FileNotFoundException if the file could not be found. @throws IOException if any other problem prevented the locating of the file.
[ "Returns", "the", "file", "object", "for", "the", "given", "path", "including", "welcome", "file", "lookup", ".", "If", "the", "file", "cannot", "be", "found", "a", "FileNotFoundException", "is", "returned", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/FileServlet.java#L106-L114
143,046
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java
DelayedGitServiceInitializer.setGitService
public void setGitService(GitService git) { if(git != null) { logger.debug("Setting git service"); this.git = git; latch.countDown(); } }
java
public void setGitService(GitService git) { if(git != null) { logger.debug("Setting git service"); this.git = git; latch.countDown(); } }
[ "public", "void", "setGitService", "(", "GitService", "git", ")", "{", "if", "(", "git", "!=", "null", ")", "{", "logger", ".", "debug", "(", "\"Setting git service\"", ")", ";", "this", ".", "git", "=", "git", ";", "latch", ".", "countDown", "(", ")", ";", "}", "}" ]
Sets the common reference an releases any threads waiting for the reference to be set. @param git
[ "Sets", "the", "common", "reference", "an", "releases", "any", "threads", "waiting", "for", "the", "reference", "to", "be", "set", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java#L150-L156
143,047
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java
DelayedGitServiceInitializer.close
@Override public void close() throws IOException { if(git != null) { IOUtils.closeQuietly(git); git = null; } latch.countDown(); try { latch.notifyAll(); } catch(Exception e) { logger.trace("Failed to notifyAll"); } try { locker.notifyAll(); } catch(Exception e) { logger.trace("Failed to notifyAll"); } }
java
@Override public void close() throws IOException { if(git != null) { IOUtils.closeQuietly(git); git = null; } latch.countDown(); try { latch.notifyAll(); } catch(Exception e) { logger.trace("Failed to notifyAll"); } try { locker.notifyAll(); } catch(Exception e) { logger.trace("Failed to notifyAll"); } }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "if", "(", "git", "!=", "null", ")", "{", "IOUtils", ".", "closeQuietly", "(", "git", ")", ";", "git", "=", "null", ";", "}", "latch", ".", "countDown", "(", ")", ";", "try", "{", "latch", ".", "notifyAll", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "trace", "(", "\"Failed to notifyAll\"", ")", ";", "}", "try", "{", "locker", ".", "notifyAll", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "trace", "(", "\"Failed to notifyAll\"", ")", ";", "}", "}" ]
Releases any used resources and waiting threads. @throws IOException
[ "Releases", "any", "used", "resources", "and", "waiting", "threads", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/git/DelayedGitServiceInitializer.java#L163-L180
143,048
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/compression/EXIInflaterInputStream.java
EXIInflaterInputStream.read
public int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } try { int n; while ((n = inf.inflate(b, off, len)) == 0) { if (inf.finished() || inf.needsDictionary()) { reachEOF = true; return -1; } if (inf.needsInput()) { fill(); } } return n; } catch (DataFormatException e) { String s = e.getMessage(); throw new ZipException(s != null ? s : "Invalid ZLIB data format"); } }
java
public int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } try { int n; while ((n = inf.inflate(b, off, len)) == 0) { if (inf.finished() || inf.needsDictionary()) { reachEOF = true; return -1; } if (inf.needsInput()) { fill(); } } return n; } catch (DataFormatException e) { String s = e.getMessage(); throw new ZipException(s != null ? s : "Invalid ZLIB data format"); } }
[ "public", "int", "read", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "ensureOpen", "(", ")", ";", "if", "(", "(", "off", "|", "len", "|", "(", "off", "+", "len", ")", "|", "(", "b", ".", "length", "-", "(", "off", "+", "len", ")", ")", ")", "<", "0", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "else", "if", "(", "len", "==", "0", ")", "{", "return", "0", ";", "}", "try", "{", "int", "n", ";", "while", "(", "(", "n", "=", "inf", ".", "inflate", "(", "b", ",", "off", ",", "len", ")", ")", "==", "0", ")", "{", "if", "(", "inf", ".", "finished", "(", ")", "||", "inf", ".", "needsDictionary", "(", ")", ")", "{", "reachEOF", "=", "true", ";", "return", "-", "1", ";", "}", "if", "(", "inf", ".", "needsInput", "(", ")", ")", "{", "fill", "(", ")", ";", "}", "}", "return", "n", ";", "}", "catch", "(", "DataFormatException", "e", ")", "{", "String", "s", "=", "e", ".", "getMessage", "(", ")", ";", "throw", "new", "ZipException", "(", "s", "!=", "null", "?", "s", ":", "\"Invalid ZLIB data format\"", ")", ";", "}", "}" ]
Reads uncompressed data into an array of bytes. This method will block until some input can be decompressed. @param b the buffer into which the data is read @param off the start offset of the data @param len the maximum number of bytes read @return the actual number of bytes read, or -1 if the end of the compressed input is reached or a preset dictionary is needed @exception ZipException if a ZIP format error has occurred @exception IOException if an I/O error has occurred
[ "Reads", "uncompressed", "data", "into", "an", "array", "of", "bytes", ".", "This", "method", "will", "block", "until", "some", "input", "can", "be", "decompressed", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/compression/EXIInflaterInputStream.java#L180-L203
143,049
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/CommonUtils.java
CommonUtils.writeTXT
public static void writeTXT(String string, File file) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(string); out.close(); }
java
public static void writeTXT(String string, File file) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(string); out.close(); }
[ "public", "static", "void", "writeTXT", "(", "String", "string", ",", "File", "file", ")", "throws", "IOException", "{", "BufferedWriter", "out", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ";", "out", ".", "write", "(", "string", ")", ";", "out", ".", "close", "(", ")", ";", "}" ]
Writes the string into the file.
[ "Writes", "the", "string", "into", "the", "file", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/CommonUtils.java#L39-L43
143,050
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/DecodingOptions.java
DecodingOptions.setOption
public void setOption(String key) throws UnsupportedOption { if (key.equals(IGNORE_SCHEMA_ID)) { options.add(key); } else { throw new UnsupportedOption("DecodingOption '" + key + "' is unknown!"); } }
java
public void setOption(String key) throws UnsupportedOption { if (key.equals(IGNORE_SCHEMA_ID)) { options.add(key); } else { throw new UnsupportedOption("DecodingOption '" + key + "' is unknown!"); } }
[ "public", "void", "setOption", "(", "String", "key", ")", "throws", "UnsupportedOption", "{", "if", "(", "key", ".", "equals", "(", "IGNORE_SCHEMA_ID", ")", ")", "{", "options", ".", "add", "(", "key", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOption", "(", "\"DecodingOption '\"", "+", "key", "+", "\"' is unknown!\"", ")", ";", "}", "}" ]
Enables given option. <p> Note: Some options (e.g. INCLUDE_SCHEMA_ID) will only take effect if the EXI options document is set to encode options in general (see INCLUDE_OPTIONS). </p> @param key referring to a specific option @throws UnsupportedOption if option is not supported
[ "Enables", "given", "option", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/DecodingOptions.java#L79-L86
143,051
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/ByteEncoderChannel.java
ByteEncoderChannel.encodeNBitUnsignedInteger
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Negative value as unsigned integer!"); } assert (b >= 0); assert (n >= 0); if (n == 0) { // 0 bytes } else if (n < 9) { // 1 byte encode(b & 0xff); } else if (n < 17) { // 2 bytes encode(b & 0x00ff); encode((b & 0xff00) >> 8); } else if (n < 25) { // 3 bytes encode(b & 0x0000ff); encode((b & 0x00ff00) >> 8); encode((b & 0xff0000) >> 16); } else if (n < 33) { // 4 bytes encode(b & 0x000000ff); encode((b & 0x0000ff00) >> 8); encode((b & 0x00ff0000) >> 16); encode((b & 0xff000000) >> 24); } else { throw new RuntimeException( "Currently not more than 4 Bytes allowed for NBitUnsignedInteger!"); } }
java
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Negative value as unsigned integer!"); } assert (b >= 0); assert (n >= 0); if (n == 0) { // 0 bytes } else if (n < 9) { // 1 byte encode(b & 0xff); } else if (n < 17) { // 2 bytes encode(b & 0x00ff); encode((b & 0xff00) >> 8); } else if (n < 25) { // 3 bytes encode(b & 0x0000ff); encode((b & 0x00ff00) >> 8); encode((b & 0xff0000) >> 16); } else if (n < 33) { // 4 bytes encode(b & 0x000000ff); encode((b & 0x0000ff00) >> 8); encode((b & 0x00ff0000) >> 16); encode((b & 0xff000000) >> 24); } else { throw new RuntimeException( "Currently not more than 4 Bytes allowed for NBitUnsignedInteger!"); } }
[ "public", "void", "encodeNBitUnsignedInteger", "(", "int", "b", ",", "int", "n", ")", "throws", "IOException", "{", "if", "(", "b", "<", "0", "||", "n", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Negative value as unsigned integer!\"", ")", ";", "}", "assert", "(", "b", ">=", "0", ")", ";", "assert", "(", "n", ">=", "0", ")", ";", "if", "(", "n", "==", "0", ")", "{", "// 0 bytes", "}", "else", "if", "(", "n", "<", "9", ")", "{", "// 1 byte", "encode", "(", "b", "&", "0xff", ")", ";", "}", "else", "if", "(", "n", "<", "17", ")", "{", "// 2 bytes", "encode", "(", "b", "&", "0x00ff", ")", ";", "encode", "(", "(", "b", "&", "0xff00", ")", ">>", "8", ")", ";", "}", "else", "if", "(", "n", "<", "25", ")", "{", "// 3 bytes", "encode", "(", "b", "&", "0x0000ff", ")", ";", "encode", "(", "(", "b", "&", "0x00ff00", ")", ">>", "8", ")", ";", "encode", "(", "(", "b", "&", "0xff0000", ")", ">>", "16", ")", ";", "}", "else", "if", "(", "n", "<", "33", ")", "{", "// 4 bytes", "encode", "(", "b", "&", "0x000000ff", ")", ";", "encode", "(", "(", "b", "&", "0x0000ff00", ")", ">>", "8", ")", ";", "encode", "(", "(", "b", "&", "0x00ff0000", ")", ">>", "16", ")", ";", "encode", "(", "(", "b", "&", "0xff000000", ")", ">>", "24", ")", ";", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Currently not more than 4 Bytes allowed for NBitUnsignedInteger!\"", ")", ";", "}", "}" ]
Encode n-bit unsigned integer using the minimum number of bytes required to store n bits. The n least significant bits of parameter b starting with the most significant, i.e. from left to right.
[ "Encode", "n", "-", "bit", "unsigned", "integer", "using", "the", "minimum", "number", "of", "bytes", "required", "to", "store", "n", "bits", ".", "The", "n", "least", "significant", "bits", "of", "parameter", "b", "starting", "with", "the", "most", "significant", "i", ".", "e", ".", "from", "left", "to", "right", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/ByteEncoderChannel.java#L93-L125
143,052
datasalt/pangool
core/src/main/java/com/datasalt/pangool/PangoolDriver.java
PangoolDriver.addClass
@SuppressWarnings("rawtypes") public void addClass(String name, Class mainClass, String description) throws Throwable { programs.put(name, new ProgramDescription(mainClass, description)); }
java
@SuppressWarnings("rawtypes") public void addClass(String name, Class mainClass, String description) throws Throwable { programs.put(name, new ProgramDescription(mainClass, description)); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "void", "addClass", "(", "String", "name", ",", "Class", "mainClass", ",", "String", "description", ")", "throws", "Throwable", "{", "programs", ".", "put", "(", "name", ",", "new", "ProgramDescription", "(", "mainClass", ",", "description", ")", ")", ";", "}" ]
This is the method that adds the classed to the repository @param name The name of the string you want the class instance to be called with @param mainClass The class that you want to add to the repository @param description The description of the class @throws NoSuchMethodException @throws SecurityException
[ "This", "is", "the", "method", "that", "adds", "the", "classed", "to", "the", "repository" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/PangoolDriver.java#L88-L91
143,053
datasalt/pangool
core/src/main/java/com/datasalt/pangool/PangoolDriver.java
PangoolDriver.driver
public void driver(String[] args) throws Throwable { // Make sure they gave us a program name. if(args.length == 0) { System.out.println("An example program must be given as the" + " first argument."); printUsage(programs); throw new IllegalArgumentException("An example program must be given " + "as the first argument."); } // And that it is good. ProgramDescription pgm = programs.get(args[0]); if(pgm == null) { System.out.println("Unknown program '" + args[0] + "' chosen."); printUsage(programs); throw new IllegalArgumentException("Unknown program '" + args[0] + "' chosen."); } // Remove the leading argument and call main String[] new_args = new String[args.length - 1]; for(int i = 1; i < args.length; ++i) { new_args[i - 1] = args[i]; } pgm.invoke(new_args); }
java
public void driver(String[] args) throws Throwable { // Make sure they gave us a program name. if(args.length == 0) { System.out.println("An example program must be given as the" + " first argument."); printUsage(programs); throw new IllegalArgumentException("An example program must be given " + "as the first argument."); } // And that it is good. ProgramDescription pgm = programs.get(args[0]); if(pgm == null) { System.out.println("Unknown program '" + args[0] + "' chosen."); printUsage(programs); throw new IllegalArgumentException("Unknown program '" + args[0] + "' chosen."); } // Remove the leading argument and call main String[] new_args = new String[args.length - 1]; for(int i = 1; i < args.length; ++i) { new_args[i - 1] = args[i]; } pgm.invoke(new_args); }
[ "public", "void", "driver", "(", "String", "[", "]", "args", ")", "throws", "Throwable", "{", "// Make sure they gave us a program name.", "if", "(", "args", ".", "length", "==", "0", ")", "{", "System", ".", "out", ".", "println", "(", "\"An example program must be given as the\"", "+", "\" first argument.\"", ")", ";", "printUsage", "(", "programs", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"An example program must be given \"", "+", "\"as the first argument.\"", ")", ";", "}", "// And that it is good.", "ProgramDescription", "pgm", "=", "programs", ".", "get", "(", "args", "[", "0", "]", ")", ";", "if", "(", "pgm", "==", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"Unknown program '\"", "+", "args", "[", "0", "]", "+", "\"' chosen.\"", ")", ";", "printUsage", "(", "programs", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"Unknown program '\"", "+", "args", "[", "0", "]", "+", "\"' chosen.\"", ")", ";", "}", "// Remove the leading argument and call main", "String", "[", "]", "new_args", "=", "new", "String", "[", "args", ".", "length", "-", "1", "]", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "args", ".", "length", ";", "++", "i", ")", "{", "new_args", "[", "i", "-", "1", "]", "=", "args", "[", "i", "]", ";", "}", "pgm", ".", "invoke", "(", "new_args", ")", ";", "}" ]
This is a driver for the example programs. It looks at the first command line argument and tries to find an example program with that name. If it is found, it calls the main method in that class with the rest of the command line arguments. @param args The argument from the user. args[0] is the command to run. @throws NoSuchMethodException @throws SecurityException @throws IllegalAccessException @throws IllegalArgumentException @throws Throwable Anything thrown by the example program's main
[ "This", "is", "a", "driver", "for", "the", "example", "programs", ".", "It", "looks", "at", "the", "first", "command", "line", "argument", "and", "tries", "to", "find", "an", "example", "program", "with", "that", "name", ".", "If", "it", "is", "found", "it", "calls", "the", "main", "method", "in", "that", "class", "with", "the", "rest", "of", "the", "command", "line", "arguments", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/PangoolDriver.java#L107-L129
143,054
datasalt/pangool
core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java
HadoopSerialization.ser
public void ser(Object datum, OutputStream output) throws IOException { Map<Class, Serializer> serializers = cachedSerializers.get(); Serializer ser = serializers.get(datum.getClass()); if(ser == null) { ser = serialization.getSerializer(datum.getClass()); if(ser == null) { throw new IOException("Serializer for class " + datum.getClass() + " not found"); } serializers.put(datum.getClass(), ser); } ser.open(output); ser.serialize(datum); ser.close(); }
java
public void ser(Object datum, OutputStream output) throws IOException { Map<Class, Serializer> serializers = cachedSerializers.get(); Serializer ser = serializers.get(datum.getClass()); if(ser == null) { ser = serialization.getSerializer(datum.getClass()); if(ser == null) { throw new IOException("Serializer for class " + datum.getClass() + " not found"); } serializers.put(datum.getClass(), ser); } ser.open(output); ser.serialize(datum); ser.close(); }
[ "public", "void", "ser", "(", "Object", "datum", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "Map", "<", "Class", ",", "Serializer", ">", "serializers", "=", "cachedSerializers", ".", "get", "(", ")", ";", "Serializer", "ser", "=", "serializers", ".", "get", "(", "datum", ".", "getClass", "(", ")", ")", ";", "if", "(", "ser", "==", "null", ")", "{", "ser", "=", "serialization", ".", "getSerializer", "(", "datum", ".", "getClass", "(", ")", ")", ";", "if", "(", "ser", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Serializer for class \"", "+", "datum", ".", "getClass", "(", ")", "+", "\" not found\"", ")", ";", "}", "serializers", ".", "put", "(", "datum", ".", "getClass", "(", ")", ",", "ser", ")", ";", "}", "ser", ".", "open", "(", "output", ")", ";", "ser", ".", "serialize", "(", "datum", ")", ";", "ser", ".", "close", "(", ")", ";", "}" ]
Serializes the given object using the Hadoop serialization system.
[ "Serializes", "the", "given", "object", "using", "the", "Hadoop", "serialization", "system", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java#L72-L85
143,055
datasalt/pangool
core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java
HadoopSerialization.deser
public <T> T deser(Object obj, InputStream in) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(obj.getClass(), deSer); } deSer.open(in); obj = deSer.deserialize(obj); deSer.close(); return (T) obj; }
java
public <T> T deser(Object obj, InputStream in) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(obj.getClass(), deSer); } deSer.open(in); obj = deSer.deserialize(obj); deSer.close(); return (T) obj; }
[ "public", "<", "T", ">", "T", "deser", "(", "Object", "obj", ",", "InputStream", "in", ")", "throws", "IOException", "{", "Map", "<", "Class", ",", "Deserializer", ">", "deserializers", "=", "cachedDeserializers", ".", "get", "(", ")", ";", "Deserializer", "deSer", "=", "deserializers", ".", "get", "(", "obj", ".", "getClass", "(", ")", ")", ";", "if", "(", "deSer", "==", "null", ")", "{", "deSer", "=", "serialization", ".", "getDeserializer", "(", "obj", ".", "getClass", "(", ")", ")", ";", "deserializers", ".", "put", "(", "obj", ".", "getClass", "(", ")", ",", "deSer", ")", ";", "}", "deSer", ".", "open", "(", "in", ")", ";", "obj", "=", "deSer", ".", "deserialize", "(", "obj", ")", ";", "deSer", ".", "close", "(", ")", ";", "return", "(", "T", ")", "obj", ";", "}" ]
Deseerializes into the given object using the Hadoop serialization system. Object cannot be null.
[ "Deseerializes", "into", "the", "given", "object", "using", "the", "Hadoop", "serialization", "system", ".", "Object", "cannot", "be", "null", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java#L91-L102
143,056
datasalt/pangool
core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java
HadoopSerialization.deser
public <T> T deser(Object obj, byte[] array, int offset, int length) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(obj.getClass(), deSer); } DataInputBuffer baIs = cachedInputStream.get(); baIs.reset(array, offset, length); deSer.open(baIs); obj = deSer.deserialize(obj); deSer.close(); baIs.close(); return (T) obj; }
java
public <T> T deser(Object obj, byte[] array, int offset, int length) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(obj.getClass(), deSer); } DataInputBuffer baIs = cachedInputStream.get(); baIs.reset(array, offset, length); deSer.open(baIs); obj = deSer.deserialize(obj); deSer.close(); baIs.close(); return (T) obj; }
[ "public", "<", "T", ">", "T", "deser", "(", "Object", "obj", ",", "byte", "[", "]", "array", ",", "int", "offset", ",", "int", "length", ")", "throws", "IOException", "{", "Map", "<", "Class", ",", "Deserializer", ">", "deserializers", "=", "cachedDeserializers", ".", "get", "(", ")", ";", "Deserializer", "deSer", "=", "deserializers", ".", "get", "(", "obj", ".", "getClass", "(", ")", ")", ";", "if", "(", "deSer", "==", "null", ")", "{", "deSer", "=", "serialization", ".", "getDeserializer", "(", "obj", ".", "getClass", "(", ")", ")", ";", "deserializers", ".", "put", "(", "obj", ".", "getClass", "(", ")", ",", "deSer", ")", ";", "}", "DataInputBuffer", "baIs", "=", "cachedInputStream", ".", "get", "(", ")", ";", "baIs", ".", "reset", "(", "array", ",", "offset", ",", "length", ")", ";", "deSer", ".", "open", "(", "baIs", ")", ";", "obj", "=", "deSer", ".", "deserialize", "(", "obj", ")", ";", "deSer", ".", "close", "(", ")", ";", "baIs", ".", "close", "(", ")", ";", "return", "(", "T", ")", "obj", ";", "}" ]
Deserialize an object using Hadoop serialization from a byte array. The object cannot be null.
[ "Deserialize", "an", "object", "using", "Hadoop", "serialization", "from", "a", "byte", "array", ".", "The", "object", "cannot", "be", "null", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/serialization/HadoopSerialization.java#L126-L140
143,057
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.copyPartialContent
public static void copyPartialContent(InputStream in, OutputStream out, Range r) throws IOException { IOUtils.copyLarge(in, out, r.start, r.length); }
java
public static void copyPartialContent(InputStream in, OutputStream out, Range r) throws IOException { IOUtils.copyLarge(in, out, r.start, r.length); }
[ "public", "static", "void", "copyPartialContent", "(", "InputStream", "in", ",", "OutputStream", "out", ",", "Range", "r", ")", "throws", "IOException", "{", "IOUtils", ".", "copyLarge", "(", "in", ",", "out", ",", "r", ".", "start", ",", "r", ".", "length", ")", ";", "}" ]
Copies the given range of bytes from the input stream to the output stream. @param in @param out @param r @throws IOException
[ "Copies", "the", "given", "range", "of", "bytes", "from", "the", "input", "stream", "to", "the", "output", "stream", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L225-L227
143,058
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.calculateRangeLength
public static Long calculateRangeLength(FileRequestContext context, Range range) { if(range.start == -1) range.start = 0; if(range.end == -1) range.end = context.file.length() - 1; range.length = range.end - range.start + 1; return range.length; }
java
public static Long calculateRangeLength(FileRequestContext context, Range range) { if(range.start == -1) range.start = 0; if(range.end == -1) range.end = context.file.length() - 1; range.length = range.end - range.start + 1; return range.length; }
[ "public", "static", "Long", "calculateRangeLength", "(", "FileRequestContext", "context", ",", "Range", "range", ")", "{", "if", "(", "range", ".", "start", "==", "-", "1", ")", "range", ".", "start", "=", "0", ";", "if", "(", "range", ".", "end", "==", "-", "1", ")", "range", ".", "end", "=", "context", ".", "file", ".", "length", "(", ")", "-", "1", ";", "range", ".", "length", "=", "range", ".", "end", "-", "range", ".", "start", "+", "1", ";", "return", "range", ".", "length", ";", "}" ]
Calculates the length of a given range. @param context @param range @return
[ "Calculates", "the", "length", "of", "a", "given", "range", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L236-L241
143,059
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.checkAccepts
protected boolean checkAccepts(FileRequestContext context) throws IOException { if (!canAccept(context.request.getHeader(ACCEPT_HEADER), false, context.contentType)) { notAcceptable(context); return true; } if (!(canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), false, "identity") || canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), false, "gzip"))) { notAcceptable(context); return true; } if (context.request.getHeader(ACCEPT_ENCODING_HEADER) != null && canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), true, "gzip") && shouldGzip(context.contentType)) { context.compress = true; } return false; }
java
protected boolean checkAccepts(FileRequestContext context) throws IOException { if (!canAccept(context.request.getHeader(ACCEPT_HEADER), false, context.contentType)) { notAcceptable(context); return true; } if (!(canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), false, "identity") || canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), false, "gzip"))) { notAcceptable(context); return true; } if (context.request.getHeader(ACCEPT_ENCODING_HEADER) != null && canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), true, "gzip") && shouldGzip(context.contentType)) { context.compress = true; } return false; }
[ "protected", "boolean", "checkAccepts", "(", "FileRequestContext", "context", ")", "throws", "IOException", "{", "if", "(", "!", "canAccept", "(", "context", ".", "request", ".", "getHeader", "(", "ACCEPT_HEADER", ")", ",", "false", ",", "context", ".", "contentType", ")", ")", "{", "notAcceptable", "(", "context", ")", ";", "return", "true", ";", "}", "if", "(", "!", "(", "canAccept", "(", "context", ".", "request", ".", "getHeader", "(", "ACCEPT_ENCODING_HEADER", ")", ",", "false", ",", "\"identity\"", ")", "||", "canAccept", "(", "context", ".", "request", ".", "getHeader", "(", "ACCEPT_ENCODING_HEADER", ")", ",", "false", ",", "\"gzip\"", ")", ")", ")", "{", "notAcceptable", "(", "context", ")", ";", "return", "true", ";", "}", "if", "(", "context", ".", "request", ".", "getHeader", "(", "ACCEPT_ENCODING_HEADER", ")", "!=", "null", "&&", "canAccept", "(", "context", ".", "request", ".", "getHeader", "(", "ACCEPT_ENCODING_HEADER", ")", ",", "true", ",", "\"gzip\"", ")", "&&", "shouldGzip", "(", "context", ".", "contentType", ")", ")", "{", "context", ".", "compress", "=", "true", ";", "}", "return", "false", ";", "}" ]
Checks the accepts headers and makes sure that we can fulfill the request. @param context @return @throws IOException
[ "Checks", "the", "accepts", "headers", "and", "makes", "sure", "that", "we", "can", "fulfill", "the", "request", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L249-L264
143,060
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.locateFileToServe
public boolean locateFileToServe( FileRequestContext context ) throws IOException { context.file = new File( contentDir, context.path); // if the path is not on the file system, send a 404. if( !context.file.exists() ) { context.response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } // redirect welcome files if needed. if( handleWelcomeRedirect(context) ) return true; // if the requested file is a directory, try to find the welcome file. if( context.file.isDirectory() ) { context.file = new File(context.file, "index.html"); } // if the file does not exist, then terminate with a 404. if( !context.file.exists() ) { context.response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } return false; }
java
public boolean locateFileToServe( FileRequestContext context ) throws IOException { context.file = new File( contentDir, context.path); // if the path is not on the file system, send a 404. if( !context.file.exists() ) { context.response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } // redirect welcome files if needed. if( handleWelcomeRedirect(context) ) return true; // if the requested file is a directory, try to find the welcome file. if( context.file.isDirectory() ) { context.file = new File(context.file, "index.html"); } // if the file does not exist, then terminate with a 404. if( !context.file.exists() ) { context.response.sendError(HttpServletResponse.SC_NOT_FOUND); return true; } return false; }
[ "public", "boolean", "locateFileToServe", "(", "FileRequestContext", "context", ")", "throws", "IOException", "{", "context", ".", "file", "=", "new", "File", "(", "contentDir", ",", "context", ".", "path", ")", ";", "// if the path is not on the file system, send a 404.", "if", "(", "!", "context", ".", "file", ".", "exists", "(", ")", ")", "{", "context", ".", "response", ".", "sendError", "(", "HttpServletResponse", ".", "SC_NOT_FOUND", ")", ";", "return", "true", ";", "}", "// redirect welcome files if needed.", "if", "(", "handleWelcomeRedirect", "(", "context", ")", ")", "return", "true", ";", "// if the requested file is a directory, try to find the welcome file.", "if", "(", "context", ".", "file", ".", "isDirectory", "(", ")", ")", "{", "context", ".", "file", "=", "new", "File", "(", "context", ".", "file", ",", "\"index.html\"", ")", ";", "}", "// if the file does not exist, then terminate with a 404.", "if", "(", "!", "context", ".", "file", ".", "exists", "(", ")", ")", "{", "context", ".", "response", ".", "sendError", "(", "HttpServletResponse", ".", "SC_NOT_FOUND", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Locates the file to serve. Returns true if locating the file caused the request to be handled. @param context @return @throws IOException
[ "Locates", "the", "file", "to", "serve", ".", "Returns", "true", "if", "locating", "the", "file", "caused", "the", "request", "to", "be", "handled", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L287-L311
143,061
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.invalidRanges
public static void invalidRanges(FileRequestContext context) throws IOException { context.response.setHeader(CONTENT_RANGE_HEADER, "*/" + context.file.length()); context.response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); }
java
public static void invalidRanges(FileRequestContext context) throws IOException { context.response.setHeader(CONTENT_RANGE_HEADER, "*/" + context.file.length()); context.response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); }
[ "public", "static", "void", "invalidRanges", "(", "FileRequestContext", "context", ")", "throws", "IOException", "{", "context", ".", "response", ".", "setHeader", "(", "CONTENT_RANGE_HEADER", ",", "\"*/\"", "+", "context", ".", "file", ".", "length", "(", ")", ")", ";", "context", ".", "response", ".", "sendError", "(", "HttpServletResponse", ".", "SC_REQUESTED_RANGE_NOT_SATISFIABLE", ")", ";", "}" ]
Sets the appropriate response headers and error status for bad ranges @param context @throws IOException
[ "Sets", "the", "appropriate", "response", "headers", "and", "error", "status", "for", "bad", "ranges" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L392-L395
143,062
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.canAccept
public static boolean canAccept(String headerValue, boolean strict, String type) { if(headerValue != null && type != null) { String availableTypes[] = headerValue.split(","); for(String availableType : availableTypes) { String typeParams[] = availableType.split(";"); double qValue = 1.0d; if(typeParams.length > 0) { for(int i=1; i<typeParams.length; i++) { if(typeParams[i].trim().startsWith("q=")) { String qString = typeParams[i].substring(2).trim(); if(qString.matches("\\A\\d+(\\.\\d*){0,1}\\Z")){ qValue = Double.parseDouble(qString); break; } } } } boolean matches = false; if(typeParams[0].equals("*") || typeParams[0].equals("*/*")) { matches = true; } else { matches = hasMatch(typeParams, type); } if(qValue == 0 && matches) { return false; } else if(matches){ return true; } } } return !strict; }
java
public static boolean canAccept(String headerValue, boolean strict, String type) { if(headerValue != null && type != null) { String availableTypes[] = headerValue.split(","); for(String availableType : availableTypes) { String typeParams[] = availableType.split(";"); double qValue = 1.0d; if(typeParams.length > 0) { for(int i=1; i<typeParams.length; i++) { if(typeParams[i].trim().startsWith("q=")) { String qString = typeParams[i].substring(2).trim(); if(qString.matches("\\A\\d+(\\.\\d*){0,1}\\Z")){ qValue = Double.parseDouble(qString); break; } } } } boolean matches = false; if(typeParams[0].equals("*") || typeParams[0].equals("*/*")) { matches = true; } else { matches = hasMatch(typeParams, type); } if(qValue == 0 && matches) { return false; } else if(matches){ return true; } } } return !strict; }
[ "public", "static", "boolean", "canAccept", "(", "String", "headerValue", ",", "boolean", "strict", ",", "String", "type", ")", "{", "if", "(", "headerValue", "!=", "null", "&&", "type", "!=", "null", ")", "{", "String", "availableTypes", "[", "]", "=", "headerValue", ".", "split", "(", "\",\"", ")", ";", "for", "(", "String", "availableType", ":", "availableTypes", ")", "{", "String", "typeParams", "[", "]", "=", "availableType", ".", "split", "(", "\";\"", ")", ";", "double", "qValue", "=", "1.0d", ";", "if", "(", "typeParams", ".", "length", ">", "0", ")", "{", "for", "(", "int", "i", "=", "1", ";", "i", "<", "typeParams", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeParams", "[", "i", "]", ".", "trim", "(", ")", ".", "startsWith", "(", "\"q=\"", ")", ")", "{", "String", "qString", "=", "typeParams", "[", "i", "]", ".", "substring", "(", "2", ")", ".", "trim", "(", ")", ";", "if", "(", "qString", ".", "matches", "(", "\"\\\\A\\\\d+(\\\\.\\\\d*){0,1}\\\\Z\"", ")", ")", "{", "qValue", "=", "Double", ".", "parseDouble", "(", "qString", ")", ";", "break", ";", "}", "}", "}", "}", "boolean", "matches", "=", "false", ";", "if", "(", "typeParams", "[", "0", "]", ".", "equals", "(", "\"*\"", ")", "||", "typeParams", "[", "0", "]", ".", "equals", "(", "\"*/*\"", ")", ")", "{", "matches", "=", "true", ";", "}", "else", "{", "matches", "=", "hasMatch", "(", "typeParams", ",", "type", ")", ";", "}", "if", "(", "qValue", "==", "0", "&&", "matches", ")", "{", "return", "false", ";", "}", "else", "if", "(", "matches", ")", "{", "return", "true", ";", "}", "}", "}", "return", "!", "strict", ";", "}" ]
Parses an Accept header value and checks to see if the type is acceptable. @param headerValue The value of the header. @param strict Forces the type to be in the header. @param type The token that we need in order to be acceptable. @return
[ "Parses", "an", "Accept", "header", "value", "and", "checks", "to", "see", "if", "the", "type", "is", "acceptable", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L451-L482
143,063
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.hasMatch
private static boolean hasMatch(String[] typeParams, String... type) { boolean matches = false; for(String t : type) { for(String typeParam : typeParams) { if(typeParam.contains("/")) { String typePart = typeParam.replace("*", ""); if(t.startsWith(typePart) || t.endsWith(typePart)) { matches = true; break; } } else if(t.equals(typeParam)) { matches = true; break; } } if(matches) { break; } } return matches; }
java
private static boolean hasMatch(String[] typeParams, String... type) { boolean matches = false; for(String t : type) { for(String typeParam : typeParams) { if(typeParam.contains("/")) { String typePart = typeParam.replace("*", ""); if(t.startsWith(typePart) || t.endsWith(typePart)) { matches = true; break; } } else if(t.equals(typeParam)) { matches = true; break; } } if(matches) { break; } } return matches; }
[ "private", "static", "boolean", "hasMatch", "(", "String", "[", "]", "typeParams", ",", "String", "...", "type", ")", "{", "boolean", "matches", "=", "false", ";", "for", "(", "String", "t", ":", "type", ")", "{", "for", "(", "String", "typeParam", ":", "typeParams", ")", "{", "if", "(", "typeParam", ".", "contains", "(", "\"/\"", ")", ")", "{", "String", "typePart", "=", "typeParam", ".", "replace", "(", "\"*\"", ",", "\"\"", ")", ";", "if", "(", "t", ".", "startsWith", "(", "typePart", ")", "||", "t", ".", "endsWith", "(", "typePart", ")", ")", "{", "matches", "=", "true", ";", "break", ";", "}", "}", "else", "if", "(", "t", ".", "equals", "(", "typeParam", ")", ")", "{", "matches", "=", "true", ";", "break", ";", "}", "}", "if", "(", "matches", ")", "{", "break", ";", "}", "}", "return", "matches", ";", "}" ]
Check to see if a Accept header accept part matches any of the given types. @param typeParams @param type @return
[ "Check", "to", "see", "if", "a", "Accept", "header", "accept", "part", "matches", "any", "of", "the", "given", "types", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L490-L510
143,064
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.handleWelcomeRedirect
public boolean handleWelcomeRedirect( FileRequestContext context ) throws IOException { if( context.file.isFile() && context.file.getName().equals("index.html")) { resolveContentType(context); String location = context.path.replaceFirst("/index.html\\Z", ""); if( location.isEmpty() ) location = "/"; if( context.request.getQueryString() != null ) location = location + "?" + context.request.getQueryString(); sendPermanentRedirect(context, location); return true; } return false; }
java
public boolean handleWelcomeRedirect( FileRequestContext context ) throws IOException { if( context.file.isFile() && context.file.getName().equals("index.html")) { resolveContentType(context); String location = context.path.replaceFirst("/index.html\\Z", ""); if( location.isEmpty() ) location = "/"; if( context.request.getQueryString() != null ) location = location + "?" + context.request.getQueryString(); sendPermanentRedirect(context, location); return true; } return false; }
[ "public", "boolean", "handleWelcomeRedirect", "(", "FileRequestContext", "context", ")", "throws", "IOException", "{", "if", "(", "context", ".", "file", ".", "isFile", "(", ")", "&&", "context", ".", "file", ".", "getName", "(", ")", ".", "equals", "(", "\"index.html\"", ")", ")", "{", "resolveContentType", "(", "context", ")", ";", "String", "location", "=", "context", ".", "path", ".", "replaceFirst", "(", "\"/index.html\\\\Z\"", ",", "\"\"", ")", ";", "if", "(", "location", ".", "isEmpty", "(", ")", ")", "location", "=", "\"/\"", ";", "if", "(", "context", ".", "request", ".", "getQueryString", "(", ")", "!=", "null", ")", "location", "=", "location", "+", "\"?\"", "+", "context", ".", "request", ".", "getQueryString", "(", ")", ";", "sendPermanentRedirect", "(", "context", ",", "location", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Forces requests for index files to not use the file name. @param context @return true if the request was handled, false otherwise. @throws IOException
[ "Forces", "requests", "for", "index", "files", "to", "not", "use", "the", "file", "name", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L553-L563
143,065
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java
BasicFileServlet.resolveContentType
public void resolveContentType(FileRequestContext context) { String contentType = lookupMimeType(context.file.getName()); if(contentType != null) { context.contentType = contentType; if(contentType.equals("text/html")) { context.contentType += ";charset=UTF-8"; } } }
java
public void resolveContentType(FileRequestContext context) { String contentType = lookupMimeType(context.file.getName()); if(contentType != null) { context.contentType = contentType; if(contentType.equals("text/html")) { context.contentType += ";charset=UTF-8"; } } }
[ "public", "void", "resolveContentType", "(", "FileRequestContext", "context", ")", "{", "String", "contentType", "=", "lookupMimeType", "(", "context", ".", "file", ".", "getName", "(", ")", ")", ";", "if", "(", "contentType", "!=", "null", ")", "{", "context", ".", "contentType", "=", "contentType", ";", "if", "(", "contentType", ".", "equals", "(", "\"text/html\"", ")", ")", "{", "context", ".", "contentType", "+=", "\";charset=UTF-8\"", ";", "}", "}", "}" ]
Looks up the mime type based on file extension and if found sets it on the FileRequestContext. @param context
[ "Looks", "up", "the", "mime", "type", "based", "on", "file", "extension", "and", "if", "found", "sets", "it", "on", "the", "FileRequestContext", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L570-L578
143,066
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java
BitOutputStream.flushBuffer
protected void flushBuffer() throws IOException { if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
java
protected void flushBuffer() throws IOException { if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
[ "protected", "void", "flushBuffer", "(", ")", "throws", "IOException", "{", "if", "(", "capacity", "==", "0", ")", "{", "ostream", ".", "write", "(", "buffer", ")", ";", "capacity", "=", "BITS_IN_BYTE", ";", "buffer", "=", "0", ";", "len", "++", ";", "}", "}" ]
If buffer is full, write it out and reset internal state. @throws IOException IO exception
[ "If", "buffer", "is", "full", "write", "it", "out", "and", "reset", "internal", "state", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java#L97-L104
143,067
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java
BitOutputStream.align
public void align() throws IOException { if (capacity < BITS_IN_BYTE) { ostream.write(buffer << capacity); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
java
public void align() throws IOException { if (capacity < BITS_IN_BYTE) { ostream.write(buffer << capacity); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
[ "public", "void", "align", "(", ")", "throws", "IOException", "{", "if", "(", "capacity", "<", "BITS_IN_BYTE", ")", "{", "ostream", ".", "write", "(", "buffer", "<<", "capacity", ")", ";", "capacity", "=", "BITS_IN_BYTE", ";", "buffer", "=", "0", ";", "len", "++", ";", "}", "}" ]
If there are some unwritten bits, pad them if necessary and write them out. @throws IOException IO exception
[ "If", "there", "are", "some", "unwritten", "bits", "pad", "them", "if", "necessary", "and", "write", "them", "out", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java#L143-L150
143,068
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java
BitOutputStream.writeBits
public void writeBits(int b, int n) throws IOException { if (n <= capacity) { // all bits fit into the current buffer buffer = (buffer << n) | (b & (0xff >> (BITS_IN_BYTE - n))); capacity -= n; if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; len++; } } else { // fill as many bits into buffer as possible buffer = (buffer << capacity) | ((b >>> (n - capacity)) & (0xff >> (BITS_IN_BYTE - capacity))); n -= capacity; ostream.write(buffer); len++; // possibly write whole bytes while (n >= 8) { n -= 8; ostream.write(b >>> n); len++; } // put the rest of bits into the buffer buffer = b; // Note: the high bits will be shifted out during // further filling capacity = BITS_IN_BYTE - n; } }
java
public void writeBits(int b, int n) throws IOException { if (n <= capacity) { // all bits fit into the current buffer buffer = (buffer << n) | (b & (0xff >> (BITS_IN_BYTE - n))); capacity -= n; if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; len++; } } else { // fill as many bits into buffer as possible buffer = (buffer << capacity) | ((b >>> (n - capacity)) & (0xff >> (BITS_IN_BYTE - capacity))); n -= capacity; ostream.write(buffer); len++; // possibly write whole bytes while (n >= 8) { n -= 8; ostream.write(b >>> n); len++; } // put the rest of bits into the buffer buffer = b; // Note: the high bits will be shifted out during // further filling capacity = BITS_IN_BYTE - n; } }
[ "public", "void", "writeBits", "(", "int", "b", ",", "int", "n", ")", "throws", "IOException", "{", "if", "(", "n", "<=", "capacity", ")", "{", "// all bits fit into the current buffer", "buffer", "=", "(", "buffer", "<<", "n", ")", "|", "(", "b", "&", "(", "0xff", ">>", "(", "BITS_IN_BYTE", "-", "n", ")", ")", ")", ";", "capacity", "-=", "n", ";", "if", "(", "capacity", "==", "0", ")", "{", "ostream", ".", "write", "(", "buffer", ")", ";", "capacity", "=", "BITS_IN_BYTE", ";", "len", "++", ";", "}", "}", "else", "{", "// fill as many bits into buffer as possible", "buffer", "=", "(", "buffer", "<<", "capacity", ")", "|", "(", "(", "b", ">>>", "(", "n", "-", "capacity", ")", ")", "&", "(", "0xff", ">>", "(", "BITS_IN_BYTE", "-", "capacity", ")", ")", ")", ";", "n", "-=", "capacity", ";", "ostream", ".", "write", "(", "buffer", ")", ";", "len", "++", ";", "// possibly write whole bytes", "while", "(", "n", ">=", "8", ")", "{", "n", "-=", "8", ";", "ostream", ".", "write", "(", "b", ">>>", "n", ")", ";", "len", "++", ";", "}", "// put the rest of bits into the buffer", "buffer", "=", "b", ";", "// Note: the high bits will be shifted out during", "// further filling", "capacity", "=", "BITS_IN_BYTE", "-", "n", ";", "}", "}" ]
Write the n least significant bits of parameter b starting with the most significant, i.e. from left to right. @param b bits @param n number of bits @throws IOException IO exception
[ "Write", "the", "n", "least", "significant", "bits", "of", "parameter", "b", "starting", "with", "the", "most", "significant", "i", ".", "e", ".", "from", "left", "to", "right", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java#L202-L232
143,069
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java
BitOutputStream.writeDirectBytes
protected void writeDirectBytes(byte[] b, int off, int len) throws IOException { ostream.write(b, off, len); len += len; }
java
protected void writeDirectBytes(byte[] b, int off, int len) throws IOException { ostream.write(b, off, len); len += len; }
[ "protected", "void", "writeDirectBytes", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "throws", "IOException", "{", "ostream", ".", "write", "(", "b", ",", "off", ",", "len", ")", ";", "len", "+=", "len", ";", "}" ]
Ignore current buffer, and write a sequence of bytes directly to the underlying stream. @param b byte array @param off byte array offset @param len byte array length @throws IOException IO exception
[ "Ignore", "current", "buffer", "and", "write", "a", "sequence", "of", "bytes", "directly", "to", "the", "underlying", "stream", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitOutputStream.java#L261-L265
143,070
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/input/TupleTextInputFormat.java
TupleTextInputFormat.adaptNumber
private static String adaptNumber(String number) { String n = number.trim(); if(n.startsWith("+")) { return n.substring(1); } else { return n; } }
java
private static String adaptNumber(String number) { String n = number.trim(); if(n.startsWith("+")) { return n.substring(1); } else { return n; } }
[ "private", "static", "String", "adaptNumber", "(", "String", "number", ")", "{", "String", "n", "=", "number", ".", "trim", "(", ")", ";", "if", "(", "n", ".", "startsWith", "(", "\"+\"", ")", ")", "{", "return", "n", ".", "substring", "(", "1", ")", ";", "}", "else", "{", "return", "n", ";", "}", "}" ]
Adapt a number for being able to be parsed by Integer and Long
[ "Adapt", "a", "number", "for", "being", "able", "to", "be", "parsed", "by", "Integer", "and", "Long" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/input/TupleTextInputFormat.java#L439-L446
143,071
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/shiro/AuthenticationManagerCommandAction.java
AuthenticationManagerCommandAction.persistRealmChanges
private void persistRealmChanges() { configManager.persistProperties(realm.getProperties(), new File(applicationContentDir, PersistablePropertiesRealm.REALM_FILE_NAME), null); }
java
private void persistRealmChanges() { configManager.persistProperties(realm.getProperties(), new File(applicationContentDir, PersistablePropertiesRealm.REALM_FILE_NAME), null); }
[ "private", "void", "persistRealmChanges", "(", ")", "{", "configManager", ".", "persistProperties", "(", "realm", ".", "getProperties", "(", ")", ",", "new", "File", "(", "applicationContentDir", ",", "PersistablePropertiesRealm", ".", "REALM_FILE_NAME", ")", ",", "null", ")", ";", "}" ]
Persists the user accounts to a properties file that is only available to this site only.
[ "Persists", "the", "user", "accounts", "to", "a", "properties", "file", "that", "is", "only", "available", "to", "this", "site", "only", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/shiro/AuthenticationManagerCommandAction.java#L80-L82
143,072
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java
HadoopUtils.stringToFile
public static void stringToFile(FileSystem fs, Path path, String string) throws IOException { OutputStream os = fs.create(path, true); PrintWriter pw = new PrintWriter(os); pw.append(string); pw.close(); }
java
public static void stringToFile(FileSystem fs, Path path, String string) throws IOException { OutputStream os = fs.create(path, true); PrintWriter pw = new PrintWriter(os); pw.append(string); pw.close(); }
[ "public", "static", "void", "stringToFile", "(", "FileSystem", "fs", ",", "Path", "path", ",", "String", "string", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "fs", ".", "create", "(", "path", ",", "true", ")", ";", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "os", ")", ";", "pw", ".", "append", "(", "string", ")", ";", "pw", ".", "close", "(", ")", ";", "}" ]
Creates a file with the given string, overwritting if needed.
[ "Creates", "a", "file", "with", "the", "given", "string", "overwritting", "if", "needed", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java#L59-L65
143,073
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java
HadoopUtils.fileToString
public static String fileToString(FileSystem fs, Path path) throws IOException { if(!fs.exists(path)) { return null; } InputStream is = fs.open(path); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); char[] buff = new char[256]; StringBuilder sb = new StringBuilder(); int read; while((read = br.read(buff)) != -1) { sb.append(buff, 0, read); } br.close(); return sb.toString(); }
java
public static String fileToString(FileSystem fs, Path path) throws IOException { if(!fs.exists(path)) { return null; } InputStream is = fs.open(path); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); char[] buff = new char[256]; StringBuilder sb = new StringBuilder(); int read; while((read = br.read(buff)) != -1) { sb.append(buff, 0, read); } br.close(); return sb.toString(); }
[ "public", "static", "String", "fileToString", "(", "FileSystem", "fs", ",", "Path", "path", ")", "throws", "IOException", "{", "if", "(", "!", "fs", ".", "exists", "(", "path", ")", ")", "{", "return", "null", ";", "}", "InputStream", "is", "=", "fs", ".", "open", "(", "path", ")", ";", "InputStreamReader", "isr", "=", "new", "InputStreamReader", "(", "is", ")", ";", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "isr", ")", ";", "char", "[", "]", "buff", "=", "new", "char", "[", "256", "]", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "read", ";", "while", "(", "(", "read", "=", "br", ".", "read", "(", "buff", ")", ")", "!=", "-", "1", ")", "{", "sb", ".", "append", "(", "buff", ",", "0", ",", "read", ")", ";", "}", "br", ".", "close", "(", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Reads the content of a file into a String. Return null if the file does not exist.
[ "Reads", "the", "content", "of", "a", "file", "into", "a", "String", ".", "Return", "null", "if", "the", "file", "does", "not", "exist", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java#L71-L87
143,074
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java
HadoopUtils.readIntIntMap
public static HashMap<Integer, Integer> readIntIntMap(Path path, FileSystem fs) throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, fs.getConf()); IntWritable topic = new IntWritable(); IntWritable value = new IntWritable(); HashMap<Integer, Integer> ret = new HashMap<Integer, Integer>(); while(reader.next(topic)) { reader.getCurrentValue(value); ret.put(topic.get(), value.get()); } reader.close(); return ret; }
java
public static HashMap<Integer, Integer> readIntIntMap(Path path, FileSystem fs) throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, fs.getConf()); IntWritable topic = new IntWritable(); IntWritable value = new IntWritable(); HashMap<Integer, Integer> ret = new HashMap<Integer, Integer>(); while(reader.next(topic)) { reader.getCurrentValue(value); ret.put(topic.get(), value.get()); } reader.close(); return ret; }
[ "public", "static", "HashMap", "<", "Integer", ",", "Integer", ">", "readIntIntMap", "(", "Path", "path", ",", "FileSystem", "fs", ")", "throws", "IOException", "{", "SequenceFile", ".", "Reader", "reader", "=", "new", "SequenceFile", ".", "Reader", "(", "fs", ",", "path", ",", "fs", ".", "getConf", "(", ")", ")", ";", "IntWritable", "topic", "=", "new", "IntWritable", "(", ")", ";", "IntWritable", "value", "=", "new", "IntWritable", "(", ")", ";", "HashMap", "<", "Integer", ",", "Integer", ">", "ret", "=", "new", "HashMap", "<", "Integer", ",", "Integer", ">", "(", ")", ";", "while", "(", "reader", ".", "next", "(", "topic", ")", ")", "{", "reader", ".", "getCurrentValue", "(", "value", ")", ";", "ret", ".", "put", "(", "topic", ".", "get", "(", ")", ",", "value", ".", "get", "(", ")", ")", ";", "}", "reader", ".", "close", "(", ")", ";", "return", "ret", ";", "}" ]
Reads maps of integer -> integer
[ "Reads", "maps", "of", "integer", "-", ">", "integer" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/HadoopUtils.java#L127-L144
143,075
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
FrutillaParser.scenario
static Scenario scenario(String text) { reset(); final Scenario scenario = new Scenario(text); sRoot = scenario; return scenario; }
java
static Scenario scenario(String text) { reset(); final Scenario scenario = new Scenario(text); sRoot = scenario; return scenario; }
[ "static", "Scenario", "scenario", "(", "String", "text", ")", "{", "reset", "(", ")", ";", "final", "Scenario", "scenario", "=", "new", "Scenario", "(", "text", ")", ";", "sRoot", "=", "scenario", ";", "return", "scenario", ";", "}" ]
Describes the scenario of the use case. @param text the sentence describing the scenario @return a Scenario object to conitnue adding sentences
[ "Describes", "the", "scenario", "of", "the", "use", "case", "." ]
4b225f8be47b0b12df1b82157f92fa6d0075e9ff
https://github.com/ignaciotcrespo/frutilla/blob/4b225f8be47b0b12df1b82157f92fa6d0075e9ff/java/src/main/java/org/frutilla/FrutillaParser.java#L24-L29
143,076
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/FrutillaParser.java
FrutillaParser.given
static Given given(String text) { reset(); final Given given = new Given(text); sRoot = given; return given; }
java
static Given given(String text) { reset(); final Given given = new Given(text); sRoot = given; return given; }
[ "static", "Given", "given", "(", "String", "text", ")", "{", "reset", "(", ")", ";", "final", "Given", "given", "=", "new", "Given", "(", "text", ")", ";", "sRoot", "=", "given", ";", "return", "given", ";", "}" ]
Describes the entry point of the use case. @param text the sentence describing the entry point @return a Given object to continue adding sentences
[ "Describes", "the", "entry", "point", "of", "the", "use", "case", "." ]
4b225f8be47b0b12df1b82157f92fa6d0075e9ff
https://github.com/ignaciotcrespo/frutilla/blob/4b225f8be47b0b12df1b82157f92fa6d0075e9ff/java/src/main/java/org/frutilla/FrutillaParser.java#L37-L42
143,077
ignaciotcrespo/frutilla
java/src/main/java/org/frutilla/ExceptionUtils.java
ExceptionUtils.insertMessage
public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != null) { field.set(onObject, "\n[\n" + msg + "\n]\n[\nMessage: " + onObject.getMessage() + "\n]"); } else { field.set(onObject, "\n[\n" + msg + "]\n"); } } catch (RuntimeException e) { throw e; } catch (Exception e) { } }
java
public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != null) { field.set(onObject, "\n[\n" + msg + "\n]\n[\nMessage: " + onObject.getMessage() + "\n]"); } else { field.set(onObject, "\n[\n" + msg + "]\n"); } } catch (RuntimeException e) { throw e; } catch (Exception e) { } }
[ "public", "static", "void", "insertMessage", "(", "Throwable", "onObject", ",", "String", "msg", ")", "{", "try", "{", "Field", "field", "=", "Throwable", ".", "class", ".", "getDeclaredField", "(", "\"detailMessage\"", ")", ";", "//Method(\"initCause\", new Class[]{Throwable.class});", "field", ".", "setAccessible", "(", "true", ")", ";", "if", "(", "onObject", ".", "getMessage", "(", ")", "!=", "null", ")", "{", "field", ".", "set", "(", "onObject", ",", "\"\\n[\\n\"", "+", "msg", "+", "\"\\n]\\n[\\nMessage: \"", "+", "onObject", ".", "getMessage", "(", ")", "+", "\"\\n]\"", ")", ";", "}", "else", "{", "field", ".", "set", "(", "onObject", ",", "\"\\n[\\n\"", "+", "msg", "+", "\"]\\n\"", ")", ";", "}", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}" ]
Addes a message at the beginning of the stacktrace.
[ "Addes", "a", "message", "at", "the", "beginning", "of", "the", "stacktrace", "." ]
4b225f8be47b0b12df1b82157f92fa6d0075e9ff
https://github.com/ignaciotcrespo/frutilla/blob/4b225f8be47b0b12df1b82157f92fa6d0075e9ff/java/src/main/java/org/frutilla/ExceptionUtils.java#L13-L26
143,078
scireum/server-sass
src/main/java/org/serversass/Parser.java
Parser.parse
public Stylesheet parse() throws ParseException { while (tokenizer.more()) { if (tokenizer.current().isKeyword(KEYWORD_IMPORT)) { // Handle @import parseImport(); } else if (tokenizer.current().isKeyword(KEYWORD_MIXIN)) { // Handle @mixin Mixin mixin = parseMixin(); if (mixin.getName() != null) { result.addMixin(mixin); } } else if (tokenizer.current().isKeyword(KEYWORD_MEDIA)) { // Handle @media result.addSection(parseSection(true)); } else if (tokenizer.current().isSpecialIdentifier("$") && tokenizer.next().isSymbol(":")) { // Handle variable definition parseVariableDeclaration(); } else { // Everything else is a "normal" section with selectors and attributes result.addSection(parseSection(false)); } } // Something went wrong? Throw an exception if (!tokenizer.getProblemCollector().isEmpty()) { throw ParseException.create(tokenizer.getProblemCollector()); } return result; }
java
public Stylesheet parse() throws ParseException { while (tokenizer.more()) { if (tokenizer.current().isKeyword(KEYWORD_IMPORT)) { // Handle @import parseImport(); } else if (tokenizer.current().isKeyword(KEYWORD_MIXIN)) { // Handle @mixin Mixin mixin = parseMixin(); if (mixin.getName() != null) { result.addMixin(mixin); } } else if (tokenizer.current().isKeyword(KEYWORD_MEDIA)) { // Handle @media result.addSection(parseSection(true)); } else if (tokenizer.current().isSpecialIdentifier("$") && tokenizer.next().isSymbol(":")) { // Handle variable definition parseVariableDeclaration(); } else { // Everything else is a "normal" section with selectors and attributes result.addSection(parseSection(false)); } } // Something went wrong? Throw an exception if (!tokenizer.getProblemCollector().isEmpty()) { throw ParseException.create(tokenizer.getProblemCollector()); } return result; }
[ "public", "Stylesheet", "parse", "(", ")", "throws", "ParseException", "{", "while", "(", "tokenizer", ".", "more", "(", ")", ")", "{", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_IMPORT", ")", ")", "{", "// Handle @import", "parseImport", "(", ")", ";", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_MIXIN", ")", ")", "{", "// Handle @mixin", "Mixin", "mixin", "=", "parseMixin", "(", ")", ";", "if", "(", "mixin", ".", "getName", "(", ")", "!=", "null", ")", "{", "result", ".", "addMixin", "(", "mixin", ")", ";", "}", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_MEDIA", ")", ")", "{", "// Handle @media", "result", ".", "addSection", "(", "parseSection", "(", "true", ")", ")", ";", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isSpecialIdentifier", "(", "\"$\"", ")", "&&", "tokenizer", ".", "next", "(", ")", ".", "isSymbol", "(", "\":\"", ")", ")", "{", "// Handle variable definition", "parseVariableDeclaration", "(", ")", ";", "}", "else", "{", "// Everything else is a \"normal\" section with selectors and attributes", "result", ".", "addSection", "(", "parseSection", "(", "false", ")", ")", ";", "}", "}", "// Something went wrong? Throw an exception", "if", "(", "!", "tokenizer", ".", "getProblemCollector", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "throw", "ParseException", ".", "create", "(", "tokenizer", ".", "getProblemCollector", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Parses the given input returning the parsed stylesheet. @return the AST representation of the parsed input @throws ParseException if one or more problems occurred while parsing
[ "Parses", "the", "given", "input", "returning", "the", "parsed", "stylesheet", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Parser.java#L155-L184
143,079
scireum/server-sass
src/main/java/org/serversass/Parser.java
Parser.parseSection
private Section parseSection(boolean mediaQuery) { Section section = new Section(); parseSectionSelector(mediaQuery, section); tokenizer.consumeExpectedSymbol("{"); while (tokenizer.more()) { if (tokenizer.current().isSymbol("}")) { tokenizer.consumeExpectedSymbol("}"); return section; } // Parse "normal" attributes like "font-weight: bold;" if (isAtAttribute()) { Attribute attr = parseAttribute(); section.addAttribute(attr); } else if (tokenizer.current().isKeyword(KEYWORD_MEDIA)) { // Take care of @media sub sections section.addSubSection(parseSection(true)); } else if (tokenizer.current().isKeyword(KEYWORD_INCLUDE)) { parseInclude(section); } else if (tokenizer.current().isKeyword(KEYWORD_EXTEND)) { parseExtend(section); } else { // If it is neither an attribute, nor a media query or instruction - it is probably a sub section... section.addSubSection(parseSection(false)); } } tokenizer.consumeExpectedSymbol("}"); return section; }
java
private Section parseSection(boolean mediaQuery) { Section section = new Section(); parseSectionSelector(mediaQuery, section); tokenizer.consumeExpectedSymbol("{"); while (tokenizer.more()) { if (tokenizer.current().isSymbol("}")) { tokenizer.consumeExpectedSymbol("}"); return section; } // Parse "normal" attributes like "font-weight: bold;" if (isAtAttribute()) { Attribute attr = parseAttribute(); section.addAttribute(attr); } else if (tokenizer.current().isKeyword(KEYWORD_MEDIA)) { // Take care of @media sub sections section.addSubSection(parseSection(true)); } else if (tokenizer.current().isKeyword(KEYWORD_INCLUDE)) { parseInclude(section); } else if (tokenizer.current().isKeyword(KEYWORD_EXTEND)) { parseExtend(section); } else { // If it is neither an attribute, nor a media query or instruction - it is probably a sub section... section.addSubSection(parseSection(false)); } } tokenizer.consumeExpectedSymbol("}"); return section; }
[ "private", "Section", "parseSection", "(", "boolean", "mediaQuery", ")", "{", "Section", "section", "=", "new", "Section", "(", ")", ";", "parseSectionSelector", "(", "mediaQuery", ",", "section", ")", ";", "tokenizer", ".", "consumeExpectedSymbol", "(", "\"{\"", ")", ";", "while", "(", "tokenizer", ".", "more", "(", ")", ")", "{", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isSymbol", "(", "\"}\"", ")", ")", "{", "tokenizer", ".", "consumeExpectedSymbol", "(", "\"}\"", ")", ";", "return", "section", ";", "}", "// Parse \"normal\" attributes like \"font-weight: bold;\"", "if", "(", "isAtAttribute", "(", ")", ")", "{", "Attribute", "attr", "=", "parseAttribute", "(", ")", ";", "section", ".", "addAttribute", "(", "attr", ")", ";", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_MEDIA", ")", ")", "{", "// Take care of @media sub sections", "section", ".", "addSubSection", "(", "parseSection", "(", "true", ")", ")", ";", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_INCLUDE", ")", ")", "{", "parseInclude", "(", "section", ")", ";", "}", "else", "if", "(", "tokenizer", ".", "current", "(", ")", ".", "isKeyword", "(", "KEYWORD_EXTEND", ")", ")", "{", "parseExtend", "(", "section", ")", ";", "}", "else", "{", "// If it is neither an attribute, nor a media query or instruction - it is probably a sub section...", "section", ".", "addSubSection", "(", "parseSection", "(", "false", ")", ")", ";", "}", "}", "tokenizer", ".", "consumeExpectedSymbol", "(", "\"}\"", ")", ";", "return", "section", ";", "}" ]
Parses a "section" which is either a media query or a css selector along with a set of attributes. @param mediaQuery determines if we're about to parse a media query or a "normal" section @return the parsed section
[ "Parses", "a", "section", "which", "is", "either", "a", "media", "query", "or", "a", "css", "selector", "along", "with", "a", "set", "of", "attributes", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Parser.java#L192-L219
143,080
duracloud/management-console
account-management-util/src/main/java/org/duracloud/account/db/util/security/impl/AnnotationParserImpl.java
AnnotationParserImpl.getValues
private Object[] getValues(Map<String, Object> annotationAtts) { if (null == annotationAtts) { throw new DuraCloudRuntimeException("Arg annotationAtts is null."); } List<Object> values = new ArrayList<Object>(); for (String key : annotationAtts.keySet()) { Object[] objects = (Object[]) annotationAtts.get(key); for (Object obj : objects) { values.add(obj); } } return values.toArray(); }
java
private Object[] getValues(Map<String, Object> annotationAtts) { if (null == annotationAtts) { throw new DuraCloudRuntimeException("Arg annotationAtts is null."); } List<Object> values = new ArrayList<Object>(); for (String key : annotationAtts.keySet()) { Object[] objects = (Object[]) annotationAtts.get(key); for (Object obj : objects) { values.add(obj); } } return values.toArray(); }
[ "private", "Object", "[", "]", "getValues", "(", "Map", "<", "String", ",", "Object", ">", "annotationAtts", ")", "{", "if", "(", "null", "==", "annotationAtts", ")", "{", "throw", "new", "DuraCloudRuntimeException", "(", "\"Arg annotationAtts is null.\"", ")", ";", "}", "List", "<", "Object", ">", "values", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "for", "(", "String", "key", ":", "annotationAtts", ".", "keySet", "(", ")", ")", "{", "Object", "[", "]", "objects", "=", "(", "Object", "[", "]", ")", "annotationAtts", ".", "get", "(", "key", ")", ";", "for", "(", "Object", "obj", ":", "objects", ")", "{", "values", ".", "add", "(", "obj", ")", ";", "}", "}", "return", "values", ".", "toArray", "(", ")", ";", "}" ]
This method extracts the annotation argument info from the annotation metadata. Since the implementation of access for annotation arguments varies, this method may need to be overwritten by additional AnnotationParsers. @param annotationAtts mapping of annotation-implementation-dependent access keys and the annotation arguments @return array of the annotation arguments
[ "This", "method", "extracts", "the", "annotation", "argument", "info", "from", "the", "annotation", "metadata", ".", "Since", "the", "implementation", "of", "access", "for", "annotation", "arguments", "varies", "this", "method", "may", "need", "to", "be", "overwritten", "by", "additional", "AnnotationParsers", "." ]
7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-util/src/main/java/org/duracloud/account/db/util/security/impl/AnnotationParserImpl.java#L148-L163
143,081
duracloud/management-console
account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java
UserAccessDecisionVoter.getOtherRolesArg
private Set<Role> getOtherRolesArg(Object[] arguments) { if (arguments.length <= NEW_ROLES_INDEX) { log.error("Illegal number of args: " + arguments.length); } Set<Role> roles = new HashSet<Role>(); Object[] rolesArray = (Object[]) arguments[NEW_ROLES_INDEX]; if (null != rolesArray && rolesArray.length > 0) { for (Object role : rolesArray) { roles.add((Role) role); } } return roles; }
java
private Set<Role> getOtherRolesArg(Object[] arguments) { if (arguments.length <= NEW_ROLES_INDEX) { log.error("Illegal number of args: " + arguments.length); } Set<Role> roles = new HashSet<Role>(); Object[] rolesArray = (Object[]) arguments[NEW_ROLES_INDEX]; if (null != rolesArray && rolesArray.length > 0) { for (Object role : rolesArray) { roles.add((Role) role); } } return roles; }
[ "private", "Set", "<", "Role", ">", "getOtherRolesArg", "(", "Object", "[", "]", "arguments", ")", "{", "if", "(", "arguments", ".", "length", "<=", "NEW_ROLES_INDEX", ")", "{", "log", ".", "error", "(", "\"Illegal number of args: \"", "+", "arguments", ".", "length", ")", ";", "}", "Set", "<", "Role", ">", "roles", "=", "new", "HashSet", "<", "Role", ">", "(", ")", ";", "Object", "[", "]", "rolesArray", "=", "(", "Object", "[", "]", ")", "arguments", "[", "NEW_ROLES_INDEX", "]", ";", "if", "(", "null", "!=", "rolesArray", "&&", "rolesArray", ".", "length", ">", "0", ")", "{", "for", "(", "Object", "role", ":", "rolesArray", ")", "{", "roles", ".", "add", "(", "(", "Role", ")", "role", ")", ";", "}", "}", "return", "roles", ";", "}" ]
This method returns roles argument of in the target method invocation.
[ "This", "method", "returns", "roles", "argument", "of", "in", "the", "target", "method", "invocation", "." ]
7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java#L170-L184
143,082
duracloud/management-console
account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java
UserAccessDecisionVoter.getOtherUserIdArg
private Long getOtherUserIdArg(Object[] arguments) { if (arguments.length <= OTHER_USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[OTHER_USER_ID_INDEX]; }
java
private Long getOtherUserIdArg(Object[] arguments) { if (arguments.length <= OTHER_USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[OTHER_USER_ID_INDEX]; }
[ "private", "Long", "getOtherUserIdArg", "(", "Object", "[", "]", "arguments", ")", "{", "if", "(", "arguments", ".", "length", "<=", "OTHER_USER_ID_INDEX", ")", "{", "log", ".", "error", "(", "\"Illegal number of args: \"", "+", "arguments", ".", "length", ")", ";", "}", "return", "(", "Long", ")", "arguments", "[", "OTHER_USER_ID_INDEX", "]", ";", "}" ]
This method returns peer userId argument of the target method invocation.
[ "This", "method", "returns", "peer", "userId", "argument", "of", "the", "target", "method", "invocation", "." ]
7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java#L189-L194
143,083
duracloud/management-console
account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java
UserAccessDecisionVoter.getUserIdArg
private Long getUserIdArg(Object[] arguments) { if (arguments.length <= USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[USER_ID_INDEX]; }
java
private Long getUserIdArg(Object[] arguments) { if (arguments.length <= USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[USER_ID_INDEX]; }
[ "private", "Long", "getUserIdArg", "(", "Object", "[", "]", "arguments", ")", "{", "if", "(", "arguments", ".", "length", "<=", "USER_ID_INDEX", ")", "{", "log", ".", "error", "(", "\"Illegal number of args: \"", "+", "arguments", ".", "length", ")", ";", "}", "return", "(", "Long", ")", "arguments", "[", "USER_ID_INDEX", "]", ";", "}" ]
This method returns userId argument of the target method invocation.
[ "This", "method", "returns", "userId", "argument", "of", "the", "target", "method", "invocation", "." ]
7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java#L199-L204
143,084
duracloud/management-console
account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java
UserAccessDecisionVoter.getAccountIdArg
private Long getAccountIdArg(Object[] arguments) { if (arguments.length <= ACCT_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[ACCT_ID_INDEX]; }
java
private Long getAccountIdArg(Object[] arguments) { if (arguments.length <= ACCT_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[ACCT_ID_INDEX]; }
[ "private", "Long", "getAccountIdArg", "(", "Object", "[", "]", "arguments", ")", "{", "if", "(", "arguments", ".", "length", "<=", "ACCT_ID_INDEX", ")", "{", "log", ".", "error", "(", "\"Illegal number of args: \"", "+", "arguments", ".", "length", ")", ";", "}", "return", "(", "Long", ")", "arguments", "[", "ACCT_ID_INDEX", "]", ";", "}" ]
This method returns acctId argument of the target method invocation.
[ "This", "method", "returns", "acctId", "argument", "of", "the", "target", "method", "invocation", "." ]
7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6
https://github.com/duracloud/management-console/blob/7331015c01f9ac5cc5c0aa8ae9a2a1a77e9f4ac6/account-management-security/src/main/java/org/duracloud/account/security/vote/UserAccessDecisionVoter.java#L216-L221
143,085
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.rgb
public static Expression rgb(Generator generator, FunctionCall input) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2)); }
java
public static Expression rgb(Generator generator, FunctionCall input) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2)); }
[ "public", "static", "Expression", "rgb", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "return", "new", "Color", "(", "input", ".", "getExpectedIntParam", "(", "0", ")", ",", "input", ".", "getExpectedIntParam", "(", "1", ")", ",", "input", ".", "getExpectedIntParam", "(", "2", ")", ")", ";", "}" ]
Creates a color from given RGB values. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Creates", "a", "color", "from", "given", "RGB", "values", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L44-L46
143,086
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.rgba
public static Expression rgba(Generator generator, FunctionCall input) { if (input.getParameters().size() == 4) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2), input.getExpectedFloatParam(3)); } if (input.getParameters().size() == 2) { Color color = input.getExpectedColorParam(0); float newA = input.getExpectedFloatParam(1); return new Color(color.getR(), color.getG(), color.getB(), newA); } throw new IllegalArgumentException("rgba must be called with either 2 or 4 parameters. Function call: " + input); }
java
public static Expression rgba(Generator generator, FunctionCall input) { if (input.getParameters().size() == 4) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2), input.getExpectedFloatParam(3)); } if (input.getParameters().size() == 2) { Color color = input.getExpectedColorParam(0); float newA = input.getExpectedFloatParam(1); return new Color(color.getR(), color.getG(), color.getB(), newA); } throw new IllegalArgumentException("rgba must be called with either 2 or 4 parameters. Function call: " + input); }
[ "public", "static", "Expression", "rgba", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "if", "(", "input", ".", "getParameters", "(", ")", ".", "size", "(", ")", "==", "4", ")", "{", "return", "new", "Color", "(", "input", ".", "getExpectedIntParam", "(", "0", ")", ",", "input", ".", "getExpectedIntParam", "(", "1", ")", ",", "input", ".", "getExpectedIntParam", "(", "2", ")", ",", "input", ".", "getExpectedFloatParam", "(", "3", ")", ")", ";", "}", "if", "(", "input", ".", "getParameters", "(", ")", ".", "size", "(", ")", "==", "2", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "float", "newA", "=", "input", ".", "getExpectedFloatParam", "(", "1", ")", ";", "return", "new", "Color", "(", "color", ".", "getR", "(", ")", ",", "color", ".", "getG", "(", ")", ",", "color", ".", "getB", "(", ")", ",", "newA", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"rgba must be called with either 2 or 4 parameters. Function call: \"", "+", "input", ")", ";", "}" ]
Creates a color from given RGB and alpha values. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Creates", "a", "color", "from", "given", "RGB", "and", "alpha", "values", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L55-L69
143,087
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.adjusthue
public static Expression adjusthue(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int changeInDegrees = input.getExpectedIntParam(1); Color.HSL hsl = color.getHSL(); hsl.setH(hsl.getH() + changeInDegrees); return hsl.getColor(); }
java
public static Expression adjusthue(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int changeInDegrees = input.getExpectedIntParam(1); Color.HSL hsl = color.getHSL(); hsl.setH(hsl.getH() + changeInDegrees); return hsl.getColor(); }
[ "public", "static", "Expression", "adjusthue", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "changeInDegrees", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "Color", ".", "HSL", "hsl", "=", "color", ".", "getHSL", "(", ")", ";", "hsl", ".", "setH", "(", "hsl", ".", "getH", "(", ")", "+", "changeInDegrees", ")", ";", "return", "hsl", ".", "getColor", "(", ")", ";", "}" ]
Adjusts the hue of the given color by the given number of degrees. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Adjusts", "the", "hue", "of", "the", "given", "color", "by", "the", "given", "number", "of", "degrees", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L78-L84
143,088
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.lighten
public static Expression lighten(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeLighteness(color, increase); }
java
public static Expression lighten(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeLighteness(color, increase); }
[ "public", "static", "Expression", "lighten", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "increase", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "return", "changeLighteness", "(", "color", ",", "increase", ")", ";", "}" ]
Increases the lightness of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Increases", "the", "lightness", "of", "the", "given", "color", "by", "N", "percent", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L93-L97
143,089
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.alpha
public static Expression alpha(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); return new Number(color.getA(), String.valueOf(color.getA()), ""); }
java
public static Expression alpha(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); return new Number(color.getA(), String.valueOf(color.getA()), ""); }
[ "public", "static", "Expression", "alpha", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "return", "new", "Number", "(", "color", ".", "getA", "(", ")", ",", "String", ".", "valueOf", "(", "color", ".", "getA", "(", ")", ")", ",", "\"\"", ")", ";", "}" ]
Returns the alpha value of the given color @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Returns", "the", "alpha", "value", "of", "the", "given", "color" ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L106-L109
143,090
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.darken
public static Expression darken(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeLighteness(color, -decrease); }
java
public static Expression darken(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeLighteness(color, -decrease); }
[ "public", "static", "Expression", "darken", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "decrease", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "return", "changeLighteness", "(", "color", ",", "-", "decrease", ")", ";", "}" ]
Decreases the lightness of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Decreases", "the", "lightness", "of", "the", "given", "color", "by", "N", "percent", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L130-L134
143,091
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.saturate
public static Expression saturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeSaturation(color, increase); }
java
public static Expression saturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeSaturation(color, increase); }
[ "public", "static", "Expression", "saturate", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "increase", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "return", "changeSaturation", "(", "color", ",", "increase", ")", ";", "}" ]
Increases the saturation of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Increases", "the", "saturation", "of", "the", "given", "color", "by", "N", "percent", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L143-L147
143,092
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.desaturate
public static Expression desaturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeSaturation(color, -decrease); }
java
public static Expression desaturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeSaturation(color, -decrease); }
[ "public", "static", "Expression", "desaturate", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "int", "decrease", "=", "input", ".", "getExpectedIntParam", "(", "1", ")", ";", "return", "changeSaturation", "(", "color", ",", "-", "decrease", ")", ";", "}" ]
Decreases the saturation of the given color by N percent. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Decreases", "the", "saturation", "of", "the", "given", "color", "by", "N", "percent", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L156-L160
143,093
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.fade_out
@SuppressWarnings("squid:S00100") public static Expression fade_out(Generator generator, FunctionCall input) { return opacify(generator, input); }
java
@SuppressWarnings("squid:S00100") public static Expression fade_out(Generator generator, FunctionCall input) { return opacify(generator, input); }
[ "@", "SuppressWarnings", "(", "\"squid:S00100\"", ")", "public", "static", "Expression", "fade_out", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "return", "opacify", "(", "generator", ",", "input", ")", ";", "}" ]
Decreases the opacity of the given color by the given amount. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Decreases", "the", "opacity", "of", "the", "given", "color", "by", "the", "given", "amount", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L207-L210
143,094
scireum/server-sass
src/main/java/org/serversass/Functions.java
Functions.mix
public static Expression mix(Generator generator, FunctionCall input) { Color color1 = input.getExpectedColorParam(0); Color color2 = input.getExpectedColorParam(1); float weight = input.getParameters().size() > 2 ? input.getExpectedFloatParam(2) : 0.5f; return new Color((int) Math.round(color1.getR() * weight + color2.getR() * (1.0 - weight)), (int) Math.round(color1.getG() * weight + color2.getG() * (1.0 - weight)), (int) Math.round(color1.getB() * weight + color2.getB() * (1.0 - weight)), (float) (color1.getA() * weight + color2.getA() * (1.0 - weight))); }
java
public static Expression mix(Generator generator, FunctionCall input) { Color color1 = input.getExpectedColorParam(0); Color color2 = input.getExpectedColorParam(1); float weight = input.getParameters().size() > 2 ? input.getExpectedFloatParam(2) : 0.5f; return new Color((int) Math.round(color1.getR() * weight + color2.getR() * (1.0 - weight)), (int) Math.round(color1.getG() * weight + color2.getG() * (1.0 - weight)), (int) Math.round(color1.getB() * weight + color2.getB() * (1.0 - weight)), (float) (color1.getA() * weight + color2.getA() * (1.0 - weight))); }
[ "public", "static", "Expression", "mix", "(", "Generator", "generator", ",", "FunctionCall", "input", ")", "{", "Color", "color1", "=", "input", ".", "getExpectedColorParam", "(", "0", ")", ";", "Color", "color2", "=", "input", ".", "getExpectedColorParam", "(", "1", ")", ";", "float", "weight", "=", "input", ".", "getParameters", "(", ")", ".", "size", "(", ")", ">", "2", "?", "input", ".", "getExpectedFloatParam", "(", "2", ")", ":", "0.5f", ";", "return", "new", "Color", "(", "(", "int", ")", "Math", ".", "round", "(", "color1", ".", "getR", "(", ")", "*", "weight", "+", "color2", ".", "getR", "(", ")", "*", "(", "1.0", "-", "weight", ")", ")", ",", "(", "int", ")", "Math", ".", "round", "(", "color1", ".", "getG", "(", ")", "*", "weight", "+", "color2", ".", "getG", "(", ")", "*", "(", "1.0", "-", "weight", ")", ")", ",", "(", "int", ")", "Math", ".", "round", "(", "color1", ".", "getB", "(", ")", "*", "weight", "+", "color2", ".", "getB", "(", ")", "*", "(", "1.0", "-", "weight", ")", ")", ",", "(", "float", ")", "(", "color1", ".", "getA", "(", ")", "*", "weight", "+", "color2", ".", "getA", "(", ")", "*", "(", "1.0", "-", "weight", ")", ")", ")", ";", "}" ]
Calculates the weighted arithmetic mean of two colors. @param generator the surrounding generator @param input the function call to evaluate @return the result of the evaluation
[ "Calculates", "the", "weighted", "arithmetic", "mean", "of", "two", "colors", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Functions.java#L219-L227
143,095
scireum/server-sass
src/main/java/org/serversass/Output.java
Output.lineBreak
public Output lineBreak() throws IOException { writer.write("\n"); if (!skipOptionalOutput) { for (int i = 0; i < indentLevel; i++) { writer.write(indentDepth); } } return this; }
java
public Output lineBreak() throws IOException { writer.write("\n"); if (!skipOptionalOutput) { for (int i = 0; i < indentLevel; i++) { writer.write(indentDepth); } } return this; }
[ "public", "Output", "lineBreak", "(", ")", "throws", "IOException", "{", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "if", "(", "!", "skipOptionalOutput", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "indentLevel", ";", "i", "++", ")", "{", "writer", ".", "write", "(", "indentDepth", ")", ";", "}", "}", "return", "this", ";", "}" ]
Outputs an indented line break in any case. @return the instance itself for fluent method calls @throws IOException in case of an io error in the underlying writer
[ "Outputs", "an", "indented", "line", "break", "in", "any", "case", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Output.java#L78-L86
143,096
scireum/server-sass
src/main/java/org/serversass/ast/Color.java
Color.getHSL
@SuppressWarnings("squid:S1244") public HSL getHSL() { // Convert the RGB values to the range 0-1 double red = r / 255.0; double green = g / 255.0; double blue = b / 255.0; // Find the minimum and maximum values of R, G and B. double min = Math.min(red, Math.min(green, blue)); double max = Math.max(red, Math.max(green, blue)); double delta = max - min; // Now calculate the luminace value by adding the max and min values and divide by 2. double l = (min + max) / 2; // The next step is to find the Saturation. double s = 0; // If the min and max value are the same, it means that there is no saturation. // If all RGB values are equal you have a shade of grey. if (Math.abs(delta) > EPSILON) { // Now we know that there is Saturation we need to do check the level of the Luminance // in order to select the correct formula. if (l < 0.5) { s = delta / (max + min); } else { s = delta / (2.0 - max - min); } } // The Hue formula is depending on what RGB color channel is the max value. double h = 0; if (delta > 0) { if (red == max) { h = (green - blue) / delta; } else if (green == max) { h = ((blue - red) / delta) + 2.0; } else { h = ((red - green) / delta) + 4.0; } } // The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle // If Hue becomes negative you need to add 360 to, because a circle has 360 degrees. h = h * 60; return new HSL((int) Math.round(h), s, l); }
java
@SuppressWarnings("squid:S1244") public HSL getHSL() { // Convert the RGB values to the range 0-1 double red = r / 255.0; double green = g / 255.0; double blue = b / 255.0; // Find the minimum and maximum values of R, G and B. double min = Math.min(red, Math.min(green, blue)); double max = Math.max(red, Math.max(green, blue)); double delta = max - min; // Now calculate the luminace value by adding the max and min values and divide by 2. double l = (min + max) / 2; // The next step is to find the Saturation. double s = 0; // If the min and max value are the same, it means that there is no saturation. // If all RGB values are equal you have a shade of grey. if (Math.abs(delta) > EPSILON) { // Now we know that there is Saturation we need to do check the level of the Luminance // in order to select the correct formula. if (l < 0.5) { s = delta / (max + min); } else { s = delta / (2.0 - max - min); } } // The Hue formula is depending on what RGB color channel is the max value. double h = 0; if (delta > 0) { if (red == max) { h = (green - blue) / delta; } else if (green == max) { h = ((blue - red) / delta) + 2.0; } else { h = ((red - green) / delta) + 4.0; } } // The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle // If Hue becomes negative you need to add 360 to, because a circle has 360 degrees. h = h * 60; return new HSL((int) Math.round(h), s, l); }
[ "@", "SuppressWarnings", "(", "\"squid:S1244\"", ")", "public", "HSL", "getHSL", "(", ")", "{", "// Convert the RGB values to the range 0-1", "double", "red", "=", "r", "/", "255.0", ";", "double", "green", "=", "g", "/", "255.0", ";", "double", "blue", "=", "b", "/", "255.0", ";", "// Find the minimum and maximum values of R, G and B.", "double", "min", "=", "Math", ".", "min", "(", "red", ",", "Math", ".", "min", "(", "green", ",", "blue", ")", ")", ";", "double", "max", "=", "Math", ".", "max", "(", "red", ",", "Math", ".", "max", "(", "green", ",", "blue", ")", ")", ";", "double", "delta", "=", "max", "-", "min", ";", "// Now calculate the luminace value by adding the max and min values and divide by 2.", "double", "l", "=", "(", "min", "+", "max", ")", "/", "2", ";", "// The next step is to find the Saturation.", "double", "s", "=", "0", ";", "// If the min and max value are the same, it means that there is no saturation.", "// If all RGB values are equal you have a shade of grey.", "if", "(", "Math", ".", "abs", "(", "delta", ")", ">", "EPSILON", ")", "{", "// Now we know that there is Saturation we need to do check the level of the Luminance", "// in order to select the correct formula.", "if", "(", "l", "<", "0.5", ")", "{", "s", "=", "delta", "/", "(", "max", "+", "min", ")", ";", "}", "else", "{", "s", "=", "delta", "/", "(", "2.0", "-", "max", "-", "min", ")", ";", "}", "}", "// The Hue formula is depending on what RGB color channel is the max value.", "double", "h", "=", "0", ";", "if", "(", "delta", ">", "0", ")", "{", "if", "(", "red", "==", "max", ")", "{", "h", "=", "(", "green", "-", "blue", ")", "/", "delta", ";", "}", "else", "if", "(", "green", "==", "max", ")", "{", "h", "=", "(", "(", "blue", "-", "red", ")", "/", "delta", ")", "+", "2.0", ";", "}", "else", "{", "h", "=", "(", "(", "red", "-", "green", ")", "/", "delta", ")", "+", "4.0", ";", "}", "}", "// The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle", "// If Hue becomes negative you need to add 360 to, because a circle has 360 degrees.", "h", "=", "h", "*", "60", ";", "return", "new", "HSL", "(", "(", "int", ")", "Math", ".", "round", "(", "h", ")", ",", "s", ",", "l", ")", ";", "}" ]
Computes the HSL value form the stored RGB values. @return a triple containing the hue, saturation and lightness
[ "Computes", "the", "HSL", "value", "form", "the", "stored", "RGB", "values", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/ast/Color.java#L238-L285
143,097
scireum/server-sass
src/main/java/org/serversass/ast/Section.java
Section.getMediaQuery
public String getMediaQuery(Scope scope, Generator gen) { StringBuilder sb = new StringBuilder(); for (Expression expr : mediaQueries) { if (sb.length() > 0) { sb.append(" and "); } sb.append(expr.eval(scope, gen)); } return sb.toString(); }
java
public String getMediaQuery(Scope scope, Generator gen) { StringBuilder sb = new StringBuilder(); for (Expression expr : mediaQueries) { if (sb.length() > 0) { sb.append(" and "); } sb.append(expr.eval(scope, gen)); } return sb.toString(); }
[ "public", "String", "getMediaQuery", "(", "Scope", "scope", ",", "Generator", "gen", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Expression", "expr", ":", "mediaQueries", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\" and \"", ")", ";", "}", "sb", ".", "append", "(", "expr", ".", "eval", "(", "scope", ",", "gen", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Compiles the effective media query of this section into a string @param scope the scope used to resolve variables @param gen the generator used to evaluate functions @return the effective media query as string or "" if there is no media query
[ "Compiles", "the", "effective", "media", "query", "of", "this", "section", "into", "a", "string" ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/ast/Section.java#L128-L137
143,098
scireum/server-sass
src/main/java/org/serversass/ast/Section.java
Section.getSelectorString
public String getSelectorString() { StringBuilder sb = new StringBuilder(); for (List<String> selector : selectors) { if (sb.length() > 0) { sb.append(","); } for (String s : selector) { if (sb.length() > 0) { sb.append(" "); } sb.append(s); } } return sb.toString(); }
java
public String getSelectorString() { StringBuilder sb = new StringBuilder(); for (List<String> selector : selectors) { if (sb.length() > 0) { sb.append(","); } for (String s : selector) { if (sb.length() > 0) { sb.append(" "); } sb.append(s); } } return sb.toString(); }
[ "public", "String", "getSelectorString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "List", "<", "String", ">", "selector", ":", "selectors", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\",\"", ")", ";", "}", "for", "(", "String", "s", ":", "selector", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\" \"", ")", ";", "}", "sb", ".", "append", "(", "s", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Compiles the effective selector string. @return a string containing all selector chains for this section
[ "Compiles", "the", "effective", "selector", "string", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/ast/Section.java#L144-L158
143,099
scireum/server-sass
src/main/java/org/serversass/Generator.java
Generator.importStylesheet
public void importStylesheet(Stylesheet sheet) { if (sheet == null) { return; } if (importedSheets.contains(sheet.getName())) { return; } importedSheets.add(sheet.getName()); for (String imp : sheet.getImports()) { importStylesheet(imp); } for (Mixin mix : sheet.getMixins()) { mixins.put(mix.getName(), mix); } for (Variable var : sheet.getVariables()) { if (!scope.has(var.getName()) || !var.isDefaultValue()) { scope.set(var.getName(), var.getValue()); } else { debug("Skipping redundant variable definition: '" + var + "'"); } } for (Section section : sheet.getSections()) { List<Section> stack = new ArrayList<>(); expand(null, section, stack); } }
java
public void importStylesheet(Stylesheet sheet) { if (sheet == null) { return; } if (importedSheets.contains(sheet.getName())) { return; } importedSheets.add(sheet.getName()); for (String imp : sheet.getImports()) { importStylesheet(imp); } for (Mixin mix : sheet.getMixins()) { mixins.put(mix.getName(), mix); } for (Variable var : sheet.getVariables()) { if (!scope.has(var.getName()) || !var.isDefaultValue()) { scope.set(var.getName(), var.getValue()); } else { debug("Skipping redundant variable definition: '" + var + "'"); } } for (Section section : sheet.getSections()) { List<Section> stack = new ArrayList<>(); expand(null, section, stack); } }
[ "public", "void", "importStylesheet", "(", "Stylesheet", "sheet", ")", "{", "if", "(", "sheet", "==", "null", ")", "{", "return", ";", "}", "if", "(", "importedSheets", ".", "contains", "(", "sheet", ".", "getName", "(", ")", ")", ")", "{", "return", ";", "}", "importedSheets", ".", "add", "(", "sheet", ".", "getName", "(", ")", ")", ";", "for", "(", "String", "imp", ":", "sheet", ".", "getImports", "(", ")", ")", "{", "importStylesheet", "(", "imp", ")", ";", "}", "for", "(", "Mixin", "mix", ":", "sheet", ".", "getMixins", "(", ")", ")", "{", "mixins", ".", "put", "(", "mix", ".", "getName", "(", ")", ",", "mix", ")", ";", "}", "for", "(", "Variable", "var", ":", "sheet", ".", "getVariables", "(", ")", ")", "{", "if", "(", "!", "scope", ".", "has", "(", "var", ".", "getName", "(", ")", ")", "||", "!", "var", ".", "isDefaultValue", "(", ")", ")", "{", "scope", ".", "set", "(", "var", ".", "getName", "(", ")", ",", "var", ".", "getValue", "(", ")", ")", ";", "}", "else", "{", "debug", "(", "\"Skipping redundant variable definition: '\"", "+", "var", "+", "\"'\"", ")", ";", "}", "}", "for", "(", "Section", "section", ":", "sheet", ".", "getSections", "(", ")", ")", "{", "List", "<", "Section", ">", "stack", "=", "new", "ArrayList", "<>", "(", ")", ";", "expand", "(", "null", ",", "section", ",", "stack", ")", ";", "}", "}" ]
Imports an already parsed stylesheet. @param sheet the stylesheet to import
[ "Imports", "an", "already", "parsed", "stylesheet", "." ]
e74af983567f10c43420d70cd31165dd080ba8fc
https://github.com/scireum/server-sass/blob/e74af983567f10c43420d70cd31165dd080ba8fc/src/main/java/org/serversass/Generator.java#L197-L222