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
36,300
bremersee/comparator
src/main/java/org/bremersee/comparator/ObjectComparatorFactory.java
ObjectComparatorFactory.newInstance
public static ObjectComparatorFactory newInstance( final String objectComparatorFactoryClassName) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (ObjectComparatorFactory) Class.forName(objectComparatorFactoryClassName).newInstance(); }
java
public static ObjectComparatorFactory newInstance( final String objectComparatorFactoryClassName) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (ObjectComparatorFactory) Class.forName(objectComparatorFactoryClassName).newInstance(); }
[ "public", "static", "ObjectComparatorFactory", "newInstance", "(", "final", "String", "objectComparatorFactoryClassName", ")", "throws", "InstantiationException", ",", "IllegalAccessException", ",", "ClassNotFoundException", "{", "return", "(", "ObjectComparatorFactory", ")", ...
Create a new instance of a the specified factory class. @param objectComparatorFactoryClassName the factory class @return a new instance of a the specified factory @throws InstantiationException if creation of the factory fails @throws IllegalAccessException if creation of the factory fails @throws ClassNotFoundException if creation of the factory fails
[ "Create", "a", "new", "instance", "of", "a", "the", "specified", "factory", "class", "." ]
6958e6e28a62589106705062f8ffc201a87d9b2a
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ObjectComparatorFactory.java#L47-L51
36,301
bremersee/comparator
src/main/java/org/bremersee/comparator/ObjectComparatorFactory.java
ObjectComparatorFactory.newInstance
public static ObjectComparatorFactory newInstance(final String objectComparatorFactoryClassName, final ClassLoader classLoader) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (ObjectComparatorFactory) Class .forName(objectComparatorFactoryClassName, true, classLoader) .newInstance(); }
java
public static ObjectComparatorFactory newInstance(final String objectComparatorFactoryClassName, final ClassLoader classLoader) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (ObjectComparatorFactory) Class .forName(objectComparatorFactoryClassName, true, classLoader) .newInstance(); }
[ "public", "static", "ObjectComparatorFactory", "newInstance", "(", "final", "String", "objectComparatorFactoryClassName", ",", "final", "ClassLoader", "classLoader", ")", "throws", "InstantiationException", ",", "IllegalAccessException", ",", "ClassNotFoundException", "{", "r...
Create a new instance of a the specified factory class by using the specified class loader. @param objectComparatorFactoryClassName the factory class @param classLoader the class loader @return a new instance of a the specified factory @throws InstantiationException if creation of the factory fails @throws IllegalAccessException if creation of the factory fails @throws ClassNotFoundException if creation of the factory fails
[ "Create", "a", "new", "instance", "of", "a", "the", "specified", "factory", "class", "by", "using", "the", "specified", "class", "loader", "." ]
6958e6e28a62589106705062f8ffc201a87d9b2a
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ObjectComparatorFactory.java#L63-L69
36,302
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.defaultInitializer
public static Initializer defaultInitializer() { return newInitializer() .setCloseConcurrency(0) .setTestOnLogicalOpen(false) .setTestOnLogicalClose(false) .setIncompleteTransactionOnClosePolicy(ConnectionPoolConnection.IncompleteTransactionPolicy.REPORT) .setOpenStatementOnClosePolicy(ConnectionPoolConnection.OpenStatementPolicy.REPORT) .setForceRealClosePolicy(ConnectionPoolConnection.ForceRealClosePolicy.CONNECTION_WITH_LIMIT) .setActivityTimeoutPolicy(ConnectionPoolConnection.ActivityTimeoutPolicy.LOG) .setCloseTimeLimitMillis(10 * 1000L) .setActiveTimeout(60, TimeUnit.SECONDS) .setConnectionLifetime(15, TimeUnit.MINUTES) .setMaxConcurrentReconnects(2) .setMaxReconnectDelay(1, TimeUnit.MINUTES) .setActiveTimeoutMonitorFrequency(30, TimeUnit.SECONDS); }
java
public static Initializer defaultInitializer() { return newInitializer() .setCloseConcurrency(0) .setTestOnLogicalOpen(false) .setTestOnLogicalClose(false) .setIncompleteTransactionOnClosePolicy(ConnectionPoolConnection.IncompleteTransactionPolicy.REPORT) .setOpenStatementOnClosePolicy(ConnectionPoolConnection.OpenStatementPolicy.REPORT) .setForceRealClosePolicy(ConnectionPoolConnection.ForceRealClosePolicy.CONNECTION_WITH_LIMIT) .setActivityTimeoutPolicy(ConnectionPoolConnection.ActivityTimeoutPolicy.LOG) .setCloseTimeLimitMillis(10 * 1000L) .setActiveTimeout(60, TimeUnit.SECONDS) .setConnectionLifetime(15, TimeUnit.MINUTES) .setMaxConcurrentReconnects(2) .setMaxReconnectDelay(1, TimeUnit.MINUTES) .setActiveTimeoutMonitorFrequency(30, TimeUnit.SECONDS); }
[ "public", "static", "Initializer", "defaultInitializer", "(", ")", "{", "return", "newInitializer", "(", ")", ".", "setCloseConcurrency", "(", "0", ")", ".", "setTestOnLogicalOpen", "(", "false", ")", ".", "setTestOnLogicalClose", "(", "false", ")", ".", "setInc...
Creates a segment initializer with default values. @return The segment initializer with default values.
[ "Creates", "a", "segment", "initializer", "with", "default", "values", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L225-L240
36,303
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.reopen
private void reopen(final ConnectionPoolConnection conn) { if(isActive) { if(conn.reopenAttempts == 0) { conn.reopenAttempts++; reopenService.execute(new Reopener(conn)); } else { long delayMillis = 100L * conn.reopenAttempts; if(delayMillis > maxReconnectDelayMillis) { delayMillis = maxReconnectDelayMillis; } conn.reopenAttempts++; reopenService.schedule(new Reopener(conn), delayMillis, TimeUnit.MILLISECONDS); } } }
java
private void reopen(final ConnectionPoolConnection conn) { if(isActive) { if(conn.reopenAttempts == 0) { conn.reopenAttempts++; reopenService.execute(new Reopener(conn)); } else { long delayMillis = 100L * conn.reopenAttempts; if(delayMillis > maxReconnectDelayMillis) { delayMillis = maxReconnectDelayMillis; } conn.reopenAttempts++; reopenService.schedule(new Reopener(conn), delayMillis, TimeUnit.MILLISECONDS); } } }
[ "private", "void", "reopen", "(", "final", "ConnectionPoolConnection", "conn", ")", "{", "if", "(", "isActive", ")", "{", "if", "(", "conn", ".", "reopenAttempts", "==", "0", ")", "{", "conn", ".", "reopenAttempts", "++", ";", "reopenService", ".", "execut...
Schedule connection reopen. @param conn The connection.
[ "Schedule", "connection", "reopen", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L722-L737
36,304
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.close
final void close(final ConnectionPoolConnection conn) { if(closeQueue != null) { closeQueue.add(conn); } else { closer.close(conn); } }
java
final void close(final ConnectionPoolConnection conn) { if(closeQueue != null) { closeQueue.add(conn); } else { closer.close(conn); } }
[ "final", "void", "close", "(", "final", "ConnectionPoolConnection", "conn", ")", "{", "if", "(", "closeQueue", "!=", "null", ")", "{", "closeQueue", ".", "add", "(", "conn", ")", ";", "}", "else", "{", "closer", ".", "close", "(", "conn", ")", ";", "...
Adds a connection to the close queue. @param conn The connection.
[ "Adds", "a", "connection", "to", "the", "close", "queue", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L923-L929
36,305
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.getPassword
final String getPassword() { if(passwordSource == null) { return dbConnection.password; } else { String usePassword = passwordSource.getPassword(dbConnection.name); if(!Strings.isNullOrEmpty(usePassword)) { return usePassword; } else { usePassword = passwordSource.getPassword(dbConnection.connectionString, dbConnection.user); return !Strings.isNullOrEmpty(usePassword) ? usePassword : dbConnection.password; } } }
java
final String getPassword() { if(passwordSource == null) { return dbConnection.password; } else { String usePassword = passwordSource.getPassword(dbConnection.name); if(!Strings.isNullOrEmpty(usePassword)) { return usePassword; } else { usePassword = passwordSource.getPassword(dbConnection.connectionString, dbConnection.user); return !Strings.isNullOrEmpty(usePassword) ? usePassword : dbConnection.password; } } }
[ "final", "String", "getPassword", "(", ")", "{", "if", "(", "passwordSource", "==", "null", ")", "{", "return", "dbConnection", ".", "password", ";", "}", "else", "{", "String", "usePassword", "=", "passwordSource", ".", "getPassword", "(", "dbConnection", "...
Gets the password for connection creation. @return The password.
[ "Gets", "the", "password", "for", "connection", "creation", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1159-L1171
36,306
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.createRealConnection
private Connection createRealConnection(final long timeoutMillis) throws SQLException { if(timeoutMillis < 1L) { String usePassword = getPassword(); Connection conn = dbConnection.datasource == null ? DriverManager.getConnection(dbConnection.connectionString, dbConnection.user, usePassword) : dbConnection.datasource.getConnection(dbConnection.user, usePassword); if(conn != null) { return conn; } else { throw new SQLException("Unable to create connection: driver/datasource returned [null]"); } } else { try { return connectionTimeLimiter.callWithTimeout(() -> createRealConnection(0L), timeoutMillis, TimeUnit.MILLISECONDS); } catch(UncheckedTimeoutException ute) { throw new SQLException("Unable to create connection after waiting " + timeoutMillis + " ms"); } catch(Exception e) { throw new SQLException("Unable to create connection: driver/datasource", e); } } }
java
private Connection createRealConnection(final long timeoutMillis) throws SQLException { if(timeoutMillis < 1L) { String usePassword = getPassword(); Connection conn = dbConnection.datasource == null ? DriverManager.getConnection(dbConnection.connectionString, dbConnection.user, usePassword) : dbConnection.datasource.getConnection(dbConnection.user, usePassword); if(conn != null) { return conn; } else { throw new SQLException("Unable to create connection: driver/datasource returned [null]"); } } else { try { return connectionTimeLimiter.callWithTimeout(() -> createRealConnection(0L), timeoutMillis, TimeUnit.MILLISECONDS); } catch(UncheckedTimeoutException ute) { throw new SQLException("Unable to create connection after waiting " + timeoutMillis + " ms"); } catch(Exception e) { throw new SQLException("Unable to create connection: driver/datasource", e); } } }
[ "private", "Connection", "createRealConnection", "(", "final", "long", "timeoutMillis", ")", "throws", "SQLException", "{", "if", "(", "timeoutMillis", "<", "1L", ")", "{", "String", "usePassword", "=", "getPassword", "(", ")", ";", "Connection", "conn", "=", ...
Creates a real database connection, failing if one is not obtained in the specified time. @param timeoutMillis The timeout in milliseconds. @return The connection. @throws SQLException on connection problem or timeout waiting for connection.
[ "Creates", "a", "real", "database", "connection", "failing", "if", "one", "is", "not", "obtained", "in", "the", "specified", "time", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1179-L1204
36,307
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.activate
final void activate() throws SQLException { for(ConnectionPoolConnection conn : connections) { conn.forceRealClose(); conn.realOpen(); conn.logicalClose(true); //Tests the connection } if(closeQueue != null) { closeQueue.clear(); } availableQueue.clear(); reopenExecutor.getQueue().clear(); List<ConnectionPoolConnection> connections = Lists.newArrayListWithCapacity(this.connections.length); for(ConnectionPoolConnection connection : this.connections) { connections.add(connection); connection.state.set(ConnectionPoolConnection.STATE_AVAILABLE); } isActive = true; stats.activate(); availableQueue.addAll(connections); }
java
final void activate() throws SQLException { for(ConnectionPoolConnection conn : connections) { conn.forceRealClose(); conn.realOpen(); conn.logicalClose(true); //Tests the connection } if(closeQueue != null) { closeQueue.clear(); } availableQueue.clear(); reopenExecutor.getQueue().clear(); List<ConnectionPoolConnection> connections = Lists.newArrayListWithCapacity(this.connections.length); for(ConnectionPoolConnection connection : this.connections) { connections.add(connection); connection.state.set(ConnectionPoolConnection.STATE_AVAILABLE); } isActive = true; stats.activate(); availableQueue.addAll(connections); }
[ "final", "void", "activate", "(", ")", "throws", "SQLException", "{", "for", "(", "ConnectionPoolConnection", "conn", ":", "connections", ")", "{", "conn", ".", "forceRealClose", "(", ")", ";", "conn", ".", "realOpen", "(", ")", ";", "conn", ".", "logicalC...
Activates the segment by opening and testing all connections. @throws SQLException if connections could not be created.
[ "Activates", "the", "segment", "by", "opening", "and", "testing", "all", "connections", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1210-L1233
36,308
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.isIdle
final boolean isIdle() { for(ConnectionPoolConnection conn : connections) { if(conn.state.get() == ConnectionPoolConnection.STATE_OPEN) { return false; } } return true; }
java
final boolean isIdle() { for(ConnectionPoolConnection conn : connections) { if(conn.state.get() == ConnectionPoolConnection.STATE_OPEN) { return false; } } return true; }
[ "final", "boolean", "isIdle", "(", ")", "{", "for", "(", "ConnectionPoolConnection", "conn", ":", "connections", ")", "{", "if", "(", "conn", ".", "state", ".", "get", "(", ")", "==", "ConnectionPoolConnection", ".", "STATE_OPEN", ")", "{", "return", "fals...
Determine if this segment is currently idle. @return Is the segment idle?
[ "Determine", "if", "this", "segment", "is", "currently", "idle", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1239-L1246
36,309
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.deactivateNow
final void deactivateNow() { isActive = false; stats.deactivate(); availableQueue.clear(); reopenExecutor.getQueue().clear(); for(ConnectionPoolConnection conn : connections) { conn.forceRealClose(); conn.state.set(ConnectionPoolConnection.STATE_DISCONNECTED); } }
java
final void deactivateNow() { isActive = false; stats.deactivate(); availableQueue.clear(); reopenExecutor.getQueue().clear(); for(ConnectionPoolConnection conn : connections) { conn.forceRealClose(); conn.state.set(ConnectionPoolConnection.STATE_DISCONNECTED); } }
[ "final", "void", "deactivateNow", "(", ")", "{", "isActive", "=", "false", ";", "stats", ".", "deactivate", "(", ")", ";", "availableQueue", ".", "clear", "(", ")", ";", "reopenExecutor", ".", "getQueue", "(", ")", ".", "clear", "(", ")", ";", "for", ...
Deactivates the pool immediately - real-closing all connections out from under the logical connections.
[ "Deactivates", "the", "pool", "immediately", "-", "real", "-", "closing", "all", "connections", "out", "from", "under", "the", "logical", "connections", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1301-L1310
36,310
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.getActiveConnectionCount
public final int getActiveConnectionCount() { if(!isActive) { return 0; } int count = 0; for(ConnectionPoolConnection conn : connections) { if(conn.state.get() != ConnectionPoolConnection.STATE_AVAILABLE) { count++; } } return count; }
java
public final int getActiveConnectionCount() { if(!isActive) { return 0; } int count = 0; for(ConnectionPoolConnection conn : connections) { if(conn.state.get() != ConnectionPoolConnection.STATE_AVAILABLE) { count++; } } return count; }
[ "public", "final", "int", "getActiveConnectionCount", "(", ")", "{", "if", "(", "!", "isActive", ")", "{", "return", "0", ";", "}", "int", "count", "=", "0", ";", "for", "(", "ConnectionPoolConnection", "conn", ":", "connections", ")", "{", "if", "(", ...
Gets the number of active connections. @return The number of active connections.
[ "Gets", "the", "number", "of", "active", "connections", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1324-L1338
36,311
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java
ConnectionPoolSegment.logError
void logError(final String message) { if(logger != null) { try { StringBuilder buf = new StringBuilder(name); buf.append(":"); buf.append(message); logger.error(buf.toString()); } catch(Throwable t) { //Ignore - logging should not kill anything } } }
java
void logError(final String message) { if(logger != null) { try { StringBuilder buf = new StringBuilder(name); buf.append(":"); buf.append(message); logger.error(buf.toString()); } catch(Throwable t) { //Ignore - logging should not kill anything } } }
[ "void", "logError", "(", "final", "String", "message", ")", "{", "if", "(", "logger", "!=", "null", ")", "{", "try", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "name", ")", ";", "buf", ".", "append", "(", "\":\"", ")", ";", "buf",...
Logs an error message. @param message The message.
[ "Logs", "an", "error", "message", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolSegment.java#L1464-L1475
36,312
attribyte/acp
src/main/java/org/attribyte/sql/pool/Util.java
Util.getStack
static final String getStack(final boolean filter) { StringBuilder buf = new StringBuilder(); StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for(int i = 2; i < stack.length; i++) { if(!filter) { buf.append(stack[i].toString()); buf.append(NEW_LINE); } else { String s = stack[i].toString(); if(!s.startsWith("org.attribyte.sql.pool")) { buf.append(s); buf.append(NEW_LINE); } } } return buf.toString(); }
java
static final String getStack(final boolean filter) { StringBuilder buf = new StringBuilder(); StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for(int i = 2; i < stack.length; i++) { if(!filter) { buf.append(stack[i].toString()); buf.append(NEW_LINE); } else { String s = stack[i].toString(); if(!s.startsWith("org.attribyte.sql.pool")) { buf.append(s); buf.append(NEW_LINE); } } } return buf.toString(); }
[ "static", "final", "String", "getStack", "(", "final", "boolean", "filter", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "StackTraceElement", "[", "]", "stack", "=", "Thread", ".", "currentThread", "(", ")", ".", "getStackTra...
Gets the current stack as a string. @param filter Should calls from the pool be filtered? @return The stack as a string.
[ "Gets", "the", "current", "stack", "as", "a", "string", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/Util.java#L97-L113
36,313
attribyte/acp
src/main/java/org/attribyte/sql/pool/Util.java
Util.createThreadFactoryBuilder
static ThreadFactory createThreadFactoryBuilder(final String baseName, final String componentName) { StringBuilder buf = new StringBuilder("ACP:"); if(!Strings.isNullOrEmpty(baseName)) { buf.append(baseName).append(":").append(componentName); } else { buf.append(componentName); } buf.append("-Thread-%d"); return new ThreadFactoryBuilder().setNameFormat(buf.toString()).build(); }
java
static ThreadFactory createThreadFactoryBuilder(final String baseName, final String componentName) { StringBuilder buf = new StringBuilder("ACP:"); if(!Strings.isNullOrEmpty(baseName)) { buf.append(baseName).append(":").append(componentName); } else { buf.append(componentName); } buf.append("-Thread-%d"); return new ThreadFactoryBuilder().setNameFormat(buf.toString()).build(); }
[ "static", "ThreadFactory", "createThreadFactoryBuilder", "(", "final", "String", "baseName", ",", "final", "String", "componentName", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "\"ACP:\"", ")", ";", "if", "(", "!", "Strings", ".", "isNul...
Creates a thread factory builder. @param baseName The (optional) base name. @param componentName The (required) component name. @return The thread factory.
[ "Creates", "a", "thread", "factory", "builder", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/Util.java#L121-L132
36,314
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.uniquePrefixSet
static final Set<String> uniquePrefixSet(final Config config) { Set<String> prefixSet = Sets.newHashSet(); for(Map.Entry<String, ConfigValue> entry : config.entrySet()) { String key = entry.getKey(); int index = key.indexOf('.'); if(index > 0) { String prefix = key.substring(0, index); prefixSet.add(prefix); } } return prefixSet; }
java
static final Set<String> uniquePrefixSet(final Config config) { Set<String> prefixSet = Sets.newHashSet(); for(Map.Entry<String, ConfigValue> entry : config.entrySet()) { String key = entry.getKey(); int index = key.indexOf('.'); if(index > 0) { String prefix = key.substring(0, index); prefixSet.add(prefix); } } return prefixSet; }
[ "static", "final", "Set", "<", "String", ">", "uniquePrefixSet", "(", "final", "Config", "config", ")", "{", "Set", "<", "String", ">", "prefixSet", "=", "Sets", ".", "newHashSet", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "...
Gets all available keys in the config. @param config The config. @return The keys.
[ "Gets", "all", "available", "keys", "in", "the", "config", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L95-L108
36,315
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.segmentFromConfig
static final ConnectionPoolSegment.Initializer segmentFromConfig(String poolName, String segmentName, final Config config, ConnectionPoolSegment.Initializer initializer, Map<String, JDBConnection> connectionMap) throws InitializationException { initializer.setName(poolName + "." + segmentName); initializer.setSize(getInt(config, "size", 1)); initializer.setCloseConcurrency(getInt(config, "closeConcurrency", 0)); initializer.setTestOnLogicalOpen(getString(config, "testOnLogicalOpen", "false").equalsIgnoreCase("true")); initializer.setTestOnLogicalClose(getString(config, "testOnLogicalClose", "false").equalsIgnoreCase("true")); String incompleteTransactionPolicy = getString(config, "incompleteTransactionPolicy"); initializer.setIncompleteTransactionOnClosePolicy( ConnectionPoolConnection.IncompleteTransactionPolicy.fromString(incompleteTransactionPolicy, ConnectionPoolConnection.IncompleteTransactionPolicy.REPORT) ); String openStatementPolicy = getString(config, "openStatementPolicy"); initializer.setOpenStatementOnClosePolicy( ConnectionPoolConnection.OpenStatementPolicy.fromString(openStatementPolicy, ConnectionPoolConnection.OpenStatementPolicy.SILENT) ); String forceRealClosePolicy = getString(config, "forceRealClosePolicy"); initializer.setForceRealClosePolicy( ConnectionPoolConnection.ForceRealClosePolicy.fromString(forceRealClosePolicy, ConnectionPoolConnection.ForceRealClosePolicy.CONNECTION) ); String activityTimeoutPolicy = getString(config, "activityTimeoutPolicy"); initializer.setActivityTimeoutPolicy( ConnectionPoolConnection.ActivityTimeoutPolicy.fromString(activityTimeoutPolicy, ConnectionPoolConnection.ActivityTimeoutPolicy.LOG) ); initializer.setCloseTimeLimitMillis(getMilliseconds(config, "closeTimeLimit")); String connectionName = getString(config, "connectionName", ""); JDBConnection conn = null; if(connectionName.length() > 0) { conn = connectionMap.get(connectionName); if(conn == null) { throw new InitializationException("No connection defined with name '" + connectionName + "'"); } } if(conn == null && !initializer.hasConnection()) { throw new InitializationException("A 'connectionName' must be specified for segment, '" + segmentName + "'"); } else if(conn != null) { initializer.setConnection(conn); } initializer.setAcquireTimeout(getMilliseconds(config, "acquireTimeout"), TimeUnit.MILLISECONDS); initializer.setActiveTimeout(getMilliseconds(config, "activeTimeout"), TimeUnit.MILLISECONDS); initializer.setConnectionLifetime(getMilliseconds(config, "connectionLifetime"), TimeUnit.MILLISECONDS); initializer.setIdleTimeBeforeShutdown(getMilliseconds(config, "idleTimeBeforeShutdown"), TimeUnit.MILLISECONDS); initializer.setMinActiveTime(getMilliseconds(config, "minActiveTime"), TimeUnit.MILLISECONDS); initializer.setMaxConcurrentReconnects(getInt(config, "reconnectConcurrency", 0)); initializer.setMaxReconnectDelay(getMilliseconds(config, "reconnectMaxWaitTime"), TimeUnit.MILLISECONDS); initializer.setActiveTimeoutMonitorFrequency(getMilliseconds(config, "activeTimeoutMonitorFrequency"), TimeUnit.MILLISECONDS); return initializer; }
java
static final ConnectionPoolSegment.Initializer segmentFromConfig(String poolName, String segmentName, final Config config, ConnectionPoolSegment.Initializer initializer, Map<String, JDBConnection> connectionMap) throws InitializationException { initializer.setName(poolName + "." + segmentName); initializer.setSize(getInt(config, "size", 1)); initializer.setCloseConcurrency(getInt(config, "closeConcurrency", 0)); initializer.setTestOnLogicalOpen(getString(config, "testOnLogicalOpen", "false").equalsIgnoreCase("true")); initializer.setTestOnLogicalClose(getString(config, "testOnLogicalClose", "false").equalsIgnoreCase("true")); String incompleteTransactionPolicy = getString(config, "incompleteTransactionPolicy"); initializer.setIncompleteTransactionOnClosePolicy( ConnectionPoolConnection.IncompleteTransactionPolicy.fromString(incompleteTransactionPolicy, ConnectionPoolConnection.IncompleteTransactionPolicy.REPORT) ); String openStatementPolicy = getString(config, "openStatementPolicy"); initializer.setOpenStatementOnClosePolicy( ConnectionPoolConnection.OpenStatementPolicy.fromString(openStatementPolicy, ConnectionPoolConnection.OpenStatementPolicy.SILENT) ); String forceRealClosePolicy = getString(config, "forceRealClosePolicy"); initializer.setForceRealClosePolicy( ConnectionPoolConnection.ForceRealClosePolicy.fromString(forceRealClosePolicy, ConnectionPoolConnection.ForceRealClosePolicy.CONNECTION) ); String activityTimeoutPolicy = getString(config, "activityTimeoutPolicy"); initializer.setActivityTimeoutPolicy( ConnectionPoolConnection.ActivityTimeoutPolicy.fromString(activityTimeoutPolicy, ConnectionPoolConnection.ActivityTimeoutPolicy.LOG) ); initializer.setCloseTimeLimitMillis(getMilliseconds(config, "closeTimeLimit")); String connectionName = getString(config, "connectionName", ""); JDBConnection conn = null; if(connectionName.length() > 0) { conn = connectionMap.get(connectionName); if(conn == null) { throw new InitializationException("No connection defined with name '" + connectionName + "'"); } } if(conn == null && !initializer.hasConnection()) { throw new InitializationException("A 'connectionName' must be specified for segment, '" + segmentName + "'"); } else if(conn != null) { initializer.setConnection(conn); } initializer.setAcquireTimeout(getMilliseconds(config, "acquireTimeout"), TimeUnit.MILLISECONDS); initializer.setActiveTimeout(getMilliseconds(config, "activeTimeout"), TimeUnit.MILLISECONDS); initializer.setConnectionLifetime(getMilliseconds(config, "connectionLifetime"), TimeUnit.MILLISECONDS); initializer.setIdleTimeBeforeShutdown(getMilliseconds(config, "idleTimeBeforeShutdown"), TimeUnit.MILLISECONDS); initializer.setMinActiveTime(getMilliseconds(config, "minActiveTime"), TimeUnit.MILLISECONDS); initializer.setMaxConcurrentReconnects(getInt(config, "reconnectConcurrency", 0)); initializer.setMaxReconnectDelay(getMilliseconds(config, "reconnectMaxWaitTime"), TimeUnit.MILLISECONDS); initializer.setActiveTimeoutMonitorFrequency(getMilliseconds(config, "activeTimeoutMonitorFrequency"), TimeUnit.MILLISECONDS); return initializer; }
[ "static", "final", "ConnectionPoolSegment", ".", "Initializer", "segmentFromConfig", "(", "String", "poolName", ",", "String", "segmentName", ",", "final", "Config", "config", ",", "ConnectionPoolSegment", ".", "Initializer", "initializer", ",", "Map", "<", "String", ...
Sets initializer properties from properties. @param poolName The pool name. @param segmentName The segment name. @param config The config. @param initializer An initializer. @param connectionMap A map of connection vs. name. @return The segment initializer. @throws InitializationException if configuration is invalid.
[ "Sets", "initializer", "properties", "from", "properties", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L244-L302
36,316
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.connectionMapFromConfig
static Map<String, JDBConnection> connectionMapFromConfig(Config config) throws InitializationException { final Config globalPropertyConfig; if(config.hasPath("acp.property")) { globalPropertyConfig = config.getObject("acp.property").toConfig(); } else if(config.hasPath("property")) { globalPropertyConfig = config.getObject("property").toConfig(); } else { globalPropertyConfig = null; } final Config connectionsConfig; if(config.hasPath("acp.connection")) { connectionsConfig = config.getObject("acp.connection").toConfig(); } else if(config.hasPath("connection")) { connectionsConfig = config.getObject("connection").toConfig(); } else { return Collections.emptyMap(); } Map<String, JDBConnection> connectionMap = Maps.newLinkedHashMap(); for(String connectionName : uniquePrefixSet(connectionsConfig)) { Config connectionConfig = connectionsConfig.getObject(connectionName).toConfig(); connectionMap.put(connectionName, createConnection(connectionName, connectionConfig, globalPropertyConfig)); } return connectionMap; }
java
static Map<String, JDBConnection> connectionMapFromConfig(Config config) throws InitializationException { final Config globalPropertyConfig; if(config.hasPath("acp.property")) { globalPropertyConfig = config.getObject("acp.property").toConfig(); } else if(config.hasPath("property")) { globalPropertyConfig = config.getObject("property").toConfig(); } else { globalPropertyConfig = null; } final Config connectionsConfig; if(config.hasPath("acp.connection")) { connectionsConfig = config.getObject("acp.connection").toConfig(); } else if(config.hasPath("connection")) { connectionsConfig = config.getObject("connection").toConfig(); } else { return Collections.emptyMap(); } Map<String, JDBConnection> connectionMap = Maps.newLinkedHashMap(); for(String connectionName : uniquePrefixSet(connectionsConfig)) { Config connectionConfig = connectionsConfig.getObject(connectionName).toConfig(); connectionMap.put(connectionName, createConnection(connectionName, connectionConfig, globalPropertyConfig)); } return connectionMap; }
[ "static", "Map", "<", "String", ",", "JDBConnection", ">", "connectionMapFromConfig", "(", "Config", "config", ")", "throws", "InitializationException", "{", "final", "Config", "globalPropertyConfig", ";", "if", "(", "config", ".", "hasPath", "(", "\"acp.property\""...
Creates a map of connection vs. name from properties. @return The connection map. @throws org.attribyte.api.InitializationException if connection could not be initialized.
[ "Creates", "a", "map", "of", "connection", "vs", ".", "name", "from", "properties", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L309-L338
36,317
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.createConnection
static JDBConnection createConnection(final String connectionName, final Config baseConfig, final Config globalPropertyConfig) throws InitializationException { Config connectionRef = ConfigFactory.load().getObject("acp.defaults.connection").toConfig(); Config config = baseConfig.withFallback(connectionRef); final String user = getString(config, "user"); final String password = getString(config, "password"); final String testSQL = getString(config, "testSQL", ""); String connectionString = getString(config, "connectionString"); final boolean debug = getString(config, "debug", "false").equalsIgnoreCase("true"); final long createTimeoutMillis = getMilliseconds(config, "createTimeout"); final long testIntervalMillis = getMilliseconds(config, "testInterval"); String propsRef = getString(config, "properties", ""); Config propsConfig; if(propsRef.length() > 0) { if(globalPropertyConfig.hasPath(propsRef)) { propsConfig = globalPropertyConfig.getObject(propsRef).toConfig(); } else { throw new InitializationException("The referenced global properties, '" + propsRef + "' is not defined"); } connectionString = buildConnectionString(connectionString, propsConfig); } return new JDBConnection(connectionName, user, password, connectionString, createTimeoutMillis, testSQL.length() > 0 ? testSQL : null, testIntervalMillis, debug); }
java
static JDBConnection createConnection(final String connectionName, final Config baseConfig, final Config globalPropertyConfig) throws InitializationException { Config connectionRef = ConfigFactory.load().getObject("acp.defaults.connection").toConfig(); Config config = baseConfig.withFallback(connectionRef); final String user = getString(config, "user"); final String password = getString(config, "password"); final String testSQL = getString(config, "testSQL", ""); String connectionString = getString(config, "connectionString"); final boolean debug = getString(config, "debug", "false").equalsIgnoreCase("true"); final long createTimeoutMillis = getMilliseconds(config, "createTimeout"); final long testIntervalMillis = getMilliseconds(config, "testInterval"); String propsRef = getString(config, "properties", ""); Config propsConfig; if(propsRef.length() > 0) { if(globalPropertyConfig.hasPath(propsRef)) { propsConfig = globalPropertyConfig.getObject(propsRef).toConfig(); } else { throw new InitializationException("The referenced global properties, '" + propsRef + "' is not defined"); } connectionString = buildConnectionString(connectionString, propsConfig); } return new JDBConnection(connectionName, user, password, connectionString, createTimeoutMillis, testSQL.length() > 0 ? testSQL : null, testIntervalMillis, debug); }
[ "static", "JDBConnection", "createConnection", "(", "final", "String", "connectionName", ",", "final", "Config", "baseConfig", ",", "final", "Config", "globalPropertyConfig", ")", "throws", "InitializationException", "{", "Config", "connectionRef", "=", "ConfigFactory", ...
Creates a connection from properties. @throws InitializationException if required parameters are unspecified.
[ "Creates", "a", "connection", "from", "properties", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L344-L378
36,318
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.initDrivers
static void initDrivers(final Config config) throws InitializationException { for(String driverName : uniquePrefixSet(config)) { Config driverConfig = config.getObject(driverName).toConfig(); if(driverConfig.hasPath("class")) { String className = driverConfig.getString("class"); try { Class.forName(className); } catch(Throwable t) { throw new InitializationException("Unable to load JDBC driver, '" + className + "'", t); } } else { throw new InitializationException("A 'class' must be specified for JDBC driver, '" + driverName + "'"); } } }
java
static void initDrivers(final Config config) throws InitializationException { for(String driverName : uniquePrefixSet(config)) { Config driverConfig = config.getObject(driverName).toConfig(); if(driverConfig.hasPath("class")) { String className = driverConfig.getString("class"); try { Class.forName(className); } catch(Throwable t) { throw new InitializationException("Unable to load JDBC driver, '" + className + "'", t); } } else { throw new InitializationException("A 'class' must be specified for JDBC driver, '" + driverName + "'"); } } }
[ "static", "void", "initDrivers", "(", "final", "Config", "config", ")", "throws", "InitializationException", "{", "for", "(", "String", "driverName", ":", "uniquePrefixSet", "(", "config", ")", ")", "{", "Config", "driverConfig", "=", "config", ".", "getObject",...
Initialize JDBC drivers from config. @throws InitializationException if driver could not be initialized
[ "Initialize", "JDBC", "drivers", "from", "config", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L384-L398
36,319
attribyte/acp
src/main/java/org/attribyte/sql/pool/TypesafeConfig.java
TypesafeConfig.buildConnectionString
private static String buildConnectionString(final String connectionString, final Config config) { if(config == null) { return connectionString; } StringBuilder buf = new StringBuilder(); Iterator<Map.Entry<String, ConfigValue>> iter = config.entrySet().iterator(); if(iter.hasNext()) { Map.Entry<String, ConfigValue> curr = iter.next(); buf.append(curr.getKey()).append("=").append(curr.getValue().unwrapped().toString()); } else { return connectionString; } while(iter.hasNext()) { Map.Entry<String, ConfigValue> curr = iter.next(); buf.append("&").append(curr.getKey()).append("=").append(curr.getValue().unwrapped().toString()); } if(connectionString.indexOf('?') > 0) { return connectionString + "&" + buf.toString(); } else { return connectionString + "?" + buf.toString(); } }
java
private static String buildConnectionString(final String connectionString, final Config config) { if(config == null) { return connectionString; } StringBuilder buf = new StringBuilder(); Iterator<Map.Entry<String, ConfigValue>> iter = config.entrySet().iterator(); if(iter.hasNext()) { Map.Entry<String, ConfigValue> curr = iter.next(); buf.append(curr.getKey()).append("=").append(curr.getValue().unwrapped().toString()); } else { return connectionString; } while(iter.hasNext()) { Map.Entry<String, ConfigValue> curr = iter.next(); buf.append("&").append(curr.getKey()).append("=").append(curr.getValue().unwrapped().toString()); } if(connectionString.indexOf('?') > 0) { return connectionString + "&" + buf.toString(); } else { return connectionString + "?" + buf.toString(); } }
[ "private", "static", "String", "buildConnectionString", "(", "final", "String", "connectionString", ",", "final", "Config", "config", ")", "{", "if", "(", "config", "==", "null", ")", "{", "return", "connectionString", ";", "}", "StringBuilder", "buf", "=", "n...
Builds a connection string with properties as parameters. @param connectionString The connection string. @return The connection string with properties as parameters.
[ "Builds", "a", "connection", "string", "with", "properties", "as", "parameters", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/TypesafeConfig.java#L405-L431
36,320
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java
ConnectionPoolConnection.logicalOpen
final void logicalOpen() { openTime = Clock.currTimeMillis; transactionState = TransactionState.NONE; if(debug) { lastTrace = Util.getFilteredStack(); } }
java
final void logicalOpen() { openTime = Clock.currTimeMillis; transactionState = TransactionState.NONE; if(debug) { lastTrace = Util.getFilteredStack(); } }
[ "final", "void", "logicalOpen", "(", ")", "{", "openTime", "=", "Clock", ".", "currTimeMillis", ";", "transactionState", "=", "TransactionState", ".", "NONE", ";", "if", "(", "debug", ")", "{", "lastTrace", "=", "Util", ".", "getFilteredStack", "(", ")", "...
Sets the connection state to open and records the open time. No tests are performed.
[ "Sets", "the", "connection", "state", "to", "open", "and", "records", "the", "open", "time", ".", "No", "tests", "are", "performed", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java#L493-L499
36,321
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java
ConnectionPoolConnection.logicalClose
final void logicalClose(final boolean withTest) throws SQLException { openTime = 0L; if(debug) { lastTrace = null; } if(logicalCloseException != null) { //Set during close() & thrown here to cause segment to reopen. Util.throwException(logicalCloseException); } if(withTest) { conn.setAutoCommit(true); if(testSQL != null && testSQL.length() > 0) { ResultSet rs = null; Statement stmt = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(testSQL); } finally { try { if(rs != null) { rs.close(); } } finally { if(stmt != null) { stmt.close(); } } } } } }
java
final void logicalClose(final boolean withTest) throws SQLException { openTime = 0L; if(debug) { lastTrace = null; } if(logicalCloseException != null) { //Set during close() & thrown here to cause segment to reopen. Util.throwException(logicalCloseException); } if(withTest) { conn.setAutoCommit(true); if(testSQL != null && testSQL.length() > 0) { ResultSet rs = null; Statement stmt = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(testSQL); } finally { try { if(rs != null) { rs.close(); } } finally { if(stmt != null) { stmt.close(); } } } } } }
[ "final", "void", "logicalClose", "(", "final", "boolean", "withTest", ")", "throws", "SQLException", "{", "openTime", "=", "0L", ";", "if", "(", "debug", ")", "{", "lastTrace", "=", "null", ";", "}", "if", "(", "logicalCloseException", "!=", "null", ")", ...
Prepares the connection for return to the active pool. @param withTest Should the connection be tested? @throws SQLException on test error or exception raised (and thrown) during application close.
[ "Prepares", "the", "connection", "for", "return", "to", "the", "active", "pool", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java#L557-L590
36,322
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java
ConnectionPoolConnection.closeStatements
private boolean closeStatements() { // JDBC API says... // Calling the method close on a Statement object that is already closed has no effect. // Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed. boolean hasUnclosed = false; if(openStatements.size() > 0) { for(Statement stmt : openStatements) { try { if(!stmt.isClosed()) { stmt.close(); hasUnclosed = true; } } catch(SQLException e) { hasUnclosed = true; setLogicalCloseException(e); } catch(Throwable t) { hasUnclosed = true; if(logicalCloseException == null) { if(Util.isRuntimeError(t)) { setLogicalCloseException(t); } else { setLogicalCloseException(new SQLException(t)); } } } } openStatements.clear(); } return hasUnclosed; }
java
private boolean closeStatements() { // JDBC API says... // Calling the method close on a Statement object that is already closed has no effect. // Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed. boolean hasUnclosed = false; if(openStatements.size() > 0) { for(Statement stmt : openStatements) { try { if(!stmt.isClosed()) { stmt.close(); hasUnclosed = true; } } catch(SQLException e) { hasUnclosed = true; setLogicalCloseException(e); } catch(Throwable t) { hasUnclosed = true; if(logicalCloseException == null) { if(Util.isRuntimeError(t)) { setLogicalCloseException(t); } else { setLogicalCloseException(new SQLException(t)); } } } } openStatements.clear(); } return hasUnclosed; }
[ "private", "boolean", "closeStatements", "(", ")", "{", "// JDBC API says...", "// Calling the method close on a Statement object that is already closed has no effect.", "// Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.", "boolean", "hasUnc...
Check for unclosed statements. @return Were any statements unclosed?
[ "Check", "for", "unclosed", "statements", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java#L596-L630
36,323
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java
ConnectionPoolConnection.setLogicalCloseException
private void setLogicalCloseException(final Throwable t) { if(logicalCloseException == null) { logicalCloseException = t; } else if(!Util.isRuntimeError(logicalCloseException) && Util.isRuntimeError(t)) { logicalCloseException = t; } }
java
private void setLogicalCloseException(final Throwable t) { if(logicalCloseException == null) { logicalCloseException = t; } else if(!Util.isRuntimeError(logicalCloseException) && Util.isRuntimeError(t)) { logicalCloseException = t; } }
[ "private", "void", "setLogicalCloseException", "(", "final", "Throwable", "t", ")", "{", "if", "(", "logicalCloseException", "==", "null", ")", "{", "logicalCloseException", "=", "t", ";", "}", "else", "if", "(", "!", "Util", ".", "isRuntimeError", "(", "log...
Sets logicalCloseException if null or replaces logicalCloseException if not null && input is a runtime error. @param t The throwable
[ "Sets", "logicalCloseException", "if", "null", "or", "replaces", "logicalCloseException", "if", "not", "null", "&&", "input", "is", "a", "runtime", "error", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java#L637-L644
36,324
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java
ConnectionPoolConnection.resolveIncompleteTransactions
private void resolveIncompleteTransactions() throws SQLException { switch(transactionState) { case COMPLETED: //All we know for certain is that at least one commit/rollback was called. Do nothing. break; case STARTED: //At least one statement was created with auto-commit false & no commit/rollback. //Follow the default policy. if(conn != null && openStatements.size() > 0) { switch(incompleteTransactionPolicy) { case REPORT: throw new SQLException("Statement closed with incomplete transaction", JDBConnection.SQLSTATE_INVALID_TRANSACTION_STATE); case COMMIT: if(!conn.isClosed()) { conn.commit(); } break; case ROLLBACK: if(!conn.isClosed()) { conn.rollback(); } } } break; } }
java
private void resolveIncompleteTransactions() throws SQLException { switch(transactionState) { case COMPLETED: //All we know for certain is that at least one commit/rollback was called. Do nothing. break; case STARTED: //At least one statement was created with auto-commit false & no commit/rollback. //Follow the default policy. if(conn != null && openStatements.size() > 0) { switch(incompleteTransactionPolicy) { case REPORT: throw new SQLException("Statement closed with incomplete transaction", JDBConnection.SQLSTATE_INVALID_TRANSACTION_STATE); case COMMIT: if(!conn.isClosed()) { conn.commit(); } break; case ROLLBACK: if(!conn.isClosed()) { conn.rollback(); } } } break; } }
[ "private", "void", "resolveIncompleteTransactions", "(", ")", "throws", "SQLException", "{", "switch", "(", "transactionState", ")", "{", "case", "COMPLETED", ":", "//All we know for certain is that at least one commit/rollback was called. Do nothing.", "break", ";", "case", ...
Attempt to deal with any transaction problems. @throws SQLException on invalid state.
[ "Attempt", "to", "deal", "with", "any", "transaction", "problems", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPoolConnection.java#L720-L746
36,325
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPool.java
ConnectionPool.closeUnmanagedConnection
public final void closeUnmanagedConnection(final Connection conn) throws SQLException { activeUnmanagedConnections.dec(); if(!conn.isClosed()) { conn.close(); } }
java
public final void closeUnmanagedConnection(final Connection conn) throws SQLException { activeUnmanagedConnections.dec(); if(!conn.isClosed()) { conn.close(); } }
[ "public", "final", "void", "closeUnmanagedConnection", "(", "final", "Connection", "conn", ")", "throws", "SQLException", "{", "activeUnmanagedConnections", ".", "dec", "(", ")", ";", "if", "(", "!", "conn", ".", "isClosed", "(", ")", ")", "{", "conn", ".", ...
Closes an unumanged connection. @param conn The conneciton. @throws SQLException If close fails.
[ "Closes", "an", "unumanged", "connection", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPool.java#L860-L865
36,326
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPool.java
ConnectionPool.signalActivateSegment
final void signalActivateSegment() throws SQLException { /* Note that 'offer' does so only if it can be done immediately without exceeding the queue capacity. The queue capacity is '1', so this means that signals may be ignored. Either way, this message will never block. */ if(segmentSignalQueue != null) { segmentSignalQueue.offer(ACTIVATE_SEGMENT_SIGNAL); } else if(activeSegments == 0) { //Single segment, no monitor, started with the one segment deactivated... synchronized(this) { if(activeSegments == 0) { //... and DCL works here because activeSegments is volatile. segments[0].activate(); activeSegments = 1; } } } }
java
final void signalActivateSegment() throws SQLException { /* Note that 'offer' does so only if it can be done immediately without exceeding the queue capacity. The queue capacity is '1', so this means that signals may be ignored. Either way, this message will never block. */ if(segmentSignalQueue != null) { segmentSignalQueue.offer(ACTIVATE_SEGMENT_SIGNAL); } else if(activeSegments == 0) { //Single segment, no monitor, started with the one segment deactivated... synchronized(this) { if(activeSegments == 0) { //... and DCL works here because activeSegments is volatile. segments[0].activate(); activeSegments = 1; } } } }
[ "final", "void", "signalActivateSegment", "(", ")", "throws", "SQLException", "{", "/*\n Note that 'offer' does so only if it can be done\n immediately without exceeding the queue capacity.\n The queue capacity is '1', so this means that\n signals may be ignored. Eith...
Signals that a new segment should be activated.
[ "Signals", "that", "a", "new", "segment", "should", "be", "activated", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPool.java#L950-L970
36,327
attribyte/acp
src/main/java/org/attribyte/sql/pool/ConnectionPool.java
ConnectionPool.shutdownNow
public final void shutdownNow() { if(isShuttingDown.compareAndSet(false, true)) { logInfo("Shutting down..."); if(idleSegmentMonitorService != null) { logInfo("Shutting down idle segment monitor service..."); idleSegmentMonitorService.shutdownNow(); } if(segmentSignalQueue != null) { segmentSignalQueue.clear(); } if(segmentSignalMonitorThread != null) { logInfo("Shutting down segment signal monitor thread..."); segmentSignalMonitorThread.interrupt(); } logInfo("Shutting down all segments..."); for(ConnectionPoolSegment segment : segments) { segment.shutdownNow(); } logInfo("Shutting down inactive monitor service..."); inactiveMonitorService.shutdownNow(); Clock.shutdown(); logInfo("Shutdown complete!"); } }
java
public final void shutdownNow() { if(isShuttingDown.compareAndSet(false, true)) { logInfo("Shutting down..."); if(idleSegmentMonitorService != null) { logInfo("Shutting down idle segment monitor service..."); idleSegmentMonitorService.shutdownNow(); } if(segmentSignalQueue != null) { segmentSignalQueue.clear(); } if(segmentSignalMonitorThread != null) { logInfo("Shutting down segment signal monitor thread..."); segmentSignalMonitorThread.interrupt(); } logInfo("Shutting down all segments..."); for(ConnectionPoolSegment segment : segments) { segment.shutdownNow(); } logInfo("Shutting down inactive monitor service..."); inactiveMonitorService.shutdownNow(); Clock.shutdown(); logInfo("Shutdown complete!"); } }
[ "public", "final", "void", "shutdownNow", "(", ")", "{", "if", "(", "isShuttingDown", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "logInfo", "(", "\"Shutting down...\"", ")", ";", "if", "(", "idleSegmentMonitorService", "!=", "null", ")",...
Shutdown the pool without waiting for any in-progress operations to complete.
[ "Shutdown", "the", "pool", "without", "waiting", "for", "any", "in", "-", "progress", "operations", "to", "complete", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/ConnectionPool.java#L1013-L1045
36,328
attribyte/acp
src/main/java/org/attribyte/sql/pool/JDBConnection.java
JDBConnection.getConnectionDescription
final String getConnectionDescription() { if(datasource != null) { return name; } String description = connectionString; int index = connectionString != null ? connectionString.indexOf('?') : 0; if(index > 0) { description = connectionString.substring(0, index); } if(!Strings.isNullOrEmpty(user)) { return user + "@" + description; } else { return description; } }
java
final String getConnectionDescription() { if(datasource != null) { return name; } String description = connectionString; int index = connectionString != null ? connectionString.indexOf('?') : 0; if(index > 0) { description = connectionString.substring(0, index); } if(!Strings.isNullOrEmpty(user)) { return user + "@" + description; } else { return description; } }
[ "final", "String", "getConnectionDescription", "(", ")", "{", "if", "(", "datasource", "!=", "null", ")", "{", "return", "name", ";", "}", "String", "description", "=", "connectionString", ";", "int", "index", "=", "connectionString", "!=", "null", "?", "con...
Gets a description of the database connection. @return A description of the connection.
[ "Gets", "a", "description", "of", "the", "database", "connection", "." ]
dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659
https://github.com/attribyte/acp/blob/dbee6ebb83fda4f19fbbbcb9d0ac2b527e3cb659/src/main/java/org/attribyte/sql/pool/JDBConnection.java#L232-L249
36,329
bremersee/comparator
src/main/java/org/bremersee/comparator/ComparatorUtils.java
ComparatorUtils.doSetAscRecursively
public static void doSetAscRecursively(ComparatorItem comparatorItem, boolean asc) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setAsc(asc); tmp = tmp.getNextComparatorItem(); } }
java
public static void doSetAscRecursively(ComparatorItem comparatorItem, boolean asc) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setAsc(asc); tmp = tmp.getNextComparatorItem(); } }
[ "public", "static", "void", "doSetAscRecursively", "(", "ComparatorItem", "comparatorItem", ",", "boolean", "asc", ")", "{", "ComparatorItem", "tmp", "=", "comparatorItem", ";", "while", "(", "tmp", "!=", "null", ")", "{", "tmp", ".", "setAsc", "(", "asc", "...
Sets the sort order of all items. @param comparatorItem the (root) item @param asc the new sort order
[ "Sets", "the", "sort", "order", "of", "all", "items", "." ]
6958e6e28a62589106705062f8ffc201a87d9b2a
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ComparatorUtils.java#L38-L44
36,330
bremersee/comparator
src/main/java/org/bremersee/comparator/ComparatorUtils.java
ComparatorUtils.doSetIgnoreCaseRecursively
public static void doSetIgnoreCaseRecursively(ComparatorItem comparatorItem, boolean ignoreCase) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setIgnoreCase(ignoreCase); tmp = tmp.getNextComparatorItem(); } }
java
public static void doSetIgnoreCaseRecursively(ComparatorItem comparatorItem, boolean ignoreCase) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setIgnoreCase(ignoreCase); tmp = tmp.getNextComparatorItem(); } }
[ "public", "static", "void", "doSetIgnoreCaseRecursively", "(", "ComparatorItem", "comparatorItem", ",", "boolean", "ignoreCase", ")", "{", "ComparatorItem", "tmp", "=", "comparatorItem", ";", "while", "(", "tmp", "!=", "null", ")", "{", "tmp", ".", "setIgnoreCase"...
Sets whether the sort is case sensitive or not to all items. @param comparatorItem the (root) item @param ignoreCase {@code true} if the sort is case sensitive, otherwise {@code false}
[ "Sets", "whether", "the", "sort", "is", "case", "sensitive", "or", "not", "to", "all", "items", "." ]
6958e6e28a62589106705062f8ffc201a87d9b2a
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ComparatorUtils.java#L52-L58
36,331
bremersee/comparator
src/main/java/org/bremersee/comparator/ComparatorUtils.java
ComparatorUtils.doSetNullIsFirstRecursively
public static void doSetNullIsFirstRecursively(ComparatorItem comparatorItem, boolean nullIsFirst) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setNullIsFirst(nullIsFirst); tmp = tmp.getNextComparatorItem(); } }
java
public static void doSetNullIsFirstRecursively(ComparatorItem comparatorItem, boolean nullIsFirst) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setNullIsFirst(nullIsFirst); tmp = tmp.getNextComparatorItem(); } }
[ "public", "static", "void", "doSetNullIsFirstRecursively", "(", "ComparatorItem", "comparatorItem", ",", "boolean", "nullIsFirst", ")", "{", "ComparatorItem", "tmp", "=", "comparatorItem", ";", "while", "(", "tmp", "!=", "null", ")", "{", "tmp", ".", "setNullIsFir...
Sets the sort order of a null value to all items. @param comparatorItem the (root) item @param nullIsFirst {@code true} if the sort order of a null value is higher than a non-null value, otherwise {@code false}
[ "Sets", "the", "sort", "order", "of", "a", "null", "value", "to", "all", "items", "." ]
6958e6e28a62589106705062f8ffc201a87d9b2a
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ComparatorUtils.java#L67-L74
36,332
jenkinsci/mask-passwords-plugin
src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java
MaskPasswordsConfig.addGlobalVarMaskRegex
public void addGlobalVarMaskRegex(VarMaskRegex varMaskRegex) { // blank values are forbidden if(StringUtils.isBlank(varMaskRegex.getRegex())) { LOGGER.fine("addGlobalVarMaskRegex NOT adding null regex"); return; } getGlobalVarMaskRegexesList().add(varMaskRegex); }
java
public void addGlobalVarMaskRegex(VarMaskRegex varMaskRegex) { // blank values are forbidden if(StringUtils.isBlank(varMaskRegex.getRegex())) { LOGGER.fine("addGlobalVarMaskRegex NOT adding null regex"); return; } getGlobalVarMaskRegexesList().add(varMaskRegex); }
[ "public", "void", "addGlobalVarMaskRegex", "(", "VarMaskRegex", "varMaskRegex", ")", "{", "// blank values are forbidden", "if", "(", "StringUtils", ".", "isBlank", "(", "varMaskRegex", ".", "getRegex", "(", ")", ")", ")", "{", "LOGGER", ".", "fine", "(", "\"add...
Adds a regex at the global level. <p>If regex is blank (as defined per the Commons Lang library), then the pair is not added.</p> @since 2.9
[ "Adds", "a", "regex", "at", "the", "global", "level", "." ]
3440b0aa5d2553889245327a9d37a006b4b17c3f
https://github.com/jenkinsci/mask-passwords-plugin/blob/3440b0aa5d2553889245327a9d37a006b4b17c3f/src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java#L165-L172
36,333
jenkinsci/mask-passwords-plugin
src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java
MaskPasswordsConfig.reset
@Restricted(NoExternalUse.class) @VisibleForTesting public final synchronized void reset() { // Wipe the data clear(); // default values for the first time the config is created addMaskedPasswordParameterDefinition(hudson.model.PasswordParameterDefinition.class.getName()); addMaskedPasswordParameterDefinition(com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition.class.getName()); }
java
@Restricted(NoExternalUse.class) @VisibleForTesting public final synchronized void reset() { // Wipe the data clear(); // default values for the first time the config is created addMaskedPasswordParameterDefinition(hudson.model.PasswordParameterDefinition.class.getName()); addMaskedPasswordParameterDefinition(com.michelin.cio.hudson.plugins.passwordparam.PasswordParameterDefinition.class.getName()); }
[ "@", "Restricted", "(", "NoExternalUse", ".", "class", ")", "@", "VisibleForTesting", "public", "final", "synchronized", "void", "reset", "(", ")", "{", "// Wipe the data", "clear", "(", ")", ";", "// default values for the first time the config is created", "addMaskedP...
Resets configuration to the default state.
[ "Resets", "configuration", "to", "the", "default", "state", "." ]
3440b0aa5d2553889245327a9d37a006b4b17c3f
https://github.com/jenkinsci/mask-passwords-plugin/blob/3440b0aa5d2553889245327a9d37a006b4b17c3f/src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java#L192-L201
36,334
jenkinsci/mask-passwords-plugin
src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java
MaskPasswordsConfig.getGlobalVarMaskRegexes
public List<VarMaskRegex> getGlobalVarMaskRegexes() { List<VarMaskRegex> r = new ArrayList<VarMaskRegex>(getGlobalVarMaskRegexesList().size()); // deep copy for(VarMaskRegex varMaskRegex: getGlobalVarMaskRegexesList()) { r.add((VarMaskRegex) varMaskRegex.clone()); } return r; }
java
public List<VarMaskRegex> getGlobalVarMaskRegexes() { List<VarMaskRegex> r = new ArrayList<VarMaskRegex>(getGlobalVarMaskRegexesList().size()); // deep copy for(VarMaskRegex varMaskRegex: getGlobalVarMaskRegexesList()) { r.add((VarMaskRegex) varMaskRegex.clone()); } return r; }
[ "public", "List", "<", "VarMaskRegex", ">", "getGlobalVarMaskRegexes", "(", ")", "{", "List", "<", "VarMaskRegex", ">", "r", "=", "new", "ArrayList", "<", "VarMaskRegex", ">", "(", "getGlobalVarMaskRegexesList", "(", ")", ".", "size", "(", ")", ")", ";", "...
Returns the list of regexes defined at the global level. <p>Modifications broughts to the returned list has no impact on this configuration (the returned value is a copy). Also, the list can be empty but never {@code null}.</p> @since 2.9
[ "Returns", "the", "list", "of", "regexes", "defined", "at", "the", "global", "level", "." ]
3440b0aa5d2553889245327a9d37a006b4b17c3f
https://github.com/jenkinsci/mask-passwords-plugin/blob/3440b0aa5d2553889245327a9d37a006b4b17c3f/src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java#L260-L269
36,335
jenkinsci/mask-passwords-plugin
src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java
MaskPasswordsConfig.isMasked
public boolean isMasked(final @CheckForNull ParameterValue value, final @Nonnull String paramValueClassName) { // We always mask sensitive variables, the configuration does not matter in such case if (value != null && value.isSensitive()) { return true; } synchronized(this) { // Check if the value is in the cache if (paramValueCache_maskedClasses.contains(paramValueClassName)) { return true; } if (paramValueCache_nonMaskedClasses.contains(paramValueClassName)) { return false; } // Now guess boolean guessSo = guessIfShouldMask(paramValueClassName); if (guessSo) { // We are pretty sure it requires masking paramValueCache_maskedClasses.add(paramValueClassName); return true; } else { // It does not require masking, but we are not so sure // The warning will be printed each time the cache is invalidated due to whatever reason LOGGER.log(Level.WARNING, "Identified the {0} class as a ParameterValue class, which does not require masking. It may be false-negative", paramValueClassName); paramValueCache_nonMaskedClasses.add(paramValueClassName); return false; } } }
java
public boolean isMasked(final @CheckForNull ParameterValue value, final @Nonnull String paramValueClassName) { // We always mask sensitive variables, the configuration does not matter in such case if (value != null && value.isSensitive()) { return true; } synchronized(this) { // Check if the value is in the cache if (paramValueCache_maskedClasses.contains(paramValueClassName)) { return true; } if (paramValueCache_nonMaskedClasses.contains(paramValueClassName)) { return false; } // Now guess boolean guessSo = guessIfShouldMask(paramValueClassName); if (guessSo) { // We are pretty sure it requires masking paramValueCache_maskedClasses.add(paramValueClassName); return true; } else { // It does not require masking, but we are not so sure // The warning will be printed each time the cache is invalidated due to whatever reason LOGGER.log(Level.WARNING, "Identified the {0} class as a ParameterValue class, which does not require masking. It may be false-negative", paramValueClassName); paramValueCache_nonMaskedClasses.add(paramValueClassName); return false; } } }
[ "public", "boolean", "isMasked", "(", "final", "@", "CheckForNull", "ParameterValue", "value", ",", "final", "@", "Nonnull", "String", "paramValueClassName", ")", "{", "// We always mask sensitive variables, the configuration does not matter in such case", "if", "(", "value",...
Returns true if the specified parameter value class name corresponds to a parameter definition class name selected in Jenkins' main configuration screen. @param value Parameter value. Without it there is a high risk of false negatives. @param paramValueClassName Class name of the {@link ParameterValue} class implementation @return {@code true} if the parameter value should be masked. {@code false} if the plugin is not sure, may be false-negative especially if the value is {@code null}. @since TODO
[ "Returns", "true", "if", "the", "specified", "parameter", "value", "class", "name", "corresponds", "to", "a", "parameter", "definition", "class", "name", "selected", "in", "Jenkins", "main", "configuration", "screen", "." ]
3440b0aa5d2553889245327a9d37a006b4b17c3f
https://github.com/jenkinsci/mask-passwords-plugin/blob/3440b0aa5d2553889245327a9d37a006b4b17c3f/src/main/java/com/michelin/cio/hudson/plugins/maskpasswords/MaskPasswordsConfig.java#L349-L380
36,336
esigate/esigate
esigate-core/src/main/java/org/esigate/impl/FragmentRedirectStrategy.java
FragmentRedirectStrategy.getLocationURI
@Override public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = this.redirectStrategy.getLocationURI(request, response, context); String resultingPageUrl = uri.toString(); DriverRequest driverRequest = ((OutgoingRequest) request).getOriginalRequest(); // Remove context if present if (StringUtils.startsWith(resultingPageUrl, driverRequest.getVisibleBaseUrl())) { resultingPageUrl = "/" + StringUtils.stripStart( StringUtils.replace(resultingPageUrl, driverRequest.getVisibleBaseUrl(), ""), "/"); } resultingPageUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false); return UriUtils.createURI(ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false)); }
java
@Override public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = this.redirectStrategy.getLocationURI(request, response, context); String resultingPageUrl = uri.toString(); DriverRequest driverRequest = ((OutgoingRequest) request).getOriginalRequest(); // Remove context if present if (StringUtils.startsWith(resultingPageUrl, driverRequest.getVisibleBaseUrl())) { resultingPageUrl = "/" + StringUtils.stripStart( StringUtils.replace(resultingPageUrl, driverRequest.getVisibleBaseUrl(), ""), "/"); } resultingPageUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false); return UriUtils.createURI(ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false)); }
[ "@", "Override", "public", "URI", "getLocationURI", "(", "HttpRequest", "request", ",", "HttpResponse", "response", ",", "HttpContext", "context", ")", "throws", "ProtocolException", "{", "URI", "uri", "=", "this", ".", "redirectStrategy", ".", "getLocationURI", "...
For local redirects, converts to relative urls. @param request must be an {@link OutgoingRequest}.
[ "For", "local", "redirects", "converts", "to", "relative", "urls", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/impl/FragmentRedirectStrategy.java#L78-L96
36,337
esigate/esigate
esigate-core/src/main/java/org/esigate/impl/UriMapping.java
UriMapping.matches
public boolean matches(String schemeParam, String hostParam, String uriParam) { // If URI mapping enforce a host, ensure it is the one used. if (this.host != null && !this.host.equalsIgnoreCase(schemeParam + "://" + hostParam)) { return false; } if (this.extension != null && !uriParam.endsWith(this.extension)) { return false; } if (this.path != null && !uriParam.startsWith(this.path)) { return false; } return true; }
java
public boolean matches(String schemeParam, String hostParam, String uriParam) { // If URI mapping enforce a host, ensure it is the one used. if (this.host != null && !this.host.equalsIgnoreCase(schemeParam + "://" + hostParam)) { return false; } if (this.extension != null && !uriParam.endsWith(this.extension)) { return false; } if (this.path != null && !uriParam.startsWith(this.path)) { return false; } return true; }
[ "public", "boolean", "matches", "(", "String", "schemeParam", ",", "String", "hostParam", ",", "String", "uriParam", ")", "{", "// If URI mapping enforce a host, ensure it is the one used.", "if", "(", "this", ".", "host", "!=", "null", "&&", "!", "this", ".", "ho...
Check this matching rule against a request. @param schemeParam @param hostParam @param uriParam @return true if the rule matches the request
[ "Check", "this", "matching", "rule", "against", "a", "request", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/impl/UriMapping.java#L116-L130
36,338
esigate/esigate
esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java
OutgoingRequestContext.setAttribute
public void setAttribute(String id, Object obj, boolean save) { if (save) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history == null) { history = new LinkedList<>(); setAttribute(historyAttribute, history); } if (this.getAttribute(id) != null) { history.add(getAttribute(id)); } } setAttribute(id, obj); }
java
public void setAttribute(String id, Object obj, boolean save) { if (save) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history == null) { history = new LinkedList<>(); setAttribute(historyAttribute, history); } if (this.getAttribute(id) != null) { history.add(getAttribute(id)); } } setAttribute(id, obj); }
[ "public", "void", "setAttribute", "(", "String", "id", ",", "Object", "obj", ",", "boolean", "save", ")", "{", "if", "(", "save", ")", "{", "String", "historyAttribute", "=", "id", "+", "\"history\"", ";", "Queue", "<", "Object", ">", "history", "=", "...
Set attribute and save previous attribute value @param id attribute name @param obj value @param save save previous attribute value to restore later
[ "Set", "attribute", "and", "save", "previous", "attribute", "value" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java#L92-L105
36,339
esigate/esigate
esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java
OutgoingRequestContext.removeAttribute
public Object removeAttribute(String id, boolean restore) { Object value = removeAttribute(id); if (restore) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history != null && !history.isEmpty()) { Object previous = history.remove(); setAttribute(id, previous); } } return value; }
java
public Object removeAttribute(String id, boolean restore) { Object value = removeAttribute(id); if (restore) { String historyAttribute = id + "history"; Queue<Object> history = (Queue<Object>) getAttribute(historyAttribute); if (history != null && !history.isEmpty()) { Object previous = history.remove(); setAttribute(id, previous); } } return value; }
[ "public", "Object", "removeAttribute", "(", "String", "id", ",", "boolean", "restore", ")", "{", "Object", "value", "=", "removeAttribute", "(", "id", ")", ";", "if", "(", "restore", ")", "{", "String", "historyAttribute", "=", "id", "+", "\"history\"", ";...
remove attribute and restore previous attribute value @param id attribute name @param restore restore previous attribute value @return attribute value
[ "remove", "attribute", "and", "restore", "previous", "attribute", "value" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/OutgoingRequestContext.java#L116-L127
36,340
esigate/esigate
esigate-core/src/main/java/org/esigate/impl/UrlRewriter.java
UrlRewriter.rewriteReferer
public String rewriteReferer(String referer, String baseUrl, String visibleBaseUrl) { URI uri = UriUtils.createURI(referer); // Base url should end with / if (!baseUrl.endsWith("/")) { baseUrl = baseUrl + "/"; } URI baseUri = UriUtils.createURI(baseUrl); // If no visible url base is defined, use base url as visible base url if (!visibleBaseUrl.endsWith("/")) { visibleBaseUrl = visibleBaseUrl + "/"; } URI visibleBaseUri = UriUtils.createURI(visibleBaseUrl); // Relativize url to visible base url URI relativeUri = visibleBaseUri.relativize(uri); // If the url is unchanged do nothing if (relativeUri.equals(uri)) { LOG.debug("url kept unchanged: [{}]", referer); return referer; } // Else rewrite replacing baseUrl by visibleBaseUrl URI result = baseUri.resolve(relativeUri); LOG.debug("referer fixed: [{}] -> [{}]", referer, result); return result.toString(); }
java
public String rewriteReferer(String referer, String baseUrl, String visibleBaseUrl) { URI uri = UriUtils.createURI(referer); // Base url should end with / if (!baseUrl.endsWith("/")) { baseUrl = baseUrl + "/"; } URI baseUri = UriUtils.createURI(baseUrl); // If no visible url base is defined, use base url as visible base url if (!visibleBaseUrl.endsWith("/")) { visibleBaseUrl = visibleBaseUrl + "/"; } URI visibleBaseUri = UriUtils.createURI(visibleBaseUrl); // Relativize url to visible base url URI relativeUri = visibleBaseUri.relativize(uri); // If the url is unchanged do nothing if (relativeUri.equals(uri)) { LOG.debug("url kept unchanged: [{}]", referer); return referer; } // Else rewrite replacing baseUrl by visibleBaseUrl URI result = baseUri.resolve(relativeUri); LOG.debug("referer fixed: [{}] -> [{}]", referer, result); return result.toString(); }
[ "public", "String", "rewriteReferer", "(", "String", "referer", ",", "String", "baseUrl", ",", "String", "visibleBaseUrl", ")", "{", "URI", "uri", "=", "UriUtils", ".", "createURI", "(", "referer", ")", ";", "// Base url should end with /", "if", "(", "!", "ba...
Fixes a referer url in a request. @param referer the url to fix (can be anything found in an html page, relative, absolute, empty...) @param baseUrl The base URL selected for this request. @param visibleBaseUrl The base URL viewed by the browser. @return the fixed url.
[ "Fixes", "a", "referer", "url", "in", "a", "request", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/impl/UrlRewriter.java#L87-L113
36,341
esigate/esigate
esigate-core/src/main/java/org/esigate/impl/UrlRewriter.java
UrlRewriter.rewriteHtml
public CharSequence rewriteHtml(CharSequence input, String requestUrl, String baseUrlParam, String visibleBaseUrl, boolean absolute) { StringBuffer result = new StringBuffer(input.length()); Matcher m = URL_PATTERN.matcher(input); while (m.find()) { String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString(); String tag = m.group(0); String quote = input.subSequence(m.end(3) - 1, m.end(3)).toString(); // Browsers tolerate urls with white spaces before or after String trimmedUrl = StringUtils.trim(url); String rewrittenUrl = url; trimmedUrl = unescapeHtml(trimmedUrl); if (trimmedUrl.isEmpty()) { LOG.debug("empty url kept unchanged"); } else if (trimmedUrl.startsWith("#")) { LOG.debug("anchor url kept unchanged: [{}]", url); } else if (JAVASCRIPT_CONCATENATION_PATTERN.matcher(trimmedUrl).find()) { LOG.debug("url in javascript kept unchanged: [{}]", url); } else if (m.group(2).equalsIgnoreCase("content")) { if (META_REFRESH_PATTERN.matcher(tag).find()) { rewrittenUrl = rewriteRefresh(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl); rewrittenUrl = escapeHtml(rewrittenUrl); LOG.debug("refresh url [{}] rewritten [{}]", url, rewrittenUrl); } else { LOG.debug("content attribute kept unchanged: [{}]", url); } } else { rewrittenUrl = rewriteUrl(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl, absolute); rewrittenUrl = escapeHtml(rewrittenUrl); LOG.debug("url [{}] rewritten [{}]", url, rewrittenUrl); } m.appendReplacement(result, ""); // Copy what is between the previous match and the current match result.append("<"); result.append(m.group(1)); result.append(m.group(2)); result.append("="); result.append(quote); result.append(rewrittenUrl); result.append(quote); if (m.groupCount() > 3) { result.append(m.group(4)); } result.append(">"); } m.appendTail(result); // Copy the reminder of the input return result; }
java
public CharSequence rewriteHtml(CharSequence input, String requestUrl, String baseUrlParam, String visibleBaseUrl, boolean absolute) { StringBuffer result = new StringBuffer(input.length()); Matcher m = URL_PATTERN.matcher(input); while (m.find()) { String url = input.subSequence(m.start(3) + 1, m.end(3) - 1).toString(); String tag = m.group(0); String quote = input.subSequence(m.end(3) - 1, m.end(3)).toString(); // Browsers tolerate urls with white spaces before or after String trimmedUrl = StringUtils.trim(url); String rewrittenUrl = url; trimmedUrl = unescapeHtml(trimmedUrl); if (trimmedUrl.isEmpty()) { LOG.debug("empty url kept unchanged"); } else if (trimmedUrl.startsWith("#")) { LOG.debug("anchor url kept unchanged: [{}]", url); } else if (JAVASCRIPT_CONCATENATION_PATTERN.matcher(trimmedUrl).find()) { LOG.debug("url in javascript kept unchanged: [{}]", url); } else if (m.group(2).equalsIgnoreCase("content")) { if (META_REFRESH_PATTERN.matcher(tag).find()) { rewrittenUrl = rewriteRefresh(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl); rewrittenUrl = escapeHtml(rewrittenUrl); LOG.debug("refresh url [{}] rewritten [{}]", url, rewrittenUrl); } else { LOG.debug("content attribute kept unchanged: [{}]", url); } } else { rewrittenUrl = rewriteUrl(trimmedUrl, requestUrl, baseUrlParam, visibleBaseUrl, absolute); rewrittenUrl = escapeHtml(rewrittenUrl); LOG.debug("url [{}] rewritten [{}]", url, rewrittenUrl); } m.appendReplacement(result, ""); // Copy what is between the previous match and the current match result.append("<"); result.append(m.group(1)); result.append(m.group(2)); result.append("="); result.append(quote); result.append(rewrittenUrl); result.append(quote); if (m.groupCount() > 3) { result.append(m.group(4)); } result.append(">"); } m.appendTail(result); // Copy the reminder of the input return result; }
[ "public", "CharSequence", "rewriteHtml", "(", "CharSequence", "input", ",", "String", "requestUrl", ",", "String", "baseUrlParam", ",", "String", "visibleBaseUrl", ",", "boolean", "absolute", ")", "{", "StringBuffer", "result", "=", "new", "StringBuffer", "(", "in...
Fixes all resources urls and returns the result. @param input The html to be processed. @param requestUrl The request URL. @param baseUrlParam The base URL selected for this request. @param visibleBaseUrl The base URL viewed by the browser. @param absolute Should the rewritten urls contain the scheme host and port @return the result of this renderer.
[ "Fixes", "all", "resources", "urls", "and", "returns", "the", "result", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/impl/UrlRewriter.java#L202-L255
36,342
esigate/esigate
esigate-core/src/main/java/org/esigate/vars/VarUtils.java
VarUtils.removeSimpleQuotes
public static String removeSimpleQuotes(String s) { if (s.startsWith("'") && s.endsWith("'")) { return s.substring(1, s.length() - 1); } return s; }
java
public static String removeSimpleQuotes(String s) { if (s.startsWith("'") && s.endsWith("'")) { return s.substring(1, s.length() - 1); } return s; }
[ "public", "static", "String", "removeSimpleQuotes", "(", "String", "s", ")", "{", "if", "(", "s", ".", "startsWith", "(", "\"'\"", ")", "&&", "s", ".", "endsWith", "(", "\"'\"", ")", ")", "{", "return", "s", ".", "substring", "(", "1", ",", "s", "....
Removes simple quotes if any. @param s input string @return input string without simple quotes.
[ "Removes", "simple", "quotes", "if", "any", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/vars/VarUtils.java#L37-L43
36,343
esigate/esigate
esigate-core/src/main/java/org/esigate/util/HttpRequestHelper.java
HttpRequestHelper.getHost
public static HttpHost getHost(HttpRequest request) { HttpHost httpHost = UriUtils.extractHost(request.getRequestLine().getUri()); String scheme = httpHost.getSchemeName(); String host = httpHost.getHostName(); int port = httpHost.getPort(); Header[] headers = request.getHeaders(HttpHeaders.HOST); if (headers != null && headers.length != 0) { String headerValue = headers[0].getValue(); String[] splitted = headerValue.split(":"); host = splitted[0]; if (splitted.length > 1) { port = Integer.parseInt(splitted[1]); } else { port = -1; } } return new HttpHost(host, port, scheme); }
java
public static HttpHost getHost(HttpRequest request) { HttpHost httpHost = UriUtils.extractHost(request.getRequestLine().getUri()); String scheme = httpHost.getSchemeName(); String host = httpHost.getHostName(); int port = httpHost.getPort(); Header[] headers = request.getHeaders(HttpHeaders.HOST); if (headers != null && headers.length != 0) { String headerValue = headers[0].getValue(); String[] splitted = headerValue.split(":"); host = splitted[0]; if (splitted.length > 1) { port = Integer.parseInt(splitted[1]); } else { port = -1; } } return new HttpHost(host, port, scheme); }
[ "public", "static", "HttpHost", "getHost", "(", "HttpRequest", "request", ")", "{", "HttpHost", "httpHost", "=", "UriUtils", ".", "extractHost", "(", "request", ".", "getRequestLine", "(", ")", ".", "getUri", "(", ")", ")", ";", "String", "scheme", "=", "h...
Returns the target host as defined in the Host header or extracted from the request URI. Usefull to generate Host header in a HttpRequest @param request @return the host formatted as host:port
[ "Returns", "the", "target", "host", "as", "defined", "in", "the", "Host", "header", "or", "extracted", "from", "the", "request", "URI", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/HttpRequestHelper.java#L64-L81
36,344
esigate/esigate
esigate-core/src/main/java/org/esigate/http/ProxyingHttpClientBuilder.java
ProxyingHttpClientBuilder.addFetchEvent
private ClientExecChain addFetchEvent(final ClientExecChain wrapped) { return new ClientExecChain() { @Override public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext httpClientContext, HttpExecutionAware execAware) throws IOException, HttpException { OutgoingRequestContext context = OutgoingRequestContext.adapt(httpClientContext); // Create request event FetchEvent fetchEvent = new FetchEvent(context, request); eventManager.fire(EventManager.EVENT_FETCH_PRE, fetchEvent); if (fetchEvent.isExit()) { if (fetchEvent.getHttpResponse() == null) { // Provide an error page in order to avoid a NullPointerException fetchEvent.setHttpResponse(HttpErrorPage.generateHttpResponse( HttpStatus.SC_INTERNAL_SERVER_ERROR, "An extension stopped the processing of the request without providing a response")); } } else { try { fetchEvent.setHttpResponse(wrapped.execute(route, request, context, execAware)); eventManager.fire(EventManager.EVENT_FETCH_POST, fetchEvent); } catch (IOException | HttpException e) { fetchEvent.setHttpResponse(HttpErrorPage.generateHttpResponse(e)); // Usually we want to render and cache the exception but we let an extension decide fetchEvent.setExit(true); eventManager.fire(EventManager.EVENT_FETCH_POST, fetchEvent); if (!fetchEvent.isExit()) throw e; // Throw the exception and let http client process it (may retry) } } return fetchEvent.getHttpResponse(); } }; }
java
private ClientExecChain addFetchEvent(final ClientExecChain wrapped) { return new ClientExecChain() { @Override public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext httpClientContext, HttpExecutionAware execAware) throws IOException, HttpException { OutgoingRequestContext context = OutgoingRequestContext.adapt(httpClientContext); // Create request event FetchEvent fetchEvent = new FetchEvent(context, request); eventManager.fire(EventManager.EVENT_FETCH_PRE, fetchEvent); if (fetchEvent.isExit()) { if (fetchEvent.getHttpResponse() == null) { // Provide an error page in order to avoid a NullPointerException fetchEvent.setHttpResponse(HttpErrorPage.generateHttpResponse( HttpStatus.SC_INTERNAL_SERVER_ERROR, "An extension stopped the processing of the request without providing a response")); } } else { try { fetchEvent.setHttpResponse(wrapped.execute(route, request, context, execAware)); eventManager.fire(EventManager.EVENT_FETCH_POST, fetchEvent); } catch (IOException | HttpException e) { fetchEvent.setHttpResponse(HttpErrorPage.generateHttpResponse(e)); // Usually we want to render and cache the exception but we let an extension decide fetchEvent.setExit(true); eventManager.fire(EventManager.EVENT_FETCH_POST, fetchEvent); if (!fetchEvent.isExit()) throw e; // Throw the exception and let http client process it (may retry) } } return fetchEvent.getHttpResponse(); } }; }
[ "private", "ClientExecChain", "addFetchEvent", "(", "final", "ClientExecChain", "wrapped", ")", "{", "return", "new", "ClientExecChain", "(", ")", "{", "@", "Override", "public", "CloseableHttpResponse", "execute", "(", "HttpRoute", "route", ",", "HttpRequestWrapper",...
Decorate with fetch event managements @param wrapped @return the decorated ClientExecChain
[ "Decorate", "with", "fetch", "event", "managements" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/ProxyingHttpClientBuilder.java#L84-L122
36,345
esigate/esigate
esigate-servlet/src/main/java/org/esigate/servlet/user/FilteredRequest.java
FilteredRequest.getRemoteUser
@Override public String getRemoteUser() { String user = getHeader("X_REMOTE_USER"); if (user != null) { return user; } else { return super.getRemoteUser(); } }
java
@Override public String getRemoteUser() { String user = getHeader("X_REMOTE_USER"); if (user != null) { return user; } else { return super.getRemoteUser(); } }
[ "@", "Override", "public", "String", "getRemoteUser", "(", ")", "{", "String", "user", "=", "getHeader", "(", "\"X_REMOTE_USER\"", ")", ";", "if", "(", "user", "!=", "null", ")", "{", "return", "user", ";", "}", "else", "{", "return", "super", ".", "ge...
Returns the user defined as parameter "user" if present.
[ "Returns", "the", "user", "defined", "as", "parameter", "user", "if", "present", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-servlet/src/main/java/org/esigate/servlet/user/FilteredRequest.java#L36-L44
36,346
esigate/esigate
esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java
Surrogate.fixSurrogateMap
private void fixSurrogateMap(LinkedHashMap<String, List<String>> targetCapabilities, String currentSurrogate) { boolean esiEnabledInEsigate = false; // Check if Esigate will perform ESI. for (String c : Esi.CAPABILITIES) { if (targetCapabilities.get(currentSurrogate).contains(c)) { esiEnabledInEsigate = true; break; } } if (esiEnabledInEsigate) { // Ensure all Esi capabilities are executed by our instance. for (String c : Esi.CAPABILITIES) { for (String device : targetCapabilities.keySet()) { if (device.equals(currentSurrogate)) { if (!targetCapabilities.get(device).contains(c)) { targetCapabilities.get(device).add(c); } } else { targetCapabilities.get(device).remove(c); } } } } }
java
private void fixSurrogateMap(LinkedHashMap<String, List<String>> targetCapabilities, String currentSurrogate) { boolean esiEnabledInEsigate = false; // Check if Esigate will perform ESI. for (String c : Esi.CAPABILITIES) { if (targetCapabilities.get(currentSurrogate).contains(c)) { esiEnabledInEsigate = true; break; } } if (esiEnabledInEsigate) { // Ensure all Esi capabilities are executed by our instance. for (String c : Esi.CAPABILITIES) { for (String device : targetCapabilities.keySet()) { if (device.equals(currentSurrogate)) { if (!targetCapabilities.get(device).contains(c)) { targetCapabilities.get(device).add(c); } } else { targetCapabilities.get(device).remove(c); } } } } }
[ "private", "void", "fixSurrogateMap", "(", "LinkedHashMap", "<", "String", ",", "List", "<", "String", ">", ">", "targetCapabilities", ",", "String", "currentSurrogate", ")", "{", "boolean", "esiEnabledInEsigate", "=", "false", ";", "// Check if Esigate will perform E...
The current implementation of ESI cannot execute rules partially. For instance if ESI-Inline is requested, ESI, ESI-Inline, X-ESI-Fragment are executed. <p> This method handles this specific case : if one requested capability enables the Esi extension in this instance, all other capabilities are moved to this instance. This prevents broken behavior. @see Esi @see org.esigate.extension.Esi @param targetCapabilities @param currentSurrogate the current surrogate id.
[ "The", "current", "implementation", "of", "ESI", "cannot", "execute", "rules", "partially", ".", "For", "instance", "if", "ESI", "-", "Inline", "is", "requested", "ESI", "ESI", "-", "Inline", "X", "-", "ESI", "-", "Fragment", "are", "executed", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java#L438-L466
36,347
esigate/esigate
esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java
Surrogate.initSurrogateMap
private void initSurrogateMap(Map<String, List<String>> targetCapabilities, SurrogateCapabilitiesHeader surrogateCapabilitiesHeader) { for (SurrogateCapabilities sc : surrogateCapabilitiesHeader.getSurrogates()) { targetCapabilities.put(sc.getDeviceToken(), new ArrayList<String>()); } }
java
private void initSurrogateMap(Map<String, List<String>> targetCapabilities, SurrogateCapabilitiesHeader surrogateCapabilitiesHeader) { for (SurrogateCapabilities sc : surrogateCapabilitiesHeader.getSurrogates()) { targetCapabilities.put(sc.getDeviceToken(), new ArrayList<String>()); } }
[ "private", "void", "initSurrogateMap", "(", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "targetCapabilities", ",", "SurrogateCapabilitiesHeader", "surrogateCapabilitiesHeader", ")", "{", "for", "(", "SurrogateCapabilities", "sc", ":", "surrogateCapabil...
Populate the Map with all current devices, with empty capabilities. @param targetCapabilities @param surrogateCapabilitiesHeader
[ "Populate", "the", "Map", "with", "all", "current", "devices", "with", "empty", "capabilities", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java#L474-L480
36,348
esigate/esigate
esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java
Surrogate.getFirstSurrogateFor
private String getFirstSurrogateFor(SurrogateCapabilitiesHeader surrogateCapabilitiesHeader, String capability) { for (SurrogateCapabilities surrogate : surrogateCapabilitiesHeader.getSurrogates()) { for (Capability sc : surrogate.getCapabilities()) { if (capability.equals(sc.toString())) { return surrogate.getDeviceToken(); } } } return null; }
java
private String getFirstSurrogateFor(SurrogateCapabilitiesHeader surrogateCapabilitiesHeader, String capability) { for (SurrogateCapabilities surrogate : surrogateCapabilitiesHeader.getSurrogates()) { for (Capability sc : surrogate.getCapabilities()) { if (capability.equals(sc.toString())) { return surrogate.getDeviceToken(); } } } return null; }
[ "private", "String", "getFirstSurrogateFor", "(", "SurrogateCapabilitiesHeader", "surrogateCapabilitiesHeader", ",", "String", "capability", ")", "{", "for", "(", "SurrogateCapabilities", "surrogate", ":", "surrogateCapabilitiesHeader", ".", "getSurrogates", "(", ")", ")", ...
Returns the first surrogate which supports the requested capability. @param surrogateCapabilitiesHeader @param capability @return a Surrogate or null if the capability is not found.
[ "Returns", "the", "first", "surrogate", "which", "supports", "the", "requested", "capability", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java#L489-L499
36,349
esigate/esigate
esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java
Surrogate.processSurrogateControlContent
private static void processSurrogateControlContent(HttpResponse response, boolean keepHeader) { if (!response.containsHeader(H_SURROGATE_CONTROL)) { return; } if (!keepHeader) { response.removeHeaders(H_SURROGATE_CONTROL); return; } MoveResponseHeader.moveHeader(response, H_X_NEXT_SURROGATE_CONTROL, H_SURROGATE_CONTROL); }
java
private static void processSurrogateControlContent(HttpResponse response, boolean keepHeader) { if (!response.containsHeader(H_SURROGATE_CONTROL)) { return; } if (!keepHeader) { response.removeHeaders(H_SURROGATE_CONTROL); return; } MoveResponseHeader.moveHeader(response, H_X_NEXT_SURROGATE_CONTROL, H_SURROGATE_CONTROL); }
[ "private", "static", "void", "processSurrogateControlContent", "(", "HttpResponse", "response", ",", "boolean", "keepHeader", ")", "{", "if", "(", "!", "response", ".", "containsHeader", "(", "H_SURROGATE_CONTROL", ")", ")", "{", "return", ";", "}", "if", "(", ...
Remove Surrogate-Control header or replace by its new value. @param response backend HTTP response. @param keepHeader should the Surrogate-Control header be forwarded to the client.
[ "Remove", "Surrogate", "-", "Control", "header", "or", "replace", "by", "its", "new", "value", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/extension/surrogate/Surrogate.java#L509-L520
36,350
esigate/esigate
esigate-core/src/main/java/org/esigate/vars/Operations.java
Operations.getOperandAsNumeric
private static Double getOperandAsNumeric(String op) { Double d = null; try { d = Double.valueOf(op); } catch (Exception e) { // Null is returned if not numeric. } return d; }
java
private static Double getOperandAsNumeric(String op) { Double d = null; try { d = Double.valueOf(op); } catch (Exception e) { // Null is returned if not numeric. } return d; }
[ "private", "static", "Double", "getOperandAsNumeric", "(", "String", "op", ")", "{", "Double", "d", "=", "null", ";", "try", "{", "d", "=", "Double", ".", "valueOf", "(", "op", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// Null is return...
Get an operand as a numeric type. @param op operand as String @return Double value or null if op is not numeric
[ "Get", "an", "operand", "as", "a", "numeric", "type", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/vars/Operations.java#L173-L181
36,351
esigate/esigate
esigate-core/src/main/java/org/esigate/util/PropertiesUtil.java
PropertiesUtil.getPropertyValue
public static Collection<String> getPropertyValue(Properties properties, String propertyName, Collection<String> defaultValue) { Collection<String> result = defaultValue; String propertyValue = properties.getProperty(propertyName); if (propertyValue != null) { result = toCollection(propertyValue); if (result.contains("*") && result.size() > 1) { throw new ConfigurationException(propertyName + " must be a comma-separated list or *"); } } return result; }
java
public static Collection<String> getPropertyValue(Properties properties, String propertyName, Collection<String> defaultValue) { Collection<String> result = defaultValue; String propertyValue = properties.getProperty(propertyName); if (propertyValue != null) { result = toCollection(propertyValue); if (result.contains("*") && result.size() > 1) { throw new ConfigurationException(propertyName + " must be a comma-separated list or *"); } } return result; }
[ "public", "static", "Collection", "<", "String", ">", "getPropertyValue", "(", "Properties", "properties", ",", "String", "propertyName", ",", "Collection", "<", "String", ">", "defaultValue", ")", "{", "Collection", "<", "String", ">", "result", "=", "defaultVa...
Retrieves a property containing a comma separated list of values, trim them and return them as a Collection of String. @param properties @param propertyName @param defaultValue @return the values
[ "Retrieves", "a", "property", "containing", "a", "comma", "separated", "list", "of", "values", "trim", "them", "and", "return", "them", "as", "a", "Collection", "of", "String", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/PropertiesUtil.java#L45-L56
36,352
esigate/esigate
esigate-core/src/main/java/org/esigate/util/PropertiesUtil.java
PropertiesUtil.toCollection
static Collection<String> toCollection(String list) { Collection<String> result = new ArrayList<>(); if (list != null) { String[] values = list.split(","); for (String value : values) { String trimmed = value.trim(); if (!trimmed.isEmpty()) { result.add(trimmed); } } } return result; }
java
static Collection<String> toCollection(String list) { Collection<String> result = new ArrayList<>(); if (list != null) { String[] values = list.split(","); for (String value : values) { String trimmed = value.trim(); if (!trimmed.isEmpty()) { result.add(trimmed); } } } return result; }
[ "static", "Collection", "<", "String", ">", "toCollection", "(", "String", "list", ")", "{", "Collection", "<", "String", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "list", "!=", "null", ")", "{", "String", "[", "]", "val...
Return the provided comma-separated String as a collection. Order is maintained. @param list @return Ordered collection
[ "Return", "the", "provided", "comma", "-", "separated", "String", "as", "a", "collection", ".", "Order", "is", "maintained", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/PropertiesUtil.java#L64-L76
36,353
esigate/esigate
esigate-server/src/main/java/org/esigate/server/ControlHandler.java
ControlHandler.cleanupStatusKey
private static String cleanupStatusKey(String s) { String result = s; if (s.startsWith(PREFIX_CONTEXT)) { result = s.substring(PREFIX_CONTEXT.length()); } if (s.startsWith(PREFIX_THREAD_POOL)) { result = s.substring(PREFIX_THREAD_POOL.length()); } return result; }
java
private static String cleanupStatusKey(String s) { String result = s; if (s.startsWith(PREFIX_CONTEXT)) { result = s.substring(PREFIX_CONTEXT.length()); } if (s.startsWith(PREFIX_THREAD_POOL)) { result = s.substring(PREFIX_THREAD_POOL.length()); } return result; }
[ "private", "static", "String", "cleanupStatusKey", "(", "String", "s", ")", "{", "String", "result", "=", "s", ";", "if", "(", "s", ".", "startsWith", "(", "PREFIX_CONTEXT", ")", ")", "{", "result", "=", "s", ".", "substring", "(", "PREFIX_CONTEXT", ".",...
Remove unnecessary prefix from Metrics meters id. @param s @return
[ "Remove", "unnecessary", "prefix", "from", "Metrics", "meters", "id", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/ControlHandler.java#L225-L237
36,354
esigate/esigate
esigate-server/src/main/java/org/esigate/server/ControlHandler.java
ControlHandler.stopServer
private void stopServer() { // Get current server final Server targetServer = this.getServer(); // Start a new thread in order to escape the destruction of this Handler // during the stop process. new Thread() { @Override public void run() { try { targetServer.stop(); } catch (Exception e) { // ignore } } }.start(); }
java
private void stopServer() { // Get current server final Server targetServer = this.getServer(); // Start a new thread in order to escape the destruction of this Handler // during the stop process. new Thread() { @Override public void run() { try { targetServer.stop(); } catch (Exception e) { // ignore } } }.start(); }
[ "private", "void", "stopServer", "(", ")", "{", "// Get current server", "final", "Server", "targetServer", "=", "this", ".", "getServer", "(", ")", ";", "// Start a new thread in order to escape the destruction of this Handler", "// during the stop process.", "new", "Thread"...
Start a new thread to shutdown the server
[ "Start", "a", "new", "thread", "to", "shutdown", "the", "server" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/ControlHandler.java#L242-L259
36,355
esigate/esigate
esigate-server/src/main/java/org/esigate/server/metrics/InstrumentedServerConnector.java
InstrumentedServerConnector.instrument
private void instrument(String id, int port, MetricRegistry registry) { this.setPort(port); this.accepts = registry.meter(id + "-accepts"); this.connects = registry.meter(id + "-connects"); this.disconnects = registry.meter(id + "-disconnects"); this.connections = registry.counter(id + "-active-connections"); }
java
private void instrument(String id, int port, MetricRegistry registry) { this.setPort(port); this.accepts = registry.meter(id + "-accepts"); this.connects = registry.meter(id + "-connects"); this.disconnects = registry.meter(id + "-disconnects"); this.connections = registry.counter(id + "-active-connections"); }
[ "private", "void", "instrument", "(", "String", "id", ",", "int", "port", ",", "MetricRegistry", "registry", ")", "{", "this", ".", "setPort", "(", "port", ")", ";", "this", ".", "accepts", "=", "registry", ".", "meter", "(", "id", "+", "\"-accepts\"", ...
Create metrics. @param id @param port @param registry
[ "Create", "metrics", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/metrics/InstrumentedServerConnector.java#L81-L88
36,356
esigate/esigate
esigate-core/src/main/java/org/esigate/http/HttpClientRequestExecutor.java
HttpClientRequestExecutor.execute
@Override public CloseableHttpResponse execute(OutgoingRequest httpRequest) throws HttpErrorPage { OutgoingRequestContext context = httpRequest.getContext(); IncomingRequest originalRequest = httpRequest.getOriginalRequest().getOriginalRequest(); if (cookieManager != null) { CookieStore cookieStore = new RequestCookieStore(cookieManager, httpRequest.getOriginalRequest()); context.setCookieStore(cookieStore); } HttpResponse result; // Create request event FragmentEvent event = new FragmentEvent(originalRequest, httpRequest, context); // EVENT pre eventManager.fire(EventManager.EVENT_FRAGMENT_PRE, event); // If exit : stop immediately. if (!event.isExit()) { // Proceed to request only if extensions did not inject a response. if (event.getHttpResponse() == null) { if (httpRequest.containsHeader(HttpHeaders.EXPECT)) { event.setHttpResponse(HttpErrorPage.generateHttpResponse(HttpStatus.SC_EXPECTATION_FAILED, "'Expect' request header is not supported")); } else { try { HttpHost physicalHost = context.getPhysicalHost(); result = httpClient.execute(physicalHost, httpRequest, context); } catch (IOException e) { result = HttpErrorPage.generateHttpResponse(e); LOG.warn(httpRequest.getRequestLine() + " -> " + result.getStatusLine().toString()); } event.setHttpResponse(BasicCloseableHttpResponse.adapt(result)); } } // EVENT post eventManager.fire(EventManager.EVENT_FRAGMENT_POST, event); } CloseableHttpResponse httpResponse = event.getHttpResponse(); if (httpResponse == null) { throw new HttpErrorPage(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Request was cancelled by server", "Request was cancelled by server"); } if (HttpResponseUtils.isError(httpResponse)) { throw new HttpErrorPage(httpResponse); } return httpResponse; }
java
@Override public CloseableHttpResponse execute(OutgoingRequest httpRequest) throws HttpErrorPage { OutgoingRequestContext context = httpRequest.getContext(); IncomingRequest originalRequest = httpRequest.getOriginalRequest().getOriginalRequest(); if (cookieManager != null) { CookieStore cookieStore = new RequestCookieStore(cookieManager, httpRequest.getOriginalRequest()); context.setCookieStore(cookieStore); } HttpResponse result; // Create request event FragmentEvent event = new FragmentEvent(originalRequest, httpRequest, context); // EVENT pre eventManager.fire(EventManager.EVENT_FRAGMENT_PRE, event); // If exit : stop immediately. if (!event.isExit()) { // Proceed to request only if extensions did not inject a response. if (event.getHttpResponse() == null) { if (httpRequest.containsHeader(HttpHeaders.EXPECT)) { event.setHttpResponse(HttpErrorPage.generateHttpResponse(HttpStatus.SC_EXPECTATION_FAILED, "'Expect' request header is not supported")); } else { try { HttpHost physicalHost = context.getPhysicalHost(); result = httpClient.execute(physicalHost, httpRequest, context); } catch (IOException e) { result = HttpErrorPage.generateHttpResponse(e); LOG.warn(httpRequest.getRequestLine() + " -> " + result.getStatusLine().toString()); } event.setHttpResponse(BasicCloseableHttpResponse.adapt(result)); } } // EVENT post eventManager.fire(EventManager.EVENT_FRAGMENT_POST, event); } CloseableHttpResponse httpResponse = event.getHttpResponse(); if (httpResponse == null) { throw new HttpErrorPage(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Request was cancelled by server", "Request was cancelled by server"); } if (HttpResponseUtils.isError(httpResponse)) { throw new HttpErrorPage(httpResponse); } return httpResponse; }
[ "@", "Override", "public", "CloseableHttpResponse", "execute", "(", "OutgoingRequest", "httpRequest", ")", "throws", "HttpErrorPage", "{", "OutgoingRequestContext", "context", "=", "httpRequest", ".", "getContext", "(", ")", ";", "IncomingRequest", "originalRequest", "=...
Execute a HTTP request. @param httpRequest HTTP request to execute. @return HTTP response. @throws HttpErrorPage if server returned no response or if the response as an error status code.
[ "Execute", "a", "HTTP", "request", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/HttpClientRequestExecutor.java#L285-L329
36,357
esigate/esigate
esigate-core/src/main/java/org/esigate/cache/CacheAdapter.java
CacheAdapter.init
public void init(Properties properties) { staleIfError = Parameters.STALE_IF_ERROR.getValue(properties); staleWhileRevalidate = Parameters.STALE_WHILE_REVALIDATE.getValue(properties); int maxAsynchronousWorkers = Parameters.MAX_ASYNCHRONOUS_WORKERS.getValue(properties); if (staleWhileRevalidate > 0 && maxAsynchronousWorkers == 0) { throw new ConfigurationException("You must set a positive value for maxAsynchronousWorkers " + "in order to enable background revalidation (staleWhileRevalidate)"); } ttl = Parameters.TTL.getValue(properties); xCacheHeader = Parameters.X_CACHE_HEADER.getValue(properties); viaHeader = Parameters.VIA_HEADER.getValue(properties); LOG.info("Initializing cache for provider " + Arrays.toString(Parameters.REMOTE_URL_BASE.getValue(properties)) + " staleIfError=" + staleIfError + " staleWhileRevalidate=" + staleWhileRevalidate + " ttl=" + ttl + " xCacheHeader=" + xCacheHeader + " viaHeader=" + viaHeader); }
java
public void init(Properties properties) { staleIfError = Parameters.STALE_IF_ERROR.getValue(properties); staleWhileRevalidate = Parameters.STALE_WHILE_REVALIDATE.getValue(properties); int maxAsynchronousWorkers = Parameters.MAX_ASYNCHRONOUS_WORKERS.getValue(properties); if (staleWhileRevalidate > 0 && maxAsynchronousWorkers == 0) { throw new ConfigurationException("You must set a positive value for maxAsynchronousWorkers " + "in order to enable background revalidation (staleWhileRevalidate)"); } ttl = Parameters.TTL.getValue(properties); xCacheHeader = Parameters.X_CACHE_HEADER.getValue(properties); viaHeader = Parameters.VIA_HEADER.getValue(properties); LOG.info("Initializing cache for provider " + Arrays.toString(Parameters.REMOTE_URL_BASE.getValue(properties)) + " staleIfError=" + staleIfError + " staleWhileRevalidate=" + staleWhileRevalidate + " ttl=" + ttl + " xCacheHeader=" + xCacheHeader + " viaHeader=" + viaHeader); }
[ "public", "void", "init", "(", "Properties", "properties", ")", "{", "staleIfError", "=", "Parameters", ".", "STALE_IF_ERROR", ".", "getValue", "(", "properties", ")", ";", "staleWhileRevalidate", "=", "Parameters", ".", "STALE_WHILE_REVALIDATE", ".", "getValue", ...
Inititalize the instance. @param properties properties
[ "Inititalize", "the", "instance", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/cache/CacheAdapter.java#L59-L73
36,358
esigate/esigate
esigate-core/src/main/java/org/esigate/DriverConfiguration.java
DriverConfiguration.parseMappings
private static List<UriMapping> parseMappings(Properties props) { List<UriMapping> mappings = new ArrayList<>(); Collection<String> mappingsParam = Parameters.MAPPINGS.getValue(props); for (String mappingParam : mappingsParam) { mappings.add(UriMapping.create(mappingParam)); } return mappings; }
java
private static List<UriMapping> parseMappings(Properties props) { List<UriMapping> mappings = new ArrayList<>(); Collection<String> mappingsParam = Parameters.MAPPINGS.getValue(props); for (String mappingParam : mappingsParam) { mappings.add(UriMapping.create(mappingParam)); } return mappings; }
[ "private", "static", "List", "<", "UriMapping", ">", "parseMappings", "(", "Properties", "props", ")", "{", "List", "<", "UriMapping", ">", "mappings", "=", "new", "ArrayList", "<>", "(", ")", ";", "Collection", "<", "String", ">", "mappingsParam", "=", "P...
Read the "Mappings" parameter and create the corresponding UriMapping rules. @param props @return The mapping rules for this driver instance.
[ "Read", "the", "Mappings", "parameter", "and", "create", "the", "corresponding", "UriMapping", "rules", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/DriverConfiguration.java#L64-L73
36,359
esigate/esigate
esigate-core/src/main/java/org/esigate/http/cookie/CookieUtil.java
CookieUtil.encodeCookie
public static String encodeCookie(Cookie cookie) { int maxAge = -1; if (cookie.getExpiryDate() != null) { maxAge = (int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / ONE_SECOND); // According to Cookie class specification, a negative value // would be considered as no value. That is not what we want! if (maxAge < 0) { maxAge = 0; } } String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); StringBuilder buffer = new StringBuilder(); // Copied from org.apache.http.impl.cookie.BrowserCompatSpec.formatCookies(List<Cookie>) if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) { buffer.append(BasicHeaderValueFormatter.INSTANCE.formatHeaderElement(null, new BasicHeaderElement(cookieName, cookieValue), false).toString()); } else { // Netscape style cookies do not support quoted values buffer.append(cookieName); buffer.append("="); if (cookieValue != null) { buffer.append(cookieValue); } } // End copy appendAttribute(buffer, "Comment", cookie.getComment()); appendAttribute(buffer, "Domain", cookie.getDomain()); appendAttribute(buffer, "Max-Age", maxAge); appendAttribute(buffer, "Path", cookie.getPath()); if (cookie.isSecure()) { appendAttribute(buffer, "Secure"); } if (((BasicClientCookie) cookie).containsAttribute(HTTP_ONLY_ATTR)) { appendAttribute(buffer, "HttpOnly"); } appendAttribute(buffer, "Version", cookie.getVersion()); return (buffer.toString()); }
java
public static String encodeCookie(Cookie cookie) { int maxAge = -1; if (cookie.getExpiryDate() != null) { maxAge = (int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / ONE_SECOND); // According to Cookie class specification, a negative value // would be considered as no value. That is not what we want! if (maxAge < 0) { maxAge = 0; } } String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); StringBuilder buffer = new StringBuilder(); // Copied from org.apache.http.impl.cookie.BrowserCompatSpec.formatCookies(List<Cookie>) if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) { buffer.append(BasicHeaderValueFormatter.INSTANCE.formatHeaderElement(null, new BasicHeaderElement(cookieName, cookieValue), false).toString()); } else { // Netscape style cookies do not support quoted values buffer.append(cookieName); buffer.append("="); if (cookieValue != null) { buffer.append(cookieValue); } } // End copy appendAttribute(buffer, "Comment", cookie.getComment()); appendAttribute(buffer, "Domain", cookie.getDomain()); appendAttribute(buffer, "Max-Age", maxAge); appendAttribute(buffer, "Path", cookie.getPath()); if (cookie.isSecure()) { appendAttribute(buffer, "Secure"); } if (((BasicClientCookie) cookie).containsAttribute(HTTP_ONLY_ATTR)) { appendAttribute(buffer, "HttpOnly"); } appendAttribute(buffer, "Version", cookie.getVersion()); return (buffer.toString()); }
[ "public", "static", "String", "encodeCookie", "(", "Cookie", "cookie", ")", "{", "int", "maxAge", "=", "-", "1", ";", "if", "(", "cookie", ".", "getExpiryDate", "(", ")", "!=", "null", ")", "{", "maxAge", "=", "(", "int", ")", "(", "(", "cookie", "...
Utility method to transform a Cookie into a Set-Cookie Header. @param cookie the {@link Cookie} to format @return the value of the Set-Cookie header
[ "Utility", "method", "to", "transform", "a", "Cookie", "into", "a", "Set", "-", "Cookie", "Header", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/cookie/CookieUtil.java#L49-L92
36,360
esigate/esigate
esigate-core/src/main/java/org/esigate/extension/ExtensionFactory.java
ExtensionFactory.getExtension
public static <T extends Extension> T getExtension(Properties properties, Parameter<String> parameter, Driver d) { T result; String className = parameter.getValue(properties); if (className == null) { return null; } try { if (LOG.isDebugEnabled()) { LOG.debug("Creating extension " + className); } result = (T) Class.forName(className).newInstance(); result.init(d, properties); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new ConfigurationException(e); } return result; }
java
public static <T extends Extension> T getExtension(Properties properties, Parameter<String> parameter, Driver d) { T result; String className = parameter.getValue(properties); if (className == null) { return null; } try { if (LOG.isDebugEnabled()) { LOG.debug("Creating extension " + className); } result = (T) Class.forName(className).newInstance(); result.init(d, properties); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new ConfigurationException(e); } return result; }
[ "public", "static", "<", "T", "extends", "Extension", ">", "T", "getExtension", "(", "Properties", "properties", ",", "Parameter", "<", "String", ">", "parameter", ",", "Driver", "d", ")", "{", "T", "result", ";", "String", "className", "=", "parameter", "...
Get an extension as configured in properties. @param properties properties @param parameter the class name parameter @param d driver @param <T> class which extends Extension class which extends Extension @return instance of {@link Extension} or null.
[ "Get", "an", "extension", "as", "configured", "in", "properties", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/extension/ExtensionFactory.java#L57-L73
36,361
esigate/esigate
esigate-core/src/main/java/org/esigate/parser/ParserContextImpl.java
ParserContextImpl.characters
void characters(CharSequence csq, int start, int end) throws IOException { getCurrent().characters(csq, start, end); }
java
void characters(CharSequence csq, int start, int end) throws IOException { getCurrent().characters(csq, start, end); }
[ "void", "characters", "(", "CharSequence", "csq", ",", "int", "start", ",", "int", "end", ")", "throws", "IOException", "{", "getCurrent", "(", ")", ".", "characters", "(", "csq", ",", "start", ",", "end", ")", ";", "}" ]
Writes characters into current writer.
[ "Writes", "characters", "into", "current", "writer", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/parser/ParserContextImpl.java#L107-L109
36,362
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.getProperty
private static int getProperty(String prefix, String name, int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(System.getProperty(prefix + name)); } catch (NumberFormatException e) { LOG.warn("Value for " + prefix + name + " must be an integer. Using default " + defaultValue); } return result; }
java
private static int getProperty(String prefix, String name, int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(System.getProperty(prefix + name)); } catch (NumberFormatException e) { LOG.warn("Value for " + prefix + name + " must be an integer. Using default " + defaultValue); } return result; }
[ "private", "static", "int", "getProperty", "(", "String", "prefix", ",", "String", "name", ",", "int", "defaultValue", ")", "{", "int", "result", "=", "defaultValue", ";", "try", "{", "result", "=", "Integer", ".", "parseInt", "(", "System", ".", "getPrope...
Get an integer from System properties @param prefix @param name @param defaultValue @return
[ "Get", "an", "integer", "from", "System", "properties" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L87-L96
36,363
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.getProperty
private static String getProperty(String prefix, String name, String defaultValue) { return System.getProperty(prefix + name, defaultValue); }
java
private static String getProperty(String prefix, String name, String defaultValue) { return System.getProperty(prefix + name, defaultValue); }
[ "private", "static", "String", "getProperty", "(", "String", "prefix", ",", "String", "name", ",", "String", "defaultValue", ")", "{", "return", "System", ".", "getProperty", "(", "prefix", "+", "name", ",", "defaultValue", ")", ";", "}" ]
Get String from System properties @param prefix @param name @param defaultValue @return
[ "Get", "String", "from", "System", "properties" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L106-L108
36,364
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.init
public static void init() { // Get configuration // Read from "server.properties" or custom file. String configFile = null; Properties serverProperties = new Properties(); try { configFile = System.getProperty(PROPERTY_PREFIX + "config", "server.properties"); LOG.info("Loading server configuration from " + configFile); try (InputStream is = new FileInputStream(configFile)) { serverProperties.load(is); } } catch (FileNotFoundException e) { LOG.warn(configFile + " not found."); } catch (IOException e) { LOG.error("Unexpected error reading " + configFile); } init(serverProperties); }
java
public static void init() { // Get configuration // Read from "server.properties" or custom file. String configFile = null; Properties serverProperties = new Properties(); try { configFile = System.getProperty(PROPERTY_PREFIX + "config", "server.properties"); LOG.info("Loading server configuration from " + configFile); try (InputStream is = new FileInputStream(configFile)) { serverProperties.load(is); } } catch (FileNotFoundException e) { LOG.warn(configFile + " not found."); } catch (IOException e) { LOG.error("Unexpected error reading " + configFile); } init(serverProperties); }
[ "public", "static", "void", "init", "(", ")", "{", "// Get configuration", "// Read from \"server.properties\" or custom file.", "String", "configFile", "=", "null", ";", "Properties", "serverProperties", "=", "new", "Properties", "(", ")", ";", "try", "{", "configFil...
Read server configuration from System properties and from server.properties.
[ "Read", "server", "configuration", "from", "System", "properties", "and", "from", "server", ".", "properties", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L113-L135
36,365
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.init
public static void init(Properties configuration) { for (Object prop : configuration.keySet()) { String serverPropertyName = (String) prop; System.setProperty(PROPERTY_PREFIX + serverPropertyName, configuration.getProperty(serverPropertyName)); } // Read system properties LOG.info("Using configuration provided using '-D' parameter and/or default values"); EsigateServer.port = getProperty(PROPERTY_PREFIX, "port", PROPERTY_DEFAULT_HTTP_PORT); EsigateServer.controlPort = getProperty(PROPERTY_PREFIX, "controlPort", PROPERTY_DEFAULT_CONTROL_PORT); EsigateServer.contextPath = getProperty(PROPERTY_PREFIX, "contextPath", "/"); EsigateServer.extraClasspath = getProperty(PROPERTY_PREFIX, "extraClasspath", null); EsigateServer.maxThreads = getProperty(PROPERTY_PREFIX, "maxThreads", 500); EsigateServer.minThreads = getProperty(PROPERTY_PREFIX, "minThreads", 40); EsigateServer.outputBufferSize = getProperty(PROPERTY_PREFIX, "outputBufferSize", 8 * 1024); EsigateServer.idleTimeout = getProperty(PROPERTY_PREFIX, "idleTimeout", 30 * 1000); EsigateServer.sessionCookieName = getProperty(PROPERTY_PREFIX, "sessionCookieName", null); }
java
public static void init(Properties configuration) { for (Object prop : configuration.keySet()) { String serverPropertyName = (String) prop; System.setProperty(PROPERTY_PREFIX + serverPropertyName, configuration.getProperty(serverPropertyName)); } // Read system properties LOG.info("Using configuration provided using '-D' parameter and/or default values"); EsigateServer.port = getProperty(PROPERTY_PREFIX, "port", PROPERTY_DEFAULT_HTTP_PORT); EsigateServer.controlPort = getProperty(PROPERTY_PREFIX, "controlPort", PROPERTY_DEFAULT_CONTROL_PORT); EsigateServer.contextPath = getProperty(PROPERTY_PREFIX, "contextPath", "/"); EsigateServer.extraClasspath = getProperty(PROPERTY_PREFIX, "extraClasspath", null); EsigateServer.maxThreads = getProperty(PROPERTY_PREFIX, "maxThreads", 500); EsigateServer.minThreads = getProperty(PROPERTY_PREFIX, "minThreads", 40); EsigateServer.outputBufferSize = getProperty(PROPERTY_PREFIX, "outputBufferSize", 8 * 1024); EsigateServer.idleTimeout = getProperty(PROPERTY_PREFIX, "idleTimeout", 30 * 1000); EsigateServer.sessionCookieName = getProperty(PROPERTY_PREFIX, "sessionCookieName", null); }
[ "public", "static", "void", "init", "(", "Properties", "configuration", ")", "{", "for", "(", "Object", "prop", ":", "configuration", ".", "keySet", "(", ")", ")", "{", "String", "serverPropertyName", "=", "(", "String", ")", "prop", ";", "System", ".", ...
Set the provided server configuration then read configuration from System properties or load defaults. @param configuration configuration to use.
[ "Set", "the", "provided", "server", "configuration", "then", "read", "configuration", "from", "System", "properties", "or", "load", "defaults", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L143-L161
36,366
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.main
public static void main(String[] args) throws Exception { if (args.length < 1) { EsigateServer.usage(); return; } switch (args[0]) { case "start": EsigateServer.init(); EsigateServer.start(); break; case "stop": EsigateServer.stop(); break; default: EsigateServer.usage(); break; } }
java
public static void main(String[] args) throws Exception { if (args.length < 1) { EsigateServer.usage(); return; } switch (args[0]) { case "start": EsigateServer.init(); EsigateServer.start(); break; case "stop": EsigateServer.stop(); break; default: EsigateServer.usage(); break; } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "if", "(", "args", ".", "length", "<", "1", ")", "{", "EsigateServer", ".", "usage", "(", ")", ";", "return", ";", "}", "switch", "(", "args", "["...
Esigate Server entry point. @param args command line arguments. @throws Exception when server cannot be started.
[ "Esigate", "Server", "entry", "point", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L180-L201
36,367
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.start
public static void start() throws Exception { MetricRegistry registry = new MetricRegistry(); QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry); threadPool.setName("esigate"); threadPool.setMaxThreads(maxThreads); threadPool.setMinThreads(minThreads); srv = new Server(threadPool); srv.setStopAtShutdown(true); srv.setStopTimeout(5000); // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setOutputBufferSize(outputBufferSize); httpConfig.setSendServerVersion(false); Timer processTime = registry.timer("processTime"); try (ServerConnector connector = new InstrumentedServerConnector("main", EsigateServer.port, srv, registry, new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime)); ServerConnector controlConnector = new ServerConnector(srv)) { // Main connector connector.setIdleTimeout(EsigateServer.idleTimeout); connector.setSoLingerTime(-1); connector.setName("main"); connector.setAcceptQueueSize(200); // Control connector controlConnector.setHost("127.0.0.1"); controlConnector.setPort(EsigateServer.controlPort); controlConnector.setName("control"); srv.setConnectors(new Connector[] {connector, controlConnector}); // War ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain(); String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm(); String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent(); File workDir = resetTempDirectory(currentDir); WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath); context.setServer(srv); context.setTempDirectory(workDir); if (StringUtils.isNoneEmpty(sessionCookieName)) { context.getSessionHandler().getSessionManager().getSessionCookieConfig().setName(sessionCookieName); } // Add extra classpath (allows to add extensions). if (EsigateServer.extraClasspath != null) { context.setExtraClasspath(EsigateServer.extraClasspath); } // Add the handlers HandlerCollection handlers = new HandlerList(); // control handler must be the first one. // Work in progress, currently disabled. handlers.addHandler(new ControlHandler(registry)); InstrumentedHandler ih = new InstrumentedHandler(registry); ih.setName("main"); ih.setHandler(context); handlers.addHandler(ih); srv.setHandler(handlers); srv.start(); srv.join(); } }
java
public static void start() throws Exception { MetricRegistry registry = new MetricRegistry(); QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry); threadPool.setName("esigate"); threadPool.setMaxThreads(maxThreads); threadPool.setMinThreads(minThreads); srv = new Server(threadPool); srv.setStopAtShutdown(true); srv.setStopTimeout(5000); // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setOutputBufferSize(outputBufferSize); httpConfig.setSendServerVersion(false); Timer processTime = registry.timer("processTime"); try (ServerConnector connector = new InstrumentedServerConnector("main", EsigateServer.port, srv, registry, new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime)); ServerConnector controlConnector = new ServerConnector(srv)) { // Main connector connector.setIdleTimeout(EsigateServer.idleTimeout); connector.setSoLingerTime(-1); connector.setName("main"); connector.setAcceptQueueSize(200); // Control connector controlConnector.setHost("127.0.0.1"); controlConnector.setPort(EsigateServer.controlPort); controlConnector.setName("control"); srv.setConnectors(new Connector[] {connector, controlConnector}); // War ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain(); String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm(); String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent(); File workDir = resetTempDirectory(currentDir); WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath); context.setServer(srv); context.setTempDirectory(workDir); if (StringUtils.isNoneEmpty(sessionCookieName)) { context.getSessionHandler().getSessionManager().getSessionCookieConfig().setName(sessionCookieName); } // Add extra classpath (allows to add extensions). if (EsigateServer.extraClasspath != null) { context.setExtraClasspath(EsigateServer.extraClasspath); } // Add the handlers HandlerCollection handlers = new HandlerList(); // control handler must be the first one. // Work in progress, currently disabled. handlers.addHandler(new ControlHandler(registry)); InstrumentedHandler ih = new InstrumentedHandler(registry); ih.setName("main"); ih.setHandler(context); handlers.addHandler(ih); srv.setHandler(handlers); srv.start(); srv.join(); } }
[ "public", "static", "void", "start", "(", ")", "throws", "Exception", "{", "MetricRegistry", "registry", "=", "new", "MetricRegistry", "(", ")", ";", "QueuedThreadPool", "threadPool", "=", "new", "InstrumentedQueuedThreadPool", "(", "registry", ")", ";", "threadPo...
Create and start server. @throws Exception when server cannot be started.
[ "Create", "and", "start", "server", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L232-L301
36,368
esigate/esigate
esigate-server/src/main/java/org/esigate/server/EsigateServer.java
EsigateServer.usage
private static void usage() { StringBuilder usageText = new StringBuilder(); usageText.append("Usage: java -D").append(PROPERTY_PREFIX) .append("config=esigate.properties -jar esigate-server.jar [start|stop]\n\t"); usageText.append("start Start the server (default)\n\t"); usageText.append("stop Stop the server gracefully\n\t"); System.out.println(usageText.toString()); System.exit(-1); }
java
private static void usage() { StringBuilder usageText = new StringBuilder(); usageText.append("Usage: java -D").append(PROPERTY_PREFIX) .append("config=esigate.properties -jar esigate-server.jar [start|stop]\n\t"); usageText.append("start Start the server (default)\n\t"); usageText.append("stop Stop the server gracefully\n\t"); System.out.println(usageText.toString()); System.exit(-1); }
[ "private", "static", "void", "usage", "(", ")", "{", "StringBuilder", "usageText", "=", "new", "StringBuilder", "(", ")", ";", "usageText", ".", "append", "(", "\"Usage: java -D\"", ")", ".", "append", "(", "PROPERTY_PREFIX", ")", ".", "append", "(", "\"conf...
Display usage information.
[ "Display", "usage", "information", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-server/src/main/java/org/esigate/server/EsigateServer.java#L322-L331
36,369
esigate/esigate
esigate-core/src/main/java/org/esigate/util/UriUtils.java
UriUtils.encodeIllegalCharacters
public static String encodeIllegalCharacters(String uri) { StringBuilder result = new StringBuilder(); int length = uri.length(); for (int i = 0; i < length; i++) { char character = uri.charAt(i); if (character == '%') { // Encode invalid escape sequences if (i >= length - 2 || !isHex(uri.charAt(i + 1)) || !isHex(uri.charAt(i + 2))) { result.append("%25"); } else { result.append('%'); } } else { int j = (int) character; if (j >= CONVERSION_TABLE_SIZE || j < 0) { result.append(encode(character)); } else { result.append(CONVERSION_TABLE[j]); } } } return result.toString(); }
java
public static String encodeIllegalCharacters(String uri) { StringBuilder result = new StringBuilder(); int length = uri.length(); for (int i = 0; i < length; i++) { char character = uri.charAt(i); if (character == '%') { // Encode invalid escape sequences if (i >= length - 2 || !isHex(uri.charAt(i + 1)) || !isHex(uri.charAt(i + 2))) { result.append("%25"); } else { result.append('%'); } } else { int j = (int) character; if (j >= CONVERSION_TABLE_SIZE || j < 0) { result.append(encode(character)); } else { result.append(CONVERSION_TABLE[j]); } } } return result.toString(); }
[ "public", "static", "String", "encodeIllegalCharacters", "(", "String", "uri", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "int", "length", "=", "uri", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "0", ...
Fixes common mistakes in URI by replacing all illegal characters by their encoded value. @param uri the URI to fix @return the fixed URI
[ "Fixes", "common", "mistakes", "in", "URI", "by", "replacing", "all", "illegal", "characters", "by", "their", "encoded", "value", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/UriUtils.java#L76-L98
36,370
esigate/esigate
esigate-core/src/main/java/org/esigate/util/UriUtils.java
UriUtils.createURI
public static String createURI(final String scheme, final String host, int port, final String path, final String query, final String fragment) { StringBuilder buffer = new StringBuilder(Parameters.SMALL_BUFFER_SIZE); if (host != null) { if (scheme != null) { buffer.append(scheme); buffer.append("://"); } buffer.append(host); if (port > 0) { buffer.append(':'); buffer.append(port); } } if (path == null || !path.startsWith("/")) { buffer.append('/'); } if (path != null) { buffer.append(path); } if (query != null) { buffer.append('?'); buffer.append(query); } if (fragment != null) { buffer.append('#'); buffer.append(fragment); } return buffer.toString(); }
java
public static String createURI(final String scheme, final String host, int port, final String path, final String query, final String fragment) { StringBuilder buffer = new StringBuilder(Parameters.SMALL_BUFFER_SIZE); if (host != null) { if (scheme != null) { buffer.append(scheme); buffer.append("://"); } buffer.append(host); if (port > 0) { buffer.append(':'); buffer.append(port); } } if (path == null || !path.startsWith("/")) { buffer.append('/'); } if (path != null) { buffer.append(path); } if (query != null) { buffer.append('?'); buffer.append(query); } if (fragment != null) { buffer.append('#'); buffer.append(fragment); } return buffer.toString(); }
[ "public", "static", "String", "createURI", "(", "final", "String", "scheme", ",", "final", "String", "host", ",", "int", "port", ",", "final", "String", "path", ",", "final", "String", "query", ",", "final", "String", "fragment", ")", "{", "StringBuilder", ...
Creates an URI as a String. @param scheme the scheme @param host the host @param port the port @param path the path @param query the query @param fragment the fragment @return the uri
[ "Creates", "an", "URI", "as", "a", "String", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/UriUtils.java#L134-L163
36,371
esigate/esigate
esigate-core/src/main/java/org/esigate/util/UriUtils.java
UriUtils.rewriteURI
public static String rewriteURI(String uri, HttpHost targetHost) { try { return URIUtils.rewriteURI(createURI(uri), targetHost).toString(); } catch (URISyntaxException e) { throw new InvalidUriException(e); } }
java
public static String rewriteURI(String uri, HttpHost targetHost) { try { return URIUtils.rewriteURI(createURI(uri), targetHost).toString(); } catch (URISyntaxException e) { throw new InvalidUriException(e); } }
[ "public", "static", "String", "rewriteURI", "(", "String", "uri", ",", "HttpHost", "targetHost", ")", "{", "try", "{", "return", "URIUtils", ".", "rewriteURI", "(", "createURI", "(", "uri", ")", ",", "targetHost", ")", ".", "toString", "(", ")", ";", "}"...
Replaces the scheme, host and port in a URI. @param uri the URI @param targetHost the target host @return the rewritten URI
[ "Replaces", "the", "scheme", "host", "and", "port", "in", "a", "URI", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/UriUtils.java#L226-L232
36,372
esigate/esigate
esigate-core/src/main/java/org/esigate/util/UriUtils.java
UriUtils.removeSessionId
public static String removeSessionId(String sessionId, String page) { String regexp = ";?jsessionid=" + Pattern.quote(sessionId); return page.replaceAll(regexp, ""); }
java
public static String removeSessionId(String sessionId, String page) { String regexp = ";?jsessionid=" + Pattern.quote(sessionId); return page.replaceAll(regexp, ""); }
[ "public", "static", "String", "removeSessionId", "(", "String", "sessionId", ",", "String", "page", ")", "{", "String", "regexp", "=", "\";?jsessionid=\"", "+", "Pattern", ".", "quote", "(", "sessionId", ")", ";", "return", "page", ".", "replaceAll", "(", "r...
Removes the jsessionid that may have been added to a URI on a java application server. @param sessionId the value of the sessionId that can also be found in a JSESSIONID cookie @param page the html code of the page @return the fixed html
[ "Removes", "the", "jsessionid", "that", "may", "have", "been", "added", "to", "a", "URI", "on", "a", "java", "application", "server", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/UriUtils.java#L243-L246
36,373
esigate/esigate
esigate-core/src/main/java/org/esigate/util/UriUtils.java
UriUtils.removeQuerystring
public static String removeQuerystring(String uriString) { URI uri = createURI(uriString); try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null) .toASCIIString(); } catch (URISyntaxException e) { throw new InvalidUriException(e); } }
java
public static String removeQuerystring(String uriString) { URI uri = createURI(uriString); try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null, null) .toASCIIString(); } catch (URISyntaxException e) { throw new InvalidUriException(e); } }
[ "public", "static", "String", "removeQuerystring", "(", "String", "uriString", ")", "{", "URI", "uri", "=", "createURI", "(", "uriString", ")", ";", "try", "{", "return", "new", "URI", "(", "uri", ".", "getScheme", "(", ")", ",", "uri", ".", "getUserInfo...
Removes the query and fragment at the end of a URI. @param uriString the original URI as a String @return the URI without querystring nor fragment
[ "Removes", "the", "query", "and", "fragment", "at", "the", "end", "of", "a", "URI", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/UriUtils.java#L384-L392
36,374
esigate/esigate
esigate-core/src/main/java/org/esigate/http/DateUtils.java
DateUtils.formatDate
public static String formatDate(Date date) { return org.apache.http.client.utils.DateUtils.formatDate(date); }
java
public static String formatDate(Date date) { return org.apache.http.client.utils.DateUtils.formatDate(date); }
[ "public", "static", "String", "formatDate", "(", "Date", "date", ")", "{", "return", "org", ".", "apache", ".", "http", ".", "client", ".", "utils", ".", "DateUtils", ".", "formatDate", "(", "date", ")", ";", "}" ]
Formats the given date according to the RFC 1123 pattern. @param date The date to format. @return An RFC 1123 formatted date string.
[ "Formats", "the", "given", "date", "according", "to", "the", "RFC", "1123", "pattern", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/DateUtils.java#L18-L20
36,375
esigate/esigate
esigate-core/src/main/java/org/esigate/aggregator/ElementAttributesFactory.java
ElementAttributesFactory.createElementAttributes
static ElementAttributes createElementAttributes(String tag) { // Parsing strings // <!--$includetemplate$aggregated2$templatewithparams.jsp$--> // or // <!--$includeblock$aggregated2$$(block)$myblock$--> // in order to retrieve driver, page and name attributes Pattern pattern = Pattern.compile("(?<=\\$)(?:[^\\$]|\\$\\()*(?=\\$)"); Matcher matcher = pattern.matcher(tag); List<String> listparameters = new ArrayList<>(); while (matcher.find()) { listparameters.add(matcher.group()); } String[] parameters = listparameters.toArray(new String[listparameters.size()]); Driver driver; String page = ""; String name = null; if (parameters.length > 1) { driver = DriverFactory.getInstance(parameters[1]); } else { driver = DriverFactory.getInstance(); } if (parameters.length > 2) { page = parameters[2]; } if (parameters.length > 3) { name = parameters[3]; } return new ElementAttributes(driver, page, name); }
java
static ElementAttributes createElementAttributes(String tag) { // Parsing strings // <!--$includetemplate$aggregated2$templatewithparams.jsp$--> // or // <!--$includeblock$aggregated2$$(block)$myblock$--> // in order to retrieve driver, page and name attributes Pattern pattern = Pattern.compile("(?<=\\$)(?:[^\\$]|\\$\\()*(?=\\$)"); Matcher matcher = pattern.matcher(tag); List<String> listparameters = new ArrayList<>(); while (matcher.find()) { listparameters.add(matcher.group()); } String[] parameters = listparameters.toArray(new String[listparameters.size()]); Driver driver; String page = ""; String name = null; if (parameters.length > 1) { driver = DriverFactory.getInstance(parameters[1]); } else { driver = DriverFactory.getInstance(); } if (parameters.length > 2) { page = parameters[2]; } if (parameters.length > 3) { name = parameters[3]; } return new ElementAttributes(driver, page, name); }
[ "static", "ElementAttributes", "createElementAttributes", "(", "String", "tag", ")", "{", "// Parsing strings", "// <!--$includetemplate$aggregated2$templatewithparams.jsp$-->", "// or", "// <!--$includeblock$aggregated2$$(block)$myblock$-->", "// in order to retrieve driver, page and name a...
Parse the tag and return the ElementAttributes @param tag the tag to parse @return ElementAttributes
[ "Parse", "the", "tag", "and", "return", "the", "ElementAttributes" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/aggregator/ElementAttributesFactory.java#L28-L62
36,376
esigate/esigate
esigate-core/src/main/java/org/esigate/http/ContentTypeHelper.java
ContentTypeHelper.isTextContentType
public boolean isTextContentType(HttpResponse httpResponse) { String contentType = HttpResponseUtils.getFirstHeader(HttpHeaders.CONTENT_TYPE, httpResponse); return isTextContentType(contentType); }
java
public boolean isTextContentType(HttpResponse httpResponse) { String contentType = HttpResponseUtils.getFirstHeader(HttpHeaders.CONTENT_TYPE, httpResponse); return isTextContentType(contentType); }
[ "public", "boolean", "isTextContentType", "(", "HttpResponse", "httpResponse", ")", "{", "String", "contentType", "=", "HttpResponseUtils", ".", "getFirstHeader", "(", "HttpHeaders", ".", "CONTENT_TYPE", ",", "httpResponse", ")", ";", "return", "isTextContentType", "(...
Check whether the given request's content-type corresponds to "parseable" text. @param httpResponse the response to analyze depending on its content-type @return true if this represents text or false if not
[ "Check", "whether", "the", "given", "request", "s", "content", "-", "type", "corresponds", "to", "parseable", "text", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/ContentTypeHelper.java#L39-L42
36,377
esigate/esigate
esigate-core/src/main/java/org/esigate/http/ContentTypeHelper.java
ContentTypeHelper.isTextContentType
public boolean isTextContentType(String contentType) { if (contentType != null) { String lowerContentType = contentType.toLowerCase(); for (String textContentType : this.parsableContentTypes) { if (lowerContentType.startsWith(textContentType)) { return true; } } } return false; }
java
public boolean isTextContentType(String contentType) { if (contentType != null) { String lowerContentType = contentType.toLowerCase(); for (String textContentType : this.parsableContentTypes) { if (lowerContentType.startsWith(textContentType)) { return true; } } } return false; }
[ "public", "boolean", "isTextContentType", "(", "String", "contentType", ")", "{", "if", "(", "contentType", "!=", "null", ")", "{", "String", "lowerContentType", "=", "contentType", ".", "toLowerCase", "(", ")", ";", "for", "(", "String", "textContentType", ":...
Check whether the given content-type corresponds to "parseable" text. @param contentType the input content-type @return true if this represents text or false if not
[ "Check", "whether", "the", "given", "content", "-", "type", "corresponds", "to", "parseable", "text", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/ContentTypeHelper.java#L51-L61
36,378
esigate/esigate
esigate-core/src/main/java/org/esigate/DriverFactory.java
DriverFactory.configure
public static void configure() { InputStream inputStream = null; try { URL configUrl = getConfigUrl(); if (configUrl == null) { throw new ConfigurationException("esigate.properties configuration file " + "was not found in the classpath"); } inputStream = configUrl.openStream(); Properties merged = new Properties(); if (inputStream != null) { Properties props = new Properties(); props.load(inputStream); merged.putAll(props); } configure(merged); } catch (IOException e) { throw new ConfigurationException("Error loading configuration", e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { throw new ConfigurationException("failed to close stream", e); } } }
java
public static void configure() { InputStream inputStream = null; try { URL configUrl = getConfigUrl(); if (configUrl == null) { throw new ConfigurationException("esigate.properties configuration file " + "was not found in the classpath"); } inputStream = configUrl.openStream(); Properties merged = new Properties(); if (inputStream != null) { Properties props = new Properties(); props.load(inputStream); merged.putAll(props); } configure(merged); } catch (IOException e) { throw new ConfigurationException("Error loading configuration", e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { throw new ConfigurationException("failed to close stream", e); } } }
[ "public", "static", "void", "configure", "(", ")", "{", "InputStream", "inputStream", "=", "null", ";", "try", "{", "URL", "configUrl", "=", "getConfigUrl", "(", ")", ";", "if", "(", "configUrl", "==", "null", ")", "{", "throw", "new", "ConfigurationExcept...
Loads all instances according to default configuration file.
[ "Loads", "all", "instances", "according", "to", "default", "configuration", "file", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/DriverFactory.java#L111-L144
36,379
esigate/esigate
esigate-core/src/main/java/org/esigate/DriverFactory.java
DriverFactory.configure
public static void configure(Properties props) { Properties defaultProperties = new Properties(); HashMap<String, Properties> driversProps = new HashMap<>(); for (Enumeration<?> enumeration = props.propertyNames(); enumeration.hasMoreElements();) { String propertyName = (String) enumeration.nextElement(); String value = props.getProperty(propertyName); int idx = propertyName.lastIndexOf('.'); if (idx < 0) { defaultProperties.put(propertyName, value); } else { String prefix = propertyName.substring(0, idx); String name = propertyName.substring(idx + 1); Properties driverProperties = driversProps.get(prefix); if (driverProperties == null) { driverProperties = new Properties(); driversProps.put(prefix, driverProperties); } driverProperties.put(name, value); } } // Merge with default properties Map<String, Driver> newInstances = new HashMap<>(); for (Entry<String, Properties> entry : driversProps.entrySet()) { String name = entry.getKey(); Properties properties = new Properties(); properties.putAll(defaultProperties); properties.putAll(entry.getValue()); newInstances.put(name, createDriver(name, properties)); } if (newInstances.get(DEFAULT_INSTANCE_NAME) == null && Parameters.REMOTE_URL_BASE.getValue(defaultProperties) != null) { newInstances.put(DEFAULT_INSTANCE_NAME, createDriver(DEFAULT_INSTANCE_NAME, defaultProperties)); } instances = new IndexedInstances(newInstances); }
java
public static void configure(Properties props) { Properties defaultProperties = new Properties(); HashMap<String, Properties> driversProps = new HashMap<>(); for (Enumeration<?> enumeration = props.propertyNames(); enumeration.hasMoreElements();) { String propertyName = (String) enumeration.nextElement(); String value = props.getProperty(propertyName); int idx = propertyName.lastIndexOf('.'); if (idx < 0) { defaultProperties.put(propertyName, value); } else { String prefix = propertyName.substring(0, idx); String name = propertyName.substring(idx + 1); Properties driverProperties = driversProps.get(prefix); if (driverProperties == null) { driverProperties = new Properties(); driversProps.put(prefix, driverProperties); } driverProperties.put(name, value); } } // Merge with default properties Map<String, Driver> newInstances = new HashMap<>(); for (Entry<String, Properties> entry : driversProps.entrySet()) { String name = entry.getKey(); Properties properties = new Properties(); properties.putAll(defaultProperties); properties.putAll(entry.getValue()); newInstances.put(name, createDriver(name, properties)); } if (newInstances.get(DEFAULT_INSTANCE_NAME) == null && Parameters.REMOTE_URL_BASE.getValue(defaultProperties) != null) { newInstances.put(DEFAULT_INSTANCE_NAME, createDriver(DEFAULT_INSTANCE_NAME, defaultProperties)); } instances = new IndexedInstances(newInstances); }
[ "public", "static", "void", "configure", "(", "Properties", "props", ")", "{", "Properties", "defaultProperties", "=", "new", "Properties", "(", ")", ";", "HashMap", "<", "String", ",", "Properties", ">", "driversProps", "=", "new", "HashMap", "<>", "(", ")"...
Loads all instances according to the properties parameter. @param props properties to use for configuration
[ "Loads", "all", "instances", "according", "to", "the", "properties", "parameter", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/DriverFactory.java#L152-L190
36,380
esigate/esigate
esigate-core/src/main/java/org/esigate/DriverFactory.java
DriverFactory.selectProvider
static MatchedRequest selectProvider(IncomingRequest request) throws HttpErrorPage { URI requestURI = UriUtils.createURI(request.getRequestLine().getUri()); String host = UriUtils.extractHost(requestURI).toHostString(); Header hostHeader = request.getFirstHeader(HttpHeaders.HOST); if (hostHeader != null) { host = hostHeader.getValue(); } String scheme = requestURI.getScheme(); String relativeUri = requestURI.getPath(); String contextPath = request.getContextPath(); if (!StringUtils.isEmpty(contextPath) && relativeUri.startsWith(contextPath)) { relativeUri = relativeUri.substring(contextPath.length()); } Driver driver = null; UriMapping uriMapping = null; for (UriMapping mapping : instances.getUrimappings().keySet()) { if (mapping.matches(scheme, host, relativeUri)) { driver = getInstance(instances.getUrimappings().get(mapping)); uriMapping = mapping; break; } } if (driver == null) { throw new HttpErrorPage(HttpStatus.SC_NOT_FOUND, "Not found", "No mapping defined for this URI."); } if (driver.getConfiguration().isStripMappingPath()) { relativeUri = DriverFactory.stripMappingPath(relativeUri, uriMapping); } MatchedRequest context = new MatchedRequest(driver, relativeUri); LOG.debug("Selected {} for scheme:{} host:{} relUrl:{}", driver, scheme, host, relativeUri); return context; }
java
static MatchedRequest selectProvider(IncomingRequest request) throws HttpErrorPage { URI requestURI = UriUtils.createURI(request.getRequestLine().getUri()); String host = UriUtils.extractHost(requestURI).toHostString(); Header hostHeader = request.getFirstHeader(HttpHeaders.HOST); if (hostHeader != null) { host = hostHeader.getValue(); } String scheme = requestURI.getScheme(); String relativeUri = requestURI.getPath(); String contextPath = request.getContextPath(); if (!StringUtils.isEmpty(contextPath) && relativeUri.startsWith(contextPath)) { relativeUri = relativeUri.substring(contextPath.length()); } Driver driver = null; UriMapping uriMapping = null; for (UriMapping mapping : instances.getUrimappings().keySet()) { if (mapping.matches(scheme, host, relativeUri)) { driver = getInstance(instances.getUrimappings().get(mapping)); uriMapping = mapping; break; } } if (driver == null) { throw new HttpErrorPage(HttpStatus.SC_NOT_FOUND, "Not found", "No mapping defined for this URI."); } if (driver.getConfiguration().isStripMappingPath()) { relativeUri = DriverFactory.stripMappingPath(relativeUri, uriMapping); } MatchedRequest context = new MatchedRequest(driver, relativeUri); LOG.debug("Selected {} for scheme:{} host:{} relUrl:{}", driver, scheme, host, relativeUri); return context; }
[ "static", "MatchedRequest", "selectProvider", "(", "IncomingRequest", "request", ")", "throws", "HttpErrorPage", "{", "URI", "requestURI", "=", "UriUtils", ".", "createURI", "(", "request", ".", "getRequestLine", "(", ")", ".", "getUri", "(", ")", ")", ";", "S...
Selects the Driver instance for this request based on the mappings declared in the configuration. @param request the incoming request @return a {@link MatchedRequest} containing the {@link Driver} instance and the relative URI @throws HttpErrorPage if no instance was found for this request
[ "Selects", "the", "Driver", "instance", "for", "this", "request", "based", "on", "the", "mappings", "declared", "in", "the", "configuration", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/DriverFactory.java#L243-L277
36,381
esigate/esigate
esigate-core/src/main/java/org/esigate/vars/VariablesResolver.java
VariablesResolver.replaceAllVariables
public static String replaceAllVariables(String strVars, DriverRequest request) { String result = strVars; if (VariablesResolver.containsVariable(strVars)) { Matcher matcher = VAR_PATTERN.matcher(strVars); while (matcher.find()) { String group = matcher.group(); String var = group.substring(2, group.length() - 1); String arg = null; // try to find argument int argIndex = var.indexOf('{'); if (argIndex != -1) { arg = VarUtils.removeSimpleQuotes(var.substring(argIndex + 1, var.indexOf('}'))); } // try to find default value // ESI 1.0 spec : // 4.2 Variable Default Values // Variables whose values are empty, nonexistent variables and // undefined substructures of variables will evaluate to an // empty string when they are accessed. String defaultValue = StringUtils.EMPTY; int defaultValueIndex = var.indexOf('|'); if (defaultValueIndex != -1) { defaultValue = VarUtils.removeSimpleQuotes(var.substring(defaultValueIndex + 1)); } String value = getProperty(var, arg, request); if (value == null) { value = defaultValue; } result = result.replace(group, value); } } return result; }
java
public static String replaceAllVariables(String strVars, DriverRequest request) { String result = strVars; if (VariablesResolver.containsVariable(strVars)) { Matcher matcher = VAR_PATTERN.matcher(strVars); while (matcher.find()) { String group = matcher.group(); String var = group.substring(2, group.length() - 1); String arg = null; // try to find argument int argIndex = var.indexOf('{'); if (argIndex != -1) { arg = VarUtils.removeSimpleQuotes(var.substring(argIndex + 1, var.indexOf('}'))); } // try to find default value // ESI 1.0 spec : // 4.2 Variable Default Values // Variables whose values are empty, nonexistent variables and // undefined substructures of variables will evaluate to an // empty string when they are accessed. String defaultValue = StringUtils.EMPTY; int defaultValueIndex = var.indexOf('|'); if (defaultValueIndex != -1) { defaultValue = VarUtils.removeSimpleQuotes(var.substring(defaultValueIndex + 1)); } String value = getProperty(var, arg, request); if (value == null) { value = defaultValue; } result = result.replace(group, value); } } return result; }
[ "public", "static", "String", "replaceAllVariables", "(", "String", "strVars", ",", "DriverRequest", "request", ")", "{", "String", "result", "=", "strVars", ";", "if", "(", "VariablesResolver", ".", "containsVariable", "(", "strVars", ")", ")", "{", "Matcher", ...
Replace all ESI variables found in strVars by their matching value in vars.properties. @param strVars a String containing variables. @param request @return The resulting String
[ "Replace", "all", "ESI", "variables", "found", "in", "strVars", "by", "their", "matching", "value", "in", "vars", ".", "properties", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/vars/VariablesResolver.java#L143-L183
36,382
esigate/esigate
esigate-core/src/main/java/org/esigate/events/EventManager.java
EventManager.register
public void register(EventDefinition eventDefinition, IEventListener listener) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { register(listenersPost, eventDefinition, listener, true); } else { register(listeners, eventDefinition, listener, false); } }
java
public void register(EventDefinition eventDefinition, IEventListener listener) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { register(listenersPost, eventDefinition, listener, true); } else { register(listeners, eventDefinition, listener, false); } }
[ "public", "void", "register", "(", "EventDefinition", "eventDefinition", ",", "IEventListener", "listener", ")", "{", "if", "(", "eventDefinition", ".", "getType", "(", ")", "==", "EventDefinition", ".", "TYPE_POST", ")", "{", "register", "(", "listenersPost", "...
Start listening to an event. @param eventDefinition @param listener
[ "Start", "listening", "to", "an", "event", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/events/EventManager.java#L127-L133
36,383
esigate/esigate
esigate-core/src/main/java/org/esigate/events/EventManager.java
EventManager.fire
public void fire(EventDefinition eventDefinition, Event eventDetails) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { fire(listenersPost, eventDefinition, eventDetails); } else { fire(listeners, eventDefinition, eventDetails); } }
java
public void fire(EventDefinition eventDefinition, Event eventDetails) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { fire(listenersPost, eventDefinition, eventDetails); } else { fire(listeners, eventDefinition, eventDetails); } }
[ "public", "void", "fire", "(", "EventDefinition", "eventDefinition", ",", "Event", "eventDetails", ")", "{", "if", "(", "eventDefinition", ".", "getType", "(", ")", "==", "EventDefinition", ".", "TYPE_POST", ")", "{", "fire", "(", "listenersPost", ",", "eventD...
Fire a new event and run all the listeners. @param eventDefinition @param eventDetails
[ "Fire", "a", "new", "event", "and", "run", "all", "the", "listeners", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/events/EventManager.java#L141-L147
36,384
esigate/esigate
esigate-core/src/main/java/org/esigate/events/EventManager.java
EventManager.unregister
public void unregister(EventDefinition eventDefinition, IEventListener eventListener) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { unregister(listenersPost, eventDefinition, eventListener); } else { unregister(listeners, eventDefinition, eventListener); } }
java
public void unregister(EventDefinition eventDefinition, IEventListener eventListener) { if (eventDefinition.getType() == EventDefinition.TYPE_POST) { unregister(listenersPost, eventDefinition, eventListener); } else { unregister(listeners, eventDefinition, eventListener); } }
[ "public", "void", "unregister", "(", "EventDefinition", "eventDefinition", ",", "IEventListener", "eventListener", ")", "{", "if", "(", "eventDefinition", ".", "getType", "(", ")", "==", "EventDefinition", ".", "TYPE_POST", ")", "{", "unregister", "(", "listenersP...
Stop listening to an event. @param eventDefinition @param eventListener
[ "Stop", "listening", "to", "an", "event", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/events/EventManager.java#L177-L183
36,385
esigate/esigate
esigate-core/src/main/java/org/esigate/http/MoveResponseHeader.java
MoveResponseHeader.moveHeader
public static void moveHeader(HttpResponse response, String srcName, String targetName) { if (response.containsHeader(srcName)) { LOG.info("Moving header {} to {}", srcName, targetName); Header[] headers = response.getHeaders(srcName); response.removeHeaders(targetName); for (Header h : headers) { response.addHeader(targetName, h.getValue()); } response.removeHeaders(srcName); } }
java
public static void moveHeader(HttpResponse response, String srcName, String targetName) { if (response.containsHeader(srcName)) { LOG.info("Moving header {} to {}", srcName, targetName); Header[] headers = response.getHeaders(srcName); response.removeHeaders(targetName); for (Header h : headers) { response.addHeader(targetName, h.getValue()); } response.removeHeaders(srcName); } }
[ "public", "static", "void", "moveHeader", "(", "HttpResponse", "response", ",", "String", "srcName", ",", "String", "targetName", ")", "{", "if", "(", "response", ".", "containsHeader", "(", "srcName", ")", ")", "{", "LOG", ".", "info", "(", "\"Moving header...
This method can be used directly to move an header. @param response HTTP response @param srcName source header name @param targetName target header name
[ "This", "method", "can", "be", "used", "directly", "to", "move", "an", "header", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/MoveResponseHeader.java#L73-L84
36,386
esigate/esigate
esigate-core/src/main/java/org/esigate/Driver.java
Driver.render
public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers) throws IOException, HttpErrorPage { DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl); // Replace ESI variables in URL // TODO: should be performed in the ESI extension String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest); String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false); String currentValue; CloseableHttpResponse response; // Retrieve URL // Get from cache to prevent multiple request to the same url if // multiple fragments are used. String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl; Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey); // content and response were not in cache if (cachedValue == null) { OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl, false); headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); int redirects = MAX_REDIRECTS; try { while (redirects > 0 && this.redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) { // Must consume the entity EntityUtils.consumeQuietly(response.getEntity()); redirects--; // Perform new request outgoingRequest = this.requestExecutor.createOutgoingRequest( driverRequest, this.redirectStrategy.getLocationURI(outgoingRequest, response, outgoingRequest.getContext()).toString(), false); this.headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); } } catch (ProtocolException e) { throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e); } response = this.headerManager.copyHeaders(outgoingRequest, incomingRequest, response); currentValue = HttpResponseUtils.toString(response, this.eventManager); // Cache cachedValue = new ImmutablePair<>(currentValue, response); incomingRequest.setAttribute(cacheKey, cachedValue); } currentValue = cachedValue.getKey(); response = cachedValue.getValue(); logAction("render", pageUrl, renderers); // Apply renderers currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers); response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response))); return response; }
java
public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers) throws IOException, HttpErrorPage { DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl); // Replace ESI variables in URL // TODO: should be performed in the ESI extension String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest); String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false); String currentValue; CloseableHttpResponse response; // Retrieve URL // Get from cache to prevent multiple request to the same url if // multiple fragments are used. String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl; Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey); // content and response were not in cache if (cachedValue == null) { OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl, false); headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); int redirects = MAX_REDIRECTS; try { while (redirects > 0 && this.redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) { // Must consume the entity EntityUtils.consumeQuietly(response.getEntity()); redirects--; // Perform new request outgoingRequest = this.requestExecutor.createOutgoingRequest( driverRequest, this.redirectStrategy.getLocationURI(outgoingRequest, response, outgoingRequest.getContext()).toString(), false); this.headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); } } catch (ProtocolException e) { throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e); } response = this.headerManager.copyHeaders(outgoingRequest, incomingRequest, response); currentValue = HttpResponseUtils.toString(response, this.eventManager); // Cache cachedValue = new ImmutablePair<>(currentValue, response); incomingRequest.setAttribute(cacheKey, cachedValue); } currentValue = cachedValue.getKey(); response = cachedValue.getValue(); logAction("render", pageUrl, renderers); // Apply renderers currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers); response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response))); return response; }
[ "public", "CloseableHttpResponse", "render", "(", "String", "pageUrl", ",", "IncomingRequest", "incomingRequest", ",", "Renderer", "...", "renderers", ")", "throws", "IOException", ",", "HttpErrorPage", "{", "DriverRequest", "driverRequest", "=", "new", "DriverRequest",...
Perform rendering on a single url content, and append result to "writer". Automatically follows redirects @param pageUrl Address of the page containing the template @param incomingRequest originating request object @param renderers the renderers to use in order to transform the output @return The resulting response @throws IOException If an IOException occurs while writing to the writer @throws HttpErrorPage If an Exception occurs while retrieving the template
[ "Perform", "rendering", "on", "a", "single", "url", "content", "and", "append", "result", "to", "writer", ".", "Automatically", "follows", "redirects" ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/Driver.java#L156-L220
36,387
esigate/esigate
esigate-core/src/main/java/org/esigate/Driver.java
Driver.proxy
public CloseableHttpResponse proxy(String relUrl, IncomingRequest incomingRequest, Renderer... renderers) throws IOException, HttpErrorPage { DriverRequest driverRequest = new DriverRequest(incomingRequest, this, relUrl); driverRequest.setCharacterEncoding(this.config.getUriEncoding()); // This is used to ensure EVENT_PROXY_POST is called once and only once. // there are 3 different cases // - Success -> the main code // - Error page -> the HttpErrorPage exception // - Unexpected error -> Other Exceptions boolean postProxyPerformed = false; // Create Proxy event ProxyEvent e = new ProxyEvent(incomingRequest); // Event pre-proxy this.eventManager.fire(EventManager.EVENT_PROXY_PRE, e); // Return immediately if exit is requested by extension if (e.isExit()) { return e.getResponse(); } logAction("proxy", relUrl, renderers); String url = ResourceUtils.getHttpUrlWithQueryString(relUrl, driverRequest, true); OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, url, true); headerManager.copyHeaders(driverRequest, outgoingRequest); try { CloseableHttpResponse response = requestExecutor.execute(outgoingRequest); response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response); e.setResponse(response); // Perform rendering e.setResponse(performRendering(relUrl, driverRequest, e.getResponse(), renderers)); // Event post-proxy // This must be done before calling sendResponse to ensure response // can still be changed. postProxyPerformed = true; this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); // Send request to the client. return e.getResponse(); } catch (HttpErrorPage errorPage) { e.setErrorPage(errorPage); // On error returned by the proxy request, perform rendering on the // error page. CloseableHttpResponse response = e.getErrorPage().getHttpResponse(); response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response); e.setErrorPage(new HttpErrorPage(performRendering(relUrl, driverRequest, response, renderers))); // Event post-proxy // This must be done before throwing exception to ensure response // can still be changed. postProxyPerformed = true; this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); throw e.getErrorPage(); } finally { if (!postProxyPerformed) { this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); } } }
java
public CloseableHttpResponse proxy(String relUrl, IncomingRequest incomingRequest, Renderer... renderers) throws IOException, HttpErrorPage { DriverRequest driverRequest = new DriverRequest(incomingRequest, this, relUrl); driverRequest.setCharacterEncoding(this.config.getUriEncoding()); // This is used to ensure EVENT_PROXY_POST is called once and only once. // there are 3 different cases // - Success -> the main code // - Error page -> the HttpErrorPage exception // - Unexpected error -> Other Exceptions boolean postProxyPerformed = false; // Create Proxy event ProxyEvent e = new ProxyEvent(incomingRequest); // Event pre-proxy this.eventManager.fire(EventManager.EVENT_PROXY_PRE, e); // Return immediately if exit is requested by extension if (e.isExit()) { return e.getResponse(); } logAction("proxy", relUrl, renderers); String url = ResourceUtils.getHttpUrlWithQueryString(relUrl, driverRequest, true); OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, url, true); headerManager.copyHeaders(driverRequest, outgoingRequest); try { CloseableHttpResponse response = requestExecutor.execute(outgoingRequest); response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response); e.setResponse(response); // Perform rendering e.setResponse(performRendering(relUrl, driverRequest, e.getResponse(), renderers)); // Event post-proxy // This must be done before calling sendResponse to ensure response // can still be changed. postProxyPerformed = true; this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); // Send request to the client. return e.getResponse(); } catch (HttpErrorPage errorPage) { e.setErrorPage(errorPage); // On error returned by the proxy request, perform rendering on the // error page. CloseableHttpResponse response = e.getErrorPage().getHttpResponse(); response = headerManager.copyHeaders(outgoingRequest, incomingRequest, response); e.setErrorPage(new HttpErrorPage(performRendering(relUrl, driverRequest, response, renderers))); // Event post-proxy // This must be done before throwing exception to ensure response // can still be changed. postProxyPerformed = true; this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); throw e.getErrorPage(); } finally { if (!postProxyPerformed) { this.eventManager.fire(EventManager.EVENT_PROXY_POST, e); } } }
[ "public", "CloseableHttpResponse", "proxy", "(", "String", "relUrl", ",", "IncomingRequest", "incomingRequest", ",", "Renderer", "...", "renderers", ")", "throws", "IOException", ",", "HttpErrorPage", "{", "DriverRequest", "driverRequest", "=", "new", "DriverRequest", ...
Retrieves a resource from the provider application and transforms it using the Renderer passed as a parameter. @param relUrl the relative URL to the resource @param incomingRequest the request @param renderers the renderers to use to transform the output @return The resulting response. @throws IOException If an IOException occurs while writing to the response @throws HttpErrorPage If the page contains incorrect tags
[ "Retrieves", "a", "resource", "from", "the", "provider", "application", "and", "transforms", "it", "using", "the", "Renderer", "passed", "as", "a", "parameter", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/Driver.java#L269-L337
36,388
esigate/esigate
esigate-core/src/main/java/org/esigate/http/HttpResponseUtils.java
HttpResponseUtils.getFirstHeader
public static String getFirstHeader(String headerName, HttpResponse httpResponse) { Header header = httpResponse.getFirstHeader(headerName); if (header != null) { return header.getValue(); } return null; }
java
public static String getFirstHeader(String headerName, HttpResponse httpResponse) { Header header = httpResponse.getFirstHeader(headerName); if (header != null) { return header.getValue(); } return null; }
[ "public", "static", "String", "getFirstHeader", "(", "String", "headerName", ",", "HttpResponse", "httpResponse", ")", "{", "Header", "header", "=", "httpResponse", ".", "getFirstHeader", "(", "headerName", ")", ";", "if", "(", "header", "!=", "null", ")", "{"...
Get the value of the first header matching "headerName". @param headerName @param httpResponse @return value of the first header or null if it doesn't exist.
[ "Get", "the", "value", "of", "the", "first", "header", "matching", "headerName", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/HttpResponseUtils.java#L82-L88
36,389
esigate/esigate
esigate-core/src/main/java/org/esigate/http/HeaderManager.java
HeaderManager.copyHeaders
public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest, HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) { HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine()); result.setEntity(httpClientResponse.getEntity()); String originalUri = incomingRequest.getRequestLine().getUri(); String baseUrl = outgoingRequest.getBaseUrl().toString(); String visibleBaseUrl = outgoingRequest.getOriginalRequest().getVisibleBaseUrl(); for (Header header : httpClientResponse.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); try { // Ignore Content-Encoding and Content-Type as these headers are // set in HttpEntity if (!HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name)) { if (isForwardedResponseHeader(name)) { // Some headers containing an URI have to be rewritten if (HttpHeaders.LOCATION.equalsIgnoreCase(name) || HttpHeaders.CONTENT_LOCATION.equalsIgnoreCase(name)) { // Header contains only an url value = urlRewriter.rewriteUrl(value, originalUri, baseUrl, visibleBaseUrl, true); value = HttpResponseUtils.removeSessionId(value, httpClientResponse); result.addHeader(name, value); } else if ("Link".equalsIgnoreCase(name)) { // Header has the following format // Link: </feed>; rel="alternate" if (value.startsWith("<") && value.contains(">")) { String urlValue = value.substring(1, value.indexOf(">")); String targetUrlValue = urlRewriter.rewriteUrl(urlValue, originalUri, baseUrl, visibleBaseUrl, true); targetUrlValue = HttpResponseUtils.removeSessionId(targetUrlValue, httpClientResponse); value = value.replace("<" + urlValue + ">", "<" + targetUrlValue + ">"); } result.addHeader(name, value); } else if ("Refresh".equalsIgnoreCase(name)) { // Header has the following format // Refresh: 5; url=http://www.example.com int urlPosition = value.indexOf("url="); if (urlPosition >= 0) { value = urlRewriter.rewriteRefresh(value, originalUri, baseUrl, visibleBaseUrl); value = HttpResponseUtils.removeSessionId(value, httpClientResponse); } result.addHeader(name, value); } else if ("P3p".equalsIgnoreCase(name)) { // Do not translate url yet. // P3P is used with a default fixed url most of the // time. result.addHeader(name, value); } else { result.addHeader(header.getName(), header.getValue()); } } } } catch (Exception e1) { // It's important not to fail here. // An application can always send corrupted headers, and we // should not crash LOG.error("Error while copying headers", e1); result.addHeader("X-Esigate-Error", "Error processing header " + name + ": " + value); } } return BasicCloseableHttpResponse.adapt(result); }
java
public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest, HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) { HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine()); result.setEntity(httpClientResponse.getEntity()); String originalUri = incomingRequest.getRequestLine().getUri(); String baseUrl = outgoingRequest.getBaseUrl().toString(); String visibleBaseUrl = outgoingRequest.getOriginalRequest().getVisibleBaseUrl(); for (Header header : httpClientResponse.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); try { // Ignore Content-Encoding and Content-Type as these headers are // set in HttpEntity if (!HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name)) { if (isForwardedResponseHeader(name)) { // Some headers containing an URI have to be rewritten if (HttpHeaders.LOCATION.equalsIgnoreCase(name) || HttpHeaders.CONTENT_LOCATION.equalsIgnoreCase(name)) { // Header contains only an url value = urlRewriter.rewriteUrl(value, originalUri, baseUrl, visibleBaseUrl, true); value = HttpResponseUtils.removeSessionId(value, httpClientResponse); result.addHeader(name, value); } else if ("Link".equalsIgnoreCase(name)) { // Header has the following format // Link: </feed>; rel="alternate" if (value.startsWith("<") && value.contains(">")) { String urlValue = value.substring(1, value.indexOf(">")); String targetUrlValue = urlRewriter.rewriteUrl(urlValue, originalUri, baseUrl, visibleBaseUrl, true); targetUrlValue = HttpResponseUtils.removeSessionId(targetUrlValue, httpClientResponse); value = value.replace("<" + urlValue + ">", "<" + targetUrlValue + ">"); } result.addHeader(name, value); } else if ("Refresh".equalsIgnoreCase(name)) { // Header has the following format // Refresh: 5; url=http://www.example.com int urlPosition = value.indexOf("url="); if (urlPosition >= 0) { value = urlRewriter.rewriteRefresh(value, originalUri, baseUrl, visibleBaseUrl); value = HttpResponseUtils.removeSessionId(value, httpClientResponse); } result.addHeader(name, value); } else if ("P3p".equalsIgnoreCase(name)) { // Do not translate url yet. // P3P is used with a default fixed url most of the // time. result.addHeader(name, value); } else { result.addHeader(header.getName(), header.getValue()); } } } } catch (Exception e1) { // It's important not to fail here. // An application can always send corrupted headers, and we // should not crash LOG.error("Error while copying headers", e1); result.addHeader("X-Esigate-Error", "Error processing header " + name + ": " + value); } } return BasicCloseableHttpResponse.adapt(result); }
[ "public", "CloseableHttpResponse", "copyHeaders", "(", "OutgoingRequest", "outgoingRequest", ",", "HttpEntityEnclosingRequest", "incomingRequest", ",", "HttpResponse", "httpClientResponse", ")", "{", "HttpResponse", "result", "=", "new", "BasicHttpResponse", "(", "httpClientR...
Copies end-to-end headers from a response received from the server to the response to be sent to the client. @param outgoingRequest the request sent @param incomingRequest the original request received from the client @param httpClientResponse the response received from the provider application @return the response to be sent to the client
[ "Copies", "end", "-", "to", "-", "end", "headers", "from", "a", "response", "received", "from", "the", "server", "to", "the", "response", "to", "be", "sent", "to", "the", "client", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/HeaderManager.java#L159-L225
36,390
esigate/esigate
esigate-core/src/main/java/org/esigate/util/FilterList.java
FilterList.add
public void add(String toAdd) { if (toAdd.contains("*")) { set.clear(); defaultContains = true; } else { if (!defaultContains) { set.add(toAdd); } else { set.remove(toAdd); } } }
java
public void add(String toAdd) { if (toAdd.contains("*")) { set.clear(); defaultContains = true; } else { if (!defaultContains) { set.add(toAdd); } else { set.remove(toAdd); } } }
[ "public", "void", "add", "(", "String", "toAdd", ")", "{", "if", "(", "toAdd", ".", "contains", "(", "\"*\"", ")", ")", "{", "set", ".", "clear", "(", ")", ";", "defaultContains", "=", "true", ";", "}", "else", "{", "if", "(", "!", "defaultContains...
Add some tokens to the list. By default the list is empty. If the list already contains the added tokens or everything, this method will have no effect. @param toAdd String token to add to the list. This argument can be: <ul> <li>A single String token</li> <li>* (in this case the list will then act as if it contained any token but you will be able to make except some tokens using the remove method)</li> </ul>
[ "Add", "some", "tokens", "to", "the", "list", ".", "By", "default", "the", "list", "is", "empty", ".", "If", "the", "list", "already", "contains", "the", "added", "tokens", "or", "everything", "this", "method", "will", "have", "no", "effect", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/FilterList.java#L30-L41
36,391
esigate/esigate
esigate-core/src/main/java/org/esigate/util/FilterList.java
FilterList.remove
public void remove(String toRemove) { if (toRemove.contains("*")) { set.clear(); defaultContains = false; } else { if (defaultContains) { set.add(toRemove); } else { set.remove(toRemove); } } }
java
public void remove(String toRemove) { if (toRemove.contains("*")) { set.clear(); defaultContains = false; } else { if (defaultContains) { set.add(toRemove); } else { set.remove(toRemove); } } }
[ "public", "void", "remove", "(", "String", "toRemove", ")", "{", "if", "(", "toRemove", ".", "contains", "(", "\"*\"", ")", ")", "{", "set", ".", "clear", "(", ")", ";", "defaultContains", "=", "false", ";", "}", "else", "{", "if", "(", "defaultConta...
Remove some tokens from the list. If the list is already empty or does not contains the tokens, this method will have no effect. @param toRemove String tokens to add to the list. This argument can be: <ul> <li>A single String token</li> <li>* (in this case the list will then be empty again)</li> </ul>
[ "Remove", "some", "tokens", "from", "the", "list", ".", "If", "the", "list", "is", "already", "empty", "or", "does", "not", "contains", "the", "tokens", "this", "method", "will", "have", "no", "effect", "." ]
50421fb224f16e1ec42715425109a72b3b55527b
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/util/FilterList.java#L54-L65
36,392
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java
RecurrencePickerDialog.updateEndCountText
private void updateEndCountText() { final String END_COUNT_MARKER = "%d"; String endString = mResources.getQuantityString(R.plurals.recurrence_end_count, mModel.endCount); int markerStart = endString.indexOf(END_COUNT_MARKER); if (markerStart != -1) { if (markerStart == 0) { Log.e(TAG, "No text to put in to recurrence's end spinner."); } else { int postTextStart = markerStart + END_COUNT_MARKER.length(); mPostEndCount.setText(endString.substring(postTextStart, endString.length()).trim()); } } }
java
private void updateEndCountText() { final String END_COUNT_MARKER = "%d"; String endString = mResources.getQuantityString(R.plurals.recurrence_end_count, mModel.endCount); int markerStart = endString.indexOf(END_COUNT_MARKER); if (markerStart != -1) { if (markerStart == 0) { Log.e(TAG, "No text to put in to recurrence's end spinner."); } else { int postTextStart = markerStart + END_COUNT_MARKER.length(); mPostEndCount.setText(endString.substring(postTextStart, endString.length()).trim()); } } }
[ "private", "void", "updateEndCountText", "(", ")", "{", "final", "String", "END_COUNT_MARKER", "=", "\"%d\"", ";", "String", "endString", "=", "mResources", ".", "getQuantityString", "(", "R", ".", "plurals", ".", "recurrence_end_count", ",", "mModel", ".", "end...
Update the "Repeat for N events" end option with the proper string values based on the value that has been entered for N.
[ "Update", "the", "Repeat", "for", "N", "events", "end", "option", "with", "the", "proper", "string", "values", "based", "on", "the", "value", "that", "has", "been", "entered", "for", "N", "." ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java#L1047-L1062
36,393
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java
RecurrencePickerDialog.onCheckedChanged
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int itemIdx = -1; for (int i = 0; i < 7; i++) { if (itemIdx == -1 && buttonView == mWeekByDayButtons[i]) { itemIdx = i; mModel.weeklyByDayOfWeek[i] = isChecked; } } updateDialog(); }
java
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int itemIdx = -1; for (int i = 0; i < 7; i++) { if (itemIdx == -1 && buttonView == mWeekByDayButtons[i]) { itemIdx = i; mModel.weeklyByDayOfWeek[i] = isChecked; } } updateDialog(); }
[ "@", "Override", "public", "void", "onCheckedChanged", "(", "CompoundButton", "buttonView", ",", "boolean", "isChecked", ")", "{", "int", "itemIdx", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "7", ";", "i", "++", ")", "{", ...
Week repeat by day of week
[ "Week", "repeat", "by", "day", "of", "week" ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java#L1122-L1132
36,394
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java
RecurrencePickerDialog.onCheckedChanged
@Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.repeatMonthlyByNthDayOfMonth) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE; } else if (checkedId == R.id.repeatMonthlyByNthDayOfTheWeek) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK; } updateDialog(); }
java
@Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.repeatMonthlyByNthDayOfMonth) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE; } else if (checkedId == R.id.repeatMonthlyByNthDayOfTheWeek) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK; } updateDialog(); }
[ "@", "Override", "public", "void", "onCheckedChanged", "(", "RadioGroup", "group", ",", "int", "checkedId", ")", "{", "if", "(", "checkedId", "==", "R", ".", "id", ".", "repeatMonthlyByNthDayOfMonth", ")", "{", "mModel", ".", "monthlyRepeat", "=", "RecurrenceM...
Month repeat by radio buttons
[ "Month", "repeat", "by", "radio", "buttons" ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/RecurrencePickerDialog.java#L1136-L1144
36,395
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/EventRecurrence.java
EventRecurrence.calendarDay2Day
public static int calendarDay2Day(int day) { switch (day) { case Calendar.SUNDAY: return SU; case Calendar.MONDAY: return MO; case Calendar.TUESDAY: return TU; case Calendar.WEDNESDAY: return WE; case Calendar.THURSDAY: return TH; case Calendar.FRIDAY: return FR; case Calendar.SATURDAY: return SA; default: throw new RuntimeException("bad day of week: " + day); } }
java
public static int calendarDay2Day(int day) { switch (day) { case Calendar.SUNDAY: return SU; case Calendar.MONDAY: return MO; case Calendar.TUESDAY: return TU; case Calendar.WEDNESDAY: return WE; case Calendar.THURSDAY: return TH; case Calendar.FRIDAY: return FR; case Calendar.SATURDAY: return SA; default: throw new RuntimeException("bad day of week: " + day); } }
[ "public", "static", "int", "calendarDay2Day", "(", "int", "day", ")", "{", "switch", "(", "day", ")", "{", "case", "Calendar", ".", "SUNDAY", ":", "return", "SU", ";", "case", "Calendar", ".", "MONDAY", ":", "return", "MO", ";", "case", "Calendar", "."...
Converts one of the Calendar.SUNDAY constants to the SU, MO, etc. constants. btw, I think we should switch to those here too, to get rid of this function, if possible.
[ "Converts", "one", "of", "the", "Calendar", ".", "SUNDAY", "constants", "to", "the", "SU", "MO", "etc", ".", "constants", ".", "btw", "I", "think", "we", "should", "switch", "to", "those", "here", "too", "to", "get", "rid", "of", "this", "function", "i...
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/EventRecurrence.java#L183-L202
36,396
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/EventRecurrence.java
EventRecurrence.parse
public void parse(String recur) { /* * From RFC 2445 section 4.3.10: * * recur = "FREQ"=freq *( * ; either UNTIL or COUNT may appear in a 'recur', * ; but UNTIL and COUNT MUST NOT occur in the same 'recur' * * ( ";" "UNTIL" "=" enddate ) / * ( ";" "COUNT" "=" 1*DIGIT ) / * * ; the rest of these keywords are optional, * ; but MUST NOT occur more than once * * ( ";" "INTERVAL" "=" 1*DIGIT ) / * ( ";" "BYSECOND" "=" byseclist ) / * ( ";" "BYMINUTE" "=" byminlist ) / * ( ";" "BYHOUR" "=" byhrlist ) / * ( ";" "BYDAY" "=" bywdaylist ) / * ( ";" "BYMONTHDAY" "=" bymodaylist ) / * ( ";" "BYYEARDAY" "=" byyrdaylist ) / * ( ";" "BYWEEKNO" "=" bywknolist ) / * ( ";" "BYMONTH" "=" bymolist ) / * ( ";" "BYSETPOS" "=" bysplist ) / * ( ";" "WKST" "=" weekday ) / * ( ";" x-name "=" text ) * ) * * The rule parts are not ordered in any particular sequence. * * Examples: * FREQ=MONTHLY;INTERVAL=2;COUNT=10;BYDAY=1SU,-1SU * FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8 * * Strategy: * (1) Split the string at ';' boundaries to get an array of rule "parts". * (2) For each part, find substrings for left/right sides of '=' (name/value). * (3) Call a <name>-specific parsing function to parse the <value> into an * output field. * * By keeping track of which names we've seen in a bit vector, we can verify the * constraints indicated above (FREQ appears first, none of them appear more than once -- * though x-[name] would require special treatment), and we have either UNTIL or COUNT * but not both. * * In general, RFC 2445 property names (e.g. "FREQ") and enumerations ("TU") must * be handled in a case-insensitive fashion, but case may be significant for other * properties. We don't have any case-sensitive values in RRULE, except possibly * for the custom "X-" properties, but we ignore those anyway. Thus, we can trivially * convert the entire string to upper case and then use simple comparisons. * * Differences from previous version: * - allows lower-case property and enumeration values [optional] * - enforces that FREQ appears first * - enforces that only one of UNTIL and COUNT may be specified * - allows (but ignores) X-* parts * - improved validation on various values (e.g. UNTIL timestamps) * - error messages are more specific * * TODO: enforce additional constraints listed in RFC 5545, notably the "N/A" entries * in section 3.3.10. For example, if FREQ=WEEKLY, we should reject a rule that * includes a BYMONTHDAY part. */ /* TODO: replace with "if (freq != 0) throw" if nothing requires this */ resetFields(); int parseFlags = 0; String[] parts; if (ALLOW_LOWER_CASE) { parts = recur.toUpperCase().split(";"); } else { parts = recur.split(";"); } for (String part : parts) { // allow empty part (e.g., double semicolon ";;") if (TextUtils.isEmpty(part)) { continue; } int equalIndex = part.indexOf('='); if (equalIndex <= 0) { /* no '=' or no LHS */ throw new InvalidFormatException("Missing LHS in " + part); } String lhs = part.substring(0, equalIndex); String rhs = part.substring(equalIndex + 1); if (rhs.length() == 0) { throw new InvalidFormatException("Missing RHS in " + part); } /* * In lieu of a "switch" statement that allows string arguments, we use a * map from strings to parsing functions. */ PartParser parser = sParsePartMap.get(lhs); if (parser == null) { if (lhs.startsWith("X-")) { //Log.d(TAG, "Ignoring custom part " + lhs); continue; } throw new InvalidFormatException("Couldn't find parser for " + lhs); } else { int flag = parser.parsePart(rhs, this); if ((parseFlags & flag) != 0) { throw new InvalidFormatException("Part " + lhs + " was specified twice"); } parseFlags |= flag; } } // If not specified, week starts on Monday. if ((parseFlags & PARSED_WKST) == 0) { wkst = MO; } // FREQ is mandatory. if ((parseFlags & PARSED_FREQ) == 0) { throw new InvalidFormatException("Must specify a FREQ value"); } // Can't have both UNTIL and COUNT. if ((parseFlags & (PARSED_UNTIL | PARSED_COUNT)) == (PARSED_UNTIL | PARSED_COUNT)) { if (ONLY_ONE_UNTIL_COUNT) { throw new InvalidFormatException("Must not specify both UNTIL and COUNT: " + recur); } else { Log.w(TAG, "Warning: rrule has both UNTIL and COUNT: " + recur); } } }
java
public void parse(String recur) { /* * From RFC 2445 section 4.3.10: * * recur = "FREQ"=freq *( * ; either UNTIL or COUNT may appear in a 'recur', * ; but UNTIL and COUNT MUST NOT occur in the same 'recur' * * ( ";" "UNTIL" "=" enddate ) / * ( ";" "COUNT" "=" 1*DIGIT ) / * * ; the rest of these keywords are optional, * ; but MUST NOT occur more than once * * ( ";" "INTERVAL" "=" 1*DIGIT ) / * ( ";" "BYSECOND" "=" byseclist ) / * ( ";" "BYMINUTE" "=" byminlist ) / * ( ";" "BYHOUR" "=" byhrlist ) / * ( ";" "BYDAY" "=" bywdaylist ) / * ( ";" "BYMONTHDAY" "=" bymodaylist ) / * ( ";" "BYYEARDAY" "=" byyrdaylist ) / * ( ";" "BYWEEKNO" "=" bywknolist ) / * ( ";" "BYMONTH" "=" bymolist ) / * ( ";" "BYSETPOS" "=" bysplist ) / * ( ";" "WKST" "=" weekday ) / * ( ";" x-name "=" text ) * ) * * The rule parts are not ordered in any particular sequence. * * Examples: * FREQ=MONTHLY;INTERVAL=2;COUNT=10;BYDAY=1SU,-1SU * FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8 * * Strategy: * (1) Split the string at ';' boundaries to get an array of rule "parts". * (2) For each part, find substrings for left/right sides of '=' (name/value). * (3) Call a <name>-specific parsing function to parse the <value> into an * output field. * * By keeping track of which names we've seen in a bit vector, we can verify the * constraints indicated above (FREQ appears first, none of them appear more than once -- * though x-[name] would require special treatment), and we have either UNTIL or COUNT * but not both. * * In general, RFC 2445 property names (e.g. "FREQ") and enumerations ("TU") must * be handled in a case-insensitive fashion, but case may be significant for other * properties. We don't have any case-sensitive values in RRULE, except possibly * for the custom "X-" properties, but we ignore those anyway. Thus, we can trivially * convert the entire string to upper case and then use simple comparisons. * * Differences from previous version: * - allows lower-case property and enumeration values [optional] * - enforces that FREQ appears first * - enforces that only one of UNTIL and COUNT may be specified * - allows (but ignores) X-* parts * - improved validation on various values (e.g. UNTIL timestamps) * - error messages are more specific * * TODO: enforce additional constraints listed in RFC 5545, notably the "N/A" entries * in section 3.3.10. For example, if FREQ=WEEKLY, we should reject a rule that * includes a BYMONTHDAY part. */ /* TODO: replace with "if (freq != 0) throw" if nothing requires this */ resetFields(); int parseFlags = 0; String[] parts; if (ALLOW_LOWER_CASE) { parts = recur.toUpperCase().split(";"); } else { parts = recur.split(";"); } for (String part : parts) { // allow empty part (e.g., double semicolon ";;") if (TextUtils.isEmpty(part)) { continue; } int equalIndex = part.indexOf('='); if (equalIndex <= 0) { /* no '=' or no LHS */ throw new InvalidFormatException("Missing LHS in " + part); } String lhs = part.substring(0, equalIndex); String rhs = part.substring(equalIndex + 1); if (rhs.length() == 0) { throw new InvalidFormatException("Missing RHS in " + part); } /* * In lieu of a "switch" statement that allows string arguments, we use a * map from strings to parsing functions. */ PartParser parser = sParsePartMap.get(lhs); if (parser == null) { if (lhs.startsWith("X-")) { //Log.d(TAG, "Ignoring custom part " + lhs); continue; } throw new InvalidFormatException("Couldn't find parser for " + lhs); } else { int flag = parser.parsePart(rhs, this); if ((parseFlags & flag) != 0) { throw new InvalidFormatException("Part " + lhs + " was specified twice"); } parseFlags |= flag; } } // If not specified, week starts on Monday. if ((parseFlags & PARSED_WKST) == 0) { wkst = MO; } // FREQ is mandatory. if ((parseFlags & PARSED_FREQ) == 0) { throw new InvalidFormatException("Must specify a FREQ value"); } // Can't have both UNTIL and COUNT. if ((parseFlags & (PARSED_UNTIL | PARSED_COUNT)) == (PARSED_UNTIL | PARSED_COUNT)) { if (ONLY_ONE_UNTIL_COUNT) { throw new InvalidFormatException("Must not specify both UNTIL and COUNT: " + recur); } else { Log.w(TAG, "Warning: rrule has both UNTIL and COUNT: " + recur); } } }
[ "public", "void", "parse", "(", "String", "recur", ")", "{", "/*\n * From RFC 2445 section 4.3.10:\n *\n * recur = \"FREQ\"=freq *(\n * ; either UNTIL or COUNT may appear in a 'recur',\n * ; but UNTIL and COUNT MUST NOT occur in the same 'recur'\n ...
Parses an rfc2445 recurrence rule string into its component pieces. Attempting to parse malformed input will result in an EventRecurrence.InvalidFormatException. @param recur The recurrence rule to parse (in un-folded form).
[ "Parses", "an", "rfc2445", "recurrence", "rule", "string", "into", "its", "component", "pieces", ".", "Attempting", "to", "parse", "malformed", "input", "will", "result", "in", "an", "EventRecurrence", ".", "InvalidFormatException", "." ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/EventRecurrence.java#L530-L659
36,397
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java
Utils.compareCursors
public static boolean compareCursors(Cursor c1, Cursor c2) { if (c1 == null || c2 == null) { return false; } int numColumns = c1.getColumnCount(); if (numColumns != c2.getColumnCount()) { return false; } if (c1.getCount() != c2.getCount()) { return false; } c1.moveToPosition(-1); c2.moveToPosition(-1); while (c1.moveToNext() && c2.moveToNext()) { for (int i = 0; i < numColumns; i++) { if (!TextUtils.equals(c1.getString(i), c2.getString(i))) { return false; } } } return true; }
java
public static boolean compareCursors(Cursor c1, Cursor c2) { if (c1 == null || c2 == null) { return false; } int numColumns = c1.getColumnCount(); if (numColumns != c2.getColumnCount()) { return false; } if (c1.getCount() != c2.getCount()) { return false; } c1.moveToPosition(-1); c2.moveToPosition(-1); while (c1.moveToNext() && c2.moveToNext()) { for (int i = 0; i < numColumns; i++) { if (!TextUtils.equals(c1.getString(i), c2.getString(i))) { return false; } } } return true; }
[ "public", "static", "boolean", "compareCursors", "(", "Cursor", "c1", ",", "Cursor", "c2", ")", "{", "if", "(", "c1", "==", "null", "||", "c2", "==", "null", ")", "{", "return", "false", ";", "}", "int", "numColumns", "=", "c1", ".", "getColumnCount", ...
Compares two cursors to see if they contain the same data. @return Returns true of the cursors contain the same data and are not null, false otherwise
[ "Compares", "two", "cursors", "to", "see", "if", "they", "contain", "the", "same", "data", "." ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L262-L287
36,398
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java
Utils.getFirstDayOfWeek
public static int getFirstDayOfWeek(Context context) { int startDay = Calendar.getInstance().getFirstDayOfWeek(); if (startDay == Calendar.SATURDAY) { return Time.SATURDAY; } else if (startDay == Calendar.MONDAY) { return Time.MONDAY; } else { return Time.SUNDAY; } }
java
public static int getFirstDayOfWeek(Context context) { int startDay = Calendar.getInstance().getFirstDayOfWeek(); if (startDay == Calendar.SATURDAY) { return Time.SATURDAY; } else if (startDay == Calendar.MONDAY) { return Time.MONDAY; } else { return Time.SUNDAY; } }
[ "public", "static", "int", "getFirstDayOfWeek", "(", "Context", "context", ")", "{", "int", "startDay", "=", "Calendar", ".", "getInstance", "(", ")", ".", "getFirstDayOfWeek", "(", ")", ";", "if", "(", "startDay", "==", "Calendar", ".", "SATURDAY", ")", "...
Get first day of week as android.text.format.Time constant. @return the first day of week in android.text.format.Time
[ "Get", "first", "day", "of", "week", "as", "android", ".", "text", ".", "format", ".", "Time", "constant", "." ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L380-L390
36,399
Shusshu/Android-RecurrencePicker
library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java
Utils.convertDayOfWeekFromTimeToCalendar
public static int convertDayOfWeekFromTimeToCalendar(int timeDayOfWeek) { switch (timeDayOfWeek) { case Time.MONDAY: return Calendar.MONDAY; case Time.TUESDAY: return Calendar.TUESDAY; case Time.WEDNESDAY: return Calendar.WEDNESDAY; case Time.THURSDAY: return Calendar.THURSDAY; case Time.FRIDAY: return Calendar.FRIDAY; case Time.SATURDAY: return Calendar.SATURDAY; case Time.SUNDAY: return Calendar.SUNDAY; default: throw new IllegalArgumentException("Argument must be between Time.SUNDAY and " + "Time.SATURDAY"); } }
java
public static int convertDayOfWeekFromTimeToCalendar(int timeDayOfWeek) { switch (timeDayOfWeek) { case Time.MONDAY: return Calendar.MONDAY; case Time.TUESDAY: return Calendar.TUESDAY; case Time.WEDNESDAY: return Calendar.WEDNESDAY; case Time.THURSDAY: return Calendar.THURSDAY; case Time.FRIDAY: return Calendar.FRIDAY; case Time.SATURDAY: return Calendar.SATURDAY; case Time.SUNDAY: return Calendar.SUNDAY; default: throw new IllegalArgumentException("Argument must be between Time.SUNDAY and " + "Time.SATURDAY"); } }
[ "public", "static", "int", "convertDayOfWeekFromTimeToCalendar", "(", "int", "timeDayOfWeek", ")", "{", "switch", "(", "timeDayOfWeek", ")", "{", "case", "Time", ".", "MONDAY", ":", "return", "Calendar", ".", "MONDAY", ";", "case", "Time", ".", "TUESDAY", ":",...
Converts the day of the week from android.text.format.Time to java.util.Calendar
[ "Converts", "the", "day", "of", "the", "week", "from", "android", ".", "text", ".", "format", ".", "Time", "to", "java", ".", "util", ".", "Calendar" ]
4f0ae74482e4d46d57a8fb13b4b7980a8613f4af
https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L404-L424