_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q3700
StatementExecutor.queryForLong
train
public long queryForLong(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt) throws SQLException { CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT_LONG); DatabaseResults results = null; try { results = compiledStatement.runQuery(null); if (results.first()) { return results.getLong(0); } else { throw new SQLException("No result found in queryForLong: " + preparedStmt.getStatement()); } } finally { IOUtils.closeThrowSqlException(results, "results"); IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } }
java
{ "resource": "" }
q3701
StatementExecutor.buildIterator
train
public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource, int resultFlags, ObjectCache objectCache) throws SQLException { prepareQueryForAll(); return buildIterator(classDao, connectionSource, preparedQueryForAll, objectCache, resultFlags); }
java
{ "resource": "" }
q3702
StatementExecutor.updateRaw
train
public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException { logger.debug("running raw update statement: {}", statement); if (arguments.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("update arguments: {}", (Object) arguments); } CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS, false); try { assignStatementArguments(compiledStatement, arguments); return compiledStatement.runUpdate(); } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } }
java
{ "resource": "" }
q3703
StatementExecutor.create
train
public int create(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedInsert == null) { mappedInsert = MappedCreate.build(dao, tableInfo); } int result = mappedInsert.insert(databaseType, databaseConnection, data, objectCache); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; }
java
{ "resource": "" }
q3704
StatementExecutor.updateId
train
public int updateId(DatabaseConnection databaseConnection, T data, ID newId, ObjectCache objectCache) throws SQLException { if (mappedUpdateId == null) { mappedUpdateId = MappedUpdateId.build(dao, tableInfo); } int result = mappedUpdateId.execute(databaseConnection, data, newId, objectCache); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; }
java
{ "resource": "" }
q3705
StatementExecutor.update
train
public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException { CompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE); try { int result = compiledStatement.runUpdate(); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } }
java
{ "resource": "" }
q3706
StatementExecutor.refresh
train
public int refresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedRefresh == null) { mappedRefresh = MappedRefresh.build(dao, tableInfo); } return mappedRefresh.executeRefresh(databaseConnection, data, objectCache); }
java
{ "resource": "" }
q3707
StatementExecutor.delete
train
public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { if (mappedDelete == null) { mappedDelete = MappedDelete.build(dao, tableInfo); } int result = mappedDelete.delete(databaseConnection, data, objectCache); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; }
java
{ "resource": "" }
q3708
StatementExecutor.deleteById
train
public int deleteById(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException { if (mappedDelete == null) { mappedDelete = MappedDelete.build(dao, tableInfo); } int result = mappedDelete.deleteById(databaseConnection, id, objectCache); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; }
java
{ "resource": "" }
q3709
StatementExecutor.delete
train
public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException { CompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE); try { int result = compiledStatement.runUpdate(); if (dao != null && !localIsInBatchMode.get()) { dao.notifyChanges(); } return result; } finally { IOUtils.closeThrowSqlException(compiledStatement, "compiled statement"); } }
java
{ "resource": "" }
q3710
StatementExecutor.callBatchTasks
train
public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException { if (connectionSource.isSingleConnection(tableInfo.getTableName())) { synchronized (this) { return doCallBatchTasks(connectionSource, callable); } } else { return doCallBatchTasks(connectionSource, callable); } }
java
{ "resource": "" }
q3711
SqlExceptionUtil.create
train
public static SQLException create(String message, Throwable cause) { SQLException sqlException; if (cause instanceof SQLException) { // if the cause is another SQLException, pass alot of the SQL state sqlException = new SQLException(message, ((SQLException) cause).getSQLState()); } else { sqlException = new SQLException(message); } sqlException.initCause(cause); return sqlException; }
java
{ "resource": "" }
q3712
BaseDaoImpl.initialize
train
public void initialize() throws SQLException { if (initialized) { // just skip it if already initialized return; } if (connectionSource == null) { throw new IllegalStateException("connectionSource was never set on " + getClass().getSimpleName()); } databaseType = connectionSource.getDatabaseType(); if (databaseType == null) { throw new IllegalStateException( "connectionSource is getting a null DatabaseType in " + getClass().getSimpleName()); } if (tableConfig == null) { tableInfo = new TableInfo<T, ID>(databaseType, dataClass); } else { tableConfig.extractFieldTypes(databaseType); tableInfo = new TableInfo<T, ID>(databaseType, tableConfig); } statementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this); /* * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the * system to go recursive and for class loops, a stack overflow. * * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations * when we reach some recursion level. But this created some bad problems because we were using the DaoManager * to cache the created DAOs that had been constructed already limited by the level. * * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized * here, we have to see if it is the top DAO. If not we save it for dao configuration later. */ List<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get(); daoConfigList.add(this); if (daoConfigList.size() > 1) { // if we have recursed then just save the dao for later configuration return; } try { /* * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient. * * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger * one during the recursion. */ for (int i = 0; i < daoConfigList.size(); i++) { BaseDaoImpl<?, ?> dao = daoConfigList.get(i); /* * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet * in the DaoManager cache. If we continue onward we might come back around and try to configure this * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also * applies to self-referencing classes. */ DaoManager.registerDao(connectionSource, dao); try { // config our fields which may go recursive for (FieldType fieldType : dao.getTableInfo().getFieldTypes()) { fieldType.configDaoInformation(connectionSource, dao.getDataClass()); } } catch (SQLException e) { // unregister the DAO we just pre-registered DaoManager.unregisterDao(connectionSource, dao); throw e; } // it's now been fully initialized dao.initialized = true; } } finally { // if we throw we want to clear our class hierarchy here daoConfigList.clear(); daoConfigLevelLocal.remove(); } }
java
{ "resource": "" }
q3713
BaseDaoImpl.createDao
train
static <T, ID> Dao<T, ID> createDao(ConnectionSource connectionSource, Class<T> clazz) throws SQLException { return new BaseDaoImpl<T, ID>(connectionSource, clazz) { }; }
java
{ "resource": "" }
q3714
BaseDaoImpl.findNoArgConstructor
train
private Constructor<T> findNoArgConstructor(Class<T> dataClass) { Constructor<T>[] constructors; try { @SuppressWarnings("unchecked") Constructor<T>[] consts = (Constructor<T>[]) dataClass.getDeclaredConstructors(); // i do this [grossness] to be able to move the Suppress inside the method constructors = consts; } catch (Exception e) { throw new IllegalArgumentException("Can't lookup declared constructors for " + dataClass, e); } for (Constructor<T> con : constructors) { if (con.getParameterTypes().length == 0) { if (!con.isAccessible()) { try { con.setAccessible(true); } catch (SecurityException e) { throw new IllegalArgumentException("Could not open access to constructor for " + dataClass); } } return con; } } if (dataClass.getEnclosingClass() == null) { throw new IllegalArgumentException("Can't find a no-arg constructor for " + dataClass); } else { throw new IllegalArgumentException( "Can't find a no-arg constructor for " + dataClass + ". Missing static on inner class?"); } }
java
{ "resource": "" }
q3715
DatabaseFieldConfig.findGetMethod
train
public static Method findGetMethod(Field field, DatabaseType databaseType, boolean throwExceptions) throws IllegalArgumentException { Method fieldGetMethod = findMethodFromNames(field, true, throwExceptions, methodFromField(field, "get", databaseType, true), methodFromField(field, "get", databaseType, false), methodFromField(field, "is", databaseType, true), methodFromField(field, "is", databaseType, false)); if (fieldGetMethod == null) { return null; } if (fieldGetMethod.getReturnType() != field.getType()) { if (throwExceptions) { throw new IllegalArgumentException("Return type of get method " + fieldGetMethod.getName() + " does not return " + field.getType()); } else { return null; } } return fieldGetMethod; }
java
{ "resource": "" }
q3716
DatabaseFieldConfig.findSetMethod
train
public static Method findSetMethod(Field field, DatabaseType databaseType, boolean throwExceptions) throws IllegalArgumentException { Method fieldSetMethod = findMethodFromNames(field, false, throwExceptions, methodFromField(field, "set", databaseType, true), methodFromField(field, "set", databaseType, false)); if (fieldSetMethod == null) { return null; } if (fieldSetMethod.getReturnType() != void.class) { if (throwExceptions) { throw new IllegalArgumentException("Return type of set method " + fieldSetMethod.getName() + " returns " + fieldSetMethod.getReturnType() + " instead of void"); } else { return null; } } return fieldSetMethod; }
java
{ "resource": "" }
q3717
DatabaseFieldConfig.postProcess
train
public void postProcess() { if (foreignColumnName != null) { foreignAutoRefresh = true; } if (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) { maxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL; } }
java
{ "resource": "" }
q3718
DatabaseFieldConfig.findMatchingEnumVal
train
public static Enum<?> findMatchingEnumVal(Field field, String unknownEnumName) { if (unknownEnumName == null || unknownEnumName.length() == 0) { return null; } for (Enum<?> enumVal : (Enum<?>[]) field.getType().getEnumConstants()) { if (enumVal.name().equals(unknownEnumName)) { return enumVal; } } throw new IllegalArgumentException("Unknwown enum unknown name " + unknownEnumName + " for field " + field); }
java
{ "resource": "" }
q3719
MappedRefresh.executeRefresh
train
public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { @SuppressWarnings("unchecked") ID id = (ID) idField.extractJavaFieldValue(data); // we don't care about the cache here T result = super.execute(databaseConnection, id, null); if (result == null) { return 0; } // copy each field from the result into the passed in object for (FieldType fieldType : resultsFieldTypes) { if (fieldType != idField) { fieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false, objectCache); } } return 1; }
java
{ "resource": "" }
q3720
QueryBuilder.selectColumns
train
public QueryBuilder<T, ID> selectColumns(String... columns) { for (String column : columns) { addSelectColumnToList(column); } return this; }
java
{ "resource": "" }
q3721
QueryBuilder.groupBy
train
public QueryBuilder<T, ID> groupBy(String columnName) { FieldType fieldType = verifyColumnName(columnName); if (fieldType.isForeignCollection()) { throw new IllegalArgumentException("Can't groupBy foreign collection field: " + columnName); } addGroupBy(ColumnNameOrRawSql.withColumnName(columnName)); return this; }
java
{ "resource": "" }
q3722
QueryBuilder.groupByRaw
train
public QueryBuilder<T, ID> groupByRaw(String rawSql) { addGroupBy(ColumnNameOrRawSql.withRawSql(rawSql)); return this; }
java
{ "resource": "" }
q3723
QueryBuilder.orderBy
train
public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) { FieldType fieldType = verifyColumnName(columnName); if (fieldType.isForeignCollection()) { throw new IllegalArgumentException("Can't orderBy foreign collection field: " + columnName); } addOrderBy(new OrderBy(columnName, ascending)); return this; }
java
{ "resource": "" }
q3724
QueryBuilder.orderByRaw
train
public QueryBuilder<T, ID> orderByRaw(String rawSql) { addOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null)); return this; }
java
{ "resource": "" }
q3725
QueryBuilder.join
train
public QueryBuilder<T, ID> join(QueryBuilder<?, ?> joinedQueryBuilder) throws SQLException { addJoinInfo(JoinType.INNER, null, null, joinedQueryBuilder, JoinWhereOperation.AND); return this; }
java
{ "resource": "" }
q3726
QueryBuilder.addJoinInfo
train
private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName, QueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException { JoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation); if (localColumnName == null) { matchJoinedFields(joinInfo, joinedQueryBuilder); } else { matchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder); } if (joinList == null) { joinList = new ArrayList<JoinInfo>(); } joinList.add(joinInfo); }
java
{ "resource": "" }
q3727
TableInfo.objectToString
train
public String objectToString(T object) { StringBuilder sb = new StringBuilder(64); sb.append(object.getClass().getSimpleName()); for (FieldType fieldType : fieldTypes) { sb.append(' ').append(fieldType.getColumnName()).append('='); try { sb.append(fieldType.extractJavaFieldValue(object)); } catch (Exception e) { throw new IllegalStateException("Could not generate toString of field " + fieldType, e); } } return sb.toString(); }
java
{ "resource": "" }
q3728
VersionUtils.logVersionWarnings
train
private static void logVersionWarnings(String label1, String version1, String label2, String version2) { if (version1 == null) { if (version2 != null) { warning(null, "Unknown version", " for {}, version for {} is '{}'", new Object[] { label1, label2, version2 }); } } else { if (version2 == null) { warning(null, "Unknown version", " for {}, version for {} is '{}'", new Object[] { label2, label1, version1 }); } else if (!version1.equals(version2)) { warning(null, "Mismatched versions", ": {} is '{}', while {} is '{}'", new Object[] { label1, version1, label2, version2 }); } } }
java
{ "resource": "" }
q3729
StatementBuilder.prepareStatement
train
protected MappedPreparedStmt<T, ID> prepareStatement(Long limit, boolean cacheStore) throws SQLException { List<ArgumentHolder> argList = new ArrayList<ArgumentHolder>(); String statement = buildStatementString(argList); ArgumentHolder[] selectArgs = argList.toArray(new ArgumentHolder[argList.size()]); FieldType[] resultFieldTypes = getResultFieldTypes(); FieldType[] argFieldTypes = new FieldType[argList.size()]; for (int selectC = 0; selectC < selectArgs.length; selectC++) { argFieldTypes[selectC] = selectArgs[selectC].getFieldType(); } if (!type.isOkForStatementBuilder()) { throw new IllegalStateException("Building a statement from a " + type + " statement is not allowed"); } return new MappedPreparedStmt<T, ID>(dao, tableInfo, statement, argFieldTypes, resultFieldTypes, selectArgs, (databaseType.isLimitSqlSupported() ? null : limit), type, cacheStore); }
java
{ "resource": "" }
q3730
StatementBuilder.prepareStatementString
train
public String prepareStatementString() throws SQLException { List<ArgumentHolder> argList = new ArrayList<ArgumentHolder>(); return buildStatementString(argList); }
java
{ "resource": "" }
q3731
StatementBuilder.appendWhereStatement
train
protected boolean appendWhereStatement(StringBuilder sb, List<ArgumentHolder> argList, WhereOperation operation) throws SQLException { if (where == null) { return operation == WhereOperation.FIRST; } operation.appendBefore(sb); where.appendSql((addTableName ? getTableName() : null), sb, argList); operation.appendAfter(sb); return false; }
java
{ "resource": "" }
q3732
MappedDeleteCollection.build
train
private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize) throws SQLException { FieldType idField = tableInfo.getIdField(); if (idField == null) { throw new SQLException( "Cannot delete " + tableInfo.getDataClass() + " because it doesn't have an id field defined"); } StringBuilder sb = new StringBuilder(128); DatabaseType databaseType = dao.getConnectionSource().getDatabaseType(); appendTableName(databaseType, sb, "DELETE FROM ", tableInfo.getTableName()); FieldType[] argFieldTypes = new FieldType[dataSize]; appendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes); return new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes); }
java
{ "resource": "" }
q3733
SelectIterator.next
train
@Override public T next() { SQLException sqlException = null; try { T result = nextThrow(); if (result != null) { return result; } } catch (SQLException e) { sqlException = e; } // we have to throw if there is no next or on a SQLException last = null; closeQuietly(); throw new IllegalStateException("Could not get next result for " + dataClass, sqlException); }
java
{ "resource": "" }
q3734
TableUtils.createTable
train
public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass); return doCreateTable(dao, false); }
java
{ "resource": "" }
q3735
TableUtils.createTable
train
public static <T> int createTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, tableConfig); return doCreateTable(dao, false); }
java
{ "resource": "" }
q3736
TableUtils.dropTable
train
public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dropTable(dao, ignoreErrors); }
java
{ "resource": "" }
q3737
TableUtils.dropTable
train
public static <T, ID> int dropTable(Dao<T, ID> dao, boolean ignoreErrors) throws SQLException { ConnectionSource connectionSource = dao.getConnectionSource(); Class<T> dataClass = dao.getDataClass(); DatabaseType databaseType = connectionSource.getDatabaseType(); if (dao instanceof BaseDaoImpl<?, ?>) { return doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors); } else { TableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, dataClass); return doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors); } }
java
{ "resource": "" }
q3738
TableUtils.dropTable
train
public static <T, ID> int dropTable(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig, boolean ignoreErrors) throws SQLException { DatabaseType databaseType = connectionSource.getDatabaseType(); Dao<T, ID> dao = DaoManager.createDao(connectionSource, tableConfig); if (dao instanceof BaseDaoImpl<?, ?>) { return doDropTable(databaseType, connectionSource, ((BaseDaoImpl<?, ?>) dao).getTableInfo(), ignoreErrors); } else { tableConfig.extractFieldTypes(databaseType); TableInfo<T, ID> tableInfo = new TableInfo<T, ID>(databaseType, tableConfig); return doDropTable(databaseType, connectionSource, tableInfo, ignoreErrors); } }
java
{ "resource": "" }
q3739
TableUtils.addDropTableStatements
train
private static <T, ID> void addDropTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo, List<String> statements, boolean logDetails) { List<String> statementsBefore = new ArrayList<String>(); List<String> statementsAfter = new ArrayList<String>(); for (FieldType fieldType : tableInfo.getFieldTypes()) { databaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter); } StringBuilder sb = new StringBuilder(64); if (logDetails) { logger.info("dropping table '{}'", tableInfo.getTableName()); } sb.append("DROP TABLE "); databaseType.appendEscapedEntityName(sb, tableInfo.getTableName()); sb.append(' '); statements.addAll(statementsBefore); statements.add(sb.toString()); statements.addAll(statementsAfter); }
java
{ "resource": "" }
q3740
TableUtils.addCreateTableStatements
train
private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo, List<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails) throws SQLException { StringBuilder sb = new StringBuilder(256); if (logDetails) { logger.info("creating table '{}'", tableInfo.getTableName()); } sb.append("CREATE TABLE "); if (ifNotExists && databaseType.isCreateIfNotExistsSupported()) { sb.append("IF NOT EXISTS "); } databaseType.appendEscapedEntityName(sb, tableInfo.getTableName()); sb.append(" ("); List<String> additionalArgs = new ArrayList<String>(); List<String> statementsBefore = new ArrayList<String>(); List<String> statementsAfter = new ArrayList<String>(); // our statement will be set here later boolean first = true; for (FieldType fieldType : tableInfo.getFieldTypes()) { // skip foreign collections if (fieldType.isForeignCollection()) { continue; } else if (first) { first = false; } else { sb.append(", "); } String columnDefinition = fieldType.getColumnDefinition(); if (columnDefinition == null) { // we have to call back to the database type for the specific create syntax databaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore, statementsAfter, queriesAfter); } else { // hand defined field databaseType.appendEscapedEntityName(sb, fieldType.getColumnName()); sb.append(' ').append(columnDefinition).append(' '); } } // add any sql that sets any primary key fields databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter, queriesAfter); // add any sql that sets any unique fields databaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter, queriesAfter); for (String arg : additionalArgs) { // we will have spat out one argument already so we don't have to do the first dance sb.append(", ").append(arg); } sb.append(") "); databaseType.appendCreateTableSuffix(sb); statements.addAll(statementsBefore); statements.add(sb.toString()); statements.addAll(statementsAfter); addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails); addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails); }
java
{ "resource": "" }
q3741
FieldType.assignField
train
public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject, ObjectCache objectCache) throws SQLException { if (logger.isLevelEnabled(Level.TRACE)) { logger.trace("assiging from data {}, val {}: {}", (data == null ? "null" : data.getClass()), (val == null ? "null" : val.getClass()), val); } // if this is a foreign object then val is the foreign object's id val if (foreignRefField != null && val != null) { // get the current field value which is the foreign-id Object foreignRef = extractJavaFieldValue(data); /* * See if we don't need to create a new foreign object. If we are refreshing and the id field has not * changed then there is no need to create a new foreign object and maybe lose previously refreshed field * information. */ if (foreignRef != null && foreignRef.equals(val)) { return; } // awhitlock: raised as OrmLite issue: bug #122 Object cachedVal; ObjectCache foreignCache = foreignDao.getObjectCache(); if (foreignCache == null) { cachedVal = null; } else { cachedVal = foreignCache.get(getType(), val); } if (cachedVal != null) { val = cachedVal; } else if (!parentObject) { // the value we are to assign to our field is now the foreign object itself val = createForeignObject(connectionSource, val, objectCache); } } if (fieldSetMethod == null) { try { field.set(data, val); } catch (IllegalArgumentException e) { if (val == null) { throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e); } else { throw SqlExceptionUtil.create( "Could not assign object '" + val + "' of type " + val.getClass() + " to field " + this, e); } } catch (IllegalAccessException e) { throw SqlExceptionUtil.create( "Could not assign object '" + val + "' of type " + val.getClass() + "' to field " + this, e); } } else { try { fieldSetMethod.invoke(data, val); } catch (Exception e) { throw SqlExceptionUtil .create("Could not call " + fieldSetMethod + " on object with '" + val + "' for " + this, e); } } }
java
{ "resource": "" }
q3742
FieldType.assignIdValue
train
public Object assignIdValue(ConnectionSource connectionSource, Object data, Number val, ObjectCache objectCache) throws SQLException { Object idVal = dataPersister.convertIdNumber(val); if (idVal == null) { throw new SQLException("Invalid class " + dataPersister + " for sequence-id " + this); } else { assignField(connectionSource, data, idVal, false, objectCache); return idVal; } }
java
{ "resource": "" }
q3743
FieldType.extractRawJavaFieldValue
train
public <FV> FV extractRawJavaFieldValue(Object object) throws SQLException { Object val; if (fieldGetMethod == null) { try { // field object may not be a T yet val = field.get(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not get field value for " + this, e); } } else { try { val = fieldGetMethod.invoke(object); } catch (Exception e) { throw SqlExceptionUtil.create("Could not call " + fieldGetMethod + " for " + this, e); } } @SuppressWarnings("unchecked") FV converted = (FV) val; return converted; }
java
{ "resource": "" }
q3744
FieldType.extractJavaFieldValue
train
public Object extractJavaFieldValue(Object object) throws SQLException { Object val = extractRawJavaFieldValue(object); // if this is a foreign object then we want its reference field if (foreignRefField != null && val != null) { val = foreignRefField.extractRawJavaFieldValue(val); } return val; }
java
{ "resource": "" }
q3745
FieldType.convertJavaFieldToSqlArgValue
train
public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException { /* * Limitation here. Some people may want to override the null with their own value in the converter but we * currently don't allow that. Specifying a default value I guess is a better mechanism. */ if (fieldVal == null) { return null; } else { return fieldConverter.javaToSqlArg(this, fieldVal); } }
java
{ "resource": "" }
q3746
FieldType.convertStringToJavaField
train
public Object convertStringToJavaField(String value, int columnPos) throws SQLException { if (value == null) { return null; } else { return fieldConverter.resultStringToJava(this, value, columnPos); } }
java
{ "resource": "" }
q3747
FieldType.moveToNextValue
train
public Object moveToNextValue(Object val) throws SQLException { if (dataPersister == null) { return null; } else { return dataPersister.moveToNextValue(val); } }
java
{ "resource": "" }
q3748
FieldType.buildForeignCollection
train
public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException { // this can happen if we have a foreign-auto-refresh scenario if (foreignFieldType == null) { return null; } @SuppressWarnings("unchecked") Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao; if (!fieldConfig.isForeignCollectionEager()) { // we know this won't go recursive so no need for the counters return new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType, fieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending()); } // try not to create level counter objects unless we have to LevelCounters levelCounters = threadLevelCounters.get(); if (levelCounters == null) { if (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) { // then return a lazy collection instead return new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType, fieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending()); } levelCounters = new LevelCounters(); threadLevelCounters.set(levelCounters); } if (levelCounters.foreignCollectionLevel == 0) { levelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel(); } // are we over our level limit? if (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) { // then return a lazy collection instead return new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType, fieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending()); } levelCounters.foreignCollectionLevel++; try { return new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType, fieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending()); } finally { levelCounters.foreignCollectionLevel--; } }
java
{ "resource": "" }
q3749
FieldType.getFieldValueIfNotDefault
train
public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException { @SuppressWarnings("unchecked") FV fieldValue = (FV) extractJavaFieldValue(object); if (isFieldValueDefault(fieldValue)) { return null; } else { return fieldValue; } }
java
{ "resource": "" }
q3750
FieldType.isObjectsFieldValueDefault
train
public boolean isObjectsFieldValueDefault(Object object) throws SQLException { Object fieldValue = extractJavaFieldValue(object); return isFieldValueDefault(fieldValue); }
java
{ "resource": "" }
q3751
FieldType.getJavaDefaultValueDefault
train
public Object getJavaDefaultValueDefault() { if (field.getType() == boolean.class) { return DEFAULT_VALUE_BOOLEAN; } else if (field.getType() == byte.class || field.getType() == Byte.class) { return DEFAULT_VALUE_BYTE; } else if (field.getType() == char.class || field.getType() == Character.class) { return DEFAULT_VALUE_CHAR; } else if (field.getType() == short.class || field.getType() == Short.class) { return DEFAULT_VALUE_SHORT; } else if (field.getType() == int.class || field.getType() == Integer.class) { return DEFAULT_VALUE_INT; } else if (field.getType() == long.class || field.getType() == Long.class) { return DEFAULT_VALUE_LONG; } else if (field.getType() == float.class || field.getType() == Float.class) { return DEFAULT_VALUE_FLOAT; } else if (field.getType() == double.class || field.getType() == Double.class) { return DEFAULT_VALUE_DOUBLE; } else { return null; } }
java
{ "resource": "" }
q3752
FieldType.createForeignShell
train
private <FT, FID> FT createForeignShell(ConnectionSource connectionSource, Object val, ObjectCache objectCache) throws SQLException { @SuppressWarnings("unchecked") Dao<FT, FID> castDao = (Dao<FT, FID>) foreignDao; FT foreignObject = castDao.createObjectInstance(); foreignIdField.assignField(connectionSource, foreignObject, val, false, objectCache); return foreignObject; }
java
{ "resource": "" }
q3753
FieldType.findForeignFieldType
train
private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao) throws SQLException { String foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName(); for (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) { if (fieldType.getType() == foreignClass && (foreignColumnName == null || fieldType.getField().getName().equals(foreignColumnName))) { if (!fieldType.fieldConfig.isForeign() && !fieldType.fieldConfig.isForeignAutoRefresh()) { // this may never be reached throw new SQLException("Foreign collection object " + clazz + " for field '" + field.getName() + "' contains a field of class " + foreignClass + " but it's not foreign"); } return fieldType; } } // build our complex error message StringBuilder sb = new StringBuilder(); sb.append("Foreign collection class ").append(clazz.getName()); sb.append(" for field '").append(field.getName()).append("' column-name does not contain a foreign field"); if (foreignColumnName != null) { sb.append(" named '").append(foreignColumnName).append('\''); } sb.append(" of class ").append(foreignClass.getName()); throw new SQLException(sb.toString()); }
java
{ "resource": "" }
q3754
MappedQueryForFieldEq.execute
train
public T execute(DatabaseConnection databaseConnection, ID id, ObjectCache objectCache) throws SQLException { if (objectCache != null) { T result = objectCache.get(clazz, id); if (result != null) { return result; } } Object[] args = new Object[] { convertIdToFieldObject(id) }; // @SuppressWarnings("unchecked") Object result = databaseConnection.queryForOne(statement, args, argFieldTypes, this, objectCache); if (result == null) { logger.debug("{} using '{}' and {} args, got no results", label, statement, args.length); } else if (result == DatabaseConnection.MORE_THAN_ONE) { logger.error("{} using '{}' and {} args, got >1 results", label, statement, args.length); logArgs(args); throw new SQLException(label + " got more than 1 result: " + statement); } else { logger.debug("{} using '{}' and {} args, got 1 result", label, statement, args.length); } logArgs(args); @SuppressWarnings("unchecked") T castResult = (T) result; return castResult; }
java
{ "resource": "" }
q3755
BaseDatabaseType.appendStringType
train
protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { if (isVarcharFieldWidthSupported()) { sb.append("VARCHAR(").append(fieldWidth).append(')'); } else { sb.append("VARCHAR"); } }
java
{ "resource": "" }
q3756
BaseDatabaseType.appendDefaultValue
train
private void appendDefaultValue(StringBuilder sb, FieldType fieldType, Object defaultValue) { if (fieldType.isEscapedDefaultValue()) { appendEscapedWord(sb, defaultValue.toString()); } else { sb.append(defaultValue); } }
java
{ "resource": "" }
q3757
BaseDatabaseType.addSingleUnique
train
private void addSingleUnique(StringBuilder sb, FieldType fieldType, List<String> additionalArgs, List<String> statementsAfter) { StringBuilder alterSb = new StringBuilder(); alterSb.append(" UNIQUE ("); appendEscapedEntityName(alterSb, fieldType.getColumnName()); alterSb.append(')'); additionalArgs.add(alterSb.toString()); }
java
{ "resource": "" }
q3758
DataPersisterManager.registerDataPersisters
train
public static void registerDataPersisters(DataPersister... dataPersisters) { // we build the map and replace it to lower the chance of concurrency issues List<DataPersister> newList = new ArrayList<DataPersister>(); if (registeredPersisters != null) { newList.addAll(registeredPersisters); } for (DataPersister persister : dataPersisters) { newList.add(persister); } registeredPersisters = newList; }
java
{ "resource": "" }
q3759
DataPersisterManager.lookupForField
train
public static DataPersister lookupForField(Field field) { // see if the any of the registered persisters are valid first if (registeredPersisters != null) { for (DataPersister persister : registeredPersisters) { if (persister.isValidForField(field)) { return persister; } // check the classes instead for (Class<?> clazz : persister.getAssociatedClasses()) { if (field.getType() == clazz) { return persister; } } } } // look it up in our built-in map by class DataPersister dataPersister = builtInMap.get(field.getType().getName()); if (dataPersister != null) { return dataPersister; } /* * Special case for enum types. We can't put this in the registered persisters because we want people to be able * to override it. */ if (field.getType().isEnum()) { return DEFAULT_ENUM_PERSISTER; } else { /* * Serializable classes return null here because we don't want them to be automatically configured for * forwards compatibility with future field types that happen to be Serializable. */ return null; } }
java
{ "resource": "" }
q3760
MappedUpdate.update
train
public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException { try { // there is always and id field as an argument so just return 0 lines updated if (argFieldTypes.length <= 1) { return 0; } Object[] args = getFieldObjects(data); Object newVersion = null; if (versionFieldType != null) { newVersion = versionFieldType.extractJavaFieldValue(data); newVersion = versionFieldType.moveToNextValue(newVersion); args[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion); } int rowC = databaseConnection.update(statement, args, argFieldTypes); if (rowC > 0) { if (newVersion != null) { // if we have updated a row then update the version field in our object to the new value versionFieldType.assignField(connectionSource, data, newVersion, false, null); } if (objectCache != null) { // if we've changed something then see if we need to update our cache Object id = idField.extractJavaFieldValue(data); T cachedData = objectCache.get(clazz, id); if (cachedData != null && cachedData != data) { // copy each field from the updated data into the cached object for (FieldType fieldType : tableInfo.getFieldTypes()) { if (fieldType != idField) { fieldType.assignField(connectionSource, cachedData, fieldType.extractJavaFieldValue(data), false, objectCache); } } } } } logger.debug("update data with statement '{}' and {} args, changed {} rows", statement, args.length, rowC); if (args.length > 0) { // need to do the (Object) cast to force args to be a single object logger.trace("update arguments: {}", (Object) args); } return rowC; } catch (SQLException e) { throw SqlExceptionUtil.create("Unable to run update stmt on object " + data + ": " + statement, e); } }
java
{ "resource": "" }
q3761
BaseMappedStatement.getFieldObjects
train
protected Object[] getFieldObjects(Object data) throws SQLException { Object[] objects = new Object[argFieldTypes.length]; for (int i = 0; i < argFieldTypes.length; i++) { FieldType fieldType = argFieldTypes[i]; if (fieldType.isAllowGeneratedIdInsert()) { objects[i] = fieldType.getFieldValueIfNotDefault(data); } else { objects[i] = fieldType.extractJavaFieldToSqlArgValue(data); } if (objects[i] == null) { // NOTE: the default value could be null as well objects[i] = fieldType.getDefaultValue(); } } return objects; }
java
{ "resource": "" }
q3762
MappedPreparedStmt.assignStatementArguments
train
private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException { boolean ok = false; try { if (limit != null) { // we use this if SQL statement LIMITs are not supported by this database type stmt.setMaxRows(limit.intValue()); } // set any arguments if we are logging our object Object[] argValues = null; if (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) { argValues = new Object[argHolders.length]; } for (int i = 0; i < argHolders.length; i++) { Object argValue = argHolders[i].getSqlArgValue(); FieldType fieldType = argFieldTypes[i]; SqlType sqlType; if (fieldType == null) { sqlType = argHolders[i].getSqlType(); } else { sqlType = fieldType.getSqlType(); } stmt.setObject(i, argValue, sqlType); if (argValues != null) { argValues[i] = argValue; } } logger.debug("prepared statement '{}' with {} args", statement, argHolders.length); if (argValues != null) { // need to do the (Object) cast to force args to be a single object logger.trace("prepared statement arguments: {}", (Object) argValues); } ok = true; return stmt; } finally { if (!ok) { IOUtils.closeThrowSqlException(stmt, "statement"); } } }
java
{ "resource": "" }
q3763
BaseConnectionSource.getSavedConnection
train
protected DatabaseConnection getSavedConnection() { NestedConnection nested = specialConnection.get(); if (nested == null) { return null; } else { return nested.connection; } }
java
{ "resource": "" }
q3764
BaseConnectionSource.isSavedConnection
train
protected boolean isSavedConnection(DatabaseConnection connection) { NestedConnection currentSaved = specialConnection.get(); if (currentSaved == null) { return false; } else if (currentSaved.connection == connection) { // ignore the release when we have a saved connection return true; } else { return false; } }
java
{ "resource": "" }
q3765
BaseConnectionSource.clearSpecial
train
protected boolean clearSpecial(DatabaseConnection connection, Logger logger) { NestedConnection currentSaved = specialConnection.get(); boolean cleared = false; if (connection == null) { // ignored } else if (currentSaved == null) { logger.error("no connection has been saved when clear() called"); } else if (currentSaved.connection == connection) { if (currentSaved.decrementAndGet() == 0) { // we only clear the connection if nested counter is 0 specialConnection.set(null); } cleared = true; } else { logger.error("connection saved {} is not the one being cleared {}", currentSaved.connection, connection); } // release should then be called after clear return cleared; }
java
{ "resource": "" }
q3766
BaseConnectionSource.isSingleConnection
train
protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException { // initialize the connections auto-commit flags conn1.setAutoCommit(true); conn2.setAutoCommit(true); try { // change conn1's auto-commit to be false conn1.setAutoCommit(false); if (conn2.isAutoCommit()) { // if the 2nd connection's auto-commit is still true then we have multiple connections return false; } else { // if the 2nd connection's auto-commit is also false then we have a single connection return true; } } finally { // restore its auto-commit conn1.setAutoCommit(true); } }
java
{ "resource": "" }
q3767
DatabaseTableConfigLoader.loadDatabaseConfigFromReader
train
public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException { List<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>(); while (true) { DatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader); if (config == null) { break; } list.add(config); } return list; }
java
{ "resource": "" }
q3768
DatabaseTableConfigLoader.fromReader
train
public static <T> DatabaseTableConfig<T> fromReader(BufferedReader reader) throws SQLException { DatabaseTableConfig<T> config = new DatabaseTableConfig<T>(); boolean anything = false; while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { throw SqlExceptionUtil.create("Could not read DatabaseTableConfig from stream", e); } if (line == null) { break; } // we do this so we can support multiple class configs per file if (line.equals(CONFIG_FILE_END_MARKER)) { break; } // we do this so we can support multiple class configs per file if (line.equals(CONFIG_FILE_FIELDS_START)) { readFields(reader, config); continue; } // skip empty lines or comments if (line.length() == 0 || line.startsWith("#") || line.equals(CONFIG_FILE_START_MARKER)) { continue; } String[] parts = line.split("=", -2); if (parts.length != 2) { throw new SQLException("DatabaseTableConfig reading from stream cannot parse line: " + line); } readTableField(config, parts[0], parts[1]); anything = true; } // if we got any config lines then we return the config if (anything) { return config; } else { // otherwise we return null for none return null; } }
java
{ "resource": "" }
q3769
DatabaseTableConfigLoader.write
train
public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException { try { writeConfig(writer, config); } catch (IOException e) { throw SqlExceptionUtil.create("Could not write config to writer", e); } }
java
{ "resource": "" }
q3770
DatabaseTableConfigLoader.writeConfig
train
private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException, SQLException { writer.append(CONFIG_FILE_START_MARKER); writer.newLine(); if (config.getDataClass() != null) { writer.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName()); writer.newLine(); } if (config.getTableName() != null) { writer.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName()); writer.newLine(); } writer.append(CONFIG_FILE_FIELDS_START); writer.newLine(); if (config.getFieldConfigs() != null) { for (DatabaseFieldConfig field : config.getFieldConfigs()) { DatabaseFieldConfigLoader.write(writer, field, config.getTableName()); } } writer.append(CONFIG_FILE_FIELDS_END); writer.newLine(); writer.append(CONFIG_FILE_END_MARKER); writer.newLine(); }
java
{ "resource": "" }
q3771
DatabaseTableConfigLoader.readTableField
train
private static <T> void readTableField(DatabaseTableConfig<T> config, String field, String value) { if (field.equals(FIELD_NAME_DATA_CLASS)) { try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(value); config.setDataClass(clazz); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Unknown class specified for dataClass: " + value); } } else if (field.equals(FIELD_NAME_TABLE_NAME)) { config.setTableName(value); } }
java
{ "resource": "" }
q3772
DatabaseTableConfigLoader.readFields
train
private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException { List<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>(); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { throw SqlExceptionUtil.create("Could not read next field from config file", e); } if (line == null || line.equals(CONFIG_FILE_FIELDS_END)) { break; } DatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader); if (fieldConfig == null) { break; } fields.add(fieldConfig); } config.setFieldConfigs(fields); }
java
{ "resource": "" }
q3773
ProtobufDeserializer.readKey
train
private Object readKey( FieldDescriptor field, JsonParser parser, DeserializationContext context ) throws IOException { if (parser.getCurrentToken() != JsonToken.FIELD_NAME) { throw reportWrongToken(JsonToken.FIELD_NAME, context, "Expected FIELD_NAME token"); } String fieldName = parser.getCurrentName(); switch (field.getJavaType()) { case INT: // lifted from StdDeserializer since there's no method to call try { return NumberInput.parseInt(fieldName.trim()); } catch (IllegalArgumentException iae) { Number number = (Number) context.handleWeirdStringValue( _valueClass, fieldName.trim(), "not a valid int value" ); return number == null ? 0 : number.intValue(); } case LONG: // lifted from StdDeserializer since there's no method to call try { return NumberInput.parseLong(fieldName.trim()); } catch (IllegalArgumentException iae) { Number number = (Number) context.handleWeirdStringValue( _valueClass, fieldName.trim(), "not a valid long value" ); return number == null ? 0L : number.longValue(); } case BOOLEAN: // lifted from StdDeserializer since there's no method to call String text = fieldName.trim(); if ("true".equals(text) || "True".equals(text)) { return true; } if ("false".equals(text) || "False".equals(text)) { return false; } Boolean b = (Boolean) context.handleWeirdStringValue( _valueClass, text, "only \"true\" or \"false\" recognized" ); return Boolean.TRUE.equals(b); case STRING: return fieldName; case ENUM: EnumValueDescriptor enumValueDescriptor = field.getEnumType().findValueByName(parser.getText()); if (enumValueDescriptor == null && !ignorableEnum(parser.getText().trim(), context)) { throw context.weirdStringException(parser.getText(), field.getEnumType().getClass(), "value not one of declared Enum instance names"); } return enumValueDescriptor; default: throw new IllegalArgumentException("Unexpected map key type: " + field.getJavaType()); } }
java
{ "resource": "" }
q3774
ShiroHelper.populateSubject
train
public static void populateSubject(final LinkedHashMap<String, CommonProfile> profiles) { if (profiles != null && profiles.size() > 0) { final List<CommonProfile> listProfiles = ProfileHelper.flatIntoAProfileList(profiles); try { if (IS_FULLY_AUTHENTICATED_AUTHORIZER.isAuthorized(null, listProfiles)) { SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, false)); } else if (IS_REMEMBERED_AUTHORIZER.isAuthorized(null, listProfiles)) { SecurityUtils.getSubject().login(new Pac4jToken(listProfiles, true)); } } catch (final HttpAction e) { throw new TechnicalException(e); } } }
java
{ "resource": "" }
q3775
Pac4jPrincipal.getName
train
@Override public String getName() { CommonProfile profile = this.getProfile(); if(null == principalNameAttribute) { return profile.getId(); } Object attrValue = profile.getAttribute(principalNameAttribute); return (null == attrValue) ? null : String.valueOf(attrValue); }
java
{ "resource": "" }
q3776
Utils.showBooks
train
public static void showBooks(final ListOfBooks booksList){ if(booksList != null && booksList.getBook() != null && !booksList.getBook().isEmpty()){ List<BookType> books = booksList.getBook(); System.out.println("\nNumber of books: " + books.size()); int cnt = 0; for (BookType book : books) { System.out.println("\nBookNum: " + (cnt++ + 1)); List<PersonType> authors = book.getAuthor(); if(authors != null && !authors.isEmpty()){ for (PersonType author : authors) { System.out.println("Author: " + author.getFirstName() + " " + author.getLastName()); } } System.out.println("Title: " + book.getTitle()); System.out.println("Year: " + book.getYearPublished()); if(book.getISBN()!=null){ System.out.println("ISBN: " + book.getISBN()); } } }else{ System.out.println("List of books is empty"); } System.out.println(""); }
java
{ "resource": "" }
q3777
ContextListener.contextInitialized
train
public void contextInitialized(ServletContextEvent event) { this.context = event.getServletContext(); // Output a simple message to the server's console System.out.println("The Simple Web App. Is Ready"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "/client.xml"); LocatorService client = (LocatorService) context .getBean("locatorService"); String serviceHost = this.context.getInitParameter("serviceHost"); try { client.registerEndpoint(new QName( "http://talend.org/esb/examples/", "GreeterService"), serviceHost, BindingType.SOAP_11, TransportType.HTTP, null); } catch (InterruptedExceptionFault e) { e.printStackTrace(); } catch (ServiceLocatorFault e) { e.printStackTrace(); } }
java
{ "resource": "" }
q3778
CXFEndpointProvider.serializeEPR
train
private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException { try { JAXBElement<EndpointReferenceType> ep = WSA_OBJECT_FACTORY.createEndpointReference(wsAddr); createMarshaller().marshal(ep, parent); } catch (JAXBException e) { if (LOG.isLoggable(Level.SEVERE)) { LOG.log(Level.SEVERE, "Failed to serialize endpoint data", e); } throw new ServiceLocatorException("Failed to serialize endpoint data", e); } }
java
{ "resource": "" }
q3779
CXFEndpointProvider.createEPR
train
private static EndpointReferenceType createEPR(String address, SLProperties props) { EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address); if (props != null) { addProperties(epr, props); } return epr; }
java
{ "resource": "" }
q3780
CXFEndpointProvider.createEPR
train
private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) { EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget(); EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR); WSAEndpointReferenceUtils.setAddress(targetEPR, address); if (props != null) { addProperties(targetEPR, props); } return targetEPR; }
java
{ "resource": "" }
q3781
CXFEndpointProvider.addProperties
train
private static void addProperties(EndpointReferenceType epr, SLProperties props) { MetadataType metadata = WSAEndpointReferenceUtils.getSetMetadata(epr); ServiceLocatorPropertiesType jaxbProps = SLPropertiesConverter.toServiceLocatorPropertiesType(props); JAXBElement<ServiceLocatorPropertiesType> slp = SL_OBJECT_FACTORY.createServiceLocatorProperties(jaxbProps); metadata.getAny().add(slp); }
java
{ "resource": "" }
q3782
CXFEndpointProvider.getServiceName
train
private static QName getServiceName(Server server) { QName serviceName; String bindingId = getBindingId(server); EndpointInfo eInfo = server.getEndpoint().getEndpointInfo(); if (JAXRS_BINDING_ID.equals(bindingId)) { serviceName = eInfo.getName(); } else { ServiceInfo serviceInfo = eInfo.getService(); serviceName = serviceInfo.getName(); } return serviceName; }
java
{ "resource": "" }
q3783
CXFEndpointProvider.getBindingId
train
private static String getBindingId(Server server) { Endpoint ep = server.getEndpoint(); BindingInfo bi = ep.getBinding().getBindingInfo(); return bi.getBindingId(); }
java
{ "resource": "" }
q3784
CXFEndpointProvider.map2BindingType
train
private static BindingType map2BindingType(String bindingId) { BindingType type; if (SOAP11_BINDING_ID.equals(bindingId)) { type = BindingType.SOAP11; } else if (SOAP12_BINDING_ID.equals(bindingId)) { type = BindingType.SOAP12; } else if (JAXRS_BINDING_ID.equals(bindingId)) { type = BindingType.JAXRS; } else { type = BindingType.OTHER; } return type; }
java
{ "resource": "" }
q3785
CXFEndpointProvider.map2TransportType
train
private static TransportType map2TransportType(String transportId) { TransportType type; if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) { type = TransportType.HTTP; } else { type = TransportType.OTHER; } return type; }
java
{ "resource": "" }
q3786
MessageToEventMapper.getEventType
train
private EventTypeEnum getEventType(Message message) { boolean isRequestor = MessageUtils.isRequestor(message); boolean isFault = MessageUtils.isFault(message); boolean isOutbound = MessageUtils.isOutbound(message); //Needed because if it is rest request and method does not exists had better to return Fault if(!isFault && isRestMessage(message)) { isFault = (message.getExchange().get("org.apache.cxf.resource.operation.name") == null); if (!isFault) { Integer responseCode = (Integer) message.get(Message.RESPONSE_CODE); if (null != responseCode) { isFault = (responseCode >= 400); } } } if (isOutbound) { if (isFault) { return EventTypeEnum.FAULT_OUT; } else { return isRequestor ? EventTypeEnum.REQ_OUT : EventTypeEnum.RESP_OUT; } } else { if (isFault) { return EventTypeEnum.FAULT_IN; } else { return isRequestor ? EventTypeEnum.RESP_IN : EventTypeEnum.REQ_IN; } } }
java
{ "resource": "" }
q3787
MessageToEventMapper.getPayload
train
protected String getPayload(Message message) { try { String encoding = (String) message.get(Message.ENCODING); if (encoding == null) { encoding = "UTF-8"; } CachedOutputStream cos = message.getContent(CachedOutputStream.class); if (cos == null) { LOG.warning("Could not find CachedOutputStream in message." + " Continuing without message content"); return ""; } return new String(cos.getBytes(), encoding); } catch (IOException e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q3788
MessageToEventMapper.handleContentLength
train
private void handleContentLength(Event event) { if (event.getContent() == null) { return; } if (maxContentLength == -1 || event.getContent().length() <= maxContentLength) { return; } if (maxContentLength < CUT_START_TAG.length() + CUT_END_TAG.length()) { event.setContent(""); event.setContentCut(true); return; } int contentLength = maxContentLength - CUT_START_TAG.length() - CUT_END_TAG.length(); event.setContent(CUT_START_TAG + event.getContent().substring(0, contentLength) + CUT_END_TAG); event.setContentCut(true); }
java
{ "resource": "" }
q3789
CriteriaAdapter.getCriterias
train
private Map<String, Criteria> getCriterias(Map<String, String[]> params) { Map<String, Criteria> result = new HashMap<String, Criteria>(); for (Map.Entry<String, String[]> param : params.entrySet()) { for (Criteria criteria : FILTER_CRITERIAS) { if (criteria.getName().equals(param.getKey())) { try { Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]); for (Criteria parsedCriteria : parsedCriterias) { result.put(parsedCriteria.getName(), parsedCriteria); } } catch (Exception e) { // Exception happened during paring LOG.log(Level.SEVERE, "Error parsing parameter " + param.getKey(), e); } break; } } } return result; }
java
{ "resource": "" }
q3790
ServiceLocatorImpl.setSessionTimeout
train
public void setSessionTimeout(int timeout) { ((ZKBackend) getBackend()).setSessionTimeout(timeout); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Locator session timeout set to: " + timeout); } }
java
{ "resource": "" }
q3791
CarRent.racRent
train
public void racRent() { pos = pos - 1; String userName = CarSearch.getLastSearchParams()[0]; String pickupDate = CarSearch.getLastSearchParams()[1]; String returnDate = CarSearch.getLastSearchParams()[2]; this.searcher.search(userName, pickupDate, returnDate); if (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) { RESStatusType resStatus = reserver.reserveCar(searcher.getCustomer() , searcher.getCars().get(pos) , pickupDate , returnDate); ConfirmationType confirm = reserver.getConfirmation(resStatus , searcher.getCustomer() , searcher.getCars().get(pos) , pickupDate , returnDate); RESCarType car = confirm.getCar(); CustomerDetailsType customer = confirm.getCustomer(); System.out.println(MessageFormat.format(CONFIRMATION , confirm.getDescription() , confirm.getReservationId() , customer.getName() , customer.getEmail() , customer.getCity() , customer.getStatus() , car.getBrand() , car.getDesignModel() , confirm.getFromDate() , confirm.getToDate() , padl(car.getRateDay(), 10) , padl(car.getRateWeekend(), 10) , padl(confirm.getCreditPoints().toString(), 7))); } else { System.out.println("Invalid selection: " + (pos+1)); //$NON-NLS-1$ } }
java
{ "resource": "" }
q3792
SLPropertiesImpl.addProperty
train
public void addProperty(String name, String... values) { List<String> valueList = new ArrayList<String>(); for (String value : values) { valueList.add(value.trim()); } properties.put(name.trim(), valueList); }
java
{ "resource": "" }
q3793
LocatorRegistrar.getRegistrar
train
protected SingleBusLocatorRegistrar getRegistrar(Bus bus) { SingleBusLocatorRegistrar registrar = busRegistrars.get(bus); if (registrar == null) { check(locatorClient, "serviceLocator", "registerService"); registrar = new SingleBusLocatorRegistrar(bus); registrar.setServiceLocator(locatorClient); registrar.setEndpointPrefix(endpointPrefix); Map<String, String> endpointPrefixes = new HashMap<String, String>(); endpointPrefixes.put("HTTP", endpointPrefixHttp); endpointPrefixes.put("HTTPS", endpointPrefixHttps); registrar.setEndpointPrefixes(endpointPrefixes); busRegistrars.put(bus, registrar); addLifeCycleListener(bus); } return registrar; }
java
{ "resource": "" }
q3794
RESTClient.useXopAttachmentServiceWithWebClient
train
public void useXopAttachmentServiceWithWebClient() throws Exception { final String serviceURI = "http://localhost:" + port + "/services/attachments/xop"; JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean(); factoryBean.setAddress(serviceURI); factoryBean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, (Object)"true")); WebClient client = factoryBean.createWebClient(); WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true"); client.type("multipart/related").accept("multipart/related"); XopBean xop = createXopBean(); System.out.println(); System.out.println("Posting a XOP attachment with a WebClient"); XopBean xopResponse = client.post(xop, XopBean.class); verifyXopResponse(xop, xopResponse); }
java
{ "resource": "" }
q3795
RESTClient.useXopAttachmentServiceWithProxy
train
public void useXopAttachmentServiceWithProxy() throws Exception { final String serviceURI = "http://localhost:" + port + "/services/attachments"; XopAttachmentService proxy = JAXRSClientFactory.create(serviceURI, XopAttachmentService.class); XopBean xop = createXopBean(); System.out.println(); System.out.println("Posting a XOP attachment with a proxy"); XopBean xopResponse = proxy.echoXopAttachment(xop); verifyXopResponse(xop, xopResponse); }
java
{ "resource": "" }
q3796
RESTClient.createXopBean
train
private XopBean createXopBean() throws Exception { XopBean xop = new XopBean(); xop.setName("xopName"); InputStream is = getClass().getResourceAsStream("/java.jpg"); byte[] data = IOUtils.readBytesFromStream(is); // Pass java.jpg as an array of bytes xop.setBytes(data); // Wrap java.jpg as a DataHandler xop.setDatahandler(new DataHandler( new ByteArrayDataSource(data, "application/octet-stream"))); if (Boolean.getBoolean("java.awt.headless")) { System.out.println("Running headless. Ignoring an Image property."); } else { xop.setImage(getImage("/java.jpg")); } return xop; }
java
{ "resource": "" }
q3797
RESTClient.verifyXopResponse
train
private void verifyXopResponse(XopBean xopOriginal, XopBean xopResponse) { if (!Arrays.equals(xopResponse.getBytes(), xopOriginal.getBytes())) { throw new RuntimeException("Received XOP attachment is corrupted"); } System.out.println(); System.out.println("XOP attachment has been successfully received"); }
java
{ "resource": "" }
q3798
MonitoringWebService.setMonitoringService
train
public void setMonitoringService(org.talend.esb.sam.common.service.MonitoringService monitoringService) { this.monitoringService = monitoringService; }
java
{ "resource": "" }
q3799
MonitoringWebService.throwFault
train
private static void throwFault(String code, String message, Throwable t) throws PutEventsFault { if (LOG.isLoggable(Level.SEVERE)) { LOG.log(Level.SEVERE, "Throw Fault " + code + " " + message, t); } FaultType faultType = new FaultType(); faultType.setFaultCode(code); faultType.setFaultMessage(message); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); t.printStackTrace(printWriter); faultType.setStackTrace(stringWriter.toString()); throw new PutEventsFault(message, faultType, t); }
java
{ "resource": "" }