_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9800 | ReflectiveObjectCopyStrategy.setFields | train | private static void setFields(final Object from, final Object to,
final Field[] fields, final boolean accessible,
final Map objMap, final Map metadataMap)
{
for (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)
{
final Field field = fields[f];
final int modifiers = field.getModifiers();
if ((Modifier.STATIC & modifiers) != 0) continue;
if ((Modifier.FINAL & modifiers) != 0)
throw new ObjectCopyException("cannot set final field [" + field.getName() + "] of class [" + from.getClass().getName() + "]");
if (!accessible && ((Modifier.PUBLIC & modifiers) == 0))
{
try
{
field.setAccessible(true);
}
catch (SecurityException e)
{
throw new ObjectCopyException("cannot access field [" + field.getName() + "] of class [" + from.getClass().getName() + "]: " + e.toString(), e);
}
}
try
{
cloneAndSetFieldValue(field, from, to, objMap, metadataMap);
}
catch (Exception e)
{
throw new ObjectCopyException("cannot set field [" + field.getName() + "] of class [" + from.getClass().getName() + "]: " + e.toString(), e);
}
}
} | java | {
"resource": ""
} |
q9801 | DragHelper.registerComponent | train | public void registerComponent(java.awt.Component c)
{
unregisterComponent(c);
if (recognizerAbstractClass == null)
{
hmDragGestureRecognizers.put(c,
dragSource.createDefaultDragGestureRecognizer(c,
dragWorker.getAcceptableActions(c), dgListener)
);
}
else
{
hmDragGestureRecognizers.put(c,
dragSource.createDragGestureRecognizer (recognizerAbstractClass,
c, dragWorker.getAcceptableActions(c), dgListener)
);
}
} | java | {
"resource": ""
} |
q9802 | DragHelper.unregisterComponent | train | public void unregisterComponent(java.awt.Component c)
{
java.awt.dnd.DragGestureRecognizer recognizer =
(java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);
if (recognizer != null)
recognizer.setComponent(null);
} | java | {
"resource": ""
} |
q9803 | Interceptor.doInvoke | train | protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)
throws Throwable
{
Method m =
getRealSubject().getClass().getMethod(
methodToBeInvoked.getName(),
methodToBeInvoked.getParameterTypes());
return m.invoke(getRealSubject(), args);
} | java | {
"resource": ""
} |
q9804 | ChainingIterator.addIterator | train | public void addIterator(OJBIterator iterator)
{
/**
* only add iterators that are not null and non-empty.
*/
if (iterator != null)
{
if (iterator.hasNext())
{
setNextIterator();
m_rsIterators.add(iterator);
}
}
} | java | {
"resource": ""
} |
q9805 | ChainingIterator.absolute | train | public boolean absolute(int row) throws PersistenceBrokerException
{
// 1. handle the special cases first.
if (row == 0)
{
return true;
}
if (row == 1)
{
m_activeIteratorIndex = 0;
m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);
m_activeIterator.absolute(1);
return true;
}
if (row == -1)
{
m_activeIteratorIndex = m_rsIterators.size();
m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);
m_activeIterator.absolute(-1);
return true;
}
// now do the real work.
boolean movedToAbsolute = false;
boolean retval = false;
setNextIterator();
// row is positive, so index from beginning.
if (row > 0)
{
int sizeCount = 0;
Iterator it = m_rsIterators.iterator();
OJBIterator temp = null;
while (it.hasNext() && !movedToAbsolute)
{
temp = (OJBIterator) it.next();
if (temp.size() < row)
{
sizeCount += temp.size();
}
else
{
// move to the offset - sizecount
m_currentCursorPosition = row - sizeCount;
retval = temp.absolute(m_currentCursorPosition);
movedToAbsolute = true;
}
}
}
// row is negative, so index from end
else if (row < 0)
{
int sizeCount = 0;
OJBIterator temp = null;
for (int i = m_rsIterators.size(); ((i >= 0) && !movedToAbsolute); i--)
{
temp = (OJBIterator) m_rsIterators.get(i);
if (temp.size() < row)
{
sizeCount += temp.size();
}
else
{
// move to the offset - sizecount
m_currentCursorPosition = row + sizeCount;
retval = temp.absolute(m_currentCursorPosition);
movedToAbsolute = true;
}
}
}
return retval;
} | java | {
"resource": ""
} |
q9806 | ChainingIterator.releaseDbResources | train | public void releaseDbResources()
{
Iterator it = m_rsIterators.iterator();
while (it.hasNext())
{
((OJBIterator) it.next()).releaseDbResources();
}
} | java | {
"resource": ""
} |
q9807 | ChainingIterator.setNextIterator | train | private boolean setNextIterator()
{
boolean retval = false;
// first, check if the activeIterator is null, and set it.
if (m_activeIterator == null)
{
if (m_rsIterators.size() > 0)
{
m_activeIteratorIndex = 0;
m_currentCursorPosition = 0;
m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);
}
}
else if (!m_activeIterator.hasNext())
{
if (m_rsIterators.size() > (m_activeIteratorIndex + 1))
{
// we still have iterators in the collection, move to the
// next one, increment the counter, and set the active
// iterator.
m_activeIteratorIndex++;
m_currentCursorPosition = 0;
m_activeIterator = (OJBIterator) m_rsIterators.get(m_activeIteratorIndex);
retval = true;
}
}
return retval;
} | java | {
"resource": ""
} |
q9808 | ChainingIterator.containsIteratorForTable | train | public boolean containsIteratorForTable(String aTable)
{
boolean result = false;
if (m_rsIterators != null)
{
for (int i = 0; i < m_rsIterators.size(); i++)
{
OJBIterator it = (OJBIterator) m_rsIterators.get(i);
if (it instanceof RsIterator)
{
if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))
{
result = true;
break;
}
}
else if (it instanceof ChainingIterator)
{
result = ((ChainingIterator) it).containsIteratorForTable(aTable);
}
}
}
return result;
} | java | {
"resource": ""
} |
q9809 | QueryByIdentity.getSearchClass | train | public Class getSearchClass()
{
Object obj = getExampleObject();
if (obj instanceof Identity)
{
return ((Identity) obj).getObjectsTopLevelClass();
}
else
{
return obj.getClass();
}
} | java | {
"resource": ""
} |
q9810 | ConfigurationServiceImpl.getBeanOrNull | train | private <T> T getBeanOrNull(String name, Class<T> requiredType) {
if (name == null || !applicationContext.containsBean(name)) {
return null;
} else {
try {
return applicationContext.getBean(name, requiredType);
} catch (BeansException be) {
log.error("Error during getBeanOrNull, not rethrown, " + be.getMessage(), be);
return null;
}
}
} | java | {
"resource": ""
} |
q9811 | CachingSupportServiceSecurityContextAdderImpl.restoreSecurityContext | train | public void restoreSecurityContext(CacheContext context) {
SavedAuthorization cached = context.get(CacheContext.SECURITY_CONTEXT_KEY, SavedAuthorization.class);
if (cached != null) {
log.debug("Restoring security context {}", cached);
securityManager.restoreSecurityContext(cached);
} else {
securityManager.clearSecurityContext();
}
} | java | {
"resource": ""
} |
q9812 | LogFileList.sortFileList | train | private void sortFileList() {
if (this.size() > 1) {
Collections.sort(this.fileList, new Comparator() {
public final int compare(final Object o1, final Object o2) {
final File f1 = (File) o1;
final File f2 = (File) o2;
final Object[] f1TimeAndCount = backupSuffixHelper
.backupTimeAndCount(f1.getName(), baseFile);
final Object[] f2TimeAndCount = backupSuffixHelper
.backupTimeAndCount(f2.getName(), baseFile);
final long f1TimeSuffix = ((Long) f1TimeAndCount[0]).longValue();
final long f2TimeSuffix = ((Long) f2TimeAndCount[0]).longValue();
if ((0L == f1TimeSuffix) && (0L == f2TimeSuffix)) {
final long f1Time = f1.lastModified();
final long f2Time = f2.lastModified();
if (f1Time < f2Time) {
return -1;
}
if (f1Time > f2Time) {
return 1;
}
return 0;
}
if (f1TimeSuffix < f2TimeSuffix) {
return -1;
}
if (f1TimeSuffix > f2TimeSuffix) {
return 1;
}
final int f1Count = ((Integer) f1TimeAndCount[1]).intValue();
final int f2Count = ((Integer) f2TimeAndCount[1]).intValue();
if (f1Count < f2Count) {
return -1;
}
if (f1Count > f2Count) {
return 1;
}
if (f1Count == f2Count) {
if (fileHelper.isCompressed(f1)) {
return -1;
}
if (fileHelper.isCompressed(f2)) {
return 1;
}
}
return 0;
}
});
}
} | java | {
"resource": ""
} |
q9813 | BrokerHelper.getRealClassDescriptor | train | private ClassDescriptor getRealClassDescriptor(ClassDescriptor aCld, Object anObj)
{
ClassDescriptor result;
if(aCld.getClassOfObject() == ProxyHelper.getRealClass(anObj))
{
result = aCld;
}
else
{
result = aCld.getRepository().getDescriptorFor(anObj.getClass());
}
return result;
} | java | {
"resource": ""
} |
q9814 | BrokerHelper.getKeyValues | train | public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql) throws PersistenceBrokerException
{
IndirectionHandler handler = ProxyHelper.getIndirectionHandler(objectOrProxy);
if(handler != null)
{
return getKeyValues(cld, handler.getIdentity(), convertToSql); //BRJ: convert Identity
}
else
{
ClassDescriptor realCld = getRealClassDescriptor(cld, objectOrProxy);
return getValuesForObject(realCld.getPkFields(), objectOrProxy, convertToSql);
}
} | java | {
"resource": ""
} |
q9815 | BrokerHelper.getKeyValues | train | public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException
{
return getKeyValues(cld, oid, true);
} | java | {
"resource": ""
} |
q9816 | BrokerHelper.getKeyValues | train | public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid, boolean convertToSql) throws PersistenceBrokerException
{
FieldDescriptor[] pkFields = cld.getPkFields();
ValueContainer[] result = new ValueContainer[pkFields.length];
Object[] pkValues = oid.getPrimaryKeyValues();
try
{
for(int i = 0; i < result.length; i++)
{
FieldDescriptor fd = pkFields[i];
Object cv = pkValues[i];
if(convertToSql)
{
// BRJ : apply type and value mapping
cv = fd.getFieldConversion().javaToSql(cv);
}
result[i] = new ValueContainer(cv, fd.getJdbcType());
}
}
catch(Exception e)
{
throw new PersistenceBrokerException("Can't generate primary key values for given Identity " + oid, e);
}
return result;
} | java | {
"resource": ""
} |
q9817 | BrokerHelper.getKeyValues | train | public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException
{
return getKeyValues(cld, objectOrProxy, true);
} | java | {
"resource": ""
} |
q9818 | BrokerHelper.hasNullPKField | train | public boolean hasNullPKField(ClassDescriptor cld, Object obj)
{
FieldDescriptor[] fields = cld.getPkFields();
boolean hasNull = false;
// an unmaterialized proxy object can never have nullified PK's
IndirectionHandler handler = ProxyHelper.getIndirectionHandler(obj);
if(handler == null || handler.alreadyMaterialized())
{
if(handler != null) obj = handler.getRealSubject();
FieldDescriptor fld;
for(int i = 0; i < fields.length; i++)
{
fld = fields[i];
hasNull = representsNull(fld, fld.getPersistentField().get(obj));
if(hasNull) break;
}
}
return hasNull;
} | java | {
"resource": ""
} |
q9819 | BrokerHelper.getValuesForObject | train | public ValueContainer[] getValuesForObject(FieldDescriptor[] fields, Object obj, boolean convertToSql, boolean assignAutoincrement) throws PersistenceBrokerException
{
ValueContainer[] result = new ValueContainer[fields.length];
for(int i = 0; i < fields.length; i++)
{
FieldDescriptor fd = fields[i];
Object cv = fd.getPersistentField().get(obj);
/*
handle autoincrement attributes if
- is a autoincrement field
- field represents a 'null' value, is nullified
and generate a new value
*/
if(assignAutoincrement && fd.isAutoIncrement() && representsNull(fd, cv))
{
/*
setAutoIncrementValue returns a value that is
properly typed for the java-world. This value
needs to be converted to it's corresponding
sql type so that the entire result array contains
objects that are properly typed for sql.
*/
cv = setAutoIncrementValue(fd, obj);
}
if(convertToSql)
{
// apply type and value conversion
cv = fd.getFieldConversion().javaToSql(cv);
}
// create ValueContainer
result[i] = new ValueContainer(cv, fd.getJdbcType());
}
return result;
} | java | {
"resource": ""
} |
q9820 | BrokerHelper.assertValidPkForDelete | train | public boolean assertValidPkForDelete(ClassDescriptor cld, Object obj)
{
if(!ProxyHelper.isProxy(obj))
{
FieldDescriptor fieldDescriptors[] = cld.getPkFields();
int fieldDescriptorSize = fieldDescriptors.length;
for(int i = 0; i < fieldDescriptorSize; i++)
{
FieldDescriptor fd = fieldDescriptors[i];
Object pkValue = fd.getPersistentField().get(obj);
if (representsNull(fd, pkValue))
{
return false;
}
}
}
return true;
} | java | {
"resource": ""
} |
q9821 | BrokerHelper.getCountQuery | train | public Query getCountQuery(Query aQuery)
{
if(aQuery instanceof QueryBySQL)
{
return getQueryBySqlCount((QueryBySQL) aQuery);
}
else if(aQuery instanceof ReportQueryByCriteria)
{
return getReportQueryByCriteriaCount((ReportQueryByCriteria) aQuery);
}
else
{
return getQueryByCriteriaCount((QueryByCriteria) aQuery);
}
} | java | {
"resource": ""
} |
q9822 | BrokerHelper.getQueryBySqlCount | train | private Query getQueryBySqlCount(QueryBySQL aQuery)
{
String countSql = aQuery.getSql();
int fromPos = countSql.toUpperCase().indexOf(" FROM ");
if(fromPos >= 0)
{
countSql = "select count(*)" + countSql.substring(fromPos);
}
int orderPos = countSql.toUpperCase().indexOf(" ORDER BY ");
if(orderPos >= 0)
{
countSql = countSql.substring(0, orderPos);
}
return new QueryBySQL(aQuery.getSearchClass(), countSql);
} | java | {
"resource": ""
} |
q9823 | BrokerHelper.getQueryByCriteriaCount | train | private Query getQueryByCriteriaCount(QueryByCriteria aQuery)
{
Class searchClass = aQuery.getSearchClass();
ReportQueryByCriteria countQuery = null;
Criteria countCrit = null;
String[] columns = new String[1];
// BRJ: copied Criteria without groupby, orderby, and prefetched relationships
if (aQuery.getCriteria() != null)
{
countCrit = aQuery.getCriteria().copy(false, false, false);
}
if (aQuery.isDistinct())
{
// BRJ: Count distinct is dbms dependent
// hsql/sapdb: select count (distinct(person_id || project_id)) from person_project
// mysql: select count (distinct person_id,project_id) from person_project
// [tomdz]
// Some databases have no support for multi-column count distinct (e.g. Derby)
// Here we use a SELECT count(*) FROM (SELECT DISTINCT ...) instead
//
// concatenation of pk-columns is a simple way to obtain a single column
// but concatenation is also dbms dependent:
//
// SELECT count(distinct concat(row1, row2, row3)) mysql
// SELECT count(distinct (row1 || row2 || row3)) ansi
// SELECT count(distinct (row1 + row2 + row3)) ms sql-server
FieldDescriptor[] pkFields = m_broker.getClassDescriptor(searchClass).getPkFields();
String[] keyColumns = new String[pkFields.length];
if (pkFields.length > 1)
{
// TODO: Use ColumnName. This is a temporary solution because
// we cannot yet resolve multiple columns in the same attribute.
for (int idx = 0; idx < pkFields.length; idx++)
{
keyColumns[idx] = pkFields[idx].getColumnName();
}
}
else
{
for (int idx = 0; idx < pkFields.length; idx++)
{
keyColumns[idx] = pkFields[idx].getAttributeName();
}
}
// [tomdz]
// TODO: Add support for databases that do not support COUNT DISTINCT over multiple columns
// if (getPlatform().supportsMultiColumnCountDistinct())
// {
// columns[0] = "count(distinct " + getPlatform().concatenate(keyColumns) + ")";
// }
// else
// {
// columns = keyColumns;
// }
columns[0] = "count(distinct " + getPlatform().concatenate(keyColumns) + ")";
}
else
{
columns[0] = "count(*)";
}
// BRJ: we have to preserve indirection table !
if (aQuery instanceof MtoNQuery)
{
MtoNQuery mnQuery = (MtoNQuery)aQuery;
ReportQueryByMtoNCriteria mnReportQuery = new ReportQueryByMtoNCriteria(searchClass, columns, countCrit);
mnReportQuery.setIndirectionTable(mnQuery.getIndirectionTable());
countQuery = mnReportQuery;
}
else
{
countQuery = new ReportQueryByCriteria(searchClass, columns, countCrit);
}
// BRJ: we have to preserve outer-join-settings (by André Markwalder)
for (Iterator outerJoinPath = aQuery.getOuterJoinPaths().iterator(); outerJoinPath.hasNext();)
{
String path = (String) outerJoinPath.next();
if (aQuery.isPathOuterJoin(path))
{
countQuery.setPathOuterJoin(path);
}
}
//BRJ: add orderBy Columns asJoinAttributes
List orderBy = aQuery.getOrderBy();
if ((orderBy != null) && !orderBy.isEmpty())
{
String[] joinAttributes = new String[orderBy.size()];
for (int idx = 0; idx < orderBy.size(); idx++)
{
joinAttributes[idx] = ((FieldHelper)orderBy.get(idx)).name;
}
countQuery.setJoinAttributes(joinAttributes);
}
// [tomdz]
// TODO:
// For those databases that do not support COUNT DISTINCT over multiple columns
// we wrap the normal SELECT DISTINCT that we just created, into a SELECT count(*)
// For this however we need a report query that gets its data from a sub query instead
// of a table (target class)
// if (aQuery.isDistinct() && !getPlatform().supportsMultiColumnCountDistinct())
// {
// }
return countQuery;
} | java | {
"resource": ""
} |
q9824 | BrokerHelper.getReportQueryByCriteriaCount | train | private Query getReportQueryByCriteriaCount(ReportQueryByCriteria aQuery)
{
ReportQueryByCriteria countQuery = (ReportQueryByCriteria) getQueryByCriteriaCount(aQuery);
// BRJ: keep the original columns to build the Join
countQuery.setJoinAttributes(aQuery.getAttributes());
// BRJ: we have to preserve groupby information
Iterator iter = aQuery.getGroupBy().iterator();
while(iter.hasNext())
{
countQuery.addGroupBy((FieldHelper) iter.next());
}
return countQuery;
} | java | {
"resource": ""
} |
q9825 | BrokerHelper.unlink | train | public boolean unlink(Object source, String attributeName, Object target)
{
return linkOrUnlink(false, source, attributeName, false);
} | java | {
"resource": ""
} |
q9826 | BrokerHelper.unlink | train | public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)
{
linkOrUnlink(false, obj, ord, insert);
} | java | {
"resource": ""
} |
q9827 | DBMetaCatalogNode._load | train | protected boolean _load ()
{
java.sql.ResultSet rs = null;
try
{
// This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1
// The documentation says synchronization is done within the driver, but they
// must have overlooked something. Without the lock we'd get mysterious error
// messages.
synchronized(getDbMeta())
{
getDbMetaTreeModel().setStatusBarMessage("Reading schemas for catalog "
+ this.getAttribute(ATT_CATALOG_NAME));
rs = getDbMeta().getSchemas();
final java.util.ArrayList alNew = new java.util.ArrayList();
int count = 0;
while (rs.next())
{
getDbMetaTreeModel().setStatusBarMessage("Creating schema " + getCatalogName() + "." + rs.getString("TABLE_SCHEM"));
alNew.add(new DBMetaSchemaNode(getDbMeta(),
getDbMetaTreeModel(),
DBMetaCatalogNode.this,
rs.getString("TABLE_SCHEM")));
count++;
}
if (count == 0)
alNew.add(new DBMetaSchemaNode(getDbMeta(),
getDbMetaTreeModel(),
DBMetaCatalogNode.this, null));
alChildren = alNew;
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
getDbMetaTreeModel().nodeStructureChanged(DBMetaCatalogNode.this);
}
});
rs.close();
}
}
catch (java.sql.SQLException sqlEx)
{
getDbMetaTreeModel().reportSqlError("Error retrieving schemas", sqlEx);
try
{
if (rs != null) rs.close ();
}
catch (java.sql.SQLException sqlEx2)
{
this.getDbMetaTreeModel().reportSqlError("Error retrieving schemas", sqlEx2);
}
return false;
}
return true;
} | java | {
"resource": ""
} |
q9828 | ConnectionRepository.removeDescriptor | train | public void removeDescriptor(Object validKey)
{
PBKey pbKey;
if (validKey instanceof PBKey)
{
pbKey = (PBKey) validKey;
}
else if (validKey instanceof JdbcConnectionDescriptor)
{
pbKey = ((JdbcConnectionDescriptor) validKey).getPBKey();
}
else
{
throw new MetadataException("Could not remove descriptor, given object was no vaild key: " +
validKey);
}
Object removed = null;
synchronized (jcdMap)
{
removed = jcdMap.remove(pbKey);
jcdAliasToPBKeyMap.remove(pbKey.getAlias());
}
log.info("Remove descriptor: " + removed);
} | java | {
"resource": ""
} |
q9829 | IdentityFactoryImpl.findIndexForName | train | private int findIndexForName(String[] fieldNames, String searchName)
{
for(int i = 0; i < fieldNames.length; i++)
{
if(searchName.equals(fieldNames[i]))
{
return i;
}
}
throw new PersistenceBrokerException("Can't find field name '" + searchName +
"' in given array of field names");
} | java | {
"resource": ""
} |
q9830 | IdentityFactoryImpl.isOrdered | train | private boolean isOrdered(FieldDescriptor[] flds, String[] pkFieldNames)
{
if((flds.length > 1 && pkFieldNames == null) || flds.length != pkFieldNames.length)
{
throw new PersistenceBrokerException("pkFieldName length does not match number of defined PK fields." +
" Expected number of PK fields is " + flds.length + ", given number was " +
(pkFieldNames != null ? pkFieldNames.length : 0));
}
boolean result = true;
for(int i = 0; i < flds.length; i++)
{
FieldDescriptor fld = flds[i];
result = result && fld.getPersistentField().getName().equals(pkFieldNames[i]);
}
return result;
} | java | {
"resource": ""
} |
q9831 | IdentityFactoryImpl.createException | train | private PersistenceBrokerException createException(final Exception ex, String message, final Object objectToIdentify, Class topLevelClass, Class realClass, Object[] pks)
{
final String eol = SystemUtils.LINE_SEPARATOR;
StringBuffer msg = new StringBuffer();
if(message == null)
{
msg.append("Unexpected error: ");
}
else
{
msg.append(message).append(" :");
}
if(topLevelClass != null) msg.append(eol).append("objectTopLevelClass=").append(topLevelClass.getName());
if(realClass != null) msg.append(eol).append("objectRealClass=").append(realClass.getName());
if(pks != null) msg.append(eol).append("pkValues=").append(ArrayUtils.toString(pks));
if(objectToIdentify != null) msg.append(eol).append("object to identify: ").append(objectToIdentify);
if(ex != null)
{
// add causing stack trace
Throwable rootCause = ExceptionUtils.getRootCause(ex);
if(rootCause != null)
{
msg.append(eol).append("The root stack trace is --> ");
String rootStack = ExceptionUtils.getStackTrace(rootCause);
msg.append(eol).append(rootStack);
}
return new PersistenceBrokerException(msg.toString(), ex);
}
else
{
return new PersistenceBrokerException(msg.toString());
}
} | java | {
"resource": ""
} |
q9832 | ObjectEnvelopeOrdering.addEdgesForVertex | train | private void addEdgesForVertex(Vertex vertex)
{
ClassDescriptor cld = vertex.getEnvelope().getClassDescriptor();
Iterator rdsIter = cld.getObjectReferenceDescriptors(true).iterator();
while (rdsIter.hasNext())
{
ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) rdsIter.next();
addObjectReferenceEdges(vertex, rds);
}
Iterator cdsIter = cld.getCollectionDescriptors(true).iterator();
while (cdsIter.hasNext())
{
CollectionDescriptor cds = (CollectionDescriptor) cdsIter.next();
addCollectionEdges(vertex, cds);
}
} | java | {
"resource": ""
} |
q9833 | ObjectEnvelopeOrdering.addObjectReferenceEdges | train | private void addObjectReferenceEdges(Vertex vertex, ObjectReferenceDescriptor rds)
{
Object refObject = rds.getPersistentField().get(vertex.getEnvelope().getRealObject());
Class refClass = rds.getItemClass();
for (int i = 0; i < vertices.length; i++)
{
Edge edge = null;
// ObjectEnvelope envelope = vertex.getEnvelope();
Vertex refVertex = vertices[i];
ObjectEnvelope refEnvelope = refVertex.getEnvelope();
if (refObject == refEnvelope.getRealObject())
{
edge = buildConcrete11Edge(vertex, refVertex, rds.hasConstraint());
}
else if (refClass.isInstance(refVertex.getEnvelope().getRealObject()))
{
edge = buildPotential11Edge(vertex, refVertex, rds.hasConstraint());
}
if (edge != null)
{
if (!edgeList.contains(edge))
{
edgeList.add(edge);
}
else
{
edge.increaseWeightTo(edge.getWeight());
}
}
}
} | java | {
"resource": ""
} |
q9834 | ObjectEnvelopeOrdering.containsObject | train | private static boolean containsObject(Object searchFor, Object[] searchIn)
{
for (int i = 0; i < searchIn.length; i++)
{
if (searchFor == searchIn[i])
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q9835 | HttpSpringLogger.getHeadersAsMap | train | protected static Map<String, String> getHeadersAsMap(ResponseEntity response) {
Map<String, List<String>> headers = new HashMap<>(response.getHeaders());
Map<String, String> map = new HashMap<>();
for ( Map.Entry<String, List<String>> header :headers.entrySet() ) {
String headerValue = Joiner.on(",").join(header.getValue());
map.put(header.getKey(), headerValue);
}
return map;
} | java | {
"resource": ""
} |
q9836 | ConnectionPoolDescriptor.init | train | private void init()
{
jdbcProperties = new Properties();
dbcpProperties = new Properties();
setFetchSize(0);
this.setTestOnBorrow(true);
this.setTestOnReturn(false);
this.setTestWhileIdle(false);
this.setLogAbandoned(false);
this.setRemoveAbandoned(false);
} | java | {
"resource": ""
} |
q9837 | ConnectionPoolDescriptor.addAttribute | train | public void addAttribute(String attributeName, String attributeValue)
{
if (attributeName != null && attributeName.startsWith(JDBC_PROPERTY_NAME_PREFIX))
{
final String jdbcPropertyName = attributeName.substring(JDBC_PROPERTY_NAME_LENGTH);
jdbcProperties.setProperty(jdbcPropertyName, attributeValue);
}
else if (attributeName != null && attributeName.startsWith(DBCP_PROPERTY_NAME_PREFIX))
{
final String dbcpPropertyName = attributeName.substring(DBCP_PROPERTY_NAME_LENGTH);
dbcpProperties.setProperty(dbcpPropertyName, attributeValue);
}
else
{
super.addAttribute(attributeName, attributeValue);
}
} | java | {
"resource": ""
} |
q9838 | DefaultSecurityContext.userInfoInit | train | private void userInfoInit() {
boolean first = true;
userId = null;
userLocale = null;
userName = null;
userOrganization = null;
userDivision = null;
if (null != authentications) {
for (Authentication auth : authentications) {
userId = combine(userId, auth.getUserId());
userName = combine(userName, auth.getUserName());
if (first) {
userLocale = auth.getUserLocale();
first = false;
} else {
if (null != auth.getUserLocale() &&
(null == userLocale || !userLocale.equals(auth.getUserLocale()))) {
userLocale = null;
}
}
userOrganization = combine(userOrganization, auth.getUserOrganization());
userDivision = combine(userDivision, auth.getUserDivision());
}
}
// now calculate the "id" for this context, this should be independent of the data order, so sort
Map<String, List<String>> idParts = new HashMap<String, List<String>>();
if (null != authentications) {
for (Authentication auth : authentications) {
List<String> auths = new ArrayList<String>();
for (BaseAuthorization ba : auth.getAuthorizations()) {
auths.add(ba.getId());
}
Collections.sort(auths);
idParts.put(auth.getSecurityServiceId(), auths);
}
}
StringBuilder sb = new StringBuilder();
List<String> sortedKeys = new ArrayList<String>(idParts.keySet());
Collections.sort(sortedKeys);
for (String key : sortedKeys) {
if (sb.length() > 0) {
sb.append('|');
}
List<String> auths = idParts.get(key);
first = true;
for (String ak : auths) {
if (first) {
first = false;
} else {
sb.append('|');
}
sb.append(ak);
}
sb.append('@');
sb.append(key);
}
id = sb.toString();
} | java | {
"resource": ""
} |
q9839 | DefaultSecurityContext.restoreSecurityContext | train | @Api
public void restoreSecurityContext(SavedAuthorization savedAuthorization) {
List<Authentication> auths = new ArrayList<Authentication>();
if (null != savedAuthorization) {
for (SavedAuthentication sa : savedAuthorization.getAuthentications()) {
Authentication auth = new Authentication();
auth.setSecurityServiceId(sa.getSecurityServiceId());
auth.setAuthorizations(sa.getAuthorizations());
auths.add(auth);
}
}
setAuthentications(null, auths);
userInfoInit();
} | java | {
"resource": ""
} |
q9840 | DeliveryArtifactsPicker.work | train | public void work(RepositoryHandler repoHandler, DbProduct product) {
if (!product.getDeliveries().isEmpty()) {
product.getDeliveries().forEach(delivery -> {
final Set<Artifact> artifacts = new HashSet<>();
final DataFetchingUtils utils = new DataFetchingUtils();
final DependencyHandler depHandler = new DependencyHandler(repoHandler);
final Set<String> deliveryDependencies = utils.getDeliveryDependencies(repoHandler, depHandler, delivery);
final Set<String> fullGAVCSet = deliveryDependencies.stream().filter(DataUtils::isFullGAVC).collect(Collectors.toSet());
final Set<String> shortIdentiferSet = deliveryDependencies.stream().filter(entry -> !DataUtils.isFullGAVC(entry)).collect(Collectors.toSet());
processDependencySet(repoHandler,
shortIdentiferSet,
batch -> String.format(BATCH_TEMPLATE_REGEX, StringUtils.join(batch, '|')),
1,
artifacts::add
);
processDependencySet(repoHandler,
fullGAVCSet,
batch -> QueryUtils.quoteIds(batch, BATCH_TEMPLATE),
10,
artifacts::add
);
if (!artifacts.isEmpty()) {
delivery.setAllArtifactDependencies(new ArrayList<>(artifacts));
}
});
repoHandler.store(product);
}
} | java | {
"resource": ""
} |
q9841 | SqlSelectStatement.getMultiJoinedClassDescriptors | train | private ClassDescriptor[] getMultiJoinedClassDescriptors(ClassDescriptor cld)
{
DescriptorRepository repository = cld.getRepository();
Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, true);
ClassDescriptor[] result = new ClassDescriptor[multiJoinedClasses.length];
for (int i = 0 ; i < multiJoinedClasses.length; i++)
{
result[i] = repository.getDescriptorFor(multiJoinedClasses[i]);
}
return result;
} | java | {
"resource": ""
} |
q9842 | SqlSelectStatement.appendClazzColumnForSelect | train | private void appendClazzColumnForSelect(StringBuffer buf)
{
ClassDescriptor cld = getSearchClassDescriptor();
ClassDescriptor[] clds = getMultiJoinedClassDescriptors(cld);
if (clds.length == 0)
{
return;
}
buf.append(",CASE");
for (int i = clds.length; i > 0; i--)
{
buf.append(" WHEN ");
ClassDescriptor subCld = clds[i - 1];
FieldDescriptor[] fieldDescriptors = subCld.getPkFields();
TableAlias alias = getTableAliasForClassDescriptor(subCld);
for (int j = 0; j < fieldDescriptors.length; j++)
{
FieldDescriptor field = fieldDescriptors[j];
if (j > 0)
{
buf.append(" AND ");
}
appendColumn(alias, field, buf);
buf.append(" IS NOT NULL");
}
buf.append(" THEN '").append(subCld.getClassNameOfObject()).append("'");
}
buf.append(" ELSE '").append(cld.getClassNameOfObject()).append("'");
buf.append(" END AS " + SqlHelper.OJB_CLASS_COLUMN);
} | java | {
"resource": ""
} |
q9843 | NamedRootsMap.lookup | train | Object lookup(String key) throws ObjectNameNotFoundException
{
Object result = null;
NamedEntry entry = localLookup(key);
// can't find local bound object
if(entry == null)
{
try
{
PersistenceBroker broker = tx.getBroker();
// build Identity to lookup entry
Identity oid = broker.serviceIdentity().buildIdentity(NamedEntry.class, key);
entry = (NamedEntry) broker.getObjectByIdentity(oid);
}
catch(Exception e)
{
log.error("Can't materialize bound object for key '" + key + "'", e);
}
}
if(entry == null)
{
log.info("No object found for key '" + key + "'");
}
else
{
Object obj = entry.getObject();
// found a persistent capable object associated with that key
if(obj instanceof Identity)
{
Identity objectIdentity = (Identity) obj;
result = tx.getBroker().getObjectByIdentity(objectIdentity);
// lock the persistance capable object
RuntimeObject rt = new RuntimeObject(result, objectIdentity, tx, false);
tx.lockAndRegister(rt, Transaction.READ, tx.getRegistrationList());
}
else
{
// nothing else to do
result = obj;
}
}
if(result == null) throw new ObjectNameNotFoundException("Can't find named object for name '" + key + "'");
return result;
} | java | {
"resource": ""
} |
q9844 | NamedRootsMap.unbind | train | void unbind(String key)
{
NamedEntry entry = new NamedEntry(key, null, false);
localUnbind(key);
addForDeletion(entry);
} | java | {
"resource": ""
} |
q9845 | MetadataManager.readDescriptorRepository | train | public DescriptorRepository readDescriptorRepository(String fileName)
{
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readDescriptorRepository(fileName);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository " + fileName, e);
}
} | java | {
"resource": ""
} |
q9846 | MetadataManager.readDescriptorRepository | train | public DescriptorRepository readDescriptorRepository(InputStream inst)
{
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readDescriptorRepository(inst);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository " + inst, e);
}
} | java | {
"resource": ""
} |
q9847 | MetadataManager.readConnectionRepository | train | public ConnectionRepository readConnectionRepository(String fileName)
{
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readConnectionRepository(fileName);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository " + fileName, e);
}
} | java | {
"resource": ""
} |
q9848 | MetadataManager.readConnectionRepository | train | public ConnectionRepository readConnectionRepository(InputStream inst)
{
try
{
RepositoryPersistor persistor = new RepositoryPersistor();
return persistor.readConnectionRepository(inst);
}
catch (Exception e)
{
throw new MetadataException("Can not read repository from " + inst, e);
}
} | java | {
"resource": ""
} |
q9849 | MetadataManager.addProfile | train | public void addProfile(Object key, DescriptorRepository repository)
{
if (metadataProfiles.contains(key))
{
throw new MetadataException("Duplicate profile key. Key '" + key + "' already exists.");
}
metadataProfiles.put(key, repository);
} | java | {
"resource": ""
} |
q9850 | MetadataManager.loadProfile | train | public void loadProfile(Object key)
{
if (!isEnablePerThreadChanges())
{
throw new MetadataException("Can not load profile with disabled per thread mode");
}
DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);
if (rep == null)
{
throw new MetadataException("Can not find profile for key '" + key + "'");
}
currentProfileKey.set(key);
setDescriptor(rep);
} | java | {
"resource": ""
} |
q9851 | MetadataManager.buildDefaultKey | train | private PBKey buildDefaultKey()
{
List descriptors = connectionRepository().getAllDescriptor();
JdbcConnectionDescriptor descriptor;
PBKey result = null;
for (Iterator iterator = descriptors.iterator(); iterator.hasNext();)
{
descriptor = (JdbcConnectionDescriptor) iterator.next();
if (descriptor.isDefaultConnection())
{
if(result != null)
{
log.error("Found additional connection descriptor with enabled 'default-connection' "
+ descriptor.getPBKey() + ". This is NOT allowed. Will use the first found descriptor " + result
+ " as default connection");
}
else
{
result = descriptor.getPBKey();
}
}
}
if(result == null)
{
log.info("No 'default-connection' attribute set in jdbc-connection-descriptors," +
" thus it's currently not possible to use 'defaultPersistenceBroker()' " +
" convenience method to lookup PersistenceBroker instances. But it's possible"+
" to enable this at runtime using 'setDefaultKey' method.");
}
return result;
} | java | {
"resource": ""
} |
q9852 | ReferenceMap.toReference | train | private Object toReference(int type, Object referent, int hash)
{
switch (type)
{
case HARD:
return referent;
case SOFT:
return new SoftRef(hash, referent, queue);
case WEAK:
return new WeakRef(hash, referent, queue);
default:
throw new Error();
}
} | java | {
"resource": ""
} |
q9853 | ReferenceMap.getEntry | train | private Entry getEntry(Object key)
{
if (key == null) return null;
int hash = hashCode(key);
int index = indexFor(hash);
for (Entry entry = table[index]; entry != null; entry = entry.next)
{
if ((entry.hash == hash) && equals(key, entry.getKey()))
{
return entry;
}
}
return null;
} | java | {
"resource": ""
} |
q9854 | ReferenceMap.indexFor | train | private int indexFor(int hash)
{
// mix the bits to avoid bucket collisions...
hash += ~(hash << 15);
hash ^= (hash >>> 10);
hash += (hash << 3);
hash ^= (hash >>> 6);
hash += ~(hash << 11);
hash ^= (hash >>> 16);
return hash & (table.length - 1);
} | java | {
"resource": ""
} |
q9855 | ReferenceMap.get | train | public Object get(Object key)
{
purge();
Entry entry = getEntry(key);
if (entry == null) return null;
return entry.getValue();
} | java | {
"resource": ""
} |
q9856 | ReferenceMap.remove | train | public Object remove(Object key)
{
if (key == null) return null;
purge();
int hash = hashCode(key);
int index = indexFor(hash);
Entry previous = null;
Entry entry = table[index];
while (entry != null)
{
if ((hash == entry.hash) && equals(key, entry.getKey()))
{
if (previous == null)
table[index] = entry.next;
else
previous.next = entry.next;
this.size--;
modCount++;
return entry.getValue();
}
previous = entry;
entry = entry.next;
}
return null;
} | java | {
"resource": ""
} |
q9857 | ReferenceMap.values | train | public Collection values()
{
if (values != null) return values;
values = new AbstractCollection()
{
public int size()
{
return size;
}
public void clear()
{
ReferenceMap.this.clear();
}
public Iterator iterator()
{
return new ValueIterator();
}
};
return values;
} | java | {
"resource": ""
} |
q9858 | DtoConverterServiceImpl.toInternal | train | public Object toInternal(Attribute<?> attribute) throws GeomajasException {
if (attribute instanceof PrimitiveAttribute<?>) {
return toPrimitiveObject((PrimitiveAttribute<?>) attribute);
} else if (attribute instanceof AssociationAttribute<?>) {
return toAssociationObject((AssociationAttribute<?>) attribute);
} else {
throw new GeomajasException(ExceptionCode.CONVERSION_PROBLEM, attribute);
}
} | java | {
"resource": ""
} |
q9859 | DtoConverterServiceImpl.toDto | train | public Feature toDto(InternalFeature feature, int featureIncludes) throws GeomajasException {
if (feature == null) {
return null;
}
Feature dto = new Feature(feature.getId());
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES) != 0 && null != feature.getAttributes()) {
// need to assure lazy attributes are converted to non-lazy attributes
Map<String, Attribute> attributes = new HashMap<String, Attribute>();
for (Map.Entry<String, Attribute> entry : feature.getAttributes().entrySet()) {
Attribute value = entry.getValue();
if (value instanceof LazyAttribute) {
value = ((LazyAttribute) value).instantiate();
}
attributes.put(entry.getKey(), value);
}
dto.setAttributes(attributes);
}
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_LABEL) != 0) {
dto.setLabel(feature.getLabel());
}
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_GEOMETRY) != 0) {
dto.setGeometry(toDto(feature.getGeometry()));
}
if ((featureIncludes & VectorLayerService.FEATURE_INCLUDE_STYLE) != 0 && null != feature.getStyleInfo()) {
dto.setStyleId(feature.getStyleInfo().getStyleId());
}
InternalFeatureImpl vFeature = (InternalFeatureImpl) feature;
dto.setClipped(vFeature.isClipped());
dto.setUpdatable(feature.isEditable());
dto.setDeletable(feature.isDeletable());
return dto;
} | java | {
"resource": ""
} |
q9860 | DtoConverterServiceImpl.toInternal | train | public Class<? extends com.vividsolutions.jts.geom.Geometry> toInternal(LayerType layerType) {
switch (layerType) {
case GEOMETRY:
return com.vividsolutions.jts.geom.Geometry.class;
case LINESTRING:
return LineString.class;
case MULTILINESTRING:
return MultiLineString.class;
case POINT:
return Point.class;
case MULTIPOINT:
return MultiPoint.class;
case POLYGON:
return Polygon.class;
case MULTIPOLYGON:
return MultiPolygon.class;
case RASTER:
return null;
default:
throw new IllegalStateException("Don't know how to handle layer type " + layerType);
}
} | java | {
"resource": ""
} |
q9861 | DtoConverterServiceImpl.toDto | train | public LayerType toDto(Class<? extends com.vividsolutions.jts.geom.Geometry> geometryClass) {
if (geometryClass == LineString.class) {
return LayerType.LINESTRING;
} else if (geometryClass == MultiLineString.class) {
return LayerType.MULTILINESTRING;
} else if (geometryClass == Point.class) {
return LayerType.POINT;
} else if (geometryClass == MultiPoint.class) {
return LayerType.MULTIPOINT;
} else if (geometryClass == Polygon.class) {
return LayerType.POLYGON;
} else if (geometryClass == MultiPolygon.class) {
return LayerType.MULTIPOLYGON;
} else {
return LayerType.GEOMETRY;
}
} | java | {
"resource": ""
} |
q9862 | IndexedCache.put | train | public void put(String key, Object object, Envelope envelope) {
index.put(key, envelope);
cache.put(key, object);
} | java | {
"resource": ""
} |
q9863 | IndexedCache.get | train | public <TYPE> TYPE get(String key, Class<TYPE> type) {
return cache.get(key, type);
} | java | {
"resource": ""
} |
q9864 | CollectionDescriptor.addFkToThisClass | train | public void addFkToThisClass(String column)
{
if (fksToThisClass == null)
{
fksToThisClass = new Vector();
}
fksToThisClass.add(column);
fksToThisClassAry = null;
} | java | {
"resource": ""
} |
q9865 | CollectionDescriptor.addFkToItemClass | train | public void addFkToItemClass(String column)
{
if (fksToItemClass == null)
{
fksToItemClass = new Vector();
}
fksToItemClass.add(column);
fksToItemClassAry = null;
} | java | {
"resource": ""
} |
q9866 | SequenceManagerStoredProcedureImpl.sp_createSequenceQuery | train | protected String sp_createSequenceQuery(String sequenceName, long maxKey)
{
return "insert into " + SEQ_TABLE_NAME + " ("
+ SEQ_NAME_STRING + "," + SEQ_ID_STRING +
") values ('" + sequenceName + "'," + maxKey + ")";
} | java | {
"resource": ""
} |
q9867 | SequenceManagerStoredProcedureImpl.getUniqueLong | train | protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException
{
boolean needsCommit = false;
long result = 0;
/*
arminw:
use the associated broker instance, check if broker was in tx or
we need to commit used connection.
*/
PersistenceBroker targetBroker = getBrokerForClass();
if(!targetBroker.isInTransaction())
{
targetBroker.beginTransaction();
needsCommit = true;
}
try
{
// lookup sequence name
String sequenceName = calculateSequenceName(field);
try
{
result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);
/*
if 0 was returned we assume that the stored procedure
did not work properly.
*/
if (result == 0)
{
throw new SequenceManagerException("No incremented value retrieved");
}
}
catch (Exception e)
{
// maybe the sequence was not created
log.info("Could not grab next key, message was " + e.getMessage() +
" - try to write a new sequence entry to database");
try
{
// on create, make sure to get the max key for the table first
long maxKey = SequenceManagerHelper.getMaxForExtent(targetBroker, field);
createSequence(targetBroker, field, sequenceName, maxKey);
}
catch (Exception e1)
{
String eol = SystemUtils.LINE_SEPARATOR;
throw new SequenceManagerException(eol + "Could not grab next id, failed with " + eol +
e.getMessage() + eol + "Creation of new sequence failed with " +
eol + e1.getMessage() + eol, e1);
}
try
{
result = buildNextSequence(targetBroker, field.getClassDescriptor(), sequenceName);
}
catch (Exception e1)
{
throw new SequenceManagerException("Could not grab next id although a sequence seems to exist", e);
}
}
}
finally
{
if(targetBroker != null && needsCommit)
{
targetBroker.commitTransaction();
}
}
return result;
} | java | {
"resource": ""
} |
q9868 | SequenceManagerStoredProcedureImpl.buildNextSequence | train | protected long buildNextSequence(PersistenceBroker broker, ClassDescriptor cld, String sequenceName)
throws LookupException, SQLException, PlatformException
{
CallableStatement cs = null;
try
{
Connection con = broker.serviceConnectionManager().getConnection();
cs = getPlatform().prepareNextValProcedureStatement(con, PROCEDURE_NAME, sequenceName);
cs.executeUpdate();
return cs.getLong(1);
}
finally
{
try
{
if (cs != null)
cs.close();
}
catch (SQLException ignore)
{
// ignore it
}
}
} | java | {
"resource": ""
} |
q9869 | SequenceManagerStoredProcedureImpl.createSequence | train | protected void createSequence(PersistenceBroker broker, FieldDescriptor field,
String sequenceName, long maxKey) throws Exception
{
Statement stmt = null;
try
{
stmt = broker.serviceStatementManager().getGenericStatement(field.getClassDescriptor(), Query.NOT_SCROLLABLE);
stmt.execute(sp_createSequenceQuery(sequenceName, maxKey));
}
catch (Exception e)
{
log.error(e);
throw new SequenceManagerException("Could not create new row in "+SEQ_TABLE_NAME+" table - TABLENAME=" +
sequenceName + " field=" + field.getColumnName(), e);
}
finally
{
try
{
if (stmt != null) stmt.close();
}
catch (SQLException sqle)
{
if(log.isDebugEnabled())
log.debug("Threw SQLException while in createSequence and closing stmt", sqle);
// ignore it
}
}
} | java | {
"resource": ""
} |
q9870 | FoundationLogger.init | train | static void init() {// NOPMD
determineIfNTEventLogIsSupported();
URL resource = null;
final String configurationOptionStr = OptionConverter.getSystemProperty(DEFAULT_CONFIGURATION_KEY, null);
if (configurationOptionStr != null) {
try {
resource = new URL(configurationOptionStr);
} catch (MalformedURLException ex) {
// so, resource is not a URL:
// attempt to get the resource from the class path
resource = Loader.getResource(configurationOptionStr);
}
}
if (resource == null) {
resource = Loader.getResource(DEFAULT_CONFIGURATION_FILE); // NOPMD
}
if (resource == null) {
System.err.println("[FoundationLogger] Can not find resource: " + DEFAULT_CONFIGURATION_FILE); // NOPMD
throw new FoundationIOException("Can not find resource: " + DEFAULT_CONFIGURATION_FILE); // NOPMD
}
// update the log manager to use the Foundation repository.
final RepositorySelector foundationRepositorySelector = new FoundationRepositorySelector(FoundationLogFactory.foundationLogHierarchy);
LogManager.setRepositorySelector(foundationRepositorySelector, null);
// set logger to info so we always want to see these logs even if root
// is set to ERROR.
final Logger logger = getLogger(FoundationLogger.class);
final String logPropFile = resource.getPath();
log4jConfigProps = getLogProperties(resource);
// select and configure again so the loggers are created with the right
// level after the repository selector was updated.
OptionConverter.selectAndConfigure(resource, null, FoundationLogFactory.foundationLogHierarchy);
// start watching for property changes
setUpPropFileReloading(logger, logPropFile, log4jConfigProps);
// add syslog appender or windows event viewer appender
// setupOSSystemLog(logger, log4jConfigProps);
// parseMarkerPatterns(log4jConfigProps);
// parseMarkerPurePattern(log4jConfigProps);
// udpateMarkerStructuredLogOverrideMap(logger);
AbstractFoundationLoggingMarker.init();
updateSniffingLoggersLevel(logger);
setupJULSupport(resource);
} | java | {
"resource": ""
} |
q9871 | FoundationLogger.updateSniffingLoggersLevel | train | private static void updateSniffingLoggersLevel(Logger logger) {
InputStream settingIS = FoundationLogger.class
.getResourceAsStream("/sniffingLogger.xml");
if (settingIS == null) {
logger.debug("file sniffingLogger.xml not found in classpath");
} else {
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(settingIS);
settingIS.close();
Element rootElement = document.getRootElement();
List<Element> sniffingloggers = rootElement
.getChildren("sniffingLogger");
for (Element sniffinglogger : sniffingloggers) {
String loggerName = sniffinglogger.getAttributeValue("id");
Logger.getLogger(loggerName).setLevel(Level.TRACE);
}
} catch (Exception e) {
logger.error(
"cannot load the sniffing logger configuration file. error is: "
+ e, e);
throw new IllegalArgumentException(
"Problem parsing sniffingLogger.xml", e);
}
}
} | java | {
"resource": ""
} |
q9872 | ObjectCacheJCSImpl.cache | train | public void cache(Identity oid, Object obj)
{
try
{
jcsCache.put(oid.toString(), obj);
}
catch (CacheException e)
{
throw new RuntimeCacheException(e);
}
} | java | {
"resource": ""
} |
q9873 | ObjectCacheJCSImpl.remove | train | public void remove(Identity oid)
{
try
{
jcsCache.remove(oid.toString());
}
catch (CacheException e)
{
throw new RuntimeCacheException(e.getMessage());
}
} | java | {
"resource": ""
} |
q9874 | YahooPlaceFinderGeocoderService.search | train | public List<GetLocationResult> search(String q, int maxRows, Locale locale)
throws Exception {
List<GetLocationResult> searchResult = new ArrayList<GetLocationResult>();
String url = URLEncoder.encode(q, "UTF8");
url = "q=select%20*%20from%20geo.placefinder%20where%20text%3D%22"
+ url + "%22";
if (maxRows > 0) {
url = url + "&count=" + maxRows;
}
url = url + "&flags=GX";
if (null != locale) {
url = url + "&locale=" + locale;
}
if (appId != null) {
url = url + "&appid=" + appId;
}
InputStream inputStream = connect(url);
if (null != inputStream) {
SAXBuilder parser = new SAXBuilder();
Document doc = parser.build(inputStream);
Element root = doc.getRootElement();
// check code for exception
String message = root.getChildText("Error");
// Integer errorCode = Integer.parseInt(message);
if (message != null && Integer.parseInt(message) != 0) {
throw new Exception(root.getChildText("ErrorMessage"));
}
Element results = root.getChild("results");
for (Object obj : results.getChildren("Result")) {
Element toponymElement = (Element) obj;
GetLocationResult location = getLocationFromElement(toponymElement);
searchResult.add(location);
}
}
return searchResult;
} | java | {
"resource": ""
} |
q9875 | DescriptorRepository.getDescriptorFor | train | public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException
{
ClassDescriptor result = discoverDescriptor(strClassName);
if (result == null)
{
throw new ClassNotPersistenceCapableException(strClassName + " not found in OJB Repository");
}
else
{
return result;
}
} | java | {
"resource": ""
} |
q9876 | DescriptorRepository.getIsolationLevelAsString | train | protected String getIsolationLevelAsString()
{
if (defaultIsolationLevel == IL_READ_UNCOMMITTED)
{
return LITERAL_IL_READ_UNCOMMITTED;
}
else if (defaultIsolationLevel == IL_READ_COMMITTED)
{
return LITERAL_IL_READ_COMMITTED;
}
else if (defaultIsolationLevel == IL_REPEATABLE_READ)
{
return LITERAL_IL_REPEATABLE_READ;
}
else if (defaultIsolationLevel == IL_SERIALIZABLE)
{
return LITERAL_IL_SERIALIZABLE;
}
else if (defaultIsolationLevel == IL_OPTIMISTIC)
{
return LITERAL_IL_OPTIMISTIC;
}
return LITERAL_IL_READ_UNCOMMITTED;
} | java | {
"resource": ""
} |
q9877 | DescriptorRepository.discoverDescriptor | train | private ClassDescriptor discoverDescriptor(Class clazz)
{
ClassDescriptor result = (ClassDescriptor) descriptorTable.get(clazz.getName());
if (result == null)
{
Class superClass = clazz.getSuperclass();
// only recurse if the superClass is not java.lang.Object
if (superClass != null)
{
result = discoverDescriptor(superClass);
}
if (result == null)
{
// we're also checking the interfaces as there could be normal
// mappings for them in the repository (using factory-class,
// factory-method, and the property field accessor)
Class[] interfaces = clazz.getInterfaces();
if ((interfaces != null) && (interfaces.length > 0))
{
for (int idx = 0; (idx < interfaces.length) && (result == null); idx++)
{
result = discoverDescriptor(interfaces[idx]);
}
}
}
if (result != null)
{
/**
* Kuali Foundation modification -- 6/19/2009
*/
synchronized (descriptorTable) {
/**
* End of Kuali Foundation modification
*/
descriptorTable.put(clazz.getName(), result);
/**
* Kuali Foundation modification -- 6/19/2009
*/
}
/**
* End of Kuali Foundation modification
*/
}
}
return result;
} | java | {
"resource": ""
} |
q9878 | DescriptorRepository.createResultSubClassesMultipleJoinedTables | train | private void createResultSubClassesMultipleJoinedTables(List result, ClassDescriptor cld, boolean wholeTree)
{
List tmp = (List) superClassMultipleJoinedTablesMap.get(cld.getClassOfObject());
if(tmp != null)
{
result.addAll(tmp);
if(wholeTree)
{
for(int i = 0; i < tmp.size(); i++)
{
Class subClass = (Class) tmp.get(i);
ClassDescriptor subCld = getDescriptorFor(subClass);
createResultSubClassesMultipleJoinedTables(result, subCld, wholeTree);
}
}
}
} | java | {
"resource": ""
} |
q9879 | WmsLayer.getProxyAuthentication | train | public ProxyAuthentication getProxyAuthentication() {
// convert authentication to layerAuthentication so we only use one
// TODO Remove when removing deprecated authentication field.
if (layerAuthentication == null && authentication != null) {
layerAuthentication = new LayerAuthentication();
layerAuthentication.setAuthenticationMethod(LayerAuthenticationMethod.valueOf(authentication
.getAuthenticationMethod().name()));
layerAuthentication.setPassword(authentication.getPassword());
layerAuthentication.setPasswordKey(authentication.getPasswordKey());
layerAuthentication.setRealm(authentication.getRealm());
layerAuthentication.setUser(authentication.getUser());
layerAuthentication.setUserKey(authentication.getUserKey());
}
// TODO Remove when removing deprecated authentication field.
return layerAuthentication;
} | java | {
"resource": ""
} |
q9880 | WmsLayer.setUseCache | train | @Api
public void setUseCache(boolean useCache) {
if (null == cacheManagerService && useCache) {
log.warn("The caching plugin needs to be available to cache WMS requests. Not setting useCache.");
} else {
this.useCache = useCache;
}
} | java | {
"resource": ""
} |
q9881 | LayerAuthorization.check | train | protected boolean check(String id, List<String> includes, List<String> excludes) {
return check(id, includes) && !check(id, excludes);
} | java | {
"resource": ""
} |
q9882 | LayerAuthorization.check | train | protected boolean check(String id, List<String> includes) {
if (null != includes) {
for (String check : includes) {
if (check(id, check)) {
return true;
}
}
}
return false;
} | java | {
"resource": ""
} |
q9883 | LayerAuthorization.check | train | protected boolean check(String value, String regex) {
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(value).matches();
} | java | {
"resource": ""
} |
q9884 | SqlPkStatement.getClassDescriptor | train | protected ClassDescriptor getClassDescriptor()
{
ClassDescriptor cld = (ClassDescriptor) m_classDescriptor.get();
if(cld == null)
{
throw new OJBRuntimeException("Requested ClassDescriptor instance was already GC by JVM");
}
return cld;
} | java | {
"resource": ""
} |
q9885 | SqlPkStatement.appendWhereClause | train | protected void appendWhereClause(FieldDescriptor[] fields, StringBuffer stmt) throws PersistenceBrokerException
{
stmt.append(" WHERE ");
for(int i = 0; i < fields.length; i++)
{
FieldDescriptor fmd = fields[i];
stmt.append(fmd.getColumnName());
stmt.append(" = ? ");
if(i < fields.length - 1)
{
stmt.append(" AND ");
}
}
} | java | {
"resource": ""
} |
q9886 | SqlPkStatement.appendWhereClause | train | protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt)
{
FieldDescriptor[] pkFields = cld.getPkFields();
FieldDescriptor[] fields;
fields = pkFields;
if(useLocking)
{
FieldDescriptor[] lockingFields = cld.getLockingFields();
if(lockingFields.length > 0)
{
fields = new FieldDescriptor[pkFields.length + lockingFields.length];
System.arraycopy(pkFields, 0, fields, 0, pkFields.length);
System.arraycopy(lockingFields, 0, fields, pkFields.length, lockingFields.length);
}
}
appendWhereClause(fields, stmt);
} | java | {
"resource": ""
} |
q9887 | SerializeObjectCopyStrategy.copy | train | public Object copy(final Object obj, PersistenceBroker broker)
throws ObjectCopyException
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
// serialize and pass the object
oos.writeObject(obj);
oos.flush();
final ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bin);
// return the new object
return ois.readObject();
}
catch (Exception e)
{
throw new ObjectCopyException(e);
}
finally
{
try
{
if (oos != null)
{
oos.close();
}
if (ois != null)
{
ois.close();
}
}
catch (IOException ioe)
{
// ignore
}
}
} | java | {
"resource": ""
} |
q9888 | StatementManager.bindDelete | train | public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException
{
Object[] pkValues = oid.getPrimaryKeyValues();
FieldDescriptor[] pkFields = cld.getPkFields();
int i = 0;
try
{
for (; i < pkValues.length; i++)
{
setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());
}
}
catch (SQLException e)
{
m_log.error("bindDelete failed for: " + oid.toString() + ", while set value '" +
pkValues[i] + "' for column " + pkFields[i].getColumnName());
throw e;
}
} | java | {
"resource": ""
} |
q9889 | StatementManager.bindDelete | train | public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException
{
if (cld.getDeleteProcedure() != null)
{
this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure());
}
else
{
int index = 1;
ValueContainer[] values, currentLockingValues;
currentLockingValues = cld.getCurrentLockingValues(obj);
// parameters for WHERE-clause pk
values = getKeyValues(m_broker, cld, obj);
for (int i = 0; i < values.length; i++)
{
setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
index++;
}
// parameters for WHERE-clause locking
values = currentLockingValues;
for (int i = 0; i < values.length; i++)
{
setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
index++;
}
}
} | java | {
"resource": ""
} |
q9890 | StatementManager.bindStatementValue | train | private int bindStatementValue(PreparedStatement stmt, int index, Object attributeOrQuery, Object value, ClassDescriptor cld)
throws SQLException
{
FieldDescriptor fld = null;
// if value is a subQuery bind it
if (value instanceof Query)
{
Query subQuery = (Query) value;
return bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);
}
// if attribute is a subQuery bind it
if (attributeOrQuery instanceof Query)
{
Query subQuery = (Query) attributeOrQuery;
bindStatement(stmt, subQuery, cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);
}
else
{
fld = cld.getFieldDescriptorForPath((String) attributeOrQuery);
}
if (fld != null)
{
// BRJ: use field conversions and platform
if (value != null)
{
m_platform.setObjectForStatement(stmt, index, fld.getFieldConversion().javaToSql(value), fld.getJdbcType().getType());
}
else
{
m_platform.setNullForStatement(stmt, index, fld.getJdbcType().getType());
}
}
else
{
if (value != null)
{
stmt.setObject(index, value);
}
else
{
stmt.setNull(index, Types.NULL);
}
}
return ++index; // increment before return
} | java | {
"resource": ""
} |
q9891 | StatementManager.bindSelect | train | public void bindSelect(PreparedStatement stmt, Identity oid, ClassDescriptor cld, boolean callableStmt) throws SQLException
{
ValueContainer[] values = null;
int i = 0;
int j = 0;
if (cld == null)
{
cld = m_broker.getClassDescriptor(oid.getObjectsRealClass());
}
try
{
if(callableStmt)
{
// First argument is the result set
m_platform.registerOutResultSet((CallableStatement) stmt, 1);
j++;
}
values = getKeyValues(m_broker, cld, oid);
for (/*void*/; i < values.length; i++, j++)
{
setObjectForStatement(stmt, j + 1, values[i].getValue(), values[i].getJdbcType().getType());
}
}
catch (SQLException e)
{
m_log.error("bindSelect failed for: " + oid.toString() + ", PK: " + i + ", value: " + values[i]);
throw e;
}
} | java | {
"resource": ""
} |
q9892 | StatementManager.getDeleteStatement | train | public PreparedStatement getDeleteStatement(ClassDescriptor cld) throws PersistenceBrokerSQLException, PersistenceBrokerException
{
try
{
return cld.getStatementsForClass(m_conMan).getDeleteStmt(m_conMan.getConnection());
}
catch (SQLException e)
{
throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
}
catch (LookupException e)
{
throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
}
} | java | {
"resource": ""
} |
q9893 | StatementManager.getInsertStatement | train | public PreparedStatement getInsertStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
{
try
{
return cds.getStatementsForClass(m_conMan).getInsertStmt(m_conMan.getConnection());
}
catch (SQLException e)
{
throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
}
catch (LookupException e)
{
throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
}
} | java | {
"resource": ""
} |
q9894 | StatementManager.getPreparedStatement | train | public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,
boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)
throws PersistenceBrokerException
{
try
{
return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);
}
catch (LookupException e)
{
throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
}
} | java | {
"resource": ""
} |
q9895 | StatementManager.getSelectByPKStatement | train | public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
{
try
{
return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection());
}
catch (SQLException e)
{
throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
}
catch (LookupException e)
{
throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
}
} | java | {
"resource": ""
} |
q9896 | StatementManager.getUpdateStatement | train | public PreparedStatement getUpdateStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
{
try
{
return cds.getStatementsForClass(m_conMan).getUpdateStmt(m_conMan.getConnection());
}
catch (SQLException e)
{
throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
}
catch (LookupException e)
{
throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
}
} | java | {
"resource": ""
} |
q9897 | StatementManager.getAllValues | train | protected ValueContainer[] getAllValues(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
return m_broker.serviceBrokerHelper().getAllRwValues(cld, obj);
} | java | {
"resource": ""
} |
q9898 | StatementManager.getKeyValues | train | protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Object obj) throws PersistenceBrokerException
{
return broker.serviceBrokerHelper().getKeyValues(cld, obj);
} | java | {
"resource": ""
} |
q9899 | StatementManager.getKeyValues | train | protected ValueContainer[] getKeyValues(PersistenceBroker broker, ClassDescriptor cld, Identity oid) throws PersistenceBrokerException
{
return broker.serviceBrokerHelper().getKeyValues(cld, oid);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.