repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftConverter.java | ThriftConverter.ToConnectionPoolException | public static ConnectionException ToConnectionPoolException(Throwable e) {
if (e instanceof ConnectionException) {
return (ConnectionException) e;
}
LOGGER.debug(e.getMessage());
if (e instanceof InvalidRequestException) {
return new com.netflix.astyanax.connectionpool.exceptions.BadRequestException(e);
}
else if (e instanceof TProtocolException) {
return new com.netflix.astyanax.connectionpool.exceptions.BadRequestException(e);
}
else if (e instanceof UnavailableException) {
return new TokenRangeOfflineException(e);
}
else if (e instanceof SocketTimeoutException) {
return new TimeoutException(e);
}
else if (e instanceof TimedOutException) {
return new OperationTimeoutException(e);
}
else if (e instanceof NotFoundException) {
return new com.netflix.astyanax.connectionpool.exceptions.NotFoundException(e);
}
else if (e instanceof TApplicationException) {
return new ThriftStateException(e);
}
else if (e instanceof AuthenticationException || e instanceof AuthorizationException) {
return new com.netflix.astyanax.connectionpool.exceptions.AuthenticationException(e);
}
else if (e instanceof SchemaDisagreementException) {
return new com.netflix.astyanax.connectionpool.exceptions.SchemaDisagreementException(e);
}
else if (e instanceof TTransportException) {
if (e.getCause() != null) {
if (e.getCause() instanceof SocketTimeoutException) {
return new TimeoutException(e);
}
if (e.getCause().getMessage() != null) {
if (e.getCause().getMessage().toLowerCase().contains("connection abort")
|| e.getCause().getMessage().toLowerCase().contains("connection reset")) {
return new ConnectionAbortedException(e);
}
}
}
return new TransportException(e);
}
else {
// e.getCause().printStackTrace();
return new UnknownException(e);
}
} | java | public static ConnectionException ToConnectionPoolException(Throwable e) {
if (e instanceof ConnectionException) {
return (ConnectionException) e;
}
LOGGER.debug(e.getMessage());
if (e instanceof InvalidRequestException) {
return new com.netflix.astyanax.connectionpool.exceptions.BadRequestException(e);
}
else if (e instanceof TProtocolException) {
return new com.netflix.astyanax.connectionpool.exceptions.BadRequestException(e);
}
else if (e instanceof UnavailableException) {
return new TokenRangeOfflineException(e);
}
else if (e instanceof SocketTimeoutException) {
return new TimeoutException(e);
}
else if (e instanceof TimedOutException) {
return new OperationTimeoutException(e);
}
else if (e instanceof NotFoundException) {
return new com.netflix.astyanax.connectionpool.exceptions.NotFoundException(e);
}
else if (e instanceof TApplicationException) {
return new ThriftStateException(e);
}
else if (e instanceof AuthenticationException || e instanceof AuthorizationException) {
return new com.netflix.astyanax.connectionpool.exceptions.AuthenticationException(e);
}
else if (e instanceof SchemaDisagreementException) {
return new com.netflix.astyanax.connectionpool.exceptions.SchemaDisagreementException(e);
}
else if (e instanceof TTransportException) {
if (e.getCause() != null) {
if (e.getCause() instanceof SocketTimeoutException) {
return new TimeoutException(e);
}
if (e.getCause().getMessage() != null) {
if (e.getCause().getMessage().toLowerCase().contains("connection abort")
|| e.getCause().getMessage().toLowerCase().contains("connection reset")) {
return new ConnectionAbortedException(e);
}
}
}
return new TransportException(e);
}
else {
// e.getCause().printStackTrace();
return new UnknownException(e);
}
} | [
"public",
"static",
"ConnectionException",
"ToConnectionPoolException",
"(",
"Throwable",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"ConnectionException",
")",
"{",
"return",
"(",
"ConnectionException",
")",
"e",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"e",
... | Convert from Thrift exceptions to an internal ConnectionPoolException
@param e
@return | [
"Convert",
"from",
"Thrift",
"exceptions",
"to",
"an",
"internal",
"ConnectionPoolException"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftConverter.java#L153-L203 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.borrowConnection | @Override
public Connection<CL> borrowConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
// Try to get a free connection without blocking.
connection = availableConnections.poll();
if (connection != null) {
return connection;
}
boolean isOpenning = tryOpenAsync();
// Wait for a connection to free up or a new one to be opened
if (timeout > 0) {
connection = waitForConnection(isOpenning ? config.getConnectTimeout() : timeout);
return connection;
}
else
throw new PoolTimeoutException("Fast fail waiting for connection from pool")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
if (connection != null) {
borrowedCount.incrementAndGet();
monitor.incConnectionBorrowed(host, System.currentTimeMillis() - startTime);
}
}
} | java | @Override
public Connection<CL> borrowConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
// Try to get a free connection without blocking.
connection = availableConnections.poll();
if (connection != null) {
return connection;
}
boolean isOpenning = tryOpenAsync();
// Wait for a connection to free up or a new one to be opened
if (timeout > 0) {
connection = waitForConnection(isOpenning ? config.getConnectTimeout() : timeout);
return connection;
}
else
throw new PoolTimeoutException("Fast fail waiting for connection from pool")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
if (connection != null) {
borrowedCount.incrementAndGet();
monitor.incConnectionBorrowed(host, System.currentTimeMillis() - startTime);
}
}
} | [
"@",
"Override",
"public",
"Connection",
"<",
"CL",
">",
"borrowConnection",
"(",
"int",
"timeout",
")",
"throws",
"ConnectionException",
"{",
"Connection",
"<",
"CL",
">",
"connection",
"=",
"null",
";",
"long",
"startTime",
"=",
"System",
".",
"currentTimeMi... | Create a connection as long the max hasn't been reached
@param timeout
- Max wait timeout if max connections have been allocated and
pool is empty. 0 to throw a MaxConnsPerHostReachedException.
@return
@throws TimeoutException
if timeout specified and no new connection is available
MaxConnsPerHostReachedException if max connections created
and no timeout was specified | [
"Create",
"a",
"connection",
"as",
"long",
"the",
"max",
"hasn",
"t",
"been",
"reached"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L183-L212 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.waitForConnection | private Connection<CL> waitForConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
blockedThreads.incrementAndGet();
connection = availableConnections.poll(timeout, TimeUnit.MILLISECONDS);
if (connection != null)
return connection;
throw new PoolTimeoutException("Timed out waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedOperationException("Thread interrupted waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
blockedThreads.decrementAndGet();
}
} | java | private Connection<CL> waitForConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
blockedThreads.incrementAndGet();
connection = availableConnections.poll(timeout, TimeUnit.MILLISECONDS);
if (connection != null)
return connection;
throw new PoolTimeoutException("Timed out waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedOperationException("Thread interrupted waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
blockedThreads.decrementAndGet();
}
} | [
"private",
"Connection",
"<",
"CL",
">",
"waitForConnection",
"(",
"int",
"timeout",
")",
"throws",
"ConnectionException",
"{",
"Connection",
"<",
"CL",
">",
"connection",
"=",
"null",
";",
"long",
"startTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")"... | Internal method to wait for a connection from the available connection
pool.
@param timeout
@return
@throws ConnectionException | [
"Internal",
"method",
"to",
"wait",
"for",
"a",
"connection",
"from",
"the",
"available",
"connection",
"pool",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L222-L244 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.returnConnection | @Override
public boolean returnConnection(Connection<CL> connection) {
returnedCount.incrementAndGet();
monitor.incConnectionReturned(host);
ConnectionException ce = connection.getLastException();
if (ce != null) {
if (ce instanceof IsDeadConnectionException) {
noteError(ce);
internalCloseConnection(connection);
return true;
}
}
errorsSinceLastSuccess.set(0);
// Still within the number of max active connection
if (activeCount.get() <= config.getMaxConnsPerHost()) {
availableConnections.add(connection);
if (isShutdown()) {
discardIdleConnections();
return true;
}
}
else {
// maxConnsPerHost was reduced. This may end up closing too many
// connections, but that's ok. We'll open them later.
internalCloseConnection(connection);
return true;
}
return false;
} | java | @Override
public boolean returnConnection(Connection<CL> connection) {
returnedCount.incrementAndGet();
monitor.incConnectionReturned(host);
ConnectionException ce = connection.getLastException();
if (ce != null) {
if (ce instanceof IsDeadConnectionException) {
noteError(ce);
internalCloseConnection(connection);
return true;
}
}
errorsSinceLastSuccess.set(0);
// Still within the number of max active connection
if (activeCount.get() <= config.getMaxConnsPerHost()) {
availableConnections.add(connection);
if (isShutdown()) {
discardIdleConnections();
return true;
}
}
else {
// maxConnsPerHost was reduced. This may end up closing too many
// connections, but that's ok. We'll open them later.
internalCloseConnection(connection);
return true;
}
return false;
} | [
"@",
"Override",
"public",
"boolean",
"returnConnection",
"(",
"Connection",
"<",
"CL",
">",
"connection",
")",
"{",
"returnedCount",
".",
"incrementAndGet",
"(",
")",
";",
"monitor",
".",
"incConnectionReturned",
"(",
"host",
")",
";",
"ConnectionException",
"c... | Return a connection to this host
@param connection | [
"Return",
"a",
"connection",
"to",
"this",
"host"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L251-L283 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.markAsDown | @Override
public void markAsDown(ConnectionException reason) {
// Make sure we're not triggering the reconnect process more than once
if (isReconnecting.compareAndSet(false, true)) {
markedDownCount.incrementAndGet();
if (reason != null && !(reason instanceof TimeoutException)) {
discardIdleConnections();
}
listener.onHostDown(this);
monitor .onHostDown(getHost(), reason);
retryContext.begin();
try {
long delay = retryContext.getNextDelay();
executor.schedule(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("RetryService : " + host.getName());
try {
if (activeCount.get() == 0)
reconnect();
// Created a new connection successfully.
try {
retryContext.success();
if (isReconnecting.compareAndSet(true, false)) {
monitor .onHostReactivated(host, SimpleHostConnectionPool.this);
listener.onHostUp(SimpleHostConnectionPool.this);
}
}
catch (Throwable t) {
LOG.error("Error reconnecting client", t);
}
return;
}
catch (Throwable t) {
// Ignore
//t.printStackTrace();
}
if (!isShutdown()) {
long delay = retryContext.getNextDelay();
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
}
}, delay, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
LOG.error("Failed to schedule retry task for " + host.getHostName(), e);
}
}
} | java | @Override
public void markAsDown(ConnectionException reason) {
// Make sure we're not triggering the reconnect process more than once
if (isReconnecting.compareAndSet(false, true)) {
markedDownCount.incrementAndGet();
if (reason != null && !(reason instanceof TimeoutException)) {
discardIdleConnections();
}
listener.onHostDown(this);
monitor .onHostDown(getHost(), reason);
retryContext.begin();
try {
long delay = retryContext.getNextDelay();
executor.schedule(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("RetryService : " + host.getName());
try {
if (activeCount.get() == 0)
reconnect();
// Created a new connection successfully.
try {
retryContext.success();
if (isReconnecting.compareAndSet(true, false)) {
monitor .onHostReactivated(host, SimpleHostConnectionPool.this);
listener.onHostUp(SimpleHostConnectionPool.this);
}
}
catch (Throwable t) {
LOG.error("Error reconnecting client", t);
}
return;
}
catch (Throwable t) {
// Ignore
//t.printStackTrace();
}
if (!isShutdown()) {
long delay = retryContext.getNextDelay();
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
}
}, delay, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
LOG.error("Failed to schedule retry task for " + host.getHostName(), e);
}
}
} | [
"@",
"Override",
"public",
"void",
"markAsDown",
"(",
"ConnectionException",
"reason",
")",
"{",
"// Make sure we're not triggering the reconnect process more than once",
"if",
"(",
"isReconnecting",
".",
"compareAndSet",
"(",
"false",
",",
"true",
")",
")",
"{",
"marke... | Mark the host as down. No new connections will be created from this host.
Connections currently in use will be allowed to continue processing. | [
"Mark",
"the",
"host",
"as",
"down",
".",
"No",
"new",
"connections",
"will",
"be",
"created",
"from",
"this",
"host",
".",
"Connections",
"currently",
"in",
"use",
"will",
"be",
"allowed",
"to",
"continue",
"processing",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L312-L367 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.tryOpenAsync | private boolean tryOpenAsync() {
Connection<CL> connection = null;
// Try to open a new connection, as long as we haven't reached the max
if (activeCount.get() < config.getMaxConnsPerHost()) {
try {
if (activeCount.incrementAndGet() <= config.getMaxConnsPerHost()) {
// Don't try to open too many connections at the same time.
if (pendingConnections.incrementAndGet() > config.getMaxPendingConnectionsPerHost()) {
pendingConnections.decrementAndGet();
}
else {
try {
connectAttempt.incrementAndGet();
connection = factory.createConnection(this);
connection.openAsync(new Connection.AsyncOpenCallback<CL>() {
@Override
public void success(Connection<CL> connection) {
openConnections.incrementAndGet();
pendingConnections.decrementAndGet();
availableConnections.add(connection);
// Sanity check in case the connection
// pool was closed
if (isShutdown()) {
discardIdleConnections();
}
}
@Override
public void failure(Connection<CL> conn, ConnectionException e) {
failedOpenConnections.incrementAndGet();
pendingConnections.decrementAndGet();
activeCount.decrementAndGet();
if (e instanceof IsDeadConnectionException) {
noteError(e);
}
}
});
return true;
}
catch (ThrottledException e) {
// Trying to open way too many connections here
}
finally {
if (connection == null)
pendingConnections.decrementAndGet();
}
}
}
}
finally {
if (connection == null) {
activeCount.decrementAndGet();
}
}
}
return false;
} | java | private boolean tryOpenAsync() {
Connection<CL> connection = null;
// Try to open a new connection, as long as we haven't reached the max
if (activeCount.get() < config.getMaxConnsPerHost()) {
try {
if (activeCount.incrementAndGet() <= config.getMaxConnsPerHost()) {
// Don't try to open too many connections at the same time.
if (pendingConnections.incrementAndGet() > config.getMaxPendingConnectionsPerHost()) {
pendingConnections.decrementAndGet();
}
else {
try {
connectAttempt.incrementAndGet();
connection = factory.createConnection(this);
connection.openAsync(new Connection.AsyncOpenCallback<CL>() {
@Override
public void success(Connection<CL> connection) {
openConnections.incrementAndGet();
pendingConnections.decrementAndGet();
availableConnections.add(connection);
// Sanity check in case the connection
// pool was closed
if (isShutdown()) {
discardIdleConnections();
}
}
@Override
public void failure(Connection<CL> conn, ConnectionException e) {
failedOpenConnections.incrementAndGet();
pendingConnections.decrementAndGet();
activeCount.decrementAndGet();
if (e instanceof IsDeadConnectionException) {
noteError(e);
}
}
});
return true;
}
catch (ThrottledException e) {
// Trying to open way too many connections here
}
finally {
if (connection == null)
pendingConnections.decrementAndGet();
}
}
}
}
finally {
if (connection == null) {
activeCount.decrementAndGet();
}
}
}
return false;
} | [
"private",
"boolean",
"tryOpenAsync",
"(",
")",
"{",
"Connection",
"<",
"CL",
">",
"connection",
"=",
"null",
";",
"// Try to open a new connection, as long as we haven't reached the max",
"if",
"(",
"activeCount",
".",
"get",
"(",
")",
"<",
"config",
".",
"getMaxCo... | Try to open a new connection asynchronously. We don't actually return a
connection here. Instead, the connection will be added to idle queue when
it's ready. | [
"Try",
"to",
"open",
"a",
"new",
"connection",
"asynchronously",
".",
"We",
"don",
"t",
"actually",
"return",
"a",
"connection",
"here",
".",
"Instead",
"the",
"connection",
"will",
"be",
"added",
"to",
"idle",
"queue",
"when",
"it",
"s",
"ready",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L416-L474 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | SimpleHostConnectionPool.discardIdleConnections | private void discardIdleConnections() {
List<Connection<CL>> connections = Lists.newArrayList();
availableConnections.drainTo(connections);
activeCount.addAndGet(-connections.size());
for (Connection<CL> connection : connections) {
try {
closedConnections.incrementAndGet();
connection.close(); // This is usually an async operation
}
catch (Throwable t) {
// TODO
}
}
} | java | private void discardIdleConnections() {
List<Connection<CL>> connections = Lists.newArrayList();
availableConnections.drainTo(connections);
activeCount.addAndGet(-connections.size());
for (Connection<CL> connection : connections) {
try {
closedConnections.incrementAndGet();
connection.close(); // This is usually an async operation
}
catch (Throwable t) {
// TODO
}
}
} | [
"private",
"void",
"discardIdleConnections",
"(",
")",
"{",
"List",
"<",
"Connection",
"<",
"CL",
">>",
"connections",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"availableConnections",
".",
"drainTo",
"(",
"connections",
")",
";",
"activeCount",
".",
... | Drain all idle connections and close them. Connections that are currently borrowed
will not be closed here. | [
"Drain",
"all",
"idle",
"connections",
"and",
"close",
"them",
".",
"Connections",
"that",
"are",
"currently",
"borrowed",
"will",
"not",
"be",
"closed",
"here",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java#L555-L569 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java | CompositeColumnEntityMapper.fillMutationBatch | public void fillMutationBatch(ColumnListMutation<ByteBuffer> clm, Object entity) throws IllegalArgumentException, IllegalAccessException {
List<?> list = (List<?>) containerField.get(entity);
if (list != null) {
for (Object element : list) {
fillColumnMutation(clm, element);
}
}
} | java | public void fillMutationBatch(ColumnListMutation<ByteBuffer> clm, Object entity) throws IllegalArgumentException, IllegalAccessException {
List<?> list = (List<?>) containerField.get(entity);
if (list != null) {
for (Object element : list) {
fillColumnMutation(clm, element);
}
}
} | [
"public",
"void",
"fillMutationBatch",
"(",
"ColumnListMutation",
"<",
"ByteBuffer",
">",
"clm",
",",
"Object",
"entity",
")",
"throws",
"IllegalArgumentException",
",",
"IllegalAccessException",
"{",
"List",
"<",
"?",
">",
"list",
"=",
"(",
"List",
"<",
"?",
... | Iterate through the list and create a column for each element
@param clm
@param entity
@throws IllegalArgumentException
@throws IllegalAccessException | [
"Iterate",
"through",
"the",
"list",
"and",
"create",
"a",
"column",
"for",
"each",
"element"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java#L111-L118 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java | CompositeColumnEntityMapper.fillColumnMutation | public void fillColumnMutation(ColumnListMutation<ByteBuffer> clm, Object entity) {
try {
ByteBuffer columnName = toColumnName(entity);
ByteBuffer value = valueMapper.toByteBuffer(entity);
clm.putColumn(columnName, value);
} catch(Exception e) {
throw new PersistenceException("failed to fill mutation batch", e);
}
} | java | public void fillColumnMutation(ColumnListMutation<ByteBuffer> clm, Object entity) {
try {
ByteBuffer columnName = toColumnName(entity);
ByteBuffer value = valueMapper.toByteBuffer(entity);
clm.putColumn(columnName, value);
} catch(Exception e) {
throw new PersistenceException("failed to fill mutation batch", e);
}
} | [
"public",
"void",
"fillColumnMutation",
"(",
"ColumnListMutation",
"<",
"ByteBuffer",
">",
"clm",
",",
"Object",
"entity",
")",
"{",
"try",
"{",
"ByteBuffer",
"columnName",
"=",
"toColumnName",
"(",
"entity",
")",
";",
"ByteBuffer",
"value",
"=",
"valueMapper",
... | Add a column based on the provided entity
@param clm
@param entity | [
"Add",
"a",
"column",
"based",
"on",
"the",
"provided",
"entity"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java#L138-L147 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java | CompositeColumnEntityMapper.setField | public boolean setField(Object entity, ColumnList<ByteBuffer> columns) throws Exception {
List<Object> list = getOrCreateField(entity);
// Iterate through columns and add embedded entities to the list
for (com.netflix.astyanax.model.Column<ByteBuffer> c : columns) {
list.add(fromColumn(c));
}
return true;
} | java | public boolean setField(Object entity, ColumnList<ByteBuffer> columns) throws Exception {
List<Object> list = getOrCreateField(entity);
// Iterate through columns and add embedded entities to the list
for (com.netflix.astyanax.model.Column<ByteBuffer> c : columns) {
list.add(fromColumn(c));
}
return true;
} | [
"public",
"boolean",
"setField",
"(",
"Object",
"entity",
",",
"ColumnList",
"<",
"ByteBuffer",
">",
"columns",
")",
"throws",
"Exception",
"{",
"List",
"<",
"Object",
">",
"list",
"=",
"getOrCreateField",
"(",
"entity",
")",
";",
"// Iterate through columns and... | Set the collection field using the provided column list of embedded entities
@param entity
@param name
@param column
@return
@throws Exception | [
"Set",
"the",
"collection",
"field",
"using",
"the",
"provided",
"column",
"list",
"of",
"embedded",
"entities"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeColumnEntityMapper.java#L178-L187 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/ByteBufferOutputStream.java | ByteBufferOutputStream.getBufferList | public List<ByteBuffer> getBufferList() {
List<ByteBuffer> result = buffers;
reset();
for (ByteBuffer buffer : result) {
buffer.flip();
}
return result;
} | java | public List<ByteBuffer> getBufferList() {
List<ByteBuffer> result = buffers;
reset();
for (ByteBuffer buffer : result) {
buffer.flip();
}
return result;
} | [
"public",
"List",
"<",
"ByteBuffer",
">",
"getBufferList",
"(",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"result",
"=",
"buffers",
";",
"reset",
"(",
")",
";",
"for",
"(",
"ByteBuffer",
"buffer",
":",
"result",
")",
"{",
"buffer",
".",
"flip",
"(",
... | Returns all data written and resets the stream to be empty. | [
"Returns",
"all",
"data",
"written",
"and",
"resets",
"the",
"stream",
"to",
"be",
"empty",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/ByteBufferOutputStream.java#L60-L67 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/ByteBufferOutputStream.java | ByteBufferOutputStream.prepend | public void prepend(List<ByteBuffer> lists) {
for (ByteBuffer buffer : lists) {
buffer.position(buffer.limit());
}
buffers.addAll(0, lists);
} | java | public void prepend(List<ByteBuffer> lists) {
for (ByteBuffer buffer : lists) {
buffer.position(buffer.limit());
}
buffers.addAll(0, lists);
} | [
"public",
"void",
"prepend",
"(",
"List",
"<",
"ByteBuffer",
">",
"lists",
")",
"{",
"for",
"(",
"ByteBuffer",
"buffer",
":",
"lists",
")",
"{",
"buffer",
".",
"position",
"(",
"buffer",
".",
"limit",
"(",
")",
")",
";",
"}",
"buffers",
".",
"addAll"... | Prepend a list of ByteBuffers to this stream. | [
"Prepend",
"a",
"list",
"of",
"ByteBuffers",
"to",
"this",
"stream",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/ByteBufferOutputStream.java#L87-L92 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/model/ColumnPath.java | ColumnPath.append | public <C2> ColumnPath<C> append(C2 name, Serializer<C2> ser) {
path.add(ByteBuffer.wrap(ser.toBytes(name)));
return this;
} | java | public <C2> ColumnPath<C> append(C2 name, Serializer<C2> ser) {
path.add(ByteBuffer.wrap(ser.toBytes(name)));
return this;
} | [
"public",
"<",
"C2",
">",
"ColumnPath",
"<",
"C",
">",
"append",
"(",
"C2",
"name",
",",
"Serializer",
"<",
"C2",
">",
"ser",
")",
"{",
"path",
".",
"add",
"(",
"ByteBuffer",
".",
"wrap",
"(",
"ser",
".",
"toBytes",
"(",
"name",
")",
")",
")",
... | Add a depth to the path
@param <C>
@param ser
@param name
@return | [
"Add",
"a",
"depth",
"to",
"the",
"path"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/model/ColumnPath.java#L76-L79 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java | TimeUUIDUtils.getUniqueTimeUUIDinMillis | public static java.util.UUID getUniqueTimeUUIDinMillis() {
return new java.util.UUID(UUIDGen.newTime(), UUIDGen.getClockSeqAndNode());
} | java | public static java.util.UUID getUniqueTimeUUIDinMillis() {
return new java.util.UUID(UUIDGen.newTime(), UUIDGen.getClockSeqAndNode());
} | [
"public",
"static",
"java",
".",
"util",
".",
"UUID",
"getUniqueTimeUUIDinMillis",
"(",
")",
"{",
"return",
"new",
"java",
".",
"util",
".",
"UUID",
"(",
"UUIDGen",
".",
"newTime",
"(",
")",
",",
"UUIDGen",
".",
"getClockSeqAndNode",
"(",
")",
")",
";",
... | Gets a new and unique time uuid in milliseconds. It is useful to use in a
TimeUUIDType sorted column family.
@return the time uuid | [
"Gets",
"a",
"new",
"and",
"unique",
"time",
"uuid",
"in",
"milliseconds",
".",
"It",
"is",
"useful",
"to",
"use",
"in",
"a",
"TimeUUIDType",
"sorted",
"column",
"family",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java#L42-L44 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java | TimeUUIDUtils.asByteBuffer | public static ByteBuffer asByteBuffer(java.util.UUID uuid) {
if (uuid == null) {
return null;
}
return ByteBuffer.wrap(asByteArray(uuid));
} | java | public static ByteBuffer asByteBuffer(java.util.UUID uuid) {
if (uuid == null) {
return null;
}
return ByteBuffer.wrap(asByteArray(uuid));
} | [
"public",
"static",
"ByteBuffer",
"asByteBuffer",
"(",
"java",
".",
"util",
".",
"UUID",
"uuid",
")",
"{",
"if",
"(",
"uuid",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"ByteBuffer",
".",
"wrap",
"(",
"asByteArray",
"(",
"uuid",
")",... | Coverts a java.util.UUID into a ByteBuffer.
@param uuid
a java.util.UUID
@return a ByteBuffer representaion of the param UUID | [
"Coverts",
"a",
"java",
".",
"util",
".",
"UUID",
"into",
"a",
"ByteBuffer",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java#L179-L185 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java | TimeUUIDUtils.uuid | public static UUID uuid(ByteBuffer bb) {
bb = bb.slice();
return new UUID(bb.getLong(), bb.getLong());
} | java | public static UUID uuid(ByteBuffer bb) {
bb = bb.slice();
return new UUID(bb.getLong(), bb.getLong());
} | [
"public",
"static",
"UUID",
"uuid",
"(",
"ByteBuffer",
"bb",
")",
"{",
"bb",
"=",
"bb",
".",
"slice",
"(",
")",
";",
"return",
"new",
"UUID",
"(",
"bb",
".",
"getLong",
"(",
")",
",",
"bb",
".",
"getLong",
"(",
")",
")",
";",
"}"
] | Converts a ByteBuffer containing a UUID into a java.util.UUID
@param bb
a ByteBuffer containing a UUID
@return a java.util.UUID | [
"Converts",
"a",
"ByteBuffer",
"containing",
"a",
"UUID",
"into",
"a",
"java",
".",
"util",
".",
"UUID"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java#L199-L202 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java | CompositeEntityMapper.toColumnName | private ByteBuffer toColumnName(Object obj) {
SimpleCompositeBuilder composite = new SimpleCompositeBuilder(bufferSize, Equality.EQUAL);
// Iterate through each component and add to a CompositeType structure
for (FieldMapper<?> mapper : components) {
try {
composite.addWithoutControl(mapper.toByteBuffer(obj));
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return composite.get();
} | java | private ByteBuffer toColumnName(Object obj) {
SimpleCompositeBuilder composite = new SimpleCompositeBuilder(bufferSize, Equality.EQUAL);
// Iterate through each component and add to a CompositeType structure
for (FieldMapper<?> mapper : components) {
try {
composite.addWithoutControl(mapper.toByteBuffer(obj));
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return composite.get();
} | [
"private",
"ByteBuffer",
"toColumnName",
"(",
"Object",
"obj",
")",
"{",
"SimpleCompositeBuilder",
"composite",
"=",
"new",
"SimpleCompositeBuilder",
"(",
"bufferSize",
",",
"Equality",
".",
"EQUAL",
")",
";",
"// Iterate through each component and add to a CompositeType st... | Return the column name byte buffer for this entity
@param obj
@return | [
"Return",
"the",
"column",
"name",
"byte",
"buffer",
"for",
"this",
"entity"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java#L226-L239 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java | CompositeEntityMapper.constructEntity | T constructEntity(K id, com.netflix.astyanax.model.Column<ByteBuffer> column) {
try {
// First, construct the parent class and give it an id
T entity = clazz.newInstance();
idMapper.setValue(entity, id);
setEntityFieldsFromColumnName(entity, column.getRawName().duplicate());
valueMapper.setField(entity, column.getByteBufferValue().duplicate());
return entity;
} catch(Exception e) {
throw new PersistenceException("failed to construct entity", e);
}
} | java | T constructEntity(K id, com.netflix.astyanax.model.Column<ByteBuffer> column) {
try {
// First, construct the parent class and give it an id
T entity = clazz.newInstance();
idMapper.setValue(entity, id);
setEntityFieldsFromColumnName(entity, column.getRawName().duplicate());
valueMapper.setField(entity, column.getByteBufferValue().duplicate());
return entity;
} catch(Exception e) {
throw new PersistenceException("failed to construct entity", e);
}
} | [
"T",
"constructEntity",
"(",
"K",
"id",
",",
"com",
".",
"netflix",
".",
"astyanax",
".",
"model",
".",
"Column",
"<",
"ByteBuffer",
">",
"column",
")",
"{",
"try",
"{",
"// First, construct the parent class and give it an id",
"T",
"entity",
"=",
"clazz",
"."... | Construct an entity object from a row key and column list.
@param id
@param cl
@return | [
"Construct",
"an",
"entity",
"object",
"from",
"a",
"row",
"key",
"and",
"column",
"list",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java#L248-L259 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java | CompositeEntityMapper.fromColumn | Object fromColumn(K id, com.netflix.astyanax.model.Column<ByteBuffer> c) {
try {
// Allocate a new entity
Object entity = clazz.newInstance();
idMapper.setValue(entity, id);
setEntityFieldsFromColumnName(entity, c.getRawName().duplicate());
valueMapper.setField(entity, c.getByteBufferValue().duplicate());
return entity;
} catch(Exception e) {
throw new PersistenceException("failed to construct entity", e);
}
} | java | Object fromColumn(K id, com.netflix.astyanax.model.Column<ByteBuffer> c) {
try {
// Allocate a new entity
Object entity = clazz.newInstance();
idMapper.setValue(entity, id);
setEntityFieldsFromColumnName(entity, c.getRawName().duplicate());
valueMapper.setField(entity, c.getByteBufferValue().duplicate());
return entity;
} catch(Exception e) {
throw new PersistenceException("failed to construct entity", e);
}
} | [
"Object",
"fromColumn",
"(",
"K",
"id",
",",
"com",
".",
"netflix",
".",
"astyanax",
".",
"model",
".",
"Column",
"<",
"ByteBuffer",
">",
"c",
")",
"{",
"try",
"{",
"// Allocate a new entity",
"Object",
"entity",
"=",
"clazz",
".",
"newInstance",
"(",
")... | Return an object from the column
@param cl
@return | [
"Return",
"an",
"object",
"from",
"the",
"column"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java#L312-L324 | train |
Netflix/astyanax | astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java | CompositeEntityMapper.getComparatorType | public String getComparatorType() {
StringBuilder sb = new StringBuilder();
sb.append("CompositeType(");
sb.append(StringUtils.join(
Collections2.transform(components, new Function<FieldMapper<?>, String>() {
public String apply(FieldMapper<?> input) {
return input.serializer.getComparatorType().getTypeName();
}
}),
","));
sb.append(")");
return sb.toString();
} | java | public String getComparatorType() {
StringBuilder sb = new StringBuilder();
sb.append("CompositeType(");
sb.append(StringUtils.join(
Collections2.transform(components, new Function<FieldMapper<?>, String>() {
public String apply(FieldMapper<?> input) {
return input.serializer.getComparatorType().getTypeName();
}
}),
","));
sb.append(")");
return sb.toString();
} | [
"public",
"String",
"getComparatorType",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"CompositeType(\"",
")",
";",
"sb",
".",
"append",
"(",
"StringUtils",
".",
"join",
"(",
"Collections2",
... | Return the cassandra comparator type for this composite structure
@return | [
"Return",
"the",
"cassandra",
"comparator",
"type",
"for",
"this",
"composite",
"structure"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-entity-mapper/src/main/java/com/netflix/astyanax/entitystore/CompositeEntityMapper.java#L356-L368 | train |
Netflix/astyanax | astyanax-recipes/src/main/java/com/netflix/astyanax/recipes/uniqueness/RowUniquenessConstraint.java | RowUniquenessConstraint.readData | public ByteBuffer readData() throws Exception {
ColumnList<C> result = keyspace
.prepareQuery(columnFamily)
.setConsistencyLevel(consistencyLevel)
.getKey(key)
.execute()
.getResult();
boolean hasColumn = false;
ByteBuffer data = null;
for (Column<C> column : result) {
if (column.getTtl() == 0) {
if (hasColumn) {
throw new IllegalStateException("Row has multiple uniquneness locks");
}
hasColumn = true;
data = column.getByteBufferValue();
}
}
if (!hasColumn) {
throw new NotFoundException(this.key.toString() + " has no uniquness lock");
}
return data;
} | java | public ByteBuffer readData() throws Exception {
ColumnList<C> result = keyspace
.prepareQuery(columnFamily)
.setConsistencyLevel(consistencyLevel)
.getKey(key)
.execute()
.getResult();
boolean hasColumn = false;
ByteBuffer data = null;
for (Column<C> column : result) {
if (column.getTtl() == 0) {
if (hasColumn) {
throw new IllegalStateException("Row has multiple uniquneness locks");
}
hasColumn = true;
data = column.getByteBufferValue();
}
}
if (!hasColumn) {
throw new NotFoundException(this.key.toString() + " has no uniquness lock");
}
return data;
} | [
"public",
"ByteBuffer",
"readData",
"(",
")",
"throws",
"Exception",
"{",
"ColumnList",
"<",
"C",
">",
"result",
"=",
"keyspace",
".",
"prepareQuery",
"(",
"columnFamily",
")",
".",
"setConsistencyLevel",
"(",
"consistencyLevel",
")",
".",
"getKey",
"(",
"key"... | Read the data stored with the unique row. This data is normally a 'foreign' key to
another column family.
@return
@throws Exception | [
"Read",
"the",
"data",
"stored",
"with",
"the",
"unique",
"row",
".",
"This",
"data",
"is",
"normally",
"a",
"foreign",
"key",
"to",
"another",
"column",
"family",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-recipes/src/main/java/com/netflix/astyanax/recipes/uniqueness/RowUniquenessConstraint.java#L156-L180 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/util/Callables.java | Callables.decorateWithBarrier | public static <T> Callable<T> decorateWithBarrier(CyclicBarrier barrier, Callable<T> callable) {
return new BarrierCallableDecorator<T>(barrier, callable);
} | java | public static <T> Callable<T> decorateWithBarrier(CyclicBarrier barrier, Callable<T> callable) {
return new BarrierCallableDecorator<T>(barrier, callable);
} | [
"public",
"static",
"<",
"T",
">",
"Callable",
"<",
"T",
">",
"decorateWithBarrier",
"(",
"CyclicBarrier",
"barrier",
",",
"Callable",
"<",
"T",
">",
"callable",
")",
"{",
"return",
"new",
"BarrierCallableDecorator",
"<",
"T",
">",
"(",
"barrier",
",",
"ca... | Create a callable that waits on a barrier before starting execution
@param barrier
@param callable
@return | [
"Create",
"a",
"callable",
"that",
"waits",
"on",
"a",
"barrier",
"before",
"starting",
"execution"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/util/Callables.java#L28-L30 | train |
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java | ThriftKeyspaceImpl.executeDdlOperation | private synchronized <R> OperationResult<R> executeDdlOperation(AbstractOperationImpl<R> operation, RetryPolicy retry)
throws OperationException, ConnectionException {
ConnectionException lastException = null;
for (int i = 0; i < 2; i++) {
operation.setPinnedHost(ddlHost);
try {
OperationResult<R> result = connectionPool.executeWithFailover(operation, retry);
ddlHost = result.getHost();
return result;
}
catch (ConnectionException e) {
lastException = e;
if (e instanceof IsDeadConnectionException) {
ddlHost = null;
}
}
}
throw lastException;
} | java | private synchronized <R> OperationResult<R> executeDdlOperation(AbstractOperationImpl<R> operation, RetryPolicy retry)
throws OperationException, ConnectionException {
ConnectionException lastException = null;
for (int i = 0; i < 2; i++) {
operation.setPinnedHost(ddlHost);
try {
OperationResult<R> result = connectionPool.executeWithFailover(operation, retry);
ddlHost = result.getHost();
return result;
}
catch (ConnectionException e) {
lastException = e;
if (e instanceof IsDeadConnectionException) {
ddlHost = null;
}
}
}
throw lastException;
} | [
"private",
"synchronized",
"<",
"R",
">",
"OperationResult",
"<",
"R",
">",
"executeDdlOperation",
"(",
"AbstractOperationImpl",
"<",
"R",
">",
"operation",
",",
"RetryPolicy",
"retry",
")",
"throws",
"OperationException",
",",
"ConnectionException",
"{",
"Connectio... | Attempt to execute the DDL operation on the same host
@param operation
@param retry
@return
@throws OperationException
@throws ConnectionException | [
"Attempt",
"to",
"execute",
"the",
"DDL",
"operation",
"on",
"the",
"same",
"host"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java#L529-L547 | train |
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java | ThriftKeyspaceImpl.precheckSchemaAgreement | private void precheckSchemaAgreement(Client client) throws Exception {
Map<String, List<String>> schemas = client.describe_schema_versions();
if (schemas.size() > 1) {
throw new SchemaDisagreementException("Can't change schema due to pending schema agreement");
}
} | java | private void precheckSchemaAgreement(Client client) throws Exception {
Map<String, List<String>> schemas = client.describe_schema_versions();
if (schemas.size() > 1) {
throw new SchemaDisagreementException("Can't change schema due to pending schema agreement");
}
} | [
"private",
"void",
"precheckSchemaAgreement",
"(",
"Client",
"client",
")",
"throws",
"Exception",
"{",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"schemas",
"=",
"client",
".",
"describe_schema_versions",
"(",
")",
";",
"if",
"(",
"schemas"... | Do a quick check to see if there is a schema disagreement. This is done as an extra precaution
to reduce the chances of putting the cluster into a bad state. This will not gurantee however, that
by the time a schema change is made the cluster will be in the same state.
@param client
@throws Exception | [
"Do",
"a",
"quick",
"check",
"to",
"see",
"if",
"there",
"is",
"a",
"schema",
"disagreement",
".",
"This",
"is",
"done",
"as",
"an",
"extra",
"precaution",
"to",
"reduce",
"the",
"chances",
"of",
"putting",
"the",
"cluster",
"into",
"a",
"bad",
"state",
... | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java#L762-L767 | train |
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java | ThriftKeyspaceImpl.toThriftColumnFamilyDefinition | private ThriftColumnFamilyDefinitionImpl toThriftColumnFamilyDefinition(Map<String, Object> options, ColumnFamily columnFamily) {
ThriftColumnFamilyDefinitionImpl def = new ThriftColumnFamilyDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
internalOptions.put("keyspace", getKeyspaceName());
if (columnFamily != null) {
internalOptions.put("name", columnFamily.getName());
if (!internalOptions.containsKey("comparator_type"))
internalOptions.put("comparator_type", columnFamily.getColumnSerializer().getComparatorType().getTypeName());
if (!internalOptions.containsKey("key_validation_class"))
internalOptions.put("key_validation_class", columnFamily.getKeySerializer().getComparatorType().getTypeName());
if (columnFamily.getDefaultValueSerializer() != null && !internalOptions.containsKey("default_validation_class"))
internalOptions.put("default_validation_class", columnFamily.getDefaultValueSerializer().getComparatorType().getTypeName());
}
def.setFields(internalOptions);
return def;
} | java | private ThriftColumnFamilyDefinitionImpl toThriftColumnFamilyDefinition(Map<String, Object> options, ColumnFamily columnFamily) {
ThriftColumnFamilyDefinitionImpl def = new ThriftColumnFamilyDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
internalOptions.put("keyspace", getKeyspaceName());
if (columnFamily != null) {
internalOptions.put("name", columnFamily.getName());
if (!internalOptions.containsKey("comparator_type"))
internalOptions.put("comparator_type", columnFamily.getColumnSerializer().getComparatorType().getTypeName());
if (!internalOptions.containsKey("key_validation_class"))
internalOptions.put("key_validation_class", columnFamily.getKeySerializer().getComparatorType().getTypeName());
if (columnFamily.getDefaultValueSerializer() != null && !internalOptions.containsKey("default_validation_class"))
internalOptions.put("default_validation_class", columnFamily.getDefaultValueSerializer().getComparatorType().getTypeName());
}
def.setFields(internalOptions);
return def;
} | [
"private",
"ThriftColumnFamilyDefinitionImpl",
"toThriftColumnFamilyDefinition",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"options",
",",
"ColumnFamily",
"columnFamily",
")",
"{",
"ThriftColumnFamilyDefinitionImpl",
"def",
"=",
"new",
"ThriftColumnFamilyDefinitionImpl",... | Convert a Map of options to an internal thrift column family definition
@param options | [
"Convert",
"a",
"Map",
"of",
"options",
"to",
"an",
"internal",
"thrift",
"column",
"family",
"definition"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java#L773-L794 | train |
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java | ThriftKeyspaceImpl.toThriftKeyspaceDefinition | private ThriftKeyspaceDefinitionImpl toThriftKeyspaceDefinition(final Map<String, Object> options) {
ThriftKeyspaceDefinitionImpl def = new ThriftKeyspaceDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
if (internalOptions.containsKey("name") && !internalOptions.get("name").equals(getKeyspaceName())) {
throw new RuntimeException(
String.format("'name' attribute must match keyspace name. Expected '%s' but got '%s'",
getKeyspaceName(), internalOptions.get("name")));
}
else {
internalOptions.put("name", getKeyspaceName());
}
def.setFields(internalOptions);
return def;
} | java | private ThriftKeyspaceDefinitionImpl toThriftKeyspaceDefinition(final Map<String, Object> options) {
ThriftKeyspaceDefinitionImpl def = new ThriftKeyspaceDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
if (internalOptions.containsKey("name") && !internalOptions.get("name").equals(getKeyspaceName())) {
throw new RuntimeException(
String.format("'name' attribute must match keyspace name. Expected '%s' but got '%s'",
getKeyspaceName(), internalOptions.get("name")));
}
else {
internalOptions.put("name", getKeyspaceName());
}
def.setFields(internalOptions);
return def;
} | [
"private",
"ThriftKeyspaceDefinitionImpl",
"toThriftKeyspaceDefinition",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"options",
")",
"{",
"ThriftKeyspaceDefinitionImpl",
"def",
"=",
"new",
"ThriftKeyspaceDefinitionImpl",
"(",
")",
";",
"Map",
"<",
"String"... | Convert a Map of options to an internal thrift keyspace definition
@param options | [
"Convert",
"a",
"Map",
"of",
"options",
"to",
"an",
"internal",
"thrift",
"keyspace",
"definition"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftKeyspaceImpl.java#L800-L819 | train |
Netflix/astyanax | astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CqlAllRowsQueryImpl.java | CqlAllRowsQueryImpl.startTasks | private List<Future<Boolean>> startTasks(ExecutorService executor, List<Callable<Boolean>> callables) {
List<Future<Boolean>> tasks = Lists.newArrayList();
for (Callable<Boolean> callable : callables) {
tasks.add(executor.submit(callable));
}
return tasks;
} | java | private List<Future<Boolean>> startTasks(ExecutorService executor, List<Callable<Boolean>> callables) {
List<Future<Boolean>> tasks = Lists.newArrayList();
for (Callable<Boolean> callable : callables) {
tasks.add(executor.submit(callable));
}
return tasks;
} | [
"private",
"List",
"<",
"Future",
"<",
"Boolean",
">",
">",
"startTasks",
"(",
"ExecutorService",
"executor",
",",
"List",
"<",
"Callable",
"<",
"Boolean",
">",
">",
"callables",
")",
"{",
"List",
"<",
"Future",
"<",
"Boolean",
">>",
"tasks",
"=",
"Lists... | Submit all the callables to the executor by synchronize their execution so they all start
AFTER the have all been submitted.
@param executor
@param callables
@return | [
"Submit",
"all",
"the",
"callables",
"to",
"the",
"executor",
"by",
"synchronize",
"their",
"execution",
"so",
"they",
"all",
"start",
"AFTER",
"the",
"have",
"all",
"been",
"submitted",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CqlAllRowsQueryImpl.java#L434-L440 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java | MappingUtil.remove | public <T, K> void remove(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
mutationBatch.withRow(columnFamily,
mapping.getIdValue(item, idFieldClass)).delete();
mutationBatch.execute();
} | java | public <T, K> void remove(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
mutationBatch.withRow(columnFamily,
mapping.getIdValue(item, idFieldClass)).delete();
mutationBatch.execute();
} | [
"public",
"<",
"T",
",",
"K",
">",
"void",
"remove",
"(",
"ColumnFamily",
"<",
"K",
",",
"String",
">",
"columnFamily",
",",
"T",
"item",
")",
"throws",
"Exception",
"{",
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
"}",
")",
"Class",
"<",
"T",
... | Remove the given item
@param columnFamily
column family of the item
@param item
the item to remove
@throws Exception
errors | [
"Remove",
"the",
"given",
"item"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java#L92-L111 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java | MappingUtil.getAll | public <T, K> List<T> getAll(ColumnFamily<K, String> columnFamily,
Class<T> itemClass) throws Exception {
Mapping<T> mapping = getMapping(itemClass);
Rows<K, String> result = keyspace.prepareQuery(columnFamily)
.getAllRows().execute().getResult();
return mapping.getAll(result);
} | java | public <T, K> List<T> getAll(ColumnFamily<K, String> columnFamily,
Class<T> itemClass) throws Exception {
Mapping<T> mapping = getMapping(itemClass);
Rows<K, String> result = keyspace.prepareQuery(columnFamily)
.getAllRows().execute().getResult();
return mapping.getAll(result);
} | [
"public",
"<",
"T",
",",
"K",
">",
"List",
"<",
"T",
">",
"getAll",
"(",
"ColumnFamily",
"<",
"K",
",",
"String",
">",
"columnFamily",
",",
"Class",
"<",
"T",
">",
"itemClass",
")",
"throws",
"Exception",
"{",
"Mapping",
"<",
"T",
">",
"mapping",
"... | Get all rows of the specified item
@param columnFamily
column family of the item
@param itemClass
item's class
@return new instances with the item's columns propagated
@throws Exception
errors | [
"Get",
"all",
"rows",
"of",
"the",
"specified",
"item"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java#L178-L184 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java | MappingUtil.getMapping | public <T> Mapping<T> getMapping(Class<T> clazz) {
return (cache != null) ? cache.getMapping(clazz, annotationSet)
: new Mapping<T>(clazz, annotationSet);
} | java | public <T> Mapping<T> getMapping(Class<T> clazz) {
return (cache != null) ? cache.getMapping(clazz, annotationSet)
: new Mapping<T>(clazz, annotationSet);
} | [
"public",
"<",
"T",
">",
"Mapping",
"<",
"T",
">",
"getMapping",
"(",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"return",
"(",
"cache",
"!=",
"null",
")",
"?",
"cache",
".",
"getMapping",
"(",
"clazz",
",",
"annotationSet",
")",
":",
"new",
"Mappi... | Return the mapping instance for the given class
@param clazz
the class
@return mapping instance (new or from cache) | [
"Return",
"the",
"mapping",
"instance",
"for",
"the",
"given",
"class"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java#L193-L196 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.start | @Override
public void start() {
ConnectionPoolMBeanManager.getInstance().registerMonitor(config.getName(), this);
String seeds = config.getSeeds();
if (seeds != null && !seeds.isEmpty()) {
setHosts(config.getSeedHosts());
}
config.getLatencyScoreStrategy().start(new Listener() {
@Override
public void onUpdate() {
rebuildPartitions();
}
@Override
public void onReset() {
rebuildPartitions();
}
});
} | java | @Override
public void start() {
ConnectionPoolMBeanManager.getInstance().registerMonitor(config.getName(), this);
String seeds = config.getSeeds();
if (seeds != null && !seeds.isEmpty()) {
setHosts(config.getSeedHosts());
}
config.getLatencyScoreStrategy().start(new Listener() {
@Override
public void onUpdate() {
rebuildPartitions();
}
@Override
public void onReset() {
rebuildPartitions();
}
});
} | [
"@",
"Override",
"public",
"void",
"start",
"(",
")",
"{",
"ConnectionPoolMBeanManager",
".",
"getInstance",
"(",
")",
".",
"registerMonitor",
"(",
"config",
".",
"getName",
"(",
")",
",",
"this",
")",
";",
"String",
"seeds",
"=",
"config",
".",
"getSeeds"... | Starts the conn pool and resources associated with it | [
"Starts",
"the",
"conn",
"pool",
"and",
"resources",
"associated",
"with",
"it"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L114-L134 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.shutdown | @Override
public void shutdown() {
ConnectionPoolMBeanManager.getInstance().unregisterMonitor(config.getName(), this);
for (Entry<Host, HostConnectionPool<CL>> pool : hosts.entrySet()) {
pool.getValue().shutdown();
}
config.getLatencyScoreStrategy().shutdown();
config.shutdown();
} | java | @Override
public void shutdown() {
ConnectionPoolMBeanManager.getInstance().unregisterMonitor(config.getName(), this);
for (Entry<Host, HostConnectionPool<CL>> pool : hosts.entrySet()) {
pool.getValue().shutdown();
}
config.getLatencyScoreStrategy().shutdown();
config.shutdown();
} | [
"@",
"Override",
"public",
"void",
"shutdown",
"(",
")",
"{",
"ConnectionPoolMBeanManager",
".",
"getInstance",
"(",
")",
".",
"unregisterMonitor",
"(",
"config",
".",
"getName",
"(",
")",
",",
"this",
")",
";",
"for",
"(",
"Entry",
"<",
"Host",
",",
"Ho... | Clean up resources associated with the conn pool | [
"Clean",
"up",
"resources",
"associated",
"with",
"the",
"conn",
"pool"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L139-L149 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.addHost | @Override
public final synchronized boolean addHost(Host host, boolean refresh) {
// Already exists
if (hosts.containsKey(host)) {
// Check to see if we are adding token ranges or if the token ranges changed
// which will force a rebuild of the token topology
Host existingHost = hosts.get(host).getHost();
if (existingHost.getTokenRanges().size() != host.getTokenRanges().size()) {
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
ArrayList<TokenRange> currentTokens = Lists.newArrayList(existingHost.getTokenRanges());
ArrayList<TokenRange> newTokens = Lists.newArrayList(host.getTokenRanges());
Collections.sort(currentTokens, compareByStartToken);
Collections.sort(newTokens, compareByStartToken);
for (int i = 0; i < currentTokens.size(); i++) {
if (!currentTokens.get(i).getStartToken().equals(newTokens.get(i).getStartToken()) ||
!currentTokens.get(i).getEndToken().equals(newTokens.get(i).getEndToken())) {
return false;
}
}
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
else {
HostConnectionPool<CL> pool = newHostConnectionPool(host, factory, config);
if (null == hosts.putIfAbsent(host, pool)) {
try {
monitor.onHostAdded(host, pool);
if (refresh) {
topology.addPool(pool);
rebuildPartitions();
}
pool.primeConnections(config.getInitConnsPerHost());
}
catch (Exception e) {
// Ignore, pool will have been marked down internally
}
return true;
}
else {
return false;
}
}
} | java | @Override
public final synchronized boolean addHost(Host host, boolean refresh) {
// Already exists
if (hosts.containsKey(host)) {
// Check to see if we are adding token ranges or if the token ranges changed
// which will force a rebuild of the token topology
Host existingHost = hosts.get(host).getHost();
if (existingHost.getTokenRanges().size() != host.getTokenRanges().size()) {
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
ArrayList<TokenRange> currentTokens = Lists.newArrayList(existingHost.getTokenRanges());
ArrayList<TokenRange> newTokens = Lists.newArrayList(host.getTokenRanges());
Collections.sort(currentTokens, compareByStartToken);
Collections.sort(newTokens, compareByStartToken);
for (int i = 0; i < currentTokens.size(); i++) {
if (!currentTokens.get(i).getStartToken().equals(newTokens.get(i).getStartToken()) ||
!currentTokens.get(i).getEndToken().equals(newTokens.get(i).getEndToken())) {
return false;
}
}
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
else {
HostConnectionPool<CL> pool = newHostConnectionPool(host, factory, config);
if (null == hosts.putIfAbsent(host, pool)) {
try {
monitor.onHostAdded(host, pool);
if (refresh) {
topology.addPool(pool);
rebuildPartitions();
}
pool.primeConnections(config.getInitConnsPerHost());
}
catch (Exception e) {
// Ignore, pool will have been marked down internally
}
return true;
}
else {
return false;
}
}
} | [
"@",
"Override",
"public",
"final",
"synchronized",
"boolean",
"addHost",
"(",
"Host",
"host",
",",
"boolean",
"refresh",
")",
"{",
"// Already exists",
"if",
"(",
"hosts",
".",
"containsKey",
"(",
"host",
")",
")",
"{",
"// Check to see if we are adding token ran... | Add host to the system. May need to rebuild the partition map of the system
@param host
@param refresh | [
"Add",
"host",
"to",
"the",
"system",
".",
"May",
"need",
"to",
"rebuild",
"the",
"partition",
"map",
"of",
"the",
"system"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L186-L232 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.getActivePools | @Override
public List<HostConnectionPool<CL>> getActivePools() {
return ImmutableList.copyOf(topology.getAllPools().getPools());
} | java | @Override
public List<HostConnectionPool<CL>> getActivePools() {
return ImmutableList.copyOf(topology.getAllPools().getPools());
} | [
"@",
"Override",
"public",
"List",
"<",
"HostConnectionPool",
"<",
"CL",
">",
">",
"getActivePools",
"(",
")",
"{",
"return",
"ImmutableList",
".",
"copyOf",
"(",
"topology",
".",
"getAllPools",
"(",
")",
".",
"getPools",
"(",
")",
")",
";",
"}"
] | list of all active pools
@return {@link List<HostConnectionPool>} | [
"list",
"of",
"all",
"active",
"pools"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L259-L262 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.removeHost | @Override
public synchronized boolean removeHost(Host host, boolean refresh) {
HostConnectionPool<CL> pool = hosts.remove(host);
if (pool != null) {
topology.removePool(pool);
rebuildPartitions();
monitor.onHostRemoved(host);
pool.shutdown();
return true;
}
else {
return false;
}
} | java | @Override
public synchronized boolean removeHost(Host host, boolean refresh) {
HostConnectionPool<CL> pool = hosts.remove(host);
if (pool != null) {
topology.removePool(pool);
rebuildPartitions();
monitor.onHostRemoved(host);
pool.shutdown();
return true;
}
else {
return false;
}
} | [
"@",
"Override",
"public",
"synchronized",
"boolean",
"removeHost",
"(",
"Host",
"host",
",",
"boolean",
"refresh",
")",
"{",
"HostConnectionPool",
"<",
"CL",
">",
"pool",
"=",
"hosts",
".",
"remove",
"(",
"host",
")",
";",
"if",
"(",
"pool",
"!=",
"null... | Remove host from the system. Shuts down pool associated with the host and rebuilds partition map
@param host
@param refresh | [
"Remove",
"host",
"from",
"the",
"system",
".",
"Shuts",
"down",
"pool",
"associated",
"with",
"the",
"host",
"and",
"rebuilds",
"partition",
"map"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L277-L290 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | AbstractHostPartitionConnectionPool.executeWithFailover | @Override
public <R> OperationResult<R> executeWithFailover(Operation<CL, R> op, RetryPolicy retry)
throws ConnectionException {
//Tracing operation
OperationTracer opsTracer = config.getOperationTracer();
final AstyanaxContext context = opsTracer.getAstyanaxContext();
if(context != null) {
opsTracer.onCall(context, op);
}
retry.begin();
ConnectionException lastException = null;
do {
try {
OperationResult<R> result = newExecuteWithFailover(op).tryOperation(op);
retry.success();
if(context != null)
opsTracer.onSuccess(context, op);
return result;
}
catch (OperationException e) {
if(context != null)
opsTracer.onException(context, op, e);
retry.failure(e);
throw e;
}
catch (ConnectionException e) {
lastException = e;
}
if (retry.allowRetry()) {
LOG.debug("Retry policy[" + retry.toString() + "] will allow a subsequent retry for operation [" + op.getClass() +
"] on keyspace [" + op.getKeyspace() + "] on pinned host[" + op.getPinnedHost() + "]");
}
} while (retry.allowRetry());
if(context != null && lastException != null)
opsTracer.onException(context, op, lastException);
retry.failure(lastException);
throw lastException;
} | java | @Override
public <R> OperationResult<R> executeWithFailover(Operation<CL, R> op, RetryPolicy retry)
throws ConnectionException {
//Tracing operation
OperationTracer opsTracer = config.getOperationTracer();
final AstyanaxContext context = opsTracer.getAstyanaxContext();
if(context != null) {
opsTracer.onCall(context, op);
}
retry.begin();
ConnectionException lastException = null;
do {
try {
OperationResult<R> result = newExecuteWithFailover(op).tryOperation(op);
retry.success();
if(context != null)
opsTracer.onSuccess(context, op);
return result;
}
catch (OperationException e) {
if(context != null)
opsTracer.onException(context, op, e);
retry.failure(e);
throw e;
}
catch (ConnectionException e) {
lastException = e;
}
if (retry.allowRetry()) {
LOG.debug("Retry policy[" + retry.toString() + "] will allow a subsequent retry for operation [" + op.getClass() +
"] on keyspace [" + op.getKeyspace() + "] on pinned host[" + op.getPinnedHost() + "]");
}
} while (retry.allowRetry());
if(context != null && lastException != null)
opsTracer.onException(context, op, lastException);
retry.failure(lastException);
throw lastException;
} | [
"@",
"Override",
"public",
"<",
"R",
">",
"OperationResult",
"<",
"R",
">",
"executeWithFailover",
"(",
"Operation",
"<",
"CL",
",",
"R",
">",
"op",
",",
"RetryPolicy",
"retry",
")",
"throws",
"ConnectionException",
"{",
"//Tracing operation",
"OperationTracer",... | Executes the operation using failover and retry strategy
@param op
@param retry
@return {@link OperationResult} | [
"Executes",
"the",
"operation",
"using",
"failover",
"and",
"retry",
"strategy"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java#L337-L381 | train |
Netflix/astyanax | astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/QueryGenCache.java | QueryGenCache.getBoundStatement | public BoundStatement getBoundStatement(Q query, boolean useCaching) {
PreparedStatement pStatement = getPreparedStatement(query, useCaching);
return bindValues(pStatement, query);
} | java | public BoundStatement getBoundStatement(Q query, boolean useCaching) {
PreparedStatement pStatement = getPreparedStatement(query, useCaching);
return bindValues(pStatement, query);
} | [
"public",
"BoundStatement",
"getBoundStatement",
"(",
"Q",
"query",
",",
"boolean",
"useCaching",
")",
"{",
"PreparedStatement",
"pStatement",
"=",
"getPreparedStatement",
"(",
"query",
",",
"useCaching",
")",
";",
"return",
"bindValues",
"(",
"pStatement",
",",
"... | Get the bound statement from the prepared statement
@param query
@param useCaching
@return BoundStatement | [
"Get",
"the",
"bound",
"statement",
"from",
"the",
"prepared",
"statement"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/QueryGenCache.java#L62-L66 | train |
Netflix/astyanax | astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CFRowRangeQueryGen.java | CFRowRangeQueryGen.addWhereClauseForRowRange | private Where addWhereClauseForRowRange(String keyAlias, Select select, RowRange<?> rowRange) {
Where where = null;
boolean keyIsPresent = false;
boolean tokenIsPresent = false;
if (rowRange.getStartKey() != null || rowRange.getEndKey() != null) {
keyIsPresent = true;
}
if (rowRange.getStartToken() != null || rowRange.getEndToken() != null) {
tokenIsPresent = true;
}
if (keyIsPresent && tokenIsPresent) {
throw new RuntimeException("Cannot provide both token and keys for range query");
}
if (keyIsPresent) {
if (rowRange.getStartKey() != null && rowRange.getEndKey() != null) {
where = select.where(gte(keyAlias, BIND_MARKER))
.and(lte(keyAlias, BIND_MARKER));
} else if (rowRange.getStartKey() != null) {
where = select.where(gte(keyAlias, BIND_MARKER));
} else if (rowRange.getEndKey() != null) {
where = select.where(lte(keyAlias, BIND_MARKER));
}
} else if (tokenIsPresent) {
String tokenOfKey ="token(" + keyAlias + ")";
if (rowRange.getStartToken() != null && rowRange.getEndToken() != null) {
where = select.where(gte(tokenOfKey, BIND_MARKER))
.and(lte(tokenOfKey, BIND_MARKER));
} else if (rowRange.getStartToken() != null) {
where = select.where(gte(tokenOfKey, BIND_MARKER));
} else if (rowRange.getEndToken() != null) {
where = select.where(lte(tokenOfKey, BIND_MARKER));
}
} else {
where = select.where();
}
if (rowRange.getCount() > 0) {
// TODO: fix this
//where.limit(rowRange.getCount());
}
return where;
} | java | private Where addWhereClauseForRowRange(String keyAlias, Select select, RowRange<?> rowRange) {
Where where = null;
boolean keyIsPresent = false;
boolean tokenIsPresent = false;
if (rowRange.getStartKey() != null || rowRange.getEndKey() != null) {
keyIsPresent = true;
}
if (rowRange.getStartToken() != null || rowRange.getEndToken() != null) {
tokenIsPresent = true;
}
if (keyIsPresent && tokenIsPresent) {
throw new RuntimeException("Cannot provide both token and keys for range query");
}
if (keyIsPresent) {
if (rowRange.getStartKey() != null && rowRange.getEndKey() != null) {
where = select.where(gte(keyAlias, BIND_MARKER))
.and(lte(keyAlias, BIND_MARKER));
} else if (rowRange.getStartKey() != null) {
where = select.where(gte(keyAlias, BIND_MARKER));
} else if (rowRange.getEndKey() != null) {
where = select.where(lte(keyAlias, BIND_MARKER));
}
} else if (tokenIsPresent) {
String tokenOfKey ="token(" + keyAlias + ")";
if (rowRange.getStartToken() != null && rowRange.getEndToken() != null) {
where = select.where(gte(tokenOfKey, BIND_MARKER))
.and(lte(tokenOfKey, BIND_MARKER));
} else if (rowRange.getStartToken() != null) {
where = select.where(gte(tokenOfKey, BIND_MARKER));
} else if (rowRange.getEndToken() != null) {
where = select.where(lte(tokenOfKey, BIND_MARKER));
}
} else {
where = select.where();
}
if (rowRange.getCount() > 0) {
// TODO: fix this
//where.limit(rowRange.getCount());
}
return where;
} | [
"private",
"Where",
"addWhereClauseForRowRange",
"(",
"String",
"keyAlias",
",",
"Select",
"select",
",",
"RowRange",
"<",
"?",
">",
"rowRange",
")",
"{",
"Where",
"where",
"=",
"null",
";",
"boolean",
"keyIsPresent",
"=",
"false",
";",
"boolean",
"tokenIsPres... | Private helper for constructing the where clause for row ranges
@param keyAlias
@param select
@param rowRange
@return | [
"Private",
"helper",
"for",
"constructing",
"the",
"where",
"clause",
"for",
"row",
"ranges"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CFRowRangeQueryGen.java#L110-L164 | train |
Netflix/astyanax | astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CFRowRangeQueryGen.java | CFRowRangeQueryGen.bindWhereClauseForRowRange | private void bindWhereClauseForRowRange(List<Object> values, RowRange<?> rowRange) {
boolean keyIsPresent = false;
boolean tokenIsPresent = false;
if (rowRange.getStartKey() != null || rowRange.getEndKey() != null) {
keyIsPresent = true;
}
if (rowRange.getStartToken() != null || rowRange.getEndToken() != null) {
tokenIsPresent = true;
}
if (keyIsPresent && tokenIsPresent) {
throw new RuntimeException("Cannot provide both token and keys for range query");
}
if (keyIsPresent) {
if (rowRange.getStartKey() != null) {
values.add(rowRange.getStartKey());
}
if (rowRange.getEndKey() != null) {
values.add(rowRange.getEndKey());
}
} else if (tokenIsPresent) {
BigInteger startTokenB = rowRange.getStartToken() != null ? new BigInteger(rowRange.getStartToken()) : null;
BigInteger endTokenB = rowRange.getEndToken() != null ? new BigInteger(rowRange.getEndToken()) : null;
Long startToken = startTokenB.longValue();
Long endToken = endTokenB.longValue();
if (startToken != null && endToken != null) {
if (startToken != null) {
values.add(startToken);
}
if (endToken != null) {
values.add(endToken);
}
}
if (rowRange.getCount() > 0) {
// TODO: fix this
//where.limit(rowRange.getCount());
}
return;
}
} | java | private void bindWhereClauseForRowRange(List<Object> values, RowRange<?> rowRange) {
boolean keyIsPresent = false;
boolean tokenIsPresent = false;
if (rowRange.getStartKey() != null || rowRange.getEndKey() != null) {
keyIsPresent = true;
}
if (rowRange.getStartToken() != null || rowRange.getEndToken() != null) {
tokenIsPresent = true;
}
if (keyIsPresent && tokenIsPresent) {
throw new RuntimeException("Cannot provide both token and keys for range query");
}
if (keyIsPresent) {
if (rowRange.getStartKey() != null) {
values.add(rowRange.getStartKey());
}
if (rowRange.getEndKey() != null) {
values.add(rowRange.getEndKey());
}
} else if (tokenIsPresent) {
BigInteger startTokenB = rowRange.getStartToken() != null ? new BigInteger(rowRange.getStartToken()) : null;
BigInteger endTokenB = rowRange.getEndToken() != null ? new BigInteger(rowRange.getEndToken()) : null;
Long startToken = startTokenB.longValue();
Long endToken = endTokenB.longValue();
if (startToken != null && endToken != null) {
if (startToken != null) {
values.add(startToken);
}
if (endToken != null) {
values.add(endToken);
}
}
if (rowRange.getCount() > 0) {
// TODO: fix this
//where.limit(rowRange.getCount());
}
return;
}
} | [
"private",
"void",
"bindWhereClauseForRowRange",
"(",
"List",
"<",
"Object",
">",
"values",
",",
"RowRange",
"<",
"?",
">",
"rowRange",
")",
"{",
"boolean",
"keyIsPresent",
"=",
"false",
";",
"boolean",
"tokenIsPresent",
"=",
"false",
";",
"if",
"(",
"rowRan... | Private helper for constructing the bind values for the given row range. Note that the assumption here is that
we have a previously constructed prepared statement that we can bind these values with.
@param keyAlias
@param select
@param rowRange
@return | [
"Private",
"helper",
"for",
"constructing",
"the",
"bind",
"values",
"for",
"the",
"given",
"row",
"range",
".",
"Note",
"that",
"the",
"assumption",
"here",
"is",
"that",
"we",
"have",
"a",
"previously",
"constructed",
"prepared",
"statement",
"that",
"we",
... | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cql/src/main/java/com/netflix/astyanax/cql/reads/CFRowRangeQueryGen.java#L175-L222 | train |
Netflix/astyanax | astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractExecuteWithFailoverImpl.java | AbstractExecuteWithFailoverImpl.tryOperation | @Override
public OperationResult<R> tryOperation(Operation<CL, R> operation) throws ConnectionException {
Operation<CL, R> filteredOperation = config.getOperationFilterFactory().attachFilter(operation);
while (true) {
attemptCounter++;
try {
connection = borrowConnection(filteredOperation);
startTime = System.currentTimeMillis();
OperationResult<R> result = connection.execute(filteredOperation);
result.setAttemptsCount(attemptCounter);
monitor.incOperationSuccess(getCurrentHost(), result.getLatency());
return result;
}
catch (Exception e) {
ConnectionException ce = (e instanceof ConnectionException) ? (ConnectionException) e
: new UnknownException(e);
try {
informException(ce);
monitor.incFailover(ce.getHost(), ce);
}
catch (ConnectionException ex) {
monitor.incOperationFailure(getCurrentHost(), ex);
throw ex;
}
}
finally {
releaseConnection();
}
}
} | java | @Override
public OperationResult<R> tryOperation(Operation<CL, R> operation) throws ConnectionException {
Operation<CL, R> filteredOperation = config.getOperationFilterFactory().attachFilter(operation);
while (true) {
attemptCounter++;
try {
connection = borrowConnection(filteredOperation);
startTime = System.currentTimeMillis();
OperationResult<R> result = connection.execute(filteredOperation);
result.setAttemptsCount(attemptCounter);
monitor.incOperationSuccess(getCurrentHost(), result.getLatency());
return result;
}
catch (Exception e) {
ConnectionException ce = (e instanceof ConnectionException) ? (ConnectionException) e
: new UnknownException(e);
try {
informException(ce);
monitor.incFailover(ce.getHost(), ce);
}
catch (ConnectionException ex) {
monitor.incOperationFailure(getCurrentHost(), ex);
throw ex;
}
}
finally {
releaseConnection();
}
}
} | [
"@",
"Override",
"public",
"OperationResult",
"<",
"R",
">",
"tryOperation",
"(",
"Operation",
"<",
"CL",
",",
"R",
">",
"operation",
")",
"throws",
"ConnectionException",
"{",
"Operation",
"<",
"CL",
",",
"R",
">",
"filteredOperation",
"=",
"config",
".",
... | Basic impl that repeatedly borrows a conn and tries to execute the operation while maintaining metrics for
success, conn attempts, failures and latencies for operation executions
@param operation
@return {@link OperationResult} | [
"Basic",
"impl",
"that",
"repeatedly",
"borrows",
"a",
"conn",
"and",
"tries",
"to",
"execute",
"the",
"operation",
"while",
"maintaining",
"metrics",
"for",
"success",
"conn",
"attempts",
"failures",
"and",
"latencies",
"for",
"operation",
"executions"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractExecuteWithFailoverImpl.java#L109-L140 | train |
Netflix/astyanax | astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftClusterImpl.java | ThriftClusterImpl.getVersion | @Override
public String getVersion() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractOperationImpl<String>(tracerFactory.newTracer(CassandraOperationType.GET_VERSION)) {
@Override
public String internalExecute(Client client, ConnectionContext state) throws Exception {
return client.describe_version();
}
}, config.getRetryPolicy().duplicate()).getResult();
} | java | @Override
public String getVersion() throws ConnectionException {
return connectionPool.executeWithFailover(
new AbstractOperationImpl<String>(tracerFactory.newTracer(CassandraOperationType.GET_VERSION)) {
@Override
public String internalExecute(Client client, ConnectionContext state) throws Exception {
return client.describe_version();
}
}, config.getRetryPolicy().duplicate()).getResult();
} | [
"@",
"Override",
"public",
"String",
"getVersion",
"(",
")",
"throws",
"ConnectionException",
"{",
"return",
"connectionPool",
".",
"executeWithFailover",
"(",
"new",
"AbstractOperationImpl",
"<",
"String",
">",
"(",
"tracerFactory",
".",
"newTracer",
"(",
"Cassandr... | Get the version from the cluster
@return
@throws OperationException | [
"Get",
"the",
"version",
"from",
"the",
"cluster"
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-thrift/src/main/java/com/netflix/astyanax/thrift/ThriftClusterImpl.java#L130-L139 | train |
Netflix/astyanax | astyanax-recipes/src/main/java/com/netflix/astyanax/recipes/reader/AllRowsReader.java | AllRowsReader.call | @Override
public Boolean call() throws Exception {
error.set(null);
List<Callable<Boolean>> subtasks = Lists.newArrayList();
// We are iterating the entire ring using an arbitrary number of threads
if (this.concurrencyLevel != null || startToken != null|| endToken != null) {
List<TokenRange> tokens = partitioner.splitTokenRange(
startToken == null ? partitioner.getMinToken() : startToken,
endToken == null ? partitioner.getMinToken() : endToken,
this.concurrencyLevel == null ? 1 : this.concurrencyLevel);
for (TokenRange range : tokens) {
subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
}
}
// We are iterating through each token range
else {
List<TokenRange> ranges = keyspace.describeRing(dc, rack);
for (TokenRange range : ranges) {
if (range.getStartToken().equals(range.getEndToken()))
subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
else
subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken()));
}
}
try {
// Use a local executor
if (executor == null) {
ExecutorService localExecutor = Executors
.newFixedThreadPool(subtasks.size(),
new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("AstyanaxAllRowsReader-%d")
.build());
try {
futures.addAll(startTasks(localExecutor, subtasks));
return waitForTasksToFinish();
}
finally {
localExecutor.shutdownNow();
}
}
// Use an externally provided executor
else {
futures.addAll(startTasks(executor, subtasks));
return waitForTasksToFinish();
}
}
catch (Exception e) {
error.compareAndSet(null, e);
LOG.warn("AllRowsReader terminated. " + e.getMessage(), e);
cancel();
throw error.get();
}
} | java | @Override
public Boolean call() throws Exception {
error.set(null);
List<Callable<Boolean>> subtasks = Lists.newArrayList();
// We are iterating the entire ring using an arbitrary number of threads
if (this.concurrencyLevel != null || startToken != null|| endToken != null) {
List<TokenRange> tokens = partitioner.splitTokenRange(
startToken == null ? partitioner.getMinToken() : startToken,
endToken == null ? partitioner.getMinToken() : endToken,
this.concurrencyLevel == null ? 1 : this.concurrencyLevel);
for (TokenRange range : tokens) {
subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
}
}
// We are iterating through each token range
else {
List<TokenRange> ranges = keyspace.describeRing(dc, rack);
for (TokenRange range : ranges) {
if (range.getStartToken().equals(range.getEndToken()))
subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
else
subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken()));
}
}
try {
// Use a local executor
if (executor == null) {
ExecutorService localExecutor = Executors
.newFixedThreadPool(subtasks.size(),
new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("AstyanaxAllRowsReader-%d")
.build());
try {
futures.addAll(startTasks(localExecutor, subtasks));
return waitForTasksToFinish();
}
finally {
localExecutor.shutdownNow();
}
}
// Use an externally provided executor
else {
futures.addAll(startTasks(executor, subtasks));
return waitForTasksToFinish();
}
}
catch (Exception e) {
error.compareAndSet(null, e);
LOG.warn("AllRowsReader terminated. " + e.getMessage(), e);
cancel();
throw error.get();
}
} | [
"@",
"Override",
"public",
"Boolean",
"call",
"(",
")",
"throws",
"Exception",
"{",
"error",
".",
"set",
"(",
"null",
")",
";",
"List",
"<",
"Callable",
"<",
"Boolean",
">",
">",
"subtasks",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"// We are ... | Main execution block for the all rows query. | [
"Main",
"execution",
"block",
"for",
"the",
"all",
"rows",
"query",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-recipes/src/main/java/com/netflix/astyanax/recipes/reader/AllRowsReader.java#L535-L593 | train |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/JaxbSerializer.java | JaxbSerializer.createStreamReader | protected XMLStreamReader createStreamReader(InputStream input) throws XMLStreamException {
if (inputFactory == null) {
inputFactory = XMLInputFactory.newInstance();
}
return inputFactory.createXMLStreamReader(input);
} | java | protected XMLStreamReader createStreamReader(InputStream input) throws XMLStreamException {
if (inputFactory == null) {
inputFactory = XMLInputFactory.newInstance();
}
return inputFactory.createXMLStreamReader(input);
} | [
"protected",
"XMLStreamReader",
"createStreamReader",
"(",
"InputStream",
"input",
")",
"throws",
"XMLStreamException",
"{",
"if",
"(",
"inputFactory",
"==",
"null",
")",
"{",
"inputFactory",
"=",
"XMLInputFactory",
".",
"newInstance",
"(",
")",
";",
"}",
"return"... | Get a new XML stream reader.
@param input
the underlying InputStream to read from.
@return a new {@link XmlStreamReader} which reads from the specified
InputStream. The reader can read anything written by
{@link #createStreamWriter(OutputStream)}.
@throws XMLStreamException | [
"Get",
"a",
"new",
"XML",
"stream",
"reader",
"."
] | bcc3fd26e2dda05a923751aa32b139f6209fecdf | https://github.com/Netflix/astyanax/blob/bcc3fd26e2dda05a923751aa32b139f6209fecdf/astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/JaxbSerializer.java#L171-L176 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java | ThriftCatalog.getThriftType | public ThriftType getThriftType(Type javaType)
throws IllegalArgumentException
{
ThriftType thriftType = getThriftTypeFromCache(javaType);
if (thriftType == null) {
thriftType = buildThriftType(javaType);
}
return thriftType;
} | java | public ThriftType getThriftType(Type javaType)
throws IllegalArgumentException
{
ThriftType thriftType = getThriftTypeFromCache(javaType);
if (thriftType == null) {
thriftType = buildThriftType(javaType);
}
return thriftType;
} | [
"public",
"ThriftType",
"getThriftType",
"(",
"Type",
"javaType",
")",
"throws",
"IllegalArgumentException",
"{",
"ThriftType",
"thriftType",
"=",
"getThriftTypeFromCache",
"(",
"javaType",
")",
";",
"if",
"(",
"thriftType",
"==",
"null",
")",
"{",
"thriftType",
"... | Gets the ThriftType for the specified Java type. The native Thrift type for the Java type will
be inferred from the Java type, and if necessary type coercions will be applied.
@return the ThriftType for the specified java type; never null
@throws IllegalArgumentException if the Java Type can not be coerced to a ThriftType | [
"Gets",
"the",
"ThriftType",
"for",
"the",
"specified",
"Java",
"type",
".",
"The",
"native",
"Thrift",
"type",
"for",
"the",
"Java",
"type",
"will",
"be",
"inferred",
"from",
"the",
"Java",
"type",
"and",
"if",
"necessary",
"type",
"coercions",
"will",
"b... | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java#L229-L237 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java | ThriftCatalog.getThriftEnumMetadata | public <T extends Enum<T>> ThriftEnumMetadata<?> getThriftEnumMetadata(Class<?> enumClass)
{
ThriftEnumMetadata<?> enumMetadata = enums.get(enumClass);
if (enumMetadata == null) {
enumMetadata = new ThriftEnumMetadataBuilder<>((Class<T>) enumClass).build();
ThriftEnumMetadata<?> current = enums.putIfAbsent(enumClass, enumMetadata);
if (current != null) {
enumMetadata = current;
}
}
return enumMetadata;
} | java | public <T extends Enum<T>> ThriftEnumMetadata<?> getThriftEnumMetadata(Class<?> enumClass)
{
ThriftEnumMetadata<?> enumMetadata = enums.get(enumClass);
if (enumMetadata == null) {
enumMetadata = new ThriftEnumMetadataBuilder<>((Class<T>) enumClass).build();
ThriftEnumMetadata<?> current = enums.putIfAbsent(enumClass, enumMetadata);
if (current != null) {
enumMetadata = current;
}
}
return enumMetadata;
} | [
"public",
"<",
"T",
"extends",
"Enum",
"<",
"T",
">",
">",
"ThriftEnumMetadata",
"<",
"?",
">",
"getThriftEnumMetadata",
"(",
"Class",
"<",
"?",
">",
"enumClass",
")",
"{",
"ThriftEnumMetadata",
"<",
"?",
">",
"enumMetadata",
"=",
"enums",
".",
"get",
"(... | Gets the ThriftEnumMetadata for the specified enum class. If the enum class contains a method
annotated with @ThriftEnumValue, the value of this method will be used for the encoded thrift
value; otherwise the Enum.ordinal() method will be used. | [
"Gets",
"the",
"ThriftEnumMetadata",
"for",
"the",
"specified",
"enum",
"class",
".",
"If",
"the",
"enum",
"class",
"contains",
"a",
"method",
"annotated",
"with"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java#L539-L551 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java | ThriftCatalog.getThriftStructMetadata | public <T> ThriftStructMetadata getThriftStructMetadata(Type structType)
{
ThriftStructMetadata structMetadata = structs.get(structType);
Class<?> structClass = TypeToken.of(structType).getRawType();
if (structMetadata == null) {
if (structClass.isAnnotationPresent(ThriftStruct.class)) {
structMetadata = extractThriftStructMetadata(structType);
}
else if (structClass.isAnnotationPresent(ThriftUnion.class)) {
structMetadata = extractThriftUnionMetadata(structType);
}
else {
throw new IllegalStateException("getThriftStructMetadata called on a class that has no @ThriftStruct or @ThriftUnion annotation");
}
ThriftStructMetadata current = structs.putIfAbsent(structType, structMetadata);
if (current != null) {
structMetadata = current;
}
}
return structMetadata;
} | java | public <T> ThriftStructMetadata getThriftStructMetadata(Type structType)
{
ThriftStructMetadata structMetadata = structs.get(structType);
Class<?> structClass = TypeToken.of(structType).getRawType();
if (structMetadata == null) {
if (structClass.isAnnotationPresent(ThriftStruct.class)) {
structMetadata = extractThriftStructMetadata(structType);
}
else if (structClass.isAnnotationPresent(ThriftUnion.class)) {
structMetadata = extractThriftUnionMetadata(structType);
}
else {
throw new IllegalStateException("getThriftStructMetadata called on a class that has no @ThriftStruct or @ThriftUnion annotation");
}
ThriftStructMetadata current = structs.putIfAbsent(structType, structMetadata);
if (current != null) {
structMetadata = current;
}
}
return structMetadata;
} | [
"public",
"<",
"T",
">",
"ThriftStructMetadata",
"getThriftStructMetadata",
"(",
"Type",
"structType",
")",
"{",
"ThriftStructMetadata",
"structMetadata",
"=",
"structs",
".",
"get",
"(",
"structType",
")",
";",
"Class",
"<",
"?",
">",
"structClass",
"=",
"TypeT... | Gets the ThriftStructMetadata for the specified struct class. The struct class must be
annotated with @ThriftStruct or @ThriftUnion. | [
"Gets",
"the",
"ThriftStructMetadata",
"for",
"the",
"specified",
"struct",
"class",
".",
"The",
"struct",
"class",
"must",
"be",
"annotated",
"with"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/ThriftCatalog.java#L557-L578 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.declareTypeField | private FieldDefinition declareTypeField()
{
FieldDefinition typeField = new FieldDefinition(a(PRIVATE, FINAL), "type", type(ThriftType.class));
classDefinition.addField(typeField);
// add constructor parameter to initialize this field
parameters.add(typeField, ThriftType.struct(metadata));
return typeField;
} | java | private FieldDefinition declareTypeField()
{
FieldDefinition typeField = new FieldDefinition(a(PRIVATE, FINAL), "type", type(ThriftType.class));
classDefinition.addField(typeField);
// add constructor parameter to initialize this field
parameters.add(typeField, ThriftType.struct(metadata));
return typeField;
} | [
"private",
"FieldDefinition",
"declareTypeField",
"(",
")",
"{",
"FieldDefinition",
"typeField",
"=",
"new",
"FieldDefinition",
"(",
"a",
"(",
"PRIVATE",
",",
"FINAL",
")",
",",
"\"type\"",
",",
"type",
"(",
"ThriftType",
".",
"class",
")",
")",
";",
"classD... | Declares the private ThriftType field type. | [
"Declares",
"the",
"private",
"ThriftType",
"field",
"type",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L200-L209 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.declareCodecFields | private Map<Short, FieldDefinition> declareCodecFields()
{
Map<Short, FieldDefinition> codecFields = new TreeMap<>();
for (ThriftFieldMetadata fieldMetadata : metadata.getFields()) {
if (needsCodec(fieldMetadata)) {
ThriftCodec<?> codec = codecManager.getCodec(fieldMetadata.getThriftType());
String fieldName = fieldMetadata.getName() + "Codec";
FieldDefinition codecField = new FieldDefinition(a(PRIVATE, FINAL), fieldName, type(codec.getClass()));
classDefinition.addField(codecField);
codecFields.put(fieldMetadata.getId(), codecField);
parameters.add(codecField, codec);
}
}
return codecFields;
} | java | private Map<Short, FieldDefinition> declareCodecFields()
{
Map<Short, FieldDefinition> codecFields = new TreeMap<>();
for (ThriftFieldMetadata fieldMetadata : metadata.getFields()) {
if (needsCodec(fieldMetadata)) {
ThriftCodec<?> codec = codecManager.getCodec(fieldMetadata.getThriftType());
String fieldName = fieldMetadata.getName() + "Codec";
FieldDefinition codecField = new FieldDefinition(a(PRIVATE, FINAL), fieldName, type(codec.getClass()));
classDefinition.addField(codecField);
codecFields.put(fieldMetadata.getId(), codecField);
parameters.add(codecField, codec);
}
}
return codecFields;
} | [
"private",
"Map",
"<",
"Short",
",",
"FieldDefinition",
">",
"declareCodecFields",
"(",
")",
"{",
"Map",
"<",
"Short",
",",
"FieldDefinition",
">",
"codecFields",
"=",
"new",
"TreeMap",
"<>",
"(",
")",
";",
"for",
"(",
"ThriftFieldMetadata",
"fieldMetadata",
... | Declares a field for each delegate codec
@return a map from field id to the codec for the field | [
"Declares",
"a",
"field",
"for",
"each",
"delegate",
"codec"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L216-L233 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineConstructor | private void defineConstructor()
{
//
// declare the constructor
MethodDefinition constructor = new MethodDefinition(
a(PUBLIC),
"<init>",
type(void.class),
parameters.getParameters()
);
// invoke super (Object) constructor
constructor.loadThis().invokeConstructor(type(Object.class));
// this.foo = foo;
for (FieldDefinition fieldDefinition : parameters.getFields()) {
constructor.loadThis()
.loadVariable(fieldDefinition.getName())
.putField(codecType, fieldDefinition);
}
// return; (implicit)
constructor.ret();
classDefinition.addMethod(constructor);
} | java | private void defineConstructor()
{
//
// declare the constructor
MethodDefinition constructor = new MethodDefinition(
a(PUBLIC),
"<init>",
type(void.class),
parameters.getParameters()
);
// invoke super (Object) constructor
constructor.loadThis().invokeConstructor(type(Object.class));
// this.foo = foo;
for (FieldDefinition fieldDefinition : parameters.getFields()) {
constructor.loadThis()
.loadVariable(fieldDefinition.getName())
.putField(codecType, fieldDefinition);
}
// return; (implicit)
constructor.ret();
classDefinition.addMethod(constructor);
} | [
"private",
"void",
"defineConstructor",
"(",
")",
"{",
"//",
"// declare the constructor",
"MethodDefinition",
"constructor",
"=",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
")",
",",
"\"<init>\"",
",",
"type",
"(",
"void",
".",
"class",
")",
",",
"pa... | Defines the constructor with a parameter for the ThriftType and the delegate codecs. The
constructor simply assigns these parameters to the class fields. | [
"Defines",
"the",
"constructor",
"with",
"a",
"parameter",
"for",
"the",
"ThriftType",
"and",
"the",
"delegate",
"codecs",
".",
"The",
"constructor",
"simply",
"assigns",
"these",
"parameters",
"to",
"the",
"class",
"fields",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L239-L264 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineGetTypeMethod | private void defineGetTypeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC), "getType", type(ThriftType.class))
.loadThis()
.getField(codecType, typeField)
.retObject()
);
} | java | private void defineGetTypeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC), "getType", type(ThriftType.class))
.loadThis()
.getField(codecType, typeField)
.retObject()
);
} | [
"private",
"void",
"defineGetTypeMethod",
"(",
")",
"{",
"classDefinition",
".",
"addMethod",
"(",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
")",
",",
"\"getType\"",
",",
"type",
"(",
"ThriftType",
".",
"class",
")",
")",
".",
"loadThis",
"(",
")... | Defines the getType method which simply returns the value of the type field. | [
"Defines",
"the",
"getType",
"method",
"which",
"simply",
"returns",
"the",
"value",
"of",
"the",
"type",
"field",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L269-L277 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineReadStructMethod | private void defineReadStructMethod()
{
MethodDefinition read = new MethodDefinition(
a(PUBLIC),
"read",
structType,
arg("protocol", TProtocol.class)
).addException(Exception.class);
// TProtocolReader reader = new TProtocolReader(protocol);
read.addLocalVariable(type(TProtocolReader.class), "reader");
read.newObject(TProtocolReader.class);
read.dup();
read.loadVariable("protocol");
read.invokeConstructor(type(TProtocolReader.class), type(TProtocol.class));
read.storeVariable("reader");
// read all of the data in to local variables
Map<Short, LocalVariableDefinition> structData = readFieldValues(read);
// build the struct
LocalVariableDefinition result = buildStruct(read, structData);
// push instance on stack, and return it
read.loadVariable(result).retObject();
classDefinition.addMethod(read);
} | java | private void defineReadStructMethod()
{
MethodDefinition read = new MethodDefinition(
a(PUBLIC),
"read",
structType,
arg("protocol", TProtocol.class)
).addException(Exception.class);
// TProtocolReader reader = new TProtocolReader(protocol);
read.addLocalVariable(type(TProtocolReader.class), "reader");
read.newObject(TProtocolReader.class);
read.dup();
read.loadVariable("protocol");
read.invokeConstructor(type(TProtocolReader.class), type(TProtocol.class));
read.storeVariable("reader");
// read all of the data in to local variables
Map<Short, LocalVariableDefinition> structData = readFieldValues(read);
// build the struct
LocalVariableDefinition result = buildStruct(read, structData);
// push instance on stack, and return it
read.loadVariable(result).retObject();
classDefinition.addMethod(read);
} | [
"private",
"void",
"defineReadStructMethod",
"(",
")",
"{",
"MethodDefinition",
"read",
"=",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
")",
",",
"\"read\"",
",",
"structType",
",",
"arg",
"(",
"\"protocol\"",
",",
"TProtocol",
".",
"class",
")",
")... | Defines the read method for a struct. | [
"Defines",
"the",
"read",
"method",
"for",
"a",
"struct",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L282-L309 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.injectStructFields | private void injectStructFields(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
injectField(read, field, instance, structData.get(field.getId()));
}
} | java | private void injectStructFields(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
injectField(read, field, instance, structData.get(field.getId()));
}
} | [
"private",
"void",
"injectStructFields",
"(",
"MethodDefinition",
"read",
",",
"LocalVariableDefinition",
"instance",
",",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"structData",
")",
"{",
"for",
"(",
"ThriftFieldMetadata",
"field",
":",
"metadata",
... | Defines the code to inject data into the struct public fields. | [
"Defines",
"the",
"code",
"to",
"inject",
"data",
"into",
"the",
"struct",
"public",
"fields",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L452-L457 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.injectStructMethods | private void injectStructMethods(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftMethodInjection methodInjection : metadata.getMethodInjections()) {
injectMethod(read, methodInjection, instance, structData);
}
} | java | private void injectStructMethods(MethodDefinition read, LocalVariableDefinition instance, Map<Short, LocalVariableDefinition> structData)
{
for (ThriftMethodInjection methodInjection : metadata.getMethodInjections()) {
injectMethod(read, methodInjection, instance, structData);
}
} | [
"private",
"void",
"injectStructMethods",
"(",
"MethodDefinition",
"read",
",",
"LocalVariableDefinition",
"instance",
",",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"structData",
")",
"{",
"for",
"(",
"ThriftMethodInjection",
"methodInjection",
":",
"... | Defines the code to inject data into the struct methods. | [
"Defines",
"the",
"code",
"to",
"inject",
"data",
"into",
"the",
"struct",
"methods",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L462-L467 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineReadUnionMethod | private void defineReadUnionMethod()
{
MethodDefinition read = new MethodDefinition(
a(PUBLIC),
"read",
structType,
arg("protocol", TProtocol.class)
).addException(Exception.class);
// TProtocolReader reader = new TProtocolReader(protocol);
read.addLocalVariable(type(TProtocolReader.class), "reader");
read.newObject(TProtocolReader.class);
read.dup();
read.loadVariable("protocol");
read.invokeConstructor(type(TProtocolReader.class), type(TProtocol.class));
read.storeVariable("reader");
// field id field.
read.addInitializedLocalVariable(type(short.class), "fieldId");
// read all of the data in to local variables
Map<Short, LocalVariableDefinition> unionData = readSingleFieldValue(read);
// build the struct
LocalVariableDefinition result = buildUnion(read, unionData);
// push instance on stack, and return it
read.loadVariable(result).retObject();
classDefinition.addMethod(read);
} | java | private void defineReadUnionMethod()
{
MethodDefinition read = new MethodDefinition(
a(PUBLIC),
"read",
structType,
arg("protocol", TProtocol.class)
).addException(Exception.class);
// TProtocolReader reader = new TProtocolReader(protocol);
read.addLocalVariable(type(TProtocolReader.class), "reader");
read.newObject(TProtocolReader.class);
read.dup();
read.loadVariable("protocol");
read.invokeConstructor(type(TProtocolReader.class), type(TProtocol.class));
read.storeVariable("reader");
// field id field.
read.addInitializedLocalVariable(type(short.class), "fieldId");
// read all of the data in to local variables
Map<Short, LocalVariableDefinition> unionData = readSingleFieldValue(read);
// build the struct
LocalVariableDefinition result = buildUnion(read, unionData);
// push instance on stack, and return it
read.loadVariable(result).retObject();
classDefinition.addMethod(read);
} | [
"private",
"void",
"defineReadUnionMethod",
"(",
")",
"{",
"MethodDefinition",
"read",
"=",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
")",
",",
"\"read\"",
",",
"structType",
",",
"arg",
"(",
"\"protocol\"",
",",
"TProtocol",
".",
"class",
")",
")"... | Defines the read method for an union. | [
"Defines",
"the",
"read",
"method",
"for",
"an",
"union",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L472-L502 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.readSingleFieldValue | private Map<Short, LocalVariableDefinition> readSingleFieldValue(MethodDefinition read)
{
LocalVariableDefinition protocol = read.getLocalVariable("reader");
// declare and init local variables here
Map<Short, LocalVariableDefinition> unionData = new TreeMap<>();
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
LocalVariableDefinition variable = read.addInitializedLocalVariable(
toParameterizedType(field.getThriftType()),
"f_" + field.getName()
);
unionData.put(field.getId(), variable);
}
// protocol.readStructBegin();
read.loadVariable(protocol).invokeVirtual(
TProtocolReader.class,
"readStructBegin",
void.class
);
// while (protocol.nextField())
read.visitLabel("while-begin");
read.loadVariable(protocol).invokeVirtual(TProtocolReader.class, "nextField", boolean.class);
read.ifZeroGoto("while-end");
// fieldId = protocol.getFieldId()
read.loadVariable(protocol).invokeVirtual(TProtocolReader.class, "getFieldId", short.class);
read.storeVariable("fieldId");
// switch (fieldId)
read.loadVariable("fieldId");
List<CaseStatement> cases = new ArrayList<>();
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
cases.add(caseStatement(field.getId(), field.getName() + "-field"));
}
read.switchStatement("default", cases);
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
// case field.id:
read.visitLabel(field.getName() + "-field");
// push protocol
read.loadVariable(protocol);
// push ThriftTypeCodec for this field
FieldDefinition codecField = codecFields.get(field.getId());
if (codecField != null) {
read.loadThis().getField(codecType, codecField);
}
// read value
Method readMethod = getReadMethod(field.getThriftType());
if (readMethod == null) {
throw new IllegalArgumentException("Unsupported field type " + field.getThriftType().getProtocolType());
}
read.invokeVirtual(readMethod);
// todo this cast should be based on readMethod return type and fieldType (or coercion type)
// add cast if necessary
if (needsCastAfterRead(field, readMethod)) {
read.checkCast(toParameterizedType(field.getThriftType()));
}
// coerce the type
if (field.getCoercion().isPresent()) {
read.invokeStatic(field.getCoercion().get().getFromThrift());
}
// store protocol value
read.storeVariable(unionData.get(field.getId()));
// go back to top of loop
read.gotoLabel("while-begin");
}
// default case
read.visitLabel("default")
.loadVariable(protocol)
.invokeVirtual(TProtocolReader.class, "skipFieldData", void.class)
.gotoLabel("while-begin");
// end of while loop
read.visitLabel("while-end");
// protocol.readStructEnd();
read.loadVariable(protocol)
.invokeVirtual(TProtocolReader.class, "readStructEnd", void.class);
return unionData;
} | java | private Map<Short, LocalVariableDefinition> readSingleFieldValue(MethodDefinition read)
{
LocalVariableDefinition protocol = read.getLocalVariable("reader");
// declare and init local variables here
Map<Short, LocalVariableDefinition> unionData = new TreeMap<>();
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
LocalVariableDefinition variable = read.addInitializedLocalVariable(
toParameterizedType(field.getThriftType()),
"f_" + field.getName()
);
unionData.put(field.getId(), variable);
}
// protocol.readStructBegin();
read.loadVariable(protocol).invokeVirtual(
TProtocolReader.class,
"readStructBegin",
void.class
);
// while (protocol.nextField())
read.visitLabel("while-begin");
read.loadVariable(protocol).invokeVirtual(TProtocolReader.class, "nextField", boolean.class);
read.ifZeroGoto("while-end");
// fieldId = protocol.getFieldId()
read.loadVariable(protocol).invokeVirtual(TProtocolReader.class, "getFieldId", short.class);
read.storeVariable("fieldId");
// switch (fieldId)
read.loadVariable("fieldId");
List<CaseStatement> cases = new ArrayList<>();
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
cases.add(caseStatement(field.getId(), field.getName() + "-field"));
}
read.switchStatement("default", cases);
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
// case field.id:
read.visitLabel(field.getName() + "-field");
// push protocol
read.loadVariable(protocol);
// push ThriftTypeCodec for this field
FieldDefinition codecField = codecFields.get(field.getId());
if (codecField != null) {
read.loadThis().getField(codecType, codecField);
}
// read value
Method readMethod = getReadMethod(field.getThriftType());
if (readMethod == null) {
throw new IllegalArgumentException("Unsupported field type " + field.getThriftType().getProtocolType());
}
read.invokeVirtual(readMethod);
// todo this cast should be based on readMethod return type and fieldType (or coercion type)
// add cast if necessary
if (needsCastAfterRead(field, readMethod)) {
read.checkCast(toParameterizedType(field.getThriftType()));
}
// coerce the type
if (field.getCoercion().isPresent()) {
read.invokeStatic(field.getCoercion().get().getFromThrift());
}
// store protocol value
read.storeVariable(unionData.get(field.getId()));
// go back to top of loop
read.gotoLabel("while-begin");
}
// default case
read.visitLabel("default")
.loadVariable(protocol)
.invokeVirtual(TProtocolReader.class, "skipFieldData", void.class)
.gotoLabel("while-begin");
// end of while loop
read.visitLabel("while-end");
// protocol.readStructEnd();
read.loadVariable(protocol)
.invokeVirtual(TProtocolReader.class, "readStructEnd", void.class);
return unionData;
} | [
"private",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"readSingleFieldValue",
"(",
"MethodDefinition",
"read",
")",
"{",
"LocalVariableDefinition",
"protocol",
"=",
"read",
".",
"getLocalVariable",
"(",
"\"reader\"",
")",
";",
"// declare and init local v... | Defines the code to read all of the data from the protocol into local variables. | [
"Defines",
"the",
"code",
"to",
"read",
"all",
"of",
"the",
"data",
"from",
"the",
"protocol",
"into",
"local",
"variables",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L507-L598 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.invokeFactoryMethod | private void invokeFactoryMethod(MethodDefinition read, Map<Short, LocalVariableDefinition> structData, LocalVariableDefinition instance)
{
if (metadata.getBuilderMethod().isPresent()) {
ThriftMethodInjection builderMethod = metadata.getBuilderMethod().get();
read.loadVariable(instance);
// push parameters on stack
for (ThriftParameterInjection parameter : builderMethod.getParameters()) {
read.loadVariable(structData.get(parameter.getId()));
}
// invoke the method
read.invokeVirtual(builderMethod.getMethod())
.storeVariable(instance);
}
} | java | private void invokeFactoryMethod(MethodDefinition read, Map<Short, LocalVariableDefinition> structData, LocalVariableDefinition instance)
{
if (metadata.getBuilderMethod().isPresent()) {
ThriftMethodInjection builderMethod = metadata.getBuilderMethod().get();
read.loadVariable(instance);
// push parameters on stack
for (ThriftParameterInjection parameter : builderMethod.getParameters()) {
read.loadVariable(structData.get(parameter.getId()));
}
// invoke the method
read.invokeVirtual(builderMethod.getMethod())
.storeVariable(instance);
}
} | [
"private",
"void",
"invokeFactoryMethod",
"(",
"MethodDefinition",
"read",
",",
"Map",
"<",
"Short",
",",
"LocalVariableDefinition",
">",
"structData",
",",
"LocalVariableDefinition",
"instance",
")",
"{",
"if",
"(",
"metadata",
".",
"getBuilderMethod",
"(",
")",
... | Defines the code that calls the builder factory method. | [
"Defines",
"the",
"code",
"that",
"calls",
"the",
"builder",
"factory",
"method",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L769-L784 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineReadBridgeMethod | private void defineReadBridgeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC, BRIDGE, SYNTHETIC), "read", type(Object.class), arg("protocol", TProtocol.class))
.addException(Exception.class)
.loadThis()
.loadVariable("protocol")
.invokeVirtual(codecType, "read", structType, type(TProtocol.class))
.retObject()
);
} | java | private void defineReadBridgeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC, BRIDGE, SYNTHETIC), "read", type(Object.class), arg("protocol", TProtocol.class))
.addException(Exception.class)
.loadThis()
.loadVariable("protocol")
.invokeVirtual(codecType, "read", structType, type(TProtocol.class))
.retObject()
);
} | [
"private",
"void",
"defineReadBridgeMethod",
"(",
")",
"{",
"classDefinition",
".",
"addMethod",
"(",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
",",
"BRIDGE",
",",
"SYNTHETIC",
")",
",",
"\"read\"",
",",
"type",
"(",
"Object",
".",
"class",
")",
... | Defines the generics bridge method with untyped args to the type specific read method. | [
"Defines",
"the",
"generics",
"bridge",
"method",
"with",
"untyped",
"args",
"to",
"the",
"type",
"specific",
"read",
"method",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L1005-L1015 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java | ThriftCodecByteCodeGenerator.defineWriteBridgeMethod | private void defineWriteBridgeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC, BRIDGE, SYNTHETIC), "write", null, arg("struct", Object.class), arg("protocol", TProtocol.class))
.addException(Exception.class)
.loadThis()
.loadVariable("struct", structType)
.loadVariable("protocol")
.invokeVirtual(
codecType,
"write",
type(void.class),
structType,
type(TProtocol.class)
)
.ret()
);
} | java | private void defineWriteBridgeMethod()
{
classDefinition.addMethod(
new MethodDefinition(a(PUBLIC, BRIDGE, SYNTHETIC), "write", null, arg("struct", Object.class), arg("protocol", TProtocol.class))
.addException(Exception.class)
.loadThis()
.loadVariable("struct", structType)
.loadVariable("protocol")
.invokeVirtual(
codecType,
"write",
type(void.class),
structType,
type(TProtocol.class)
)
.ret()
);
} | [
"private",
"void",
"defineWriteBridgeMethod",
"(",
")",
"{",
"classDefinition",
".",
"addMethod",
"(",
"new",
"MethodDefinition",
"(",
"a",
"(",
"PUBLIC",
",",
"BRIDGE",
",",
"SYNTHETIC",
")",
",",
"\"write\"",
",",
"null",
",",
"arg",
"(",
"\"struct\"",
","... | Defines the generics bridge method with untyped args to the type specific write method. | [
"Defines",
"the",
"generics",
"bridge",
"method",
"with",
"untyped",
"args",
"to",
"the",
"type",
"specific",
"write",
"method",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/compiler/ThriftCodecByteCodeGenerator.java#L1020-L1037 | train |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java | ThriftServerModule.bindFrameCodecFactory | public static ScopedBindingBuilder bindFrameCodecFactory(Binder binder, String key, Class<? extends ThriftFrameCodecFactory> frameCodecFactoryClass)
{
return newMapBinder(binder, String.class, ThriftFrameCodecFactory.class).addBinding(key).to(frameCodecFactoryClass);
} | java | public static ScopedBindingBuilder bindFrameCodecFactory(Binder binder, String key, Class<? extends ThriftFrameCodecFactory> frameCodecFactoryClass)
{
return newMapBinder(binder, String.class, ThriftFrameCodecFactory.class).addBinding(key).to(frameCodecFactoryClass);
} | [
"public",
"static",
"ScopedBindingBuilder",
"bindFrameCodecFactory",
"(",
"Binder",
"binder",
",",
"String",
"key",
",",
"Class",
"<",
"?",
"extends",
"ThriftFrameCodecFactory",
">",
"frameCodecFactoryClass",
")",
"{",
"return",
"newMapBinder",
"(",
"binder",
",",
"... | helpers for binding frame codec factories | [
"helpers",
"for",
"binding",
"frame",
"codec",
"factories"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java#L91-L94 | train |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java | ThriftServerModule.bindProtocolFactory | public static ScopedBindingBuilder bindProtocolFactory(Binder binder, String key, Class<? extends TDuplexProtocolFactory> protocolFactoryClass)
{
return newMapBinder(binder, String.class, TDuplexProtocolFactory.class).addBinding(key).to(protocolFactoryClass);
} | java | public static ScopedBindingBuilder bindProtocolFactory(Binder binder, String key, Class<? extends TDuplexProtocolFactory> protocolFactoryClass)
{
return newMapBinder(binder, String.class, TDuplexProtocolFactory.class).addBinding(key).to(protocolFactoryClass);
} | [
"public",
"static",
"ScopedBindingBuilder",
"bindProtocolFactory",
"(",
"Binder",
"binder",
",",
"String",
"key",
",",
"Class",
"<",
"?",
"extends",
"TDuplexProtocolFactory",
">",
"protocolFactoryClass",
")",
"{",
"return",
"newMapBinder",
"(",
"binder",
",",
"Strin... | helpers for binding protocol factories | [
"helpers",
"for",
"binding",
"protocol",
"factories"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java#L103-L106 | train |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java | ThriftServerModule.bindWorkerExecutor | public static ScopedBindingBuilder bindWorkerExecutor(Binder binder, String key, Class<? extends ExecutorService> executorServiceClass)
{
return workerExecutorBinder(binder).addBinding(key).to(executorServiceClass);
} | java | public static ScopedBindingBuilder bindWorkerExecutor(Binder binder, String key, Class<? extends ExecutorService> executorServiceClass)
{
return workerExecutorBinder(binder).addBinding(key).to(executorServiceClass);
} | [
"public",
"static",
"ScopedBindingBuilder",
"bindWorkerExecutor",
"(",
"Binder",
"binder",
",",
"String",
"key",
",",
"Class",
"<",
"?",
"extends",
"ExecutorService",
">",
"executorServiceClass",
")",
"{",
"return",
"workerExecutorBinder",
"(",
"binder",
")",
".",
... | Helpers for binding worker executors | [
"Helpers",
"for",
"binding",
"worker",
"executors"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/guice/ThriftServerModule.java#L115-L118 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/ReflectionHelper.java | ReflectionHelper.findAnnotatedMethods | public static Collection<Method> findAnnotatedMethods(Class<?> type, Class<? extends Annotation> annotation)
{
List<Method> result = new ArrayList<>();
// gather all publicly available methods
// this returns everything, even if it's declared in a parent
for (Method method : type.getMethods()) {
// skip methods that are used internally by the vm for implementing covariance, etc
if (method.isSynthetic() || method.isBridge() || isStatic(method.getModifiers())) {
continue;
}
// look for annotations recursively in super-classes or interfaces
Method managedMethod = findAnnotatedMethod(
type,
annotation,
method.getName(),
method.getParameterTypes());
if (managedMethod != null) {
result.add(managedMethod);
}
}
return result;
} | java | public static Collection<Method> findAnnotatedMethods(Class<?> type, Class<? extends Annotation> annotation)
{
List<Method> result = new ArrayList<>();
// gather all publicly available methods
// this returns everything, even if it's declared in a parent
for (Method method : type.getMethods()) {
// skip methods that are used internally by the vm for implementing covariance, etc
if (method.isSynthetic() || method.isBridge() || isStatic(method.getModifiers())) {
continue;
}
// look for annotations recursively in super-classes or interfaces
Method managedMethod = findAnnotatedMethod(
type,
annotation,
method.getName(),
method.getParameterTypes());
if (managedMethod != null) {
result.add(managedMethod);
}
}
return result;
} | [
"public",
"static",
"Collection",
"<",
"Method",
">",
"findAnnotatedMethods",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotation",
")",
"{",
"List",
"<",
"Method",
">",
"result",
"=",
"new",
"ArrayList",
... | Find methods that are tagged with a given annotation somewhere in the hierarchy | [
"Find",
"methods",
"that",
"are",
"tagged",
"with",
"a",
"given",
"annotation",
"somewhere",
"in",
"the",
"hierarchy"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/ReflectionHelper.java#L162-L186 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/builtin/VoidThriftCodec.java | VoidThriftCodec.read | @Override
public Void read(TProtocol protocol)
throws Exception
{
Preconditions.checkNotNull(protocol, "protocol is null");
return null;
} | java | @Override
public Void read(TProtocol protocol)
throws Exception
{
Preconditions.checkNotNull(protocol, "protocol is null");
return null;
} | [
"@",
"Override",
"public",
"Void",
"read",
"(",
"TProtocol",
"protocol",
")",
"throws",
"Exception",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"protocol",
",",
"\"protocol is null\"",
")",
";",
"return",
"null",
";",
"}"
] | Always returns null without reading anything from the stream. | [
"Always",
"returns",
"null",
"without",
"reading",
"anything",
"from",
"the",
"stream",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/builtin/VoidThriftCodec.java#L40-L46 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/internal/builtin/VoidThriftCodec.java | VoidThriftCodec.write | @Override
public void write(Void value, TProtocol protocol)
throws Exception
{
Preconditions.checkNotNull(protocol, "protocol is null");
} | java | @Override
public void write(Void value, TProtocol protocol)
throws Exception
{
Preconditions.checkNotNull(protocol, "protocol is null");
} | [
"@",
"Override",
"public",
"void",
"write",
"(",
"Void",
"value",
",",
"TProtocol",
"protocol",
")",
"throws",
"Exception",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"protocol",
",",
"\"protocol is null\"",
")",
";",
"}"
] | Always returns without writing to the stream. | [
"Always",
"returns",
"without",
"writing",
"to",
"the",
"stream",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/internal/builtin/VoidThriftCodec.java#L51-L56 | train |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java | ThriftServerConfig.setMaxFrameSize | @Config("thrift.max-frame-size")
public ThriftServerConfig setMaxFrameSize(DataSize maxFrameSize)
{
checkArgument(maxFrameSize.toBytes() <= 0x3FFFFFFF);
this.maxFrameSize = maxFrameSize;
return this;
} | java | @Config("thrift.max-frame-size")
public ThriftServerConfig setMaxFrameSize(DataSize maxFrameSize)
{
checkArgument(maxFrameSize.toBytes() <= 0x3FFFFFFF);
this.maxFrameSize = maxFrameSize;
return this;
} | [
"@",
"Config",
"(",
"\"thrift.max-frame-size\"",
")",
"public",
"ThriftServerConfig",
"setMaxFrameSize",
"(",
"DataSize",
"maxFrameSize",
")",
"{",
"checkArgument",
"(",
"maxFrameSize",
".",
"toBytes",
"(",
")",
"<=",
"0x3FFFFFFF",
")",
";",
"this",
".",
"maxFrame... | Sets a maximum frame size
@param maxFrameSize
@return | [
"Sets",
"a",
"maximum",
"frame",
"size"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java#L114-L120 | train |
facebookarchive/swift | swift-service/src/main/java/com/facebook/swift/service/ThriftClientManager.java | ThriftClientManager.getRemoteAddress | public HostAndPort getRemoteAddress(Object client)
{
NiftyClientChannel niftyChannel = getNiftyChannel(client);
try {
Channel nettyChannel = niftyChannel.getNettyChannel();
SocketAddress address = nettyChannel.getRemoteAddress();
InetSocketAddress inetAddress = (InetSocketAddress) address;
return HostAndPort.fromParts(inetAddress.getHostString(), inetAddress.getPort());
}
catch (NullPointerException | ClassCastException e) {
throw new IllegalArgumentException("Invalid swift client object", e);
}
} | java | public HostAndPort getRemoteAddress(Object client)
{
NiftyClientChannel niftyChannel = getNiftyChannel(client);
try {
Channel nettyChannel = niftyChannel.getNettyChannel();
SocketAddress address = nettyChannel.getRemoteAddress();
InetSocketAddress inetAddress = (InetSocketAddress) address;
return HostAndPort.fromParts(inetAddress.getHostString(), inetAddress.getPort());
}
catch (NullPointerException | ClassCastException e) {
throw new IllegalArgumentException("Invalid swift client object", e);
}
} | [
"public",
"HostAndPort",
"getRemoteAddress",
"(",
"Object",
"client",
")",
"{",
"NiftyClientChannel",
"niftyChannel",
"=",
"getNiftyChannel",
"(",
"client",
")",
";",
"try",
"{",
"Channel",
"nettyChannel",
"=",
"niftyChannel",
".",
"getNettyChannel",
"(",
")",
";"... | Returns the remote address that a Swift client is connected to
@throws IllegalArgumentException if the client is not a Swift client or is not connected
through an internet socket | [
"Returns",
"the",
"remote",
"address",
"that",
"a",
"Swift",
"client",
"is",
"connected",
"to"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-service/src/main/java/com/facebook/swift/service/ThriftClientManager.java#L335-L348 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/AbstractThriftMetadataBuilder.java | AbstractThriftMetadataBuilder.inferThriftFieldIds | protected final Set<String> inferThriftFieldIds()
{
Set<String> fieldsWithConflictingIds = new HashSet<>();
// group fields by explicit name or by name extracted from field, method or property
Multimap<String, FieldMetadata> fieldsByExplicitOrExtractedName = Multimaps.index(fields, getOrExtractThriftFieldName());
inferThriftFieldIds(fieldsByExplicitOrExtractedName, fieldsWithConflictingIds);
// group fields by name extracted from field, method or property
// this allows thrift name to be set explicitly without having to duplicate the name on getters and setters
// todo should this be the only way this works?
Multimap<String, FieldMetadata> fieldsByExtractedName = Multimaps.index(fields, extractThriftFieldName());
inferThriftFieldIds(fieldsByExtractedName, fieldsWithConflictingIds);
return fieldsWithConflictingIds;
} | java | protected final Set<String> inferThriftFieldIds()
{
Set<String> fieldsWithConflictingIds = new HashSet<>();
// group fields by explicit name or by name extracted from field, method or property
Multimap<String, FieldMetadata> fieldsByExplicitOrExtractedName = Multimaps.index(fields, getOrExtractThriftFieldName());
inferThriftFieldIds(fieldsByExplicitOrExtractedName, fieldsWithConflictingIds);
// group fields by name extracted from field, method or property
// this allows thrift name to be set explicitly without having to duplicate the name on getters and setters
// todo should this be the only way this works?
Multimap<String, FieldMetadata> fieldsByExtractedName = Multimaps.index(fields, extractThriftFieldName());
inferThriftFieldIds(fieldsByExtractedName, fieldsWithConflictingIds);
return fieldsWithConflictingIds;
} | [
"protected",
"final",
"Set",
"<",
"String",
">",
"inferThriftFieldIds",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"fieldsWithConflictingIds",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"// group fields by explicit name or by name extracted from field, method or property"... | Assigns all fields an id if possible. Fields are grouped by name and for each group, if there
is a single id, all fields in the group are assigned this id. If the group has multiple ids,
an error is reported. | [
"Assigns",
"all",
"fields",
"an",
"id",
"if",
"possible",
".",
"Fields",
"are",
"grouped",
"by",
"name",
"and",
"for",
"each",
"group",
"if",
"there",
"is",
"a",
"single",
"id",
"all",
"fields",
"in",
"the",
"group",
"are",
"assigned",
"this",
"id",
".... | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/AbstractThriftMetadataBuilder.java#L552-L567 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/metadata/AbstractThriftMetadataBuilder.java | AbstractThriftMetadataBuilder.verifyFieldType | protected final void verifyFieldType(short id, String name, Collection<FieldMetadata> fields, ThriftCatalog catalog)
{
boolean isSupportedType = true;
for (FieldMetadata field : fields) {
if (!catalog.isSupportedStructFieldType(field.getJavaType())) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type", structName, name, id, TypeToken.of(field.getJavaType()));
isSupportedType = false;
// only report the error once
break;
}
}
// fields must have the same type
if (isSupportedType) {
Set<ThriftTypeReference> types = new HashSet<>();
for (FieldMetadata field : fields) {
types.add(catalog.getFieldThriftTypeReference(field));
}
if (types.size() > 1) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' has multiple types: %s", structName, name, id, types);
}
}
} | java | protected final void verifyFieldType(short id, String name, Collection<FieldMetadata> fields, ThriftCatalog catalog)
{
boolean isSupportedType = true;
for (FieldMetadata field : fields) {
if (!catalog.isSupportedStructFieldType(field.getJavaType())) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type", structName, name, id, TypeToken.of(field.getJavaType()));
isSupportedType = false;
// only report the error once
break;
}
}
// fields must have the same type
if (isSupportedType) {
Set<ThriftTypeReference> types = new HashSet<>();
for (FieldMetadata field : fields) {
types.add(catalog.getFieldThriftTypeReference(field));
}
if (types.size() > 1) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' has multiple types: %s", structName, name, id, types);
}
}
} | [
"protected",
"final",
"void",
"verifyFieldType",
"(",
"short",
"id",
",",
"String",
"name",
",",
"Collection",
"<",
"FieldMetadata",
">",
"fields",
",",
"ThriftCatalog",
"catalog",
")",
"{",
"boolean",
"isSupportedType",
"=",
"true",
";",
"for",
"(",
"FieldMet... | Verifies that the the fields all have a supported Java type and that all fields map to the
exact same ThriftType. | [
"Verifies",
"that",
"the",
"the",
"fields",
"all",
"have",
"a",
"supported",
"Java",
"type",
"and",
"that",
"all",
"fields",
"map",
"to",
"the",
"exact",
"same",
"ThriftType",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/metadata/AbstractThriftMetadataBuilder.java#L716-L738 | train |
facebookarchive/swift | swift-javadoc/src/main/java/com/facebook/swift/javadoc/JavaDocProcessor.java | JavaDocProcessor.escapeJavaString | private static String escapeJavaString(String input)
{
int len = input.length();
// assume (for performance, not for correctness) that string will not expand by more than 10 chars
StringBuilder out = new StringBuilder(len + 10);
for (int i = 0; i < len; i++) {
char c = input.charAt(i);
if (c >= 32 && c <= 0x7f) {
if (c == '"') {
out.append('\\');
out.append('"');
} else if (c == '\\') {
out.append('\\');
out.append('\\');
} else {
out.append(c);
}
} else {
out.append('\\');
out.append('u');
// one liner hack to have the hex string of length exactly 4
out.append(Integer.toHexString(c | 0x10000).substring(1));
}
}
return out.toString();
} | java | private static String escapeJavaString(String input)
{
int len = input.length();
// assume (for performance, not for correctness) that string will not expand by more than 10 chars
StringBuilder out = new StringBuilder(len + 10);
for (int i = 0; i < len; i++) {
char c = input.charAt(i);
if (c >= 32 && c <= 0x7f) {
if (c == '"') {
out.append('\\');
out.append('"');
} else if (c == '\\') {
out.append('\\');
out.append('\\');
} else {
out.append(c);
}
} else {
out.append('\\');
out.append('u');
// one liner hack to have the hex string of length exactly 4
out.append(Integer.toHexString(c | 0x10000).substring(1));
}
}
return out.toString();
} | [
"private",
"static",
"String",
"escapeJavaString",
"(",
"String",
"input",
")",
"{",
"int",
"len",
"=",
"input",
".",
"length",
"(",
")",
";",
"// assume (for performance, not for correctness) that string will not expand by more than 10 chars",
"StringBuilder",
"out",
"=",
... | in Guava 15 when released | [
"in",
"Guava",
"15",
"when",
"released"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-javadoc/src/main/java/com/facebook/swift/javadoc/JavaDocProcessor.java#L262-L287 | train |
facebookarchive/swift | swift-codec/src/main/java/com/facebook/swift/codec/ThriftCodecManager.java | ThriftCodecManager.addCodec | public void addCodec(ThriftCodec<?> codec)
{
catalog.addThriftType(codec.getType());
typeCodecs.put(codec.getType(), codec);
} | java | public void addCodec(ThriftCodec<?> codec)
{
catalog.addThriftType(codec.getType());
typeCodecs.put(codec.getType(), codec);
} | [
"public",
"void",
"addCodec",
"(",
"ThriftCodec",
"<",
"?",
">",
"codec",
")",
"{",
"catalog",
".",
"addThriftType",
"(",
"codec",
".",
"getType",
"(",
")",
")",
";",
"typeCodecs",
".",
"put",
"(",
"codec",
".",
"getType",
"(",
")",
",",
"codec",
")"... | Adds or replaces the codec associated with the type contained in the codec. This does not
replace any current users of the existing codec associated with the type. | [
"Adds",
"or",
"replaces",
"the",
"codec",
"associated",
"with",
"the",
"type",
"contained",
"in",
"the",
"codec",
".",
"This",
"does",
"not",
"replace",
"any",
"current",
"users",
"of",
"the",
"existing",
"codec",
"associated",
"with",
"the",
"type",
"."
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-codec/src/main/java/com/facebook/swift/codec/ThriftCodecManager.java#L282-L286 | train |
facebookarchive/swift | swift-generator/src/main/java/com/facebook/swift/generator/swift2thrift/Swift2ThriftGenerator.java | Swift2ThriftGenerator.convertToThrift | private Object convertToThrift(Class<?> cls)
{
Set<ThriftService> serviceAnnotations = ReflectionHelper.getEffectiveClassAnnotations(cls, ThriftService.class);
if (!serviceAnnotations.isEmpty()) {
// it's a service
ThriftServiceMetadata serviceMetadata = new ThriftServiceMetadata(cls, codecManager.getCatalog());
if (verbose) {
LOG.info("Found thrift service: %s", cls.getSimpleName());
}
return serviceMetadata;
} else {
// it's a type (will throw if it's not)
ThriftType thriftType = codecManager.getCatalog().getThriftType(cls);
if (verbose) {
LOG.info("Found thrift type: %s", thriftTypeRenderer.toString(thriftType));
}
return thriftType;
}
} | java | private Object convertToThrift(Class<?> cls)
{
Set<ThriftService> serviceAnnotations = ReflectionHelper.getEffectiveClassAnnotations(cls, ThriftService.class);
if (!serviceAnnotations.isEmpty()) {
// it's a service
ThriftServiceMetadata serviceMetadata = new ThriftServiceMetadata(cls, codecManager.getCatalog());
if (verbose) {
LOG.info("Found thrift service: %s", cls.getSimpleName());
}
return serviceMetadata;
} else {
// it's a type (will throw if it's not)
ThriftType thriftType = codecManager.getCatalog().getThriftType(cls);
if (verbose) {
LOG.info("Found thrift type: %s", thriftTypeRenderer.toString(thriftType));
}
return thriftType;
}
} | [
"private",
"Object",
"convertToThrift",
"(",
"Class",
"<",
"?",
">",
"cls",
")",
"{",
"Set",
"<",
"ThriftService",
">",
"serviceAnnotations",
"=",
"ReflectionHelper",
".",
"getEffectiveClassAnnotations",
"(",
"cls",
",",
"ThriftService",
".",
"class",
")",
";",
... | returns ThriftType, ThriftServiceMetadata or null | [
"returns",
"ThriftType",
"ThriftServiceMetadata",
"or",
"null"
] | 3f1f098a50d6106f50cd6fe1c361dd373ede0197 | https://github.com/facebookarchive/swift/blob/3f1f098a50d6106f50cd6fe1c361dd373ede0197/swift-generator/src/main/java/com/facebook/swift/generator/swift2thrift/Swift2ThriftGenerator.java#L445-L463 | train |
elastic/elasticsearch-mapper-attachments | src/main/java/org/elasticsearch/mapper/attachments/TikaImpl.java | TikaImpl.parse | static String parse(final byte content[], final Metadata metadata, final int limit) throws TikaException, IOException {
// check that its not unprivileged code like a script
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws TikaException, IOException {
return TIKA_INSTANCE.parseToString(StreamInput.wrap(content), metadata, limit);
}
});
} catch (PrivilegedActionException e) {
// checked exception from tika: unbox it
Throwable cause = e.getCause();
if (cause instanceof TikaException) {
throw (TikaException) cause;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else {
throw new AssertionError(cause);
}
}
} | java | static String parse(final byte content[], final Metadata metadata, final int limit) throws TikaException, IOException {
// check that its not unprivileged code like a script
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
@Override
public String run() throws TikaException, IOException {
return TIKA_INSTANCE.parseToString(StreamInput.wrap(content), metadata, limit);
}
});
} catch (PrivilegedActionException e) {
// checked exception from tika: unbox it
Throwable cause = e.getCause();
if (cause instanceof TikaException) {
throw (TikaException) cause;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else {
throw new AssertionError(cause);
}
}
} | [
"static",
"String",
"parse",
"(",
"final",
"byte",
"content",
"[",
"]",
",",
"final",
"Metadata",
"metadata",
",",
"final",
"int",
"limit",
")",
"throws",
"TikaException",
",",
"IOException",
"{",
"// check that its not unprivileged code like a script",
"SecurityManag... | only package private for testing! | [
"only",
"package",
"private",
"for",
"testing!"
] | 5660ada22ccf918d3180db8820e92dae717cc5a9 | https://github.com/elastic/elasticsearch-mapper-attachments/blob/5660ada22ccf918d3180db8820e92dae717cc5a9/src/main/java/org/elasticsearch/mapper/attachments/TikaImpl.java#L44-L69 | train |
tuenti/SmsRadar | library/src/main/java/com/tuenti/smsradar/SmsRadar.java | SmsRadar.initializeSmsRadarService | public static void initializeSmsRadarService(Context context, SmsListener smsListener) {
SmsRadar.smsListener = smsListener;
Intent intent = new Intent(context, SmsRadarService.class);
context.startService(intent);
} | java | public static void initializeSmsRadarService(Context context, SmsListener smsListener) {
SmsRadar.smsListener = smsListener;
Intent intent = new Intent(context, SmsRadarService.class);
context.startService(intent);
} | [
"public",
"static",
"void",
"initializeSmsRadarService",
"(",
"Context",
"context",
",",
"SmsListener",
"smsListener",
")",
"{",
"SmsRadar",
".",
"smsListener",
"=",
"smsListener",
";",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"context",
",",
"SmsRadarServic... | Starts the service and store the listener to be notified when a new incoming or outgoing sms be processed
inside the SMS content provider
@param context used to start the service
@param smsListener to notify when the sms content provider gets a new sms | [
"Starts",
"the",
"service",
"and",
"store",
"the",
"listener",
"to",
"be",
"notified",
"when",
"a",
"new",
"incoming",
"or",
"outgoing",
"sms",
"be",
"processed",
"inside",
"the",
"SMS",
"content",
"provider"
] | 598553c69c474634a1d4041a39f015f0b4c33a6d | https://github.com/tuenti/SmsRadar/blob/598553c69c474634a1d4041a39f015f0b4c33a6d/library/src/main/java/com/tuenti/smsradar/SmsRadar.java#L39-L43 | train |
tuenti/SmsRadar | library/src/main/java/com/tuenti/smsradar/SmsRadar.java | SmsRadar.stopSmsRadarService | public static void stopSmsRadarService(Context context) {
SmsRadar.smsListener = null;
Intent intent = new Intent(context, SmsRadarService.class);
context.stopService(intent);
} | java | public static void stopSmsRadarService(Context context) {
SmsRadar.smsListener = null;
Intent intent = new Intent(context, SmsRadarService.class);
context.stopService(intent);
} | [
"public",
"static",
"void",
"stopSmsRadarService",
"(",
"Context",
"context",
")",
"{",
"SmsRadar",
".",
"smsListener",
"=",
"null",
";",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"context",
",",
"SmsRadarService",
".",
"class",
")",
";",
"context",
"."... | Stops the service and remove the SmsListener added when the SmsRadar was initialized
@param context used to stop the service | [
"Stops",
"the",
"service",
"and",
"remove",
"the",
"SmsListener",
"added",
"when",
"the",
"SmsRadar",
"was",
"initialized"
] | 598553c69c474634a1d4041a39f015f0b4c33a6d | https://github.com/tuenti/SmsRadar/blob/598553c69c474634a1d4041a39f015f0b4c33a6d/library/src/main/java/com/tuenti/smsradar/SmsRadar.java#L50-L54 | train |
paoding-code/paoding-rose | paoding-rose-web/src/main/java/net/paoding/rose/web/impl/thread/RootEngine.java | RootEngine.saveAttributesBeforeInclude | private void saveAttributesBeforeInclude(final Invocation inv) {
ServletRequest request = inv.getRequest();
logger.debug("Taking snapshot of request attributes before include");
Map<String, Object> attributesSnapshot = new HashMap<String, Object>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
inv.setAttribute("$$paoding-rose.attributesBeforeInclude", attributesSnapshot);
} | java | private void saveAttributesBeforeInclude(final Invocation inv) {
ServletRequest request = inv.getRequest();
logger.debug("Taking snapshot of request attributes before include");
Map<String, Object> attributesSnapshot = new HashMap<String, Object>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
inv.setAttribute("$$paoding-rose.attributesBeforeInclude", attributesSnapshot);
} | [
"private",
"void",
"saveAttributesBeforeInclude",
"(",
"final",
"Invocation",
"inv",
")",
"{",
"ServletRequest",
"request",
"=",
"inv",
".",
"getRequest",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"Taking snapshot of request attributes before include\"",
")",
";",... | Keep a snapshot of the request attributes in case of an include, to
be able to restore the original attributes after the include.
@param inv | [
"Keep",
"a",
"snapshot",
"of",
"the",
"request",
"attributes",
"in",
"case",
"of",
"an",
"include",
"to",
"be",
"able",
"to",
"restore",
"the",
"original",
"attributes",
"after",
"the",
"include",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-web/src/main/java/net/paoding/rose/web/impl/thread/RootEngine.java#L155-L165 | train |
paoding-code/paoding-rose | paoding-rose-web/src/main/java/net/paoding/rose/web/impl/thread/RootEngine.java | RootEngine.restoreRequestAttributesAfterInclude | private void restoreRequestAttributesAfterInclude(Invocation inv) {
logger.debug("Restoring snapshot of request attributes after include");
HttpServletRequest request = inv.getRequest();
@SuppressWarnings("unchecked")
Map<String, Object> attributesSnapshot = (Map<String, Object>) inv
.getAttribute("$$paoding-rose.attributesBeforeInclude");
// Need to copy into separate Collection here, to avoid side effects
// on the Enumeration when removing attributes.
Set<String> attrsToCheck = new HashSet<String>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
attrsToCheck.add(attrName);
}
// Iterate over the attributes to check, restoring the original value
// or removing the attribute, respectively, if appropriate.
for (String attrName : attrsToCheck) {
Object attrValue = attributesSnapshot.get(attrName);
if (attrValue != null) {
if (logger.isDebugEnabled()) {
logger.debug("Restoring original value of attribute [" + attrName
+ "] after include");
}
request.setAttribute(attrName, attrValue);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Removing attribute [" + attrName + "] after include");
}
request.removeAttribute(attrName);
}
}
} | java | private void restoreRequestAttributesAfterInclude(Invocation inv) {
logger.debug("Restoring snapshot of request attributes after include");
HttpServletRequest request = inv.getRequest();
@SuppressWarnings("unchecked")
Map<String, Object> attributesSnapshot = (Map<String, Object>) inv
.getAttribute("$$paoding-rose.attributesBeforeInclude");
// Need to copy into separate Collection here, to avoid side effects
// on the Enumeration when removing attributes.
Set<String> attrsToCheck = new HashSet<String>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
attrsToCheck.add(attrName);
}
// Iterate over the attributes to check, restoring the original value
// or removing the attribute, respectively, if appropriate.
for (String attrName : attrsToCheck) {
Object attrValue = attributesSnapshot.get(attrName);
if (attrValue != null) {
if (logger.isDebugEnabled()) {
logger.debug("Restoring original value of attribute [" + attrName
+ "] after include");
}
request.setAttribute(attrName, attrValue);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Removing attribute [" + attrName + "] after include");
}
request.removeAttribute(attrName);
}
}
} | [
"private",
"void",
"restoreRequestAttributesAfterInclude",
"(",
"Invocation",
"inv",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Restoring snapshot of request attributes after include\"",
")",
";",
"HttpServletRequest",
"request",
"=",
"inv",
".",
"getRequest",
"(",
")",
... | Restore the request attributes after an include.
@param request current HTTP request
@param attributesSnapshot the snapshot of the request attributes
before the include | [
"Restore",
"the",
"request",
"attributes",
"after",
"an",
"include",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-web/src/main/java/net/paoding/rose/web/impl/thread/RootEngine.java#L174-L209 | train |
paoding-code/paoding-rose | paoding-rose-jade/src/main/java/net/paoding/rose/jade/context/spring/JadeComponentProvider.java | JadeComponentProvider.isCandidateComponent | protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
}
return false;
} | java | protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
}
return false;
} | [
"protected",
"boolean",
"isCandidateComponent",
"(",
"MetadataReader",
"metadataReader",
")",
"throws",
"IOException",
"{",
"for",
"(",
"TypeFilter",
"tf",
":",
"this",
".",
"excludeFilters",
")",
"{",
"if",
"(",
"tf",
".",
"match",
"(",
"metadataReader",
",",
... | Determine whether the given class does not match any exclude filter
and does match at least one include filter.
@param metadataReader the ASM ClassReader for the class
@return whether the class qualifies as a candidate component | [
"Determine",
"whether",
"the",
"given",
"class",
"does",
"not",
"match",
"any",
"exclude",
"filter",
"and",
"does",
"match",
"at",
"least",
"one",
"include",
"filter",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-jade/src/main/java/net/paoding/rose/jade/context/spring/JadeComponentProvider.java#L217-L229 | train |
paoding-code/paoding-rose | paoding-rose-web/src/main/java/net/paoding/rose/web/paramresolver/ServletRequestDataBinder.java | ServletRequestDataBinder.getInternalBindingResult | @Override
protected AbstractPropertyBindingResult getInternalBindingResult() {
AbstractPropertyBindingResult bindingResult = super.getInternalBindingResult();
// by rose
PropertyEditorRegistry registry = bindingResult.getPropertyEditorRegistry();
registry.registerCustomEditor(Date.class, new DateEditor(Date.class));
registry.registerCustomEditor(java.sql.Date.class, new DateEditor(java.sql.Date.class));
registry.registerCustomEditor(java.sql.Time.class, new DateEditor(java.sql.Time.class));
registry.registerCustomEditor(java.sql.Timestamp.class, new DateEditor(
java.sql.Timestamp.class));
return bindingResult;
} | java | @Override
protected AbstractPropertyBindingResult getInternalBindingResult() {
AbstractPropertyBindingResult bindingResult = super.getInternalBindingResult();
// by rose
PropertyEditorRegistry registry = bindingResult.getPropertyEditorRegistry();
registry.registerCustomEditor(Date.class, new DateEditor(Date.class));
registry.registerCustomEditor(java.sql.Date.class, new DateEditor(java.sql.Date.class));
registry.registerCustomEditor(java.sql.Time.class, new DateEditor(java.sql.Time.class));
registry.registerCustomEditor(java.sql.Timestamp.class, new DateEditor(
java.sql.Timestamp.class));
return bindingResult;
} | [
"@",
"Override",
"protected",
"AbstractPropertyBindingResult",
"getInternalBindingResult",
"(",
")",
"{",
"AbstractPropertyBindingResult",
"bindingResult",
"=",
"super",
".",
"getInternalBindingResult",
"(",
")",
";",
"// by rose\r",
"PropertyEditorRegistry",
"registry",
"=",... | Return the internal BindingResult held by this DataBinder, as
AbstractPropertyBindingResult. | [
"Return",
"the",
"internal",
"BindingResult",
"held",
"by",
"this",
"DataBinder",
"as",
"AbstractPropertyBindingResult",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-web/src/main/java/net/paoding/rose/web/paramresolver/ServletRequestDataBinder.java#L109-L121 | train |
paoding-code/paoding-rose | paoding-rose-web/src/main/java/net/paoding/rose/util/Base64.java | Base64.decode | public final byte[] decode(byte[] source, int off, int len) {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for (i = off; i < off + len; i++) {
sbiCrop = (byte)(source[i] & 0x7f); // only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // white space, equals sign or better
if (sbiDecode >= PADDING_CHAR_ENC) {
b4[b4Posn++] = sbiCrop;
if (b4Posn > 3) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
b4Posn = 0;
// if that was the padding char, break out of 'for' loop
if (sbiCrop == PADDING_CHAR) {
break;
}
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
//discard
}
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} | java | public final byte[] decode(byte[] source, int off, int len) {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for (i = off; i < off + len; i++) {
sbiCrop = (byte)(source[i] & 0x7f); // only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // white space, equals sign or better
if (sbiDecode >= PADDING_CHAR_ENC) {
b4[b4Posn++] = sbiCrop;
if (b4Posn > 3) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
b4Posn = 0;
// if that was the padding char, break out of 'for' loop
if (sbiCrop == PADDING_CHAR) {
break;
}
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
//discard
}
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} | [
"public",
"final",
"byte",
"[",
"]",
"decode",
"(",
"byte",
"[",
"]",
"source",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"int",
"len34",
"=",
"len",
"*",
"3",
"/",
"4",
";",
"byte",
"[",
"]",
"outBuff",
"=",
"new",
"byte",
"[",
"len34",
... | Very low-level access to decoding ASCII characters in
the form of a byte array.
@param source the Base64 encoded data
@param off the offset of where to begin decoding
@param len the length of characters to decode
@return decoded data | [
"Very",
"low",
"-",
"level",
"access",
"to",
"decoding",
"ASCII",
"characters",
"in",
"the",
"form",
"of",
"a",
"byte",
"array",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-web/src/main/java/net/paoding/rose/util/Base64.java#L388-L424 | train |
paoding-code/paoding-rose | paoding-rose-jade/src/main/java/net/paoding/rose/jade/rowmapper/BeanPropertyRowMapper.java | BeanPropertyRowMapper.initialize | protected void initialize() {
this.mappedFields = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
if (checkProperties) {
mappedProperties = new HashSet<String>();
}
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
if (pd.getWriteMethod() != null) {
if (checkProperties) {
this.mappedProperties.add(pd.getName());
}
this.mappedFields.put(pd.getName().toLowerCase(), pd);
for (String underscoredName : underscoreName(pd.getName())) {
if (underscoredName != null
&& !pd.getName().toLowerCase().equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
}
}
}
} | java | protected void initialize() {
this.mappedFields = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
if (checkProperties) {
mappedProperties = new HashSet<String>();
}
for (int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
if (pd.getWriteMethod() != null) {
if (checkProperties) {
this.mappedProperties.add(pd.getName());
}
this.mappedFields.put(pd.getName().toLowerCase(), pd);
for (String underscoredName : underscoreName(pd.getName())) {
if (underscoredName != null
&& !pd.getName().toLowerCase().equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
}
}
}
} | [
"protected",
"void",
"initialize",
"(",
")",
"{",
"this",
".",
"mappedFields",
"=",
"new",
"HashMap",
"<",
"String",
",",
"PropertyDescriptor",
">",
"(",
")",
";",
"PropertyDescriptor",
"[",
"]",
"pds",
"=",
"BeanUtils",
".",
"getPropertyDescriptors",
"(",
"... | Initialize the mapping metadata for the given class.
@param mappedClass the mapped class. | [
"Initialize",
"the",
"mapping",
"metadata",
"for",
"the",
"given",
"class",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-jade/src/main/java/net/paoding/rose/jade/rowmapper/BeanPropertyRowMapper.java#L111-L132 | train |
paoding-code/paoding-rose | paoding-rose-jade/src/main/java/net/paoding/rose/jade/rowmapper/BeanPropertyRowMapper.java | BeanPropertyRowMapper.underscoreName | private String[] underscoreName(String camelCaseName) {
StringBuilder result = new StringBuilder();
if (camelCaseName != null && camelCaseName.length() > 0) {
result.append(camelCaseName.substring(0, 1).toLowerCase());
for (int i = 1; i < camelCaseName.length(); i++) {
char ch = camelCaseName.charAt(i);
if (Character.isUpperCase(ch)) {
result.append("_");
result.append(Character.toLowerCase(ch));
} else {
result.append(ch);
}
}
}
String name = result.toString();
// 当name为user1_name2时,使name2为user_1_name_2
// 这使得列user_1_name_2的列能映射到user1Name2属性
String name2 = null;
boolean digitFound = false;
for (int i = name.length() - 1; i >= 0; i--) {
if (Character.isDigit(name.charAt(i))) {
// 遇到数字就做一个标识并continue,直到不是时才不continue
digitFound = true;
continue;
}
// 只有上一个字符是数字才做下划线
if (digitFound && i < name.length() - 1 && i > 0) {
if (name2 == null) {
name2 = name;
}
name2 = name2.substring(0, i + 1) + "_" + name2.substring(i + 1);
}
digitFound = false;
}
return new String[] { name, name2 };
} | java | private String[] underscoreName(String camelCaseName) {
StringBuilder result = new StringBuilder();
if (camelCaseName != null && camelCaseName.length() > 0) {
result.append(camelCaseName.substring(0, 1).toLowerCase());
for (int i = 1; i < camelCaseName.length(); i++) {
char ch = camelCaseName.charAt(i);
if (Character.isUpperCase(ch)) {
result.append("_");
result.append(Character.toLowerCase(ch));
} else {
result.append(ch);
}
}
}
String name = result.toString();
// 当name为user1_name2时,使name2为user_1_name_2
// 这使得列user_1_name_2的列能映射到user1Name2属性
String name2 = null;
boolean digitFound = false;
for (int i = name.length() - 1; i >= 0; i--) {
if (Character.isDigit(name.charAt(i))) {
// 遇到数字就做一个标识并continue,直到不是时才不continue
digitFound = true;
continue;
}
// 只有上一个字符是数字才做下划线
if (digitFound && i < name.length() - 1 && i > 0) {
if (name2 == null) {
name2 = name;
}
name2 = name2.substring(0, i + 1) + "_" + name2.substring(i + 1);
}
digitFound = false;
}
return new String[] { name, name2 };
} | [
"private",
"String",
"[",
"]",
"underscoreName",
"(",
"String",
"camelCaseName",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
"camelCaseName",
"!=",
"null",
"&&",
"camelCaseName",
".",
"length",
"(",
")",
">",
... | Convert a name in camelCase to an underscored name in lower case.
Any upper case letters are converted to lower case with a preceding
underscore.
@param camelCaseName the string containing original name
@return the converted name | [
"Convert",
"a",
"name",
"in",
"camelCase",
"to",
"an",
"underscored",
"name",
"in",
"lower",
"case",
".",
"Any",
"upper",
"case",
"letters",
"are",
"converted",
"to",
"lower",
"case",
"with",
"a",
"preceding",
"underscore",
"."
] | 8b512704174dd6cba95e544c7d6ab66105cb8ec4 | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-jade/src/main/java/net/paoding/rose/jade/rowmapper/BeanPropertyRowMapper.java#L142-L177 | train |
highsource/maven-jaxb2-plugin | plugin/src/main/java/org/jvnet/mjiip/v_2/OptionsFactory.java | OptionsFactory.createOptions | public Options createOptions(OptionsConfiguration optionsConfiguration)
throws MojoExecutionException {
final Options options = new Options();
options.verbose = optionsConfiguration.isVerbose();
options.debugMode = optionsConfiguration.isDebugMode();
options.classpaths.addAll(optionsConfiguration.getPlugins());
options.target = createSpecVersion(optionsConfiguration
.getSpecVersion());
final String encoding = optionsConfiguration.getEncoding();
if (encoding != null) {
options.encoding = createEncoding(encoding);
}
options.setSchemaLanguage(createLanguage(optionsConfiguration
.getSchemaLanguage()));
options.entityResolver = optionsConfiguration.getEntityResolver();
for (InputSource grammar : optionsConfiguration.getGrammars()) {
options.addGrammar(grammar);
}
for (InputSource bindFile : optionsConfiguration.getBindFiles()) {
options.addBindFile(bindFile);
}
// Setup Other Options
options.defaultPackage = optionsConfiguration.getGeneratePackage();
options.targetDir = optionsConfiguration.getGenerateDirectory();
options.strictCheck = optionsConfiguration.isStrict();
options.readOnly = optionsConfiguration.isReadOnly();
options.packageLevelAnnotations = optionsConfiguration
.isPackageLevelAnnotations();
options.noFileHeader = optionsConfiguration.isNoFileHeader();
options.enableIntrospection = optionsConfiguration
.isEnableIntrospection();
options.disableXmlSecurity = optionsConfiguration
.isDisableXmlSecurity();
if (optionsConfiguration.getAccessExternalSchema() != null) {
System.setProperty("javax.xml.accessExternalSchema",
optionsConfiguration.getAccessExternalSchema());
}
if (optionsConfiguration.getAccessExternalDTD() != null) {
System.setProperty("javax.xml.accessExternalDTD",
optionsConfiguration.getAccessExternalDTD());
}
if (optionsConfiguration.isEnableExternalEntityProcessing()) {
System.setProperty("enableExternalEntityProcessing", Boolean.TRUE.toString());
}
options.contentForWildcard = optionsConfiguration
.isContentForWildcard();
if (optionsConfiguration.isExtension()) {
options.compatibilityMode = Options.EXTENSION;
}
final List<String> arguments = optionsConfiguration.getArguments();
try {
options.parseArguments(arguments.toArray(new String[arguments
.size()]));
}
catch (BadCommandLineException bclex) {
throw new MojoExecutionException("Error parsing the command line ["
+ arguments + "]", bclex);
}
return options;
} | java | public Options createOptions(OptionsConfiguration optionsConfiguration)
throws MojoExecutionException {
final Options options = new Options();
options.verbose = optionsConfiguration.isVerbose();
options.debugMode = optionsConfiguration.isDebugMode();
options.classpaths.addAll(optionsConfiguration.getPlugins());
options.target = createSpecVersion(optionsConfiguration
.getSpecVersion());
final String encoding = optionsConfiguration.getEncoding();
if (encoding != null) {
options.encoding = createEncoding(encoding);
}
options.setSchemaLanguage(createLanguage(optionsConfiguration
.getSchemaLanguage()));
options.entityResolver = optionsConfiguration.getEntityResolver();
for (InputSource grammar : optionsConfiguration.getGrammars()) {
options.addGrammar(grammar);
}
for (InputSource bindFile : optionsConfiguration.getBindFiles()) {
options.addBindFile(bindFile);
}
// Setup Other Options
options.defaultPackage = optionsConfiguration.getGeneratePackage();
options.targetDir = optionsConfiguration.getGenerateDirectory();
options.strictCheck = optionsConfiguration.isStrict();
options.readOnly = optionsConfiguration.isReadOnly();
options.packageLevelAnnotations = optionsConfiguration
.isPackageLevelAnnotations();
options.noFileHeader = optionsConfiguration.isNoFileHeader();
options.enableIntrospection = optionsConfiguration
.isEnableIntrospection();
options.disableXmlSecurity = optionsConfiguration
.isDisableXmlSecurity();
if (optionsConfiguration.getAccessExternalSchema() != null) {
System.setProperty("javax.xml.accessExternalSchema",
optionsConfiguration.getAccessExternalSchema());
}
if (optionsConfiguration.getAccessExternalDTD() != null) {
System.setProperty("javax.xml.accessExternalDTD",
optionsConfiguration.getAccessExternalDTD());
}
if (optionsConfiguration.isEnableExternalEntityProcessing()) {
System.setProperty("enableExternalEntityProcessing", Boolean.TRUE.toString());
}
options.contentForWildcard = optionsConfiguration
.isContentForWildcard();
if (optionsConfiguration.isExtension()) {
options.compatibilityMode = Options.EXTENSION;
}
final List<String> arguments = optionsConfiguration.getArguments();
try {
options.parseArguments(arguments.toArray(new String[arguments
.size()]));
}
catch (BadCommandLineException bclex) {
throw new MojoExecutionException("Error parsing the command line ["
+ arguments + "]", bclex);
}
return options;
} | [
"public",
"Options",
"createOptions",
"(",
"OptionsConfiguration",
"optionsConfiguration",
")",
"throws",
"MojoExecutionException",
"{",
"final",
"Options",
"options",
"=",
"new",
"Options",
"(",
")",
";",
"options",
".",
"verbose",
"=",
"optionsConfiguration",
".",
... | Creates and initializes an instance of XJC options. | [
"Creates",
"and",
"initializes",
"an",
"instance",
"of",
"XJC",
"options",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin/src/main/java/org/jvnet/mjiip/v_2/OptionsFactory.java#L24-L100 | train |
highsource/maven-jaxb2-plugin | plugin-core/src/main/java/org/jvnet/jaxb2/maven2/util/IOUtils.java | IOUtils.getInputSource | public static InputSource getInputSource(File file) {
try {
final URL url = file.toURI().toURL();
return getInputSource(url);
} catch (MalformedURLException e) {
return new InputSource(file.getPath());
}
} | java | public static InputSource getInputSource(File file) {
try {
final URL url = file.toURI().toURL();
return getInputSource(url);
} catch (MalformedURLException e) {
return new InputSource(file.getPath());
}
} | [
"public",
"static",
"InputSource",
"getInputSource",
"(",
"File",
"file",
")",
"{",
"try",
"{",
"final",
"URL",
"url",
"=",
"file",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
";",
"return",
"getInputSource",
"(",
"url",
")",
";",
"}",
"catch",
"... | Creates an input source for the given file.
@param file
file to create input source for.
@return Created input source object. | [
"Creates",
"an",
"input",
"source",
"for",
"the",
"given",
"file",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin-core/src/main/java/org/jvnet/jaxb2/maven2/util/IOUtils.java#L28-L35 | train |
highsource/maven-jaxb2-plugin | plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java | RawXJC2Mojo.execute | public void execute() throws MojoExecutionException {
synchronized (lock) {
injectDependencyDefaults();
resolveArtifacts();
// Install project dependencies into classloader's class path
// and execute xjc2.
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = createClassLoader(currentClassLoader);
Thread.currentThread().setContextClassLoader(classLoader);
final Locale currentDefaultLocale = Locale.getDefault();
try {
final Locale locale = LocaleUtils.valueOf(getLocale());
Locale.setDefault(locale);
//
doExecute();
} finally {
Locale.setDefault(currentDefaultLocale);
// Set back the old classloader
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
} | java | public void execute() throws MojoExecutionException {
synchronized (lock) {
injectDependencyDefaults();
resolveArtifacts();
// Install project dependencies into classloader's class path
// and execute xjc2.
final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader classLoader = createClassLoader(currentClassLoader);
Thread.currentThread().setContextClassLoader(classLoader);
final Locale currentDefaultLocale = Locale.getDefault();
try {
final Locale locale = LocaleUtils.valueOf(getLocale());
Locale.setDefault(locale);
//
doExecute();
} finally {
Locale.setDefault(currentDefaultLocale);
// Set back the old classloader
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
} | [
"public",
"void",
"execute",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"injectDependencyDefaults",
"(",
")",
";",
"resolveArtifacts",
"(",
")",
";",
"// Install project dependencies into classloader's class path\r",
"// and ... | Execute the maven2 mojo to invoke the xjc2 compiler based on any
configuration settings. | [
"Execute",
"the",
"maven2",
"mojo",
"to",
"invoke",
"the",
"xjc2",
"compiler",
"based",
"on",
"any",
"configuration",
"settings",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java#L304-L327 | train |
highsource/maven-jaxb2-plugin | plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java | RawXJC2Mojo.setupMavenPaths | protected void setupMavenPaths() {
if (getAddCompileSourceRoot()) {
getProject().addCompileSourceRoot(getGenerateDirectory().getPath());
}
if (getAddTestCompileSourceRoot()) {
getProject().addTestCompileSourceRoot(getGenerateDirectory().getPath());
}
if (getEpisode() && getEpisodeFile() != null) {
final String episodeFilePath = getEpisodeFile().getAbsolutePath();
final String generatedDirectoryPath = getGenerateDirectory().getAbsolutePath();
if (episodeFilePath.startsWith(generatedDirectoryPath + File.separator)) {
final String path = episodeFilePath.substring(generatedDirectoryPath.length() + 1);
final Resource resource = new Resource();
resource.setDirectory(generatedDirectoryPath);
resource.addInclude(path);
if (getAddCompileSourceRoot()) {
getProject().addResource(resource);
}
if (getAddTestCompileSourceRoot()) {
getProject().addTestResource(resource);
}
}
}
} | java | protected void setupMavenPaths() {
if (getAddCompileSourceRoot()) {
getProject().addCompileSourceRoot(getGenerateDirectory().getPath());
}
if (getAddTestCompileSourceRoot()) {
getProject().addTestCompileSourceRoot(getGenerateDirectory().getPath());
}
if (getEpisode() && getEpisodeFile() != null) {
final String episodeFilePath = getEpisodeFile().getAbsolutePath();
final String generatedDirectoryPath = getGenerateDirectory().getAbsolutePath();
if (episodeFilePath.startsWith(generatedDirectoryPath + File.separator)) {
final String path = episodeFilePath.substring(generatedDirectoryPath.length() + 1);
final Resource resource = new Resource();
resource.setDirectory(generatedDirectoryPath);
resource.addInclude(path);
if (getAddCompileSourceRoot()) {
getProject().addResource(resource);
}
if (getAddTestCompileSourceRoot()) {
getProject().addTestResource(resource);
}
}
}
} | [
"protected",
"void",
"setupMavenPaths",
"(",
")",
"{",
"if",
"(",
"getAddCompileSourceRoot",
"(",
")",
")",
"{",
"getProject",
"(",
")",
".",
"addCompileSourceRoot",
"(",
"getGenerateDirectory",
"(",
")",
".",
"getPath",
"(",
")",
")",
";",
"}",
"if",
"(",... | Augments Maven paths with generated resources. | [
"Augments",
"Maven",
"paths",
"with",
"generated",
"resources",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java#L621-L648 | train |
highsource/maven-jaxb2-plugin | plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java | RawXJC2Mojo.logConfiguration | protected void logConfiguration() throws MojoExecutionException {
super.logConfiguration();
// TODO clean up
getLog().info("catalogURIs (calculated):" + getCatalogURIs());
getLog().info("resolvedCatalogURIs (calculated):" + getResolvedCatalogURIs());
getLog().info("schemaFiles (calculated):" + getSchemaFiles());
getLog().info("schemaURIs (calculated):" + getSchemaURIs());
getLog().info("resolvedSchemaURIs (calculated):" + getResolvedSchemaURIs());
getLog().info("bindingFiles (calculated):" + getBindingFiles());
getLog().info("bindingURIs (calculated):" + getBindingURIs());
getLog().info("resolvedBindingURIs (calculated):" + getResolvedBindingURIs());
getLog().info("xjcPluginArtifacts (resolved):" + getXjcPluginArtifacts());
getLog().info("xjcPluginFiles (resolved):" + getXjcPluginFiles());
getLog().info("xjcPluginURLs (resolved):" + getXjcPluginURLs());
getLog().info("episodeArtifacts (resolved):" + getEpisodeArtifacts());
getLog().info("episodeFiles (resolved):" + getEpisodeFiles());
getLog().info("dependsURIs (resolved):" + getDependsURIs());
} | java | protected void logConfiguration() throws MojoExecutionException {
super.logConfiguration();
// TODO clean up
getLog().info("catalogURIs (calculated):" + getCatalogURIs());
getLog().info("resolvedCatalogURIs (calculated):" + getResolvedCatalogURIs());
getLog().info("schemaFiles (calculated):" + getSchemaFiles());
getLog().info("schemaURIs (calculated):" + getSchemaURIs());
getLog().info("resolvedSchemaURIs (calculated):" + getResolvedSchemaURIs());
getLog().info("bindingFiles (calculated):" + getBindingFiles());
getLog().info("bindingURIs (calculated):" + getBindingURIs());
getLog().info("resolvedBindingURIs (calculated):" + getResolvedBindingURIs());
getLog().info("xjcPluginArtifacts (resolved):" + getXjcPluginArtifacts());
getLog().info("xjcPluginFiles (resolved):" + getXjcPluginFiles());
getLog().info("xjcPluginURLs (resolved):" + getXjcPluginURLs());
getLog().info("episodeArtifacts (resolved):" + getEpisodeArtifacts());
getLog().info("episodeFiles (resolved):" + getEpisodeFiles());
getLog().info("dependsURIs (resolved):" + getDependsURIs());
} | [
"protected",
"void",
"logConfiguration",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"super",
".",
"logConfiguration",
"(",
")",
";",
"// TODO clean up\r",
"getLog",
"(",
")",
".",
"info",
"(",
"\"catalogURIs (calculated):\"",
"+",
"getCatalogURIs",
"(",
")",... | Log the configuration settings. Shown when exception thrown or when verbose
is true. | [
"Log",
"the",
"configuration",
"settings",
".",
"Shown",
"when",
"exception",
"thrown",
"or",
"when",
"verbose",
"is",
"true",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java#L774-L791 | train |
highsource/maven-jaxb2-plugin | plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java | RawXJC2Mojo.createCatalogResolver | protected CatalogResolver createCatalogResolver() throws MojoExecutionException {
final CatalogManager catalogManager = new CatalogManager();
catalogManager.setIgnoreMissingProperties(true);
catalogManager.setUseStaticCatalog(false);
// TODO Logging
if (getLog().isDebugEnabled()) {
catalogManager.setVerbosity(Integer.MAX_VALUE);
}
if (getCatalogResolver() == null) {
return new MavenCatalogResolver(catalogManager, this, getLog());
} else {
final String catalogResolverClassName = getCatalogResolver().trim();
return createCatalogResolverByClassName(catalogResolverClassName);
}
} | java | protected CatalogResolver createCatalogResolver() throws MojoExecutionException {
final CatalogManager catalogManager = new CatalogManager();
catalogManager.setIgnoreMissingProperties(true);
catalogManager.setUseStaticCatalog(false);
// TODO Logging
if (getLog().isDebugEnabled()) {
catalogManager.setVerbosity(Integer.MAX_VALUE);
}
if (getCatalogResolver() == null) {
return new MavenCatalogResolver(catalogManager, this, getLog());
} else {
final String catalogResolverClassName = getCatalogResolver().trim();
return createCatalogResolverByClassName(catalogResolverClassName);
}
} | [
"protected",
"CatalogResolver",
"createCatalogResolver",
"(",
")",
"throws",
"MojoExecutionException",
"{",
"final",
"CatalogManager",
"catalogManager",
"=",
"new",
"CatalogManager",
"(",
")",
";",
"catalogManager",
".",
"setIgnoreMissingProperties",
"(",
"true",
")",
"... | Creates an instance of catalog resolver.
@return Instance of the catalog resolver.
@throws MojoExecutionException
If catalog resolver cannot be instantiated. | [
"Creates",
"an",
"instance",
"of",
"catalog",
"resolver",
"."
] | a4d3955be5a8c2a5f6137c0f436798c95ef95176 | https://github.com/highsource/maven-jaxb2-plugin/blob/a4d3955be5a8c2a5f6137c0f436798c95ef95176/plugin-core/src/main/java/org/jvnet/jaxb2/maven2/RawXJC2Mojo.java#L891-L905 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/MeetMeManager.java | MeetMeManager.getOrCreateRoomImpl | MeetMeRoomImpl getOrCreateRoomImpl(String roomNumber)
{
MeetMeRoomImpl room;
boolean created = false;
synchronized (rooms)
{
room = rooms.get(roomNumber);
if (room == null)
{
room = new MeetMeRoomImpl(server, roomNumber);
populateRoom(room);
rooms.put(roomNumber, room);
created = true;
}
}
if (created)
{
logger.debug("Created MeetMeRoom " + roomNumber);
}
return room;
} | java | MeetMeRoomImpl getOrCreateRoomImpl(String roomNumber)
{
MeetMeRoomImpl room;
boolean created = false;
synchronized (rooms)
{
room = rooms.get(roomNumber);
if (room == null)
{
room = new MeetMeRoomImpl(server, roomNumber);
populateRoom(room);
rooms.put(roomNumber, room);
created = true;
}
}
if (created)
{
logger.debug("Created MeetMeRoom " + roomNumber);
}
return room;
} | [
"MeetMeRoomImpl",
"getOrCreateRoomImpl",
"(",
"String",
"roomNumber",
")",
"{",
"MeetMeRoomImpl",
"room",
";",
"boolean",
"created",
"=",
"false",
";",
"synchronized",
"(",
"rooms",
")",
"{",
"room",
"=",
"rooms",
".",
"get",
"(",
"roomNumber",
")",
";",
"if... | Returns the room with the given number or creates a new one if none is
there yet.
@param roomNumber number of the room to get or create.
@return the room with the given number. | [
"Returns",
"the",
"room",
"with",
"the",
"given",
"number",
"or",
"creates",
"a",
"new",
"one",
"if",
"none",
"is",
"there",
"yet",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java#L378-L401 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java | SkypeChatMessageEvent.getDecodedMessage | public String getDecodedMessage()
{
if (message == null)
{
return null;
}
return new String(Base64.base64ToByteArray(message), Charset.forName("UTF-8"));
} | java | public String getDecodedMessage()
{
if (message == null)
{
return null;
}
return new String(Base64.base64ToByteArray(message), Charset.forName("UTF-8"));
} | [
"public",
"String",
"getDecodedMessage",
"(",
")",
"{",
"if",
"(",
"message",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"String",
"(",
"Base64",
".",
"base64ToByteArray",
"(",
"message",
")",
",",
"Charset",
".",
"forName",
"("... | Returns the decoded message.
@return the decoded message. | [
"Returns",
"the",
"decoded",
"message",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java#L111-L118 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java | CallerIDImpl.buildFromComponents | public static CallerID buildFromComponents(final String firstname, final String lastname, final String number)
{
String name = ""; //$NON-NLS-1$
if (firstname != null)
{
name += firstname.trim();
}
if (lastname != null)
{
if (name.length() > 0)
{
name += " "; //$NON-NLS-1$
}
name += lastname.trim();
}
return PBXFactory.getActivePBX().buildCallerID(number, name);
} | java | public static CallerID buildFromComponents(final String firstname, final String lastname, final String number)
{
String name = ""; //$NON-NLS-1$
if (firstname != null)
{
name += firstname.trim();
}
if (lastname != null)
{
if (name.length() > 0)
{
name += " "; //$NON-NLS-1$
}
name += lastname.trim();
}
return PBXFactory.getActivePBX().buildCallerID(number, name);
} | [
"public",
"static",
"CallerID",
"buildFromComponents",
"(",
"final",
"String",
"firstname",
",",
"final",
"String",
"lastname",
",",
"final",
"String",
"number",
")",
"{",
"String",
"name",
"=",
"\"\"",
";",
"//$NON-NLS-1$",
"if",
"(",
"firstname",
"!=",
"null... | This is a little helper class which will buid the name component of a
clid from the first and lastnames. If both firstname and lastname are
null then the name component will be an empty string.
@param firstname the person's firstname, may be null.
@param lastname the person's lastname, may be null
@param number the phone number.
@return | [
"This",
"is",
"a",
"little",
"helper",
"class",
"which",
"will",
"buid",
"the",
"name",
"component",
"of",
"a",
"clid",
"from",
"the",
"first",
"and",
"lastnames",
".",
"If",
"both",
"firstname",
"and",
"lastname",
"are",
"null",
"then",
"the",
"name",
"... | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java#L46-L64 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.idChanged | void idChanged(Date date, String id)
{
final String oldId = this.id;
if (oldId != null && oldId.equals(id))
{
return;
}
this.id = id;
firePropertyChange(PROPERTY_ID, oldId, id);
} | java | void idChanged(Date date, String id)
{
final String oldId = this.id;
if (oldId != null && oldId.equals(id))
{
return;
}
this.id = id;
firePropertyChange(PROPERTY_ID, oldId, id);
} | [
"void",
"idChanged",
"(",
"Date",
"date",
",",
"String",
"id",
")",
"{",
"final",
"String",
"oldId",
"=",
"this",
".",
"id",
";",
"if",
"(",
"oldId",
"!=",
"null",
"&&",
"oldId",
".",
"equals",
"(",
"id",
")",
")",
"{",
"return",
";",
"}",
"this"... | Changes the id of this channel.
@param date date of the name change.
@param id the new unique id of this channel. | [
"Changes",
"the",
"id",
"of",
"this",
"channel",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L205-L216 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.nameChanged | void nameChanged(Date date, String name)
{
final String oldName = this.name;
if (oldName != null && oldName.equals(name))
{
return;
}
this.name = name;
firePropertyChange(PROPERTY_NAME, oldName, name);
} | java | void nameChanged(Date date, String name)
{
final String oldName = this.name;
if (oldName != null && oldName.equals(name))
{
return;
}
this.name = name;
firePropertyChange(PROPERTY_NAME, oldName, name);
} | [
"void",
"nameChanged",
"(",
"Date",
"date",
",",
"String",
"name",
")",
"{",
"final",
"String",
"oldName",
"=",
"this",
".",
"name",
";",
"if",
"(",
"oldName",
"!=",
"null",
"&&",
"oldName",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
";",
... | Changes the name of this channel.
@param date date of the name change.
@param name the new name of this channel. | [
"Changes",
"the",
"name",
"of",
"this",
"channel",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L239-L250 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.setCallerId | void setCallerId(final CallerId callerId)
{
final CallerId oldCallerId = this.callerId;
this.callerId = callerId;
firePropertyChange(PROPERTY_CALLER_ID, oldCallerId, callerId);
} | java | void setCallerId(final CallerId callerId)
{
final CallerId oldCallerId = this.callerId;
this.callerId = callerId;
firePropertyChange(PROPERTY_CALLER_ID, oldCallerId, callerId);
} | [
"void",
"setCallerId",
"(",
"final",
"CallerId",
"callerId",
")",
"{",
"final",
"CallerId",
"oldCallerId",
"=",
"this",
".",
"callerId",
";",
"this",
".",
"callerId",
"=",
"callerId",
";",
"firePropertyChange",
"(",
"PROPERTY_CALLER_ID",
",",
"oldCallerId",
",",... | Sets the caller id of this channel.
@param callerId the caller id of this channel. | [
"Sets",
"the",
"caller",
"id",
"of",
"this",
"channel",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L262-L268 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.stateChanged | synchronized void stateChanged(Date date, ChannelState state)
{
final ChannelStateHistoryEntry historyEntry;
final ChannelState oldState = this.state;
if (oldState == state)
{
return;
}
// System.err.println(id + " state change: " + oldState + " => " + state
// + " (" + name + ")");
historyEntry = new ChannelStateHistoryEntry(date, state);
synchronized (stateHistory)
{
stateHistory.add(historyEntry);
}
this.state = state;
firePropertyChange(PROPERTY_STATE, oldState, state);
} | java | synchronized void stateChanged(Date date, ChannelState state)
{
final ChannelStateHistoryEntry historyEntry;
final ChannelState oldState = this.state;
if (oldState == state)
{
return;
}
// System.err.println(id + " state change: " + oldState + " => " + state
// + " (" + name + ")");
historyEntry = new ChannelStateHistoryEntry(date, state);
synchronized (stateHistory)
{
stateHistory.add(historyEntry);
}
this.state = state;
firePropertyChange(PROPERTY_STATE, oldState, state);
} | [
"synchronized",
"void",
"stateChanged",
"(",
"Date",
"date",
",",
"ChannelState",
"state",
")",
"{",
"final",
"ChannelStateHistoryEntry",
"historyEntry",
";",
"final",
"ChannelState",
"oldState",
"=",
"this",
".",
"state",
";",
"if",
"(",
"oldState",
"==",
"stat... | Changes the state of this channel.
@param date when the state change occurred.
@param state the new state of this channel. | [
"Changes",
"the",
"state",
"of",
"this",
"channel",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L303-L323 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.setAccount | void setAccount(String account)
{
final String oldAccount = this.account;
this.account = account;
firePropertyChange(PROPERTY_ACCOUNT, oldAccount, account);
} | java | void setAccount(String account)
{
final String oldAccount = this.account;
this.account = account;
firePropertyChange(PROPERTY_ACCOUNT, oldAccount, account);
} | [
"void",
"setAccount",
"(",
"String",
"account",
")",
"{",
"final",
"String",
"oldAccount",
"=",
"this",
".",
"account",
";",
"this",
".",
"account",
"=",
"account",
";",
"firePropertyChange",
"(",
"PROPERTY_ACCOUNT",
",",
"oldAccount",
",",
"account",
")",
"... | Sets the account code used to bill this channel.
@param account the account code used to bill this channel. | [
"Sets",
"the",
"account",
"code",
"used",
"to",
"bill",
"this",
"channel",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L335-L341 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.extensionVisited | void extensionVisited(Date date, Extension extension)
{
final Extension oldCurrentExtension = getCurrentExtension();
final ExtensionHistoryEntry historyEntry;
historyEntry = new ExtensionHistoryEntry(date, extension);
synchronized (extensionHistory)
{
extensionHistory.add(historyEntry);
}
firePropertyChange(PROPERTY_CURRENT_EXTENSION, oldCurrentExtension, extension);
} | java | void extensionVisited(Date date, Extension extension)
{
final Extension oldCurrentExtension = getCurrentExtension();
final ExtensionHistoryEntry historyEntry;
historyEntry = new ExtensionHistoryEntry(date, extension);
synchronized (extensionHistory)
{
extensionHistory.add(historyEntry);
}
firePropertyChange(PROPERTY_CURRENT_EXTENSION, oldCurrentExtension, extension);
} | [
"void",
"extensionVisited",
"(",
"Date",
"date",
",",
"Extension",
"extension",
")",
"{",
"final",
"Extension",
"oldCurrentExtension",
"=",
"getCurrentExtension",
"(",
")",
";",
"final",
"ExtensionHistoryEntry",
"historyEntry",
";",
"historyEntry",
"=",
"new",
"Exte... | Adds a visted dialplan entry to the history.
@param date the date the extension has been visited.
@param extension the visted dialplan entry to add. | [
"Adds",
"a",
"visted",
"dialplan",
"entry",
"to",
"the",
"history",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L399-L412 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.getDialedChannels | public List<AsteriskChannel> getDialedChannels()
{
final List<AsteriskChannel> copy;
synchronized (dialedChannels)
{
copy = new ArrayList<>(dialedChannels);
}
return copy;
} | java | public List<AsteriskChannel> getDialedChannels()
{
final List<AsteriskChannel> copy;
synchronized (dialedChannels)
{
copy = new ArrayList<>(dialedChannels);
}
return copy;
} | [
"public",
"List",
"<",
"AsteriskChannel",
">",
"getDialedChannels",
"(",
")",
"{",
"final",
"List",
"<",
"AsteriskChannel",
">",
"copy",
";",
"synchronized",
"(",
"dialedChannels",
")",
"{",
"copy",
"=",
"new",
"ArrayList",
"<>",
"(",
"dialedChannels",
")",
... | Retrives the conplete List of all dialed channels associated to ths calls
@return List of all dialed channels | [
"Retrives",
"the",
"conplete",
"List",
"of",
"all",
"dialed",
"channels",
"associated",
"to",
"ths",
"calls"
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L469-L479 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java | AsteriskChannelImpl.channelLinked | synchronized void channelLinked(Date date, AsteriskChannel linkedChannel)
{
final AsteriskChannel oldLinkedChannel;
synchronized (this.linkedChannels)
{
if (this.linkedChannels.isEmpty())
{
oldLinkedChannel = null;
this.linkedChannels.add(linkedChannel);
}
else
{
oldLinkedChannel = this.linkedChannels.get(0);
this.linkedChannels.set(0, linkedChannel);
}
}
final LinkedChannelHistoryEntry historyEntry;
historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel);
synchronized (linkedChannelHistory)
{
linkedChannelHistory.add(historyEntry);
}
this.wasLinked = true;
firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel);
} | java | synchronized void channelLinked(Date date, AsteriskChannel linkedChannel)
{
final AsteriskChannel oldLinkedChannel;
synchronized (this.linkedChannels)
{
if (this.linkedChannels.isEmpty())
{
oldLinkedChannel = null;
this.linkedChannels.add(linkedChannel);
}
else
{
oldLinkedChannel = this.linkedChannels.get(0);
this.linkedChannels.set(0, linkedChannel);
}
}
final LinkedChannelHistoryEntry historyEntry;
historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel);
synchronized (linkedChannelHistory)
{
linkedChannelHistory.add(historyEntry);
}
this.wasLinked = true;
firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel);
} | [
"synchronized",
"void",
"channelLinked",
"(",
"Date",
"date",
",",
"AsteriskChannel",
"linkedChannel",
")",
"{",
"final",
"AsteriskChannel",
"oldLinkedChannel",
";",
"synchronized",
"(",
"this",
".",
"linkedChannels",
")",
"{",
"if",
"(",
"this",
".",
"linkedChann... | Sets the channel this channel is bridged with.
@param date the date this channel was linked.
@param linkedChannel the channel this channel is bridged with. | [
"Sets",
"the",
"channel",
"this",
"channel",
"is",
"bridged",
"with",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java#L597-L623 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java | ManagerConnectionImpl.determineVersionByCoreSettings | protected AsteriskVersion determineVersionByCoreSettings() throws Exception
{
ManagerResponse response = sendAction(new CoreSettingsAction());
if (!(response instanceof CoreSettingsResponse))
{
// NOTE: you need system or reporting permissions
logger.info("Could not get core settings, do we have the necessary permissions?");
return null;
}
String ver = ((CoreSettingsResponse) response).getAsteriskVersion();
return AsteriskVersion.getDetermineVersionFromString("Asterisk " + ver);
} | java | protected AsteriskVersion determineVersionByCoreSettings() throws Exception
{
ManagerResponse response = sendAction(new CoreSettingsAction());
if (!(response instanceof CoreSettingsResponse))
{
// NOTE: you need system or reporting permissions
logger.info("Could not get core settings, do we have the necessary permissions?");
return null;
}
String ver = ((CoreSettingsResponse) response).getAsteriskVersion();
return AsteriskVersion.getDetermineVersionFromString("Asterisk " + ver);
} | [
"protected",
"AsteriskVersion",
"determineVersionByCoreSettings",
"(",
")",
"throws",
"Exception",
"{",
"ManagerResponse",
"response",
"=",
"sendAction",
"(",
"new",
"CoreSettingsAction",
"(",
")",
")",
";",
"if",
"(",
"!",
"(",
"response",
"instanceof",
"CoreSettin... | Get asterisk version by 'core settings' actions. This is supported from
Asterisk 1.6 onwards.
@return
@throws Exception | [
"Get",
"asterisk",
"version",
"by",
"core",
"settings",
"actions",
".",
"This",
"is",
"supported",
"from",
"Asterisk",
"1",
".",
"6",
"onwards",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java#L675-L688 | train |
asterisk-java/asterisk-java | src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java | ManagerConnectionImpl.determineVersionByCoreShowVersion | protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception
{
final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction(CMD_SHOW_VERSION));
if (coreShowVersionResponse == null || !(coreShowVersionResponse instanceof CommandResponse))
{
// this needs 'command' permissions
logger.info("Could not get response for 'core show version'");
return null;
}
final List<String> coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult();
if (coreShowVersionResult == null || coreShowVersionResult.isEmpty())
{
logger.warn("Got empty response for 'core show version'");
return null;
}
final String coreLine = coreShowVersionResult.get(0);
return AsteriskVersion.getDetermineVersionFromString(coreLine);
} | java | protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception
{
final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction(CMD_SHOW_VERSION));
if (coreShowVersionResponse == null || !(coreShowVersionResponse instanceof CommandResponse))
{
// this needs 'command' permissions
logger.info("Could not get response for 'core show version'");
return null;
}
final List<String> coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult();
if (coreShowVersionResult == null || coreShowVersionResult.isEmpty())
{
logger.warn("Got empty response for 'core show version'");
return null;
}
final String coreLine = coreShowVersionResult.get(0);
return AsteriskVersion.getDetermineVersionFromString(coreLine);
} | [
"protected",
"AsteriskVersion",
"determineVersionByCoreShowVersion",
"(",
")",
"throws",
"Exception",
"{",
"final",
"ManagerResponse",
"coreShowVersionResponse",
"=",
"sendAction",
"(",
"new",
"CommandAction",
"(",
"CMD_SHOW_VERSION",
")",
")",
";",
"if",
"(",
"coreShow... | Determine version by the 'core show version' command. This needs
'command' permissions.
@return
@throws Exception | [
"Determine",
"version",
"by",
"the",
"core",
"show",
"version",
"command",
".",
"This",
"needs",
"command",
"permissions",
"."
] | cdc9849270d97ef75afa447a02c5194ed29121eb | https://github.com/asterisk-java/asterisk-java/blob/cdc9849270d97ef75afa447a02c5194ed29121eb/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java#L697-L717 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.