_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q164300 | EntityManagerImpl.merge | train | @Override
public final <E> E merge(E e)
{
checkClosed();
checkTransactionNeeded();
try
{
return getPersistenceDelegator().merge(e);
}
catch (Exception ex)
{
// on Rollback
doRollback();
throw new KunderaException(ex);
}
} | java | {
"resource": ""
} |
q164301 | EntityManagerImpl.find | train | @Override
public final <E> E find(Class<E> entityClass, Object primaryKey)
{
checkClosed();
checkTransactionNeeded();
return getPersistenceDelegator().findById(entityClass, primaryKey);
} | java | {
"resource": ""
} |
q164302 | EntityManagerImpl.find | train | @Override
public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties)
{
checkClosed();
checkTransactionNeeded();
// Store current properties in a variable for post-find reset
Map<String, Object> currentProperties = getProperties();
// Populate properties in client
getPersistenceDelegator().populateClientProperties(properties);
T result = find(entityClass, primaryKey);
// Reset Client properties
getPersistenceDelegator().populateClientProperties(currentProperties);
return result;
} | java | {
"resource": ""
} |
q164303 | EntityManagerImpl.refresh | train | @Override
public void refresh(Object entity, Map<String, Object> properties)
{
checkClosed();
// Store current properties in a variable for post-find reset
Map<String, Object> currentProperties = getProperties();
// Populate properties in client
getPersistenceDelegator().populateClientProperties(properties);
// Refresh state of entity
refresh(entity);
// Reset Client properties
getPersistenceDelegator().populateClientProperties(currentProperties);
} | java | {
"resource": ""
} |
q164304 | EntityManagerImpl.setProperty | train | @Override
public void setProperty(String paramString, Object paramObject)
{
checkClosed();
if (getProperties() == null)
{
this.properties = new HashMap<String, Object>();
}
this.properties.put(paramString, paramObject);
getPersistenceDelegator().populateClientProperties(this.properties);
} | java | {
"resource": ""
} |
q164305 | PropertyReader.getProps | train | public static Properties getProps(String fileName) throws Exception
{
Properties properties = new Properties();
InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(fileName);
if (inputStream != null)
{
try
{
properties.load(inputStream);
}
catch (IOException e)
{
LOGGER.error("JSON is null or empty.");
throw new KunderaException("JSON is null or empty.");
}
}
else
{
throw new KunderaException("Property file: [" + fileName + "] not found in the classpath");
}
return properties;
} | java | {
"resource": ""
} |
q164306 | DefaultKunderaEntity.onBind | train | private static void onBind(Class clazz)
{
if (((MetamodelImpl) em.getMetamodel()).getEntityMetadataMap().isEmpty())
{
EntityMetadata metadata = new EntityMetadata(clazz);
metadata.setPersistenceUnit(getPersistenceUnit());
setSchemaAndPU(clazz, metadata);
new TableProcessor(em.getEntityManagerFactory().getProperties(),
((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance())
.process(clazz, metadata);
KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory())
.getKunderaMetadataInstance();
new IndexProcessor(kunderaMetadata).process(clazz, metadata);
ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
((MetamodelImpl) em.getMetamodel()).addEntityMetadata(clazz, metadata);
((MetamodelImpl) em.getMetamodel()).addEntityNameToClassMapping(clazz.getSimpleName(), clazz);
appMetadata.getMetamodelMap().put(getPersistenceUnit(), em.getMetamodel());
Map<String, List<String>> clazzToPuMap = new HashMap<String, List<String>>();
List<String> persistenceUnits = new ArrayList<String>();
persistenceUnits.add(getPersistenceUnit());
clazzToPuMap.put(clazz.getName(), persistenceUnits);
appMetadata.setClazzToPuMap(clazzToPuMap);
new SchemaConfiguration(em.getEntityManagerFactory().getProperties(), kunderaMetadata, getPersistenceUnit())
.configure();
}
} | java | {
"resource": ""
} |
q164307 | DefaultKunderaEntity.setSchemaAndPU | train | private static void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata)
{
Table table = clazz.getAnnotation(Table.class);
if (table != null)
{
metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName());
String schemaStr = table.schema();
MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr,
em.getEntityManagerFactory().getProperties());
}
else
{
metadata.setTableName(clazz.getSimpleName());
metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get("kundera.keyspace"));
}
if (metadata.getPersistenceUnit() == null)
{
metadata.setPersistenceUnit(getPersistenceUnit());
}
} | java | {
"resource": ""
} |
q164308 | CouchbaseQuery.addWhereCondition | train | public Statement addWhereCondition(AsPath asPath, String identifier, String colName, String val, String tableName)
{
com.couchbase.client.java.query.dsl.Expression exp;
switch (identifier)
{
case "<":
exp = x(colName).lt(x(val));
break;
case "<=":
exp = x(colName).lte(x(val));
break;
case ">":
exp = x(colName).gt(x(val));
break;
case ">=":
exp = x(colName).gte(x(val));
break;
case "=":
exp = x(colName).eq(x(val));
break;
default:
LOGGER.error("Operator " + identifier + " is not supported in the JPA query for Couchbase.");
throw new KunderaException("Operator " + identifier + " is not supported in the JPA query for Couchbase.");
}
return asPath.where(exp.and(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x("'" + tableName) + "'")));
} | java | {
"resource": ""
} |
q164309 | JoinTableMetadata.addJoinColumns | train | public void addJoinColumns(String joinColumn)
{
if (joinColumns == null || joinColumns.isEmpty())
{
joinColumns = new HashSet<String>();
}
joinColumns.add(joinColumn);
} | java | {
"resource": ""
} |
q164310 | JoinTableMetadata.addInverseJoinColumns | train | public void addInverseJoinColumns(String inverseJoinColumn)
{
if (inverseJoinColumns == null || inverseJoinColumns.isEmpty())
{
inverseJoinColumns = new HashSet<String>();
}
inverseJoinColumns.add(inverseJoinColumn);
} | java | {
"resource": ""
} |
q164311 | EntityMetadata.getTableName | train | public String getTableName()
{
getEntityType();
return this.entityType != null && !StringUtils.isBlank(((AbstractManagedType) this.entityType).getTableName()) ? ((AbstractManagedType) this.entityType)
.getTableName() : tableName;
} | java | {
"resource": ""
} |
q164312 | EntityMetadata.getSchema | train | public String getSchema()
{
getEntityType();
return this.entityType != null && !StringUtils.isBlank(((AbstractManagedType) this.entityType).getSchemaName()) ? ((AbstractManagedType) this.entityType)
.getSchemaName() : schema;
} | java | {
"resource": ""
} |
q164313 | EntityMetadata.addRelation | train | public void addRelation(String property, Relation relation)
{
relationsMap.put(property, relation);
addRelationName(relation);
} | java | {
"resource": ""
} |
q164314 | EntityMetadata.addRelationName | train | private void addRelationName(Relation rField)
{
if (rField != null && !rField.isRelatedViaJoinTable())
{
String relationName = getJoinColumnName(rField.getProperty());
if (rField.getProperty().isAnnotationPresent(PrimaryKeyJoinColumn.class))
{
relationName = this.getIdAttribute().getName();
}
addToRelationNameCollection(relationName);
}
} | java | {
"resource": ""
} |
q164315 | EntityMetadata.addToRelationNameCollection | train | private void addToRelationNameCollection(String relationName)
{
if (relationNames == null)
{
relationNames = new ArrayList<String>();
}
if (relationName != null)
{
relationNames.add(relationName);
}
} | java | {
"resource": ""
} |
q164316 | EntityMetadata.getJoinColumnName | train | private String getJoinColumnName(Field relation)
{
String columnName = null;
JoinColumn ann = relation.getAnnotation(JoinColumn.class);
if (ann != null)
{
columnName = ann.name();
}
return StringUtils.isBlank(columnName) ? relation.getName() : columnName;
} | java | {
"resource": ""
} |
q164317 | GraphGenerator.generateGraph | train | public <E> ObjectGraph generateGraph(E entity, PersistenceDelegator delegator, NodeState state)
{
this.builder.assign(this);
Node node = generate(entity, delegator, delegator.getPersistenceCache(), state);
this.builder.assignHeadNode(node);
return this.builder.getGraph();
} | java | {
"resource": ""
} |
q164318 | GraphGenerator.onIfSharedByPK | train | private Object onIfSharedByPK(Relation relation, Object childObject, EntityMetadata childMetadata, Object entityId)
{
if (relation.isJoinedByPrimaryKey())
{
PropertyAccessorHelper.setId(childObject, childMetadata, entityId);
}
return childObject;
} | java | {
"resource": ""
} |
q164319 | GraphGenerator.onBuildChildNode | train | void onBuildChildNode(Object childObject, EntityMetadata childMetadata, PersistenceDelegator delegator,
PersistenceCache pc, Node node, Relation relation)
{
Node childNode = generate(childObject, delegator, pc, null);
if (childNode != null)
{
assignNodeLinkProperty(node, relation, childNode);
}
} | java | {
"resource": ""
} |
q164320 | GraphGenerator.assignNodeLinkProperty | train | private void assignNodeLinkProperty(Node node, Relation relation, Node childNode)
{
// Construct Node Link for this relationship
NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId());
setLink(node, relation, childNode, nodeLink);
} | java | {
"resource": ""
} |
q164321 | GraphGenerator.setLink | train | void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink)
{
nodeLink.setMultiplicity(relation.getType());
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator()
.getKunderaMetadata(), node.getDataClass());
nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator()
.getKunderaMetadata()));
// Add Parent node to this child
childNode.addParentNode(nodeLink, node);
// Add child node to this node
node.addChildNode(nodeLink, childNode);
} | java | {
"resource": ""
} |
q164322 | CriteriaQueryTranslator.translate | train | static <S> String translate(CriteriaQuery criteriaQuery)
{
QueryBuilder builder = new CriteriaQueryTranslator.QueryBuilder();
// validate if criteria query is valid
/**
* select, from clause is mandatory
*
* multiple from clause not support where clause is optional
*
*/
Selection<S> select = criteriaQuery.getSelection();
if (select != null)
{
builder.appendSelectClause();
}
if (select.getClass().isAssignableFrom(DefaultCompoundSelection.class)
&& ((CompoundSelection) select).isCompoundSelection())
{
List<Selection<?>> selections = ((CompoundSelection) select).getCompoundSelectionItems();
builder.appendMultiSelect(selections);
}
else if (select instanceof AggregateExpression)
{
builder.appendAggregate(((AggregateExpression) select).getAggregation());
}
else
{
String alias = select.getAlias();
if (!StringUtils.isEmpty(alias))
{
builder.appendAlias(alias);
}
Attribute attribute = ((DefaultPath) select).getAttribute();
if (attribute != null)
{
builder.appendAttribute(attribute);
}
}
Class<? extends S> clazzType = select.getJavaType();
Set<Root<?>> roots = criteriaQuery.getRoots();
Root<?> from = roots.iterator().next();
Class entityClazz = from.getJavaType();
builder.appendFromClause();
// select.alias(paramString)
builder.appendFrom(entityClazz);
builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());
Predicate where = criteriaQuery.getRestriction(); // this could be null.
if (where != null)
{
builder.appendWhereClause();
List<Expression<Boolean>> expressions = where.getExpressions();
for (Expression expr : expressions)
{
builder.appendWhere(expr, from.getAlias());
}
}
List<Order> orderings = criteriaQuery.getOrderList();
if (orderings != null && !orderings.isEmpty())
{
builder.appendOrderClause(where == null);
String alias = from.getAlias() != null ? from.getAlias() : select.getAlias();
builder.appendMultiOrdering(orderings, alias);
}
return builder.getQuery();
// check that roots has to be one. multiple clause not yet supported
} | java | {
"resource": ""
} |
q164323 | EtherObjectConverterUtil.convertEtherBlockToKunderaBlock | train | public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions)
{
Block kunderaBlk = new Block();
org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock();
kunderaBlk.setAuthor(blk.getAuthor());
kunderaBlk.setDifficulty(blk.getDifficultyRaw());
kunderaBlk.setExtraData(blk.getExtraData());
kunderaBlk.setGasLimit(blk.getGasLimitRaw());
kunderaBlk.setGasUsed(blk.getGasUsedRaw());
kunderaBlk.setHash(blk.getHash());
kunderaBlk.setLogsBloom(blk.getLogsBloom());
kunderaBlk.setMiner(blk.getMiner());
kunderaBlk.setMixHash(blk.getMixHash());
kunderaBlk.setNonce(blk.getNonceRaw());
kunderaBlk.setNumber(blk.getNumberRaw());
kunderaBlk.setParentHash(blk.getParentHash());
kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot());
kunderaBlk.setSealFields(blk.getSealFields());
kunderaBlk.setSha3Uncles(blk.getSha3Uncles());
kunderaBlk.setSize(blk.getSizeRaw());
kunderaBlk.setStateRoot(blk.getStateRoot());
kunderaBlk.setTimestamp(blk.getTimestampRaw());
kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw());
kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot());
kunderaBlk.setUncles(blk.getUncles());
if (includeTransactions)
{
List<Transaction> kunderaTxs = new ArrayList<>();
List<TransactionResult> txResults = block.getBlock().getTransactions();
if (txResults != null && !txResults.isEmpty())
{
for (TransactionResult transactionResult : txResults)
{
kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult));
}
kunderaBlk.setTransactions(kunderaTxs);
}
}
return kunderaBlk;
} | java | {
"resource": ""
} |
q164324 | EtherObjectConverterUtil.convertEtherTxToKunderaTx | train | public static Transaction convertEtherTxToKunderaTx(TransactionResult transactionResult)
{
Transaction kunderaTx = new Transaction();
TransactionObject txObj = (TransactionObject) transactionResult;
kunderaTx.setBlockHash(txObj.getBlockHash());
kunderaTx.setBlockNumber(txObj.getBlockNumberRaw());
kunderaTx.setCreates(txObj.getCreates());
kunderaTx.setFrom(txObj.getFrom());
kunderaTx.setGas(txObj.getGasRaw());
kunderaTx.setGasPrice(txObj.getGasPriceRaw());
kunderaTx.setHash(txObj.getHash());
kunderaTx.setInput(txObj.getInput());
kunderaTx.setNonce(txObj.getNonceRaw());
kunderaTx.setPublicKey(txObj.getPublicKey());
kunderaTx.setR(txObj.getR());
kunderaTx.setRaw(txObj.getRaw());
kunderaTx.setS(txObj.getS());
kunderaTx.setTo(txObj.getTo());
kunderaTx.setTransactionIndex(txObj.getTransactionIndexRaw());
kunderaTx.setV(txObj.getV());
kunderaTx.setValue(txObj.getValueRaw());
return kunderaTx;
} | java | {
"resource": ""
} |
q164325 | Neo4JClient.find | train | @Override
public Object find(Class entityClass, Object key)
{
GraphDatabaseService graphDb = null;
if (resource != null)
{
graphDb = getConnection();
}
if (graphDb == null)
graphDb = factory.getConnection();
EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
Object entity = null;
Node node = mapper.searchNode(key, m, graphDb, true);
if (node != null && !((Neo4JTransaction) resource).containsNodeId(node.getId()))
{
entity = getEntityWithAssociationFromNode(m, node);
}
return entity;
} | java | {
"resource": ""
} |
q164326 | Neo4JClient.delete | train | @Override
public void delete(Object entity, Object key)
{
// All Modifying Neo4J operations must be executed within a transaction
checkActiveTransaction();
GraphDatabaseService graphDb = getConnection();
// Find Node for this particular entity
EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
Node node = mapper.searchNode(key, m, graphDb, true);
if (node != null)
{
// Remove this particular node, if not already deleted in current
// transaction
if (!((Neo4JTransaction) resource).containsNodeId(node.getId()))
{
node.delete();
// Manually remove node index if applicable
indexer.deleteNodeIndex(m, graphDb, node);
// Remove all relationship edges attached to this node
// (otherwise an
// exception is thrown)
for (Relationship relationship : node.getRelationships())
{
relationship.delete();
// Manually remove relationship index if applicable
indexer.deleteRelationshipIndex(m, graphDb, relationship);
}
((Neo4JTransaction) resource).addNodeId(node.getId());
}
}
else
{
if (log.isDebugEnabled())
log.debug("Entity to be deleted doesn't exist in graph. Doing nothing");
}
} | java | {
"resource": ""
} |
q164327 | Neo4JClient.onPersist | train | @Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
if (log.isDebugEnabled())
log.debug("Persisting " + entity);
// All Modifying Neo4J operations must be executed within a transaction
checkActiveTransaction();
GraphDatabaseService graphDb = getConnection();
try
{
// Top level node
Node node = mapper.getNodeFromEntity(entity, id, graphDb, entityMetadata, isUpdate);
if (node != null)
{
MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
getPersistenceUnit());
((Neo4JTransaction) resource).addProcessedNode(id, node);
if (!rlHolders.isEmpty())
{
for (RelationHolder rh : rlHolders)
{
// Search Node (to be connected to ) in Neo4J graph
EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
rh.getRelationValue().getClass());
Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(), targetNodeMetadata);
// Node targetNode = mapper.searchNode(targetNodeKey,
// targetNodeMetadata, graphDb);
Node targetNode = null; // Target node connected through
// relationship
/**
* If Relationship is with an entity in Neo4J, Target
* node must already have been created Get a handle of
* it from processed nodes and add edges to it. Else, if
* relationship is with an entity in a database other
* than Neo4J, create a "Proxy Node" that points to a
* row in other database. This proxy node contains key
* equal to primary key of row in other database.
* */
if (isEntityForNeo4J(targetNodeMetadata))
{
targetNode = ((Neo4JTransaction) resource).getProcessedNode(targetNodeKey);
}
else
{
// Create Proxy nodes for insert requests
if (!isUpdate)
{
targetNode = mapper.createProxyNode(id, targetNodeKey, graphDb, entityMetadata,
targetNodeMetadata);
}
}
if (targetNode != null)
{
// Join this node (source node) to target node via
// relationship
DynamicRelationshipType relType = DynamicRelationshipType.withName(rh.getRelationName());
Relationship relationship = node.createRelationshipTo(targetNode, relType);
// Populate relationship's own properties into it
Object relationshipObj = rh.getRelationVia();
if (relationshipObj != null)
{
mapper.populateRelationshipProperties(entityMetadata, targetNodeMetadata, relationship,
relationshipObj);
// After relationship creation, manually index
// it if desired
EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(
kunderaMetadata, relationshipObj.getClass());
if (!isUpdate)
{
indexer.indexRelationship(relationMetadata, graphDb, relationship, metamodel);
}
else
{
indexer.updateRelationshipIndex(relationMetadata, graphDb, relationship, metamodel);
}
}
}
}
}
// After node creation, manually index this node, if desired
if (!isUpdate)
{
indexer.indexNode(entityMetadata, graphDb, node, metamodel);
}
else
{
indexer.updateNodeIndex(entityMetadata, graphDb, node, metamodel);
}
}
}
catch (Exception e)
{
log.error("Error while persisting entity " + entity + ", Caused by: ", e);
throw new PersistenceException(e);
}
} | java | {
"resource": ""
} |
q164328 | Neo4JClient.bind | train | @Override
public void bind(TransactionResource resource)
{
if (resource != null && resource instanceof Neo4JTransaction)
{
((Neo4JTransaction) resource).setGraphDb(factory.getConnection());
this.resource = resource;
}
else
{
throw new KunderaTransactionException("Invalid transaction resource provided:" + resource
+ " Should have been an instance of :" + Neo4JTransaction.class);
}
} | java | {
"resource": ""
} |
q164329 | Neo4JClient.executeLuceneQuery | train | public List<Object> executeLuceneQuery(EntityMetadata m, String luceneQuery)
{
log.info("Executing Lucene Query on Neo4J:" + luceneQuery);
GraphDatabaseService graphDb = getConnection();
List<Object> entities = new ArrayList<Object>();
if (!indexer.isNodeAutoIndexingEnabled(graphDb) && m.isIndexable())
{
Index<Node> nodeIndex = graphDb.index().forNodes(m.getIndexName());
IndexHits<Node> hits = nodeIndex.query(luceneQuery);
addEntityFromIndexHits(m, entities, hits);
}
else
{
ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();
IndexHits<Node> hits = autoNodeIndex.query(luceneQuery);
addEntityFromIndexHits(m, entities, hits);
}
return entities;
} | java | {
"resource": ""
} |
q164330 | Neo4JClient.addEntityFromIndexHits | train | protected void addEntityFromIndexHits(EntityMetadata m, List<Object> entities, IndexHits<Node> hits)
{
for (Node node : hits)
{
if (node != null)
{
Object entity = getEntityWithAssociationFromNode(m, node);
if (entity != null)
{
entities.add(entity);
}
}
}
} | java | {
"resource": ""
} |
q164331 | Neo4JClient.getEntityWithAssociationFromNode | train | private Object getEntityWithAssociationFromNode(EntityMetadata m, Node node)
{
Map<String, Object> relationMap = new HashMap<String, Object>();
/**
* Map containing Node ID as key and Entity object as value. Helps cache
* entity objects found earlier for faster lookup and prevents repeated
* processing
*/
Map<Long, Object> nodeIdToEntityMap = new HashMap<Long, Object>();
Object entity = mapper.getEntityFromNode(node, m);
nodeIdToEntityMap.put(node.getId(), entity);
populateRelations(m, entity, relationMap, node, nodeIdToEntityMap);
nodeIdToEntityMap.clear();
if (!relationMap.isEmpty() && entity != null)
{
return new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationMap);
}
else
{
return entity;
}
} | java | {
"resource": ""
} |
q164332 | ESClient.addDiscriminator | train | private void addDiscriminator(Map<String, Object> values, EntityType entityType)
{
String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();
// No need to check for empty or blank, as considering it as valid name
// for nosql!
if (discrColumn != null && discrValue != null)
{
values.put(discrColumn, discrValue);
}
} | java | {
"resource": ""
} |
q164333 | ESClient.addRelations | train | private void addRelations(List<RelationHolder> rlHolders, Map<String, Object> values)
{
if (rlHolders != null)
{
for (RelationHolder relation : rlHolders)
{
values.put(relation.getRelationName(), relation.getRelationValue());
}
}
} | java | {
"resource": ""
} |
q164334 | ESClient.addSource | train | private void addSource(Object entity, Map<String, Object> values, EntityType entityType)
{
Set<Attribute> attributes = entityType.getAttributes();
for (Attribute attrib : attributes)
{
if (!attrib.isAssociation())
{
Object value = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());
values.put(((AbstractAttribute) attrib).getJPAColumnName(), value);
}
}
} | java | {
"resource": ""
} |
q164335 | ESClient.addSortOrder | train | private void addSortOrder(SearchRequestBuilder builder, KunderaQuery query, EntityMetadata entityMetadata)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
List<OrderByItem> orderList = KunderaQueryUtils.getOrderByItems(query.getJpqlExpression());
for (OrderByItem orderByItem : orderList)
{
String ordering = orderByItem.getOrdering().toString();
if (ordering.equalsIgnoreCase(ESConstants.DEFAULT))
{
ordering = Expression.ASC;
}
builder.addSort(KunderaCoreUtils.getJPAColumnName(orderByItem.getExpression().toParsedText(),
entityMetadata, metaModel), SortOrder.valueOf(ordering));
}
} | java | {
"resource": ""
} |
q164336 | ESClient.addFieldsToBuilder | train | private void addFieldsToBuilder(String[] fieldsToSelect, Class clazz, MetamodelImpl metaModel,
SearchRequestBuilder builder)
{
if (fieldsToSelect != null && fieldsToSelect.length > 1 && !(fieldsToSelect[1] == null))
{
logger.debug("Fields added in query are: ");
for (int i = 1; i < fieldsToSelect.length; i++)
{
logger.debug(i + " : " + fieldsToSelect[i]);
builder = builder.addField(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[i]))
.getJPAColumnName());
}
}
} | java | {
"resource": ""
} |
q164337 | ESClient.getKeyAsString | train | private String getKeyAsString(Object id, EntityMetadata metadata, MetamodelImpl metaModel)
{
if (metaModel.isEmbeddable(((AbstractAttribute) metadata.getIdAttribute()).getBindableJavaType()))
{
return KunderaCoreUtils.prepareCompositeKey(metadata, id);
}
return id.toString();
} | java | {
"resource": ""
} |
q164338 | ESClient.setRefreshIndexes | train | private void setRefreshIndexes(Properties puProps, Map<String, Object> externalProperties)
{
Object refreshIndexes = null;
/*
* Check from properties set while creating emf
*
*/
if (externalProperties.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES) != null)
{
refreshIndexes = externalProperties.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES);
}
/*
* Check from PU Properties
*
*/
if (refreshIndexes == null && puProps.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES) != null)
{
refreshIndexes = puProps.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES);
}
if (refreshIndexes != null)
{
if (refreshIndexes instanceof Boolean)
{
this.setRereshIndexes = (boolean) refreshIndexes;
}
else
{
this.setRereshIndexes = Boolean.parseBoolean((String) refreshIndexes);
}
}
} | java | {
"resource": ""
} |
q164339 | ESClient.isRefreshIndexes | train | private boolean isRefreshIndexes()
{
if (clientProperties != null)
{
Object refreshIndexes = clientProperties.get(ESConstants.ES_REFRESH_INDEXES);
if (refreshIndexes != null && refreshIndexes instanceof Boolean)
{
return (boolean) refreshIndexes;
}
else
{
return Boolean.parseBoolean((String) refreshIndexes);
}
}
else
{
return this.setRereshIndexes;
}
} | java | {
"resource": ""
} |
q164340 | SparkDataHandler.loadDataAndPopulateResults | train | public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery)
{
if (kunderaQuery != null && kunderaQuery.isAggregated())
{
return dataFrame.collectAsList();
}
// TODO: handle the case of specific field selection
else
{
return populateEntityObjectsList(dataFrame, m);
}
} | java | {
"resource": ""
} |
q164341 | SparkDataHandler.populateEntityObjectsList | train | private List<?> populateEntityObjectsList(DataFrame dataFrame, EntityMetadata m)
{
List results = new ArrayList();
String[] columns = dataFrame.columns();
Map<String, Integer> map = createMapOfColumnIndex(columns);
for (Row row : dataFrame.collectAsList())
{
Object entity = populateEntityFromDataFrame(m, map, row);
results.add(entity);
}
return results;
} | java | {
"resource": ""
} |
q164342 | SparkDataHandler.populateEntityFromDataFrame | train | private Object populateEntityFromDataFrame(EntityMetadata m, Map<String, Integer> columnIndexMap, Row row)
{
try
{
// create entity instance
Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
// handle relations
Map<String, Object> relations = new HashMap<String, Object>();
if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
{
relations = ((EnhanceEntity) entity).getRelations();
entity = ((EnhanceEntity) entity).getEntity();
}
// get a Set of attributes
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();
// iterate over attributes and find its value
for (Attribute attribute : attributes)
{
String columnName = getColumnName(attribute);
Object columnValue = row.get(columnIndexMap.get(columnName));
if (columnValue != null)
{
Object value = PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),
columnValue.getClass(), columnValue);
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
}
}
// find the value of @Id field for EnhanceEntity
SingularAttribute attrib = m.getIdAttribute();
Object rowKey = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, rowKey, relations);
}
return entity;
}
catch (PropertyAccessException e1)
{
throw new RuntimeException(e1);
}
} | java | {
"resource": ""
} |
q164343 | SparkDataHandler.createMapOfColumnIndex | train | private Map<String, Integer> createMapOfColumnIndex(String[] columns)
{
int i = 0;
Map<String, Integer> map = new HashMap<String, Integer>();
for (String column : columns)
{
map.put(column, i++);
}
return map;
} | java | {
"resource": ""
} |
q164344 | FlushManager.buildFlushStack | train | public void buildFlushStack(Node headNode, EventType eventType)
{
if (headNode != null)
{
headNode.setTraversed(false);
addNodesToFlushStack(headNode, eventType);
}
} | java | {
"resource": ""
} |
q164345 | FlushManager.clearFlushStack | train | public void clearFlushStack()
{
if (stackQueue != null && !stackQueue.isEmpty())
{
stackQueue.clear();
}
if (joinTableDataCollection != null && !joinTableDataCollection.isEmpty())
{
joinTableDataCollection.clear();
}
if (eventLogQueue != null)
{
eventLogQueue.clear();
}
} | java | {
"resource": ""
} |
q164346 | FlushManager.onRollBack | train | private void onRollBack(PersistenceDelegator delegator, Map<Object, EventLog> eventCol)
{
if (eventCol != null && !eventCol.isEmpty())
{
Collection<EventLog> events = eventCol.values();
Iterator<EventLog> iter = events.iterator();
while (iter.hasNext())
{
try
{
EventLog event = iter.next();
Node node = event.getNode();
Class clazz = node.getDataClass();
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(), clazz);
Client client = delegator.getClient(metadata);
// do manual rollback, if data is processed, and running
// without transaction or with kundera's default transaction
// support!
if (node.isProcessed()
&& (!delegator.isTransactionInProgress() || MetadataUtils
.defaultTransactionSupported(metadata.getPersistenceUnit(), delegator.getKunderaMetadata())))
{
if (node.getOriginalNode() == null)
{
Object entityId = node.getEntityId();
client.remove(node.getData(), entityId);
}
else
{
client.persist(node.getOriginalNode());
}
}
// mark it null for garbage collection.
event = null;
}
catch (Exception ex)
{
log.warn("Caught exception during rollback, Caused by:", ex);
// bypass to next event
}
}
}
// mark it null for garbage collection.
eventCol = null;
} | java | {
"resource": ""
} |
q164347 | FlushManager.addJoinTableData | train | private void addJoinTableData(OPERATION operation, String schemaName, String joinTableName, String joinColumnName,
String invJoinColumnName, Class<?> entityClass, Object joinColumnValue, Set<Object> invJoinColumnValues)
{
JoinTableData joinTableData = new JoinTableData(operation, schemaName, joinTableName, joinColumnName,
invJoinColumnName, entityClass);
joinTableData.addJoinTableRecord(joinColumnValue, invJoinColumnValues);
joinTableDataCollection.add(joinTableData);
} | java | {
"resource": ""
} |
q164348 | FlushManager.logEvent | train | private void logEvent(Node node, EventType eventType)
{
// Node contains original as well as transactional copy.
EventLog log = new EventLog(eventType, node);
eventLogQueue.onEvent(log, eventType);
} | java | {
"resource": ""
} |
q164349 | ThriftClient.persistJoinTable | train | @Override
public void persistJoinTable(JoinTableData joinTableData)
{
String joinTableName = joinTableData.getJoinTableName();
String invJoinColumnName = joinTableData.getInverseJoinColumnName();
Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
joinTableData.getEntityClass());
Connection conn = null;
try
{
conn = getConnection();
if (isCql3Enabled(entityMetadata))
{
persistJoinTableByCql(joinTableData, conn.getClient());
}
else
{
KunderaCoreUtils.printQuery("Persist join table:" + joinTableName, showQuery);
for (Object key : joinTableRecords.keySet())
{
PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata
.getIdAttribute().getJavaMember());
byte[] rowKey = accessor.toBytes(key);
Set<Object> values = joinTableRecords.get(key);
List<Column> columns = new ArrayList<Column>();
// Create Insertion List
List<Mutation> insertionList = new ArrayList<Mutation>();
Class columnType = null;
for (Object value : values)
{
Column column = new Column();
column.setName(PropertyAccessorFactory.STRING.toBytes(invJoinColumnName
+ Constants.JOIN_COLUMN_NAME_SEPARATOR + value));
column.setValue(PropertyAccessorHelper.getBytes(value));
column.setTimestamp(generator.getTimestamp());
columnType = value.getClass();
columns.add(column);
Mutation mut = new Mutation();
mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));
insertionList.add(mut);
}
createIndexesOnColumns(entityMetadata, joinTableName, columns, columnType);
// Create Mutation Map
Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();
columnFamilyValues.put(joinTableName, insertionList);
Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
mulationMap.put(ByteBuffer.wrap(rowKey), columnFamilyValues);
// Write Mutation map to database
conn.getClient().set_keyspace(entityMetadata.getSchema());
conn.getClient().batch_mutate(mulationMap, getConsistencyLevel());
}
}
}
catch (InvalidRequestException e)
{
log.error("Error while inserting record into join table, Caused by: .", e);
throw new PersistenceException(e);
}
catch (TException e)
{
log.error("Error while inserting record into join table, Caused by: .", e);
throw new PersistenceException(e);
}
finally
{
releaseConnection(conn);
}
} | java | {
"resource": ""
} |
q164350 | ThriftClient.loadSuperColumns | train | @Override
protected final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,
String... superColumnNames)
{
// TODO::: super column abstract entity and discriminator column
if (!isOpen())
throw new PersistenceException("ThriftClient is closed.");
byte[] rowKey = rowId.getBytes();
SlicePredicate predicate = new SlicePredicate();
List<ByteBuffer> columnNames = new ArrayList<ByteBuffer>();
for (String superColumnName : superColumnNames)
{
KunderaCoreUtils.printQuery("Fetch superColumn:" + superColumnName, showQuery);
columnNames.add(ByteBuffer.wrap(superColumnName.getBytes()));
}
predicate.setColumn_names(columnNames);
ColumnParent parent = new ColumnParent(columnFamily);
List<ColumnOrSuperColumn> coscList;
Connection conn = null;
try
{
conn = getConnection();
coscList = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate, getConsistencyLevel());
}
catch (InvalidRequestException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (UnavailableException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TimedOutException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
finally
{
releaseConnection(conn);
}
List<SuperColumn> superColumns = ThriftDataResultHelper.transformThriftResult(coscList,
ColumnFamilyType.SUPER_COLUMN, null);
return superColumns;
} | java | {
"resource": ""
} |
q164351 | ThriftClient.getColumnsById | train | @Override
public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,
Object pKeyColumnValue, Class columnJavaType)
{
List<Object> foreignKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
foreignKeys = getColumnsByIdUsingCql(schemaName, tableName, pKeyColumnName, columnName, pKeyColumnValue,
columnJavaType);
}
else
{
byte[] rowKey = CassandraUtilities.toBytes(pKeyColumnValue);
if (rowKey != null)
{
SlicePredicate predicate = new SlicePredicate();
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[0]);
sliceRange.setFinish(new byte[0]);
predicate.setSlice_range(sliceRange);
ColumnParent parent = new ColumnParent(tableName);
List<ColumnOrSuperColumn> results;
Connection conn = null;
try
{
conn = getConnection();
results = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate,
getConsistencyLevel());
}
catch (InvalidRequestException e)
{
log.error("Error while getting columns for row Key {} , Caused by: .", pKeyColumnValue, e);
throw new EntityReaderException(e);
}
catch (UnavailableException e)
{
log.error("Error while getting columns for row Key {} , Caused by: .", pKeyColumnValue, e);
throw new EntityReaderException(e);
}
catch (TimedOutException e)
{
log.error("Error while getting columns for row Key {} , Caused by: .", pKeyColumnValue, e);
throw new EntityReaderException(e);
}
catch (TException e)
{
log.error("Error while getting columns for row Key {} , Caused by: .", pKeyColumnValue, e);
throw new EntityReaderException(e);
}
finally
{
releaseConnection(conn);
}
List<Column> columns = ThriftDataResultHelper.transformThriftResult(results, ColumnFamilyType.COLUMN,
null);
foreignKeys = dataHandler.getForeignKeysFromJoinTable(columnName, columns, columnJavaType);
}
}
return (List<E>) foreignKeys;
} | java | {
"resource": ""
} |
q164352 | ThriftClient.findIdsByColumn | train | @Override
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
Object columnValue, Class entityClazz)
{
List<Object> rowKeys = new ArrayList<Object>();
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
{
rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);
}
else
{
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
SlicePredicate slicePredicate = new SlicePredicate();
slicePredicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER,
ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE));
String childIdStr = PropertyAccessorHelper.getString(columnValue);
IndexExpression ie = new IndexExpression(UTF8Type.instance.decompose(columnName
+ Constants.JOIN_COLUMN_NAME_SEPARATOR + childIdStr), IndexOperator.EQ,
UTF8Type.instance.decompose(childIdStr));
List<IndexExpression> expressions = new ArrayList<IndexExpression>();
expressions.add(ie);
IndexClause ix = new IndexClause();
ix.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);
ix.setCount(Integer.MAX_VALUE);
ix.setExpressions(expressions);
ColumnParent columnParent = new ColumnParent(tableName);
Connection conn = null;
try
{
conn = getConnection();
List<KeySlice> keySlices = conn.getClient().get_indexed_slices(columnParent, ix, slicePredicate,
getConsistencyLevel());
rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, metadata);
}
catch (InvalidRequestException e)
{
log.error("Error while fetching key slices of column family {} for column name {} , Caused by: .",
tableName, columnName, e);
throw new KunderaException(e);
}
catch (UnavailableException e)
{
log.error("Error while fetching key slices of column family {} for column name {} , Caused by: .",
tableName, columnName, e);
throw new KunderaException(e);
}
catch (TimedOutException e)
{
log.error("Error while fetching key slices of column family {} for column name {} , Caused by: .",
tableName, columnName, e);
throw new KunderaException(e);
}
catch (TException e)
{
log.error("Error while fetching key slices of column family {} for column name {} , Caused by: .",
tableName, columnName, e);
throw new KunderaException(e);
}
finally
{
releaseConnection(conn);
}
}
if (rowKeys != null && !rowKeys.isEmpty())
{
return rowKeys.toArray(new Object[0]);
}
if (log.isInfoEnabled())
{
log.info("No record found!, returning null.");
}
return null;
} | java | {
"resource": ""
} |
q164353 | ThriftClient.executeQuery | train | @Override
public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery)
{
if (clazz == null)
{
return super.executeScalarQuery(cqlQuery);
}
return super.executeSelectQuery(clazz, relationalField, dataHandler, isNative, cqlQuery);
} | java | {
"resource": ""
} |
q164354 | AbstractProxyCollection.createEmptyDataCollection | train | private void createEmptyDataCollection()
{
Class<?> collectionClass = getRelation().getProperty().getType();
if (collectionClass.isAssignableFrom(Set.class))
{
dataCollection = new HashSet();
}
else if (collectionClass.isAssignableFrom(List.class))
{
dataCollection = new ArrayList();
}
} | java | {
"resource": ""
} |
q164355 | ApplicationMetadata.getMetamodelMap | train | public Map<String, Metamodel> getMetamodelMap()
{
if (metamodelMap == null)
{
metamodelMap = new HashMap<String, Metamodel>();
}
return metamodelMap;
} | java | {
"resource": ""
} |
q164356 | ApplicationMetadata.setClazzToPuMap | train | public void setClazzToPuMap(Map<String, List<String>> map)
{
if (clazzToPuMap == null)
{
this.clazzToPuMap = map;
}
else
{
clazzToPuMap.putAll(map);
}
} | java | {
"resource": ""
} |
q164357 | ApplicationMetadata.getMappedPersistenceUnit | train | public List<String> getMappedPersistenceUnit(Class<?> clazz)
{
return this.clazzToPuMap != null ? this.clazzToPuMap.get(clazz.getName()) : null;
} | java | {
"resource": ""
} |
q164358 | ApplicationMetadata.getMappedPersistenceUnit | train | public String getMappedPersistenceUnit(String clazzName)
{
List<String> pus = clazzToPuMap.get(clazzName);
final int _first = 0;
String pu = null;
if (pus != null && !pus.isEmpty())
{
if (pus.size() == 2)
{
onError(clazzName);
}
return pus.get(_first);
}
else
{
Set<String> mappedClasses = this.clazzToPuMap.keySet();
boolean found = false;
for (String clazz : mappedClasses)
{
if (found && clazz.endsWith("." + clazzName))
{
onError(clazzName);
}
else if (clazz.endsWith("." + clazzName) || clazz.endsWith("$" + clazzName))
{
pu = clazzToPuMap.get(clazz).get(_first);
found = true;
}
}
}
return pu;
} | java | {
"resource": ""
} |
q164359 | ApplicationMetadata.addQueryToCollection | train | public void addQueryToCollection(String queryName, String query, boolean isNativeQuery, Class clazz)
{
if (namedNativeQueries == null)
{
namedNativeQueries = new ConcurrentHashMap<String, QueryWrapper>();
}
if (!namedNativeQueries.containsKey(queryName))
{
namedNativeQueries.put(queryName, new QueryWrapper(queryName, query, isNativeQuery, clazz));
}
// No null check made as it will never hold null value
else if (queryName != null && !getQuery(queryName).equals(query))
{
logger.error("Duplicate named/native query with name:" + queryName
+ "found! Already there is a query with same name:" + namedNativeQueries.get(queryName));
throw new ApplicationLoaderException("Duplicate named/native query with name:" + queryName
+ "found! Already there is a query with same name:" + namedNativeQueries.get(queryName));
}
} | java | {
"resource": ""
} |
q164360 | ApplicationMetadata.getQuery | train | public String getQuery(String name)
{
QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;
return wrapper != null ? wrapper.getQuery() : null;
} | java | {
"resource": ""
} |
q164361 | ApplicationMetadata.isNative | train | public boolean isNative(String name)
{
QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;
return wrapper != null ? wrapper.isNativeQuery() : false;
} | java | {
"resource": ""
} |
q164362 | EntityEventDispatcher.fireEventListeners | train | public void fireEventListeners(EntityMetadata metadata, Object entity, Class<?> event)
{
// handle external listeners first
List<? extends CallbackMethod> callBackMethods = metadata.getCallbackMethods(event);
if (null != callBackMethods && !callBackMethods.isEmpty() && null != entity)
{
log.debug("Callback >> " + event.getSimpleName() + " on " + metadata.getEntityClazz().getName());
for (CallbackMethod callback : callBackMethods)
{
log.debug("Firing >> " + callback);
callback.invoke(entity);
}
}
} | java | {
"resource": ""
} |
q164363 | KunderaQueryParser.isKeyword | train | private boolean isKeyword(String token)
{
// Compare the passed token against the provided keyword list, or their
// lowercase form
for (int i = 0; i < KunderaQuery.SINGLE_STRING_KEYWORDS.length; i++)
{
if (token.equalsIgnoreCase(KunderaQuery.SINGLE_STRING_KEYWORDS[i]))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164364 | LikeComparatorFactory.likeToRegex | train | static String likeToRegex(String like)
{
StringBuilder builder = new StringBuilder();
boolean wasPercent = false;
for (int i = 0; i < like.length(); ++i)
{
char c = like.charAt(i);
if (isPlain(c))
{
if (wasPercent)
{
wasPercent = false;
builder.append(".*");
}
builder.append(c);
}
else if (wasPercent)
{
wasPercent = false;
if (c == '%')
{
builder.append('%');
}
else
{
builder.append(".*").append(c);
}
}
else
{
if (c == '%')
{
wasPercent = true;
}
else
{
builder.append('\\').append(c);
}
}
}
if (wasPercent)
{
builder.append(".*");
}
return builder.toString();
} | java | {
"resource": ""
} |
q164365 | MetadataBuilder.belongsToPersistenceUnit | train | private EntityMetadata belongsToPersistenceUnit(EntityMetadata metadata)
{
// if pu is null and client is not rdbms OR metadata pu does not match
// with configured one. don't process for anything.
PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()
.getPersistenceUnitMetadata(persistenceUnit);
String keyspace = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE):null;
keyspace = keyspace == null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE):keyspace;
if (metadata.getPersistenceUnit() != null && !metadata.getPersistenceUnit().equals(persistenceUnit)
|| (keyspace != null && metadata.getSchema() != null && !metadata.getSchema().equals(keyspace)))
{
metadata = null;
}
else
{
applyMetadataChanges(metadata);
}
/*
* if ((metadata.getPersistenceUnit() == null &&
* !(Constants.RDBMS_CLIENT_FACTORY.equalsIgnoreCase(client) ||
* Constants.NEO4J_CLIENT_FACTORY .equalsIgnoreCase(client))) ||
* metadata.getPersistenceUnit() != null &&
* !metadata.getPersistenceUnit().equals(persistenceUnit)) { metadata =
* null; }
*/
return metadata;
} | java | {
"resource": ""
} |
q164366 | KuduDBClientFactory.initializePropertyReader | train | private void initializePropertyReader()
{
if (propertyReader == null)
{
propertyReader = new KuduDBPropertyReader(externalProperties,
kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));
propertyReader.read(getPersistenceUnit());
}
} | java | {
"resource": ""
} |
q164367 | PersistenceXMLLoader.getDocument | train | private static Document getDocument(URL pathToPersistenceXml) throws InvalidConfigurationException
{
InputStream is = null;
Document xmlRootNode = null;
try
{
if (pathToPersistenceXml != null)
{
URLConnection conn = pathToPersistenceXml.openConnection();
conn.setUseCaches(false); // avoid JAR locking on Windows and
// Tomcat.
is = conn.getInputStream();
}
if (is == null)
{
throw new IOException("Failed to obtain InputStream from url: " + pathToPersistenceXml);
}
xmlRootNode = parseDocument(is);
validateDocumentAgainstSchema(xmlRootNode);
}
catch (IOException e)
{
throw new InvalidConfigurationException(e);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException ex)
{
log.warn("Input stream could not be closed after parsing persistence.xml, caused by: {}", ex);
}
}
}
return xmlRootNode;
} | java | {
"resource": ""
} |
q164368 | PersistenceXMLLoader.validateDocumentAgainstSchema | train | private static void validateDocumentAgainstSchema(final Document xmlRootNode) throws InvalidConfigurationException
{
final Element rootElement = xmlRootNode.getDocumentElement();
final String version = rootElement.getAttribute("version");
String schemaFileName = "persistence_" + version.replace(".", "_") + ".xsd";
try
{
final List validationErrors = new ArrayList();
final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName));
final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource);
final Validator schemaValidator = schemaDefinition.newValidator();
schemaValidator.setErrorHandler(new ErrorLogger("XML InputStream", validationErrors));
schemaValidator.validate(new DOMSource(xmlRootNode));
if (!validationErrors.isEmpty())
{
final String exceptionText = "persistence.xml is not conform against the supported schema definitions.";
throw new InvalidConfigurationException(exceptionText);
}
}
catch (SAXException e)
{
final String exceptionText = "Error validating persistence.xml against schema defintion, caused by: ";
throw new InvalidConfigurationException(exceptionText, e);
}
catch (IOException e)
{
final String exceptionText = "Error opening xsd schema file. The given persistence.xml descriptor version "
+ version + " might not be supported yet.";
throw new InvalidConfigurationException(exceptionText, e);
}
} | java | {
"resource": ""
} |
q164369 | PersistenceXMLLoader.getStreamFromClasspath | train | private static InputStream getStreamFromClasspath(String fileName)
{
String path = fileName;
InputStream dtdStream = PersistenceXMLLoader.class.getClassLoader().getResourceAsStream(path);
return dtdStream;
} | java | {
"resource": ""
} |
q164370 | PersistenceXMLLoader.getTransactionType | train | public static PersistenceUnitTransactionType getTransactionType(String elementContent)
{
if (elementContent == null || elementContent.isEmpty())
{
return null;
}
else if (elementContent.equalsIgnoreCase("JTA"))
{
return PersistenceUnitTransactionType.JTA;
}
else if (elementContent.equalsIgnoreCase("RESOURCE_LOCAL"))
{
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
else
{
throw new PersistenceException("Unknown TransactionType: " + elementContent);
}
} | java | {
"resource": ""
} |
q164371 | PersistenceXMLLoader.getElementContent | train | private static String getElementContent(Element element, String defaultStr)
{
if (element == null)
{
return defaultStr;
}
NodeList children = element.getChildNodes();
StringBuilder result = new StringBuilder("");
for (int i = 0; i < children.getLength(); i++)
{
if (children.item(i).getNodeType() == Node.TEXT_NODE
|| children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)
{
result.append(children.item(i).getNodeValue());
}
}
return result.toString().trim();
} | java | {
"resource": ""
} |
q164372 | PersistenceXMLLoader.getPersistenceRootUrl | train | private static URL getPersistenceRootUrl(URL url)
{
String f = url.getFile();
f = parseFilePath(f);
URL jarUrl = url;
try
{
if (AllowedProtocol.isJarProtocol(url.getProtocol()))
{
jarUrl = new URL(f);
if (jarUrl.getProtocol() != null
&& AllowedProtocol.FILE.name().equals(jarUrl.getProtocol().toUpperCase())
&& StringUtils.contains(f, " "))
{
jarUrl = new File(f).toURI().toURL();
}
}
else if (AllowedProtocol.isValidProtocol(url.getProtocol()))
{
if (StringUtils.contains(f, " "))
{
jarUrl = new File(f).toURI().toURL();
}
else
{
jarUrl = new File(f).toURL();
}
}
}
catch (MalformedURLException mex)
{
log.error("Error during getPersistenceRootUrl(), Caused by: {}.", mex);
throw new IllegalArgumentException("Invalid jar URL[] provided!" + url);
}
return jarUrl;
} | java | {
"resource": ""
} |
q164373 | PersistenceXMLLoader.parseFilePath | train | private static String parseFilePath(String file)
{
final String excludePattern = "/META-INF/persistence.xml";
file = file.substring(0, file.length() - excludePattern.length());
// in case protocol is "file".
file = file.endsWith("!") ? file.substring(0, file.length() - 1) : file;
return file;
} | java | {
"resource": ""
} |
q164374 | CouchDBObjectMapper.onViaEmbeddable | train | private static void onViaEmbeddable(EntityType entityType, Attribute column, EntityMetadata m, Object entity,
EmbeddableType embeddable, JsonObject jsonObj)
{
Field embeddedField = (Field) column.getJavaMember();
JsonElement embeddedDocumentObject = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
if (!column.isCollection())
{
PropertyAccessorHelper.set(
entity,
embeddedField,
getObjectFromJson(embeddedDocumentObject.getAsJsonObject(),
((AbstractAttribute) column).getBindableJavaType(), embeddable.getAttributes()));
}
} | java | {
"resource": ""
} |
q164375 | CouchDBObjectMapper.getObjectFromJson | train | static Object getObjectFromJson(JsonObject jsonObj, Class clazz, Set<Attribute> columns)
{
Object obj = KunderaCoreUtils.createNewInstance(clazz);
for (Attribute column : columns)
{
JsonElement value = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
setFieldValue(obj, column, value);
}
return obj;
} | java | {
"resource": ""
} |
q164376 | CouchDBObjectMapper.getJsonPrimitive | train | private static JsonElement getJsonPrimitive(Object value, Class clazz)
{
if (value != null)
{
if (clazz.isAssignableFrom(Number.class) || value instanceof Number)
{
return new JsonPrimitive((Number) value);
}
else if (clazz.isAssignableFrom(Boolean.class) || value instanceof Boolean)
{
return new JsonPrimitive((Boolean) value);
}
else if (clazz.isAssignableFrom(Character.class) || value instanceof Character)
{
return new JsonPrimitive((Character) value);
}
else if (clazz.isAssignableFrom(byte[].class) || value instanceof byte[])
{
return new JsonPrimitive(PropertyAccessorFactory.STRING.fromBytes(String.class, (byte[]) value));
}
else
{
return new JsonPrimitive(PropertyAccessorHelper.getString(value));
}
} | java | {
"resource": ""
} |
q164377 | RDBMSClientFactory.getConfigurationObject | train | private void getConfigurationObject()
{
RDBMSPropertyReader reader = new RDBMSPropertyReader(externalProperties, kunderaMetadata
.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));
this.conf = reader.load(getPersistenceUnit());
} | java | {
"resource": ""
} |
q164378 | AbstractManagedType.getSingularAttribute | train | private SingularAttribute<? super X, ?> getSingularAttribute(String paramString, boolean checkValidity)
{
SingularAttribute<? super X, ?> attribute = getDeclaredSingularAttribute(paramString, false);
try
{
if (attribute == null && superClazzType != null)
{
attribute = superClazzType.getSingularAttribute(paramString);
}
}
catch (IllegalArgumentException iaex)
{
attribute = null;
onValidity(paramString, checkValidity, attribute);
}
onValidity(paramString, checkValidity, attribute);
return attribute;
} | java | {
"resource": ""
} |
q164379 | AbstractManagedType.addSingularAttribute | train | public void addSingularAttribute(String attributeName, SingularAttribute<X, ?> attribute)
{
if (declaredSingluarAttribs == null)
{
declaredSingluarAttribs = new HashMap<String, SingularAttribute<X, ?>>();
}
declaredSingluarAttribs.put(attributeName, attribute);
onValidateAttributeConstraints((Field) attribute.getJavaMember());
onEmbeddableAttribute((Field) attribute.getJavaMember());
} | java | {
"resource": ""
} |
q164380 | AbstractManagedType.addPluralAttribute | train | public void addPluralAttribute(String attributeName, PluralAttribute<X, ?, ?> attribute)
{
if (declaredPluralAttributes == null)
{
declaredPluralAttributes = new HashMap<String, PluralAttribute<X, ?, ?>>();
}
declaredPluralAttributes.put(attributeName, attribute);
onValidateAttributeConstraints((Field) attribute.getJavaMember());
onEmbeddableAttribute((Field) attribute.getJavaMember());
} | java | {
"resource": ""
} |
q164381 | AbstractManagedType.addSubManagedType | train | private void addSubManagedType(ManagedType inheritedType)
{
if (Modifier.isAbstract(this.getJavaType().getModifiers()))
{
subManagedTypes.add(inheritedType);
}
} | java | {
"resource": ""
} |
q164382 | AbstractManagedType.getDeclaredPluralAttribute | train | private PluralAttribute<X, ?, ?> getDeclaredPluralAttribute(String paramName)
{
return declaredPluralAttributes != null ? declaredPluralAttributes.get(paramName) : null;
} | java | {
"resource": ""
} |
q164383 | AbstractManagedType.getPluralAttriute | train | private PluralAttribute<? super X, ?, ?> getPluralAttriute(String paramName)
{
if (superClazzType != null)
{
return ((AbstractManagedType<? super X>) superClazzType).getDeclaredPluralAttribute(paramName);
}
return null;
} | java | {
"resource": ""
} |
q164384 | AbstractManagedType.onCheckCollectionAttribute | train | private <E> boolean onCheckCollectionAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)
{
if (pluralAttribute != null)
{
if (isCollectionAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164385 | AbstractManagedType.onCheckSetAttribute | train | private <E> boolean onCheckSetAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)
{
if (pluralAttribute != null)
{
if (isSetAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164386 | AbstractManagedType.onCheckListAttribute | train | private <E> boolean onCheckListAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)
{
if (pluralAttribute != null)
{
if (isListAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164387 | AbstractManagedType.onCheckMapAttribute | train | private <V> boolean onCheckMapAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<V> valueClazz)
{
if (pluralAttribute != null)
{
if (isMapAttribute(pluralAttribute) && isBindable(pluralAttribute, valueClazz))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164388 | AbstractManagedType.isCollectionAttribute | train | private boolean isCollectionAttribute(PluralAttribute<? super X, ?, ?> attribute)
{
return attribute != null && attribute.getCollectionType().equals(CollectionType.COLLECTION);
} | java | {
"resource": ""
} |
q164389 | AbstractManagedType.isListAttribute | train | private boolean isListAttribute(PluralAttribute<? super X, ?, ?> attribute)
{
return attribute != null && attribute.getCollectionType().equals(CollectionType.LIST);
} | java | {
"resource": ""
} |
q164390 | AbstractManagedType.isSetAttribute | train | private boolean isSetAttribute(PluralAttribute<? super X, ?, ?> attribute)
{
return attribute != null && attribute.getCollectionType().equals(CollectionType.SET);
} | java | {
"resource": ""
} |
q164391 | AbstractManagedType.isMapAttribute | train | private boolean isMapAttribute(PluralAttribute<? super X, ?, ?> attribute)
{
return attribute != null && attribute.getCollectionType().equals(CollectionType.MAP);
} | java | {
"resource": ""
} |
q164392 | AbstractManagedType.isBindable | train | private <E> boolean isBindable(Bindable<?> attribute, Class<E> elementType)
{
return attribute != null && attribute.getBindableJavaType().equals(elementType);
} | java | {
"resource": ""
} |
q164393 | AbstractManagedType.checkForValid | train | private void checkForValid(String paramName, Attribute<? super X, ?> attribute)
{
if (attribute == null)
{
throw new IllegalArgumentException(
"attribute of the given name and type is not present in the managed type, for name:" + paramName);
}
} | java | {
"resource": ""
} |
q164394 | AbstractManagedType.getDeclaredAttribute | train | private Attribute<X, ?> getDeclaredAttribute(String paramName, boolean checkValidity)
{
Attribute<X, ?> attribute = (Attribute<X, ?>) getSingularAttribute(paramName, false);
if (attribute == null)
{
attribute = (Attribute<X, ?>) getDeclaredPluralAttribute(paramName);
}
if (checkValidity)
{
checkForValid(paramName, attribute);
}
return attribute;
} | java | {
"resource": ""
} |
q164395 | AbstractManagedType.onValidity | train | private void onValidity(String paramString, boolean checkValidity, SingularAttribute<? super X, ?> attribute)
{
if (checkValidity)
{
checkForValid(paramString, attribute);
}
} | java | {
"resource": ""
} |
q164396 | AbstractManagedType.bindTypeAnnotations | train | private void bindTypeAnnotations()
{
// TODO:: need to check @Embeddable attributes as well!
// TODO:: need to Handle association override in
// RelationMetadataProcessor.
for (Class<? extends Annotation> ann : validJPAAnnotations)
{
if (getJavaType().isAnnotationPresent(ann))
{
checkForValid();
Annotation annotation = getJavaType().getAnnotation(ann);
if (ann.isAssignableFrom(AttributeOverride.class))
{
bindAttribute(annotation);
}
else if (ann.isAssignableFrom(AttributeOverrides.class))
{
AttributeOverride[] attribAnns = ((AttributeOverrides) annotation).value();
for (AttributeOverride attribOverann : attribAnns)
{
bindAttribute(attribOverann);
}
}
}
}
} | java | {
"resource": ""
} |
q164397 | AbstractManagedType.bindAttribute | train | private void bindAttribute(Annotation annotation)
{
String fieldname = ((AttributeOverride) annotation).name();
Column column = ((AttributeOverride) annotation).column();
((AbstractManagedType) this.superClazzType).columnBindings.put(fieldname, column);
} | java | {
"resource": ""
} |
q164398 | AbstractManagedType.buildInheritenceModel | train | private InheritanceModel buildInheritenceModel()
{
InheritanceModel model = null;
if (superClazzType != null)
{
// means there is a super class
// scan for inheritence model.
if (superClazzType.getPersistenceType().equals(PersistenceType.ENTITY)
&& superClazzType.getJavaType().isAnnotationPresent(Inheritance.class))
{
Inheritance inheritenceAnn = superClazzType.getJavaType().getAnnotation(Inheritance.class);
InheritanceType strategyType = inheritenceAnn.strategy();
String descriminator = null;
String descriminatorValue = null;
String tableName = null;
String schemaName = null;
tableName = superClazzType.getJavaType().getSimpleName();
if (superClazzType.getJavaType().isAnnotationPresent(Table.class))
{
tableName = superClazzType.getJavaType().getAnnotation(Table.class).name();
schemaName = superClazzType.getJavaType().getAnnotation(Table.class).schema();
}
model = onStrategyType(model, strategyType, descriminator, descriminatorValue, tableName, schemaName);
}
}
return model;
} | java | {
"resource": ""
} |
q164399 | AbstractManagedType.onStrategyType | train | private InheritanceModel onStrategyType(InheritanceModel model, InheritanceType strategyType, String descriminator,
String descriminatorValue, String tableName, String schemaName)
{
switch (strategyType)
{
case SINGLE_TABLE:
// if single table
if (superClazzType.getJavaType().isAnnotationPresent(DiscriminatorColumn.class))
{
descriminator = superClazzType.getJavaType().getAnnotation(DiscriminatorColumn.class).name();
descriminatorValue = getJavaType().getAnnotation(DiscriminatorValue.class).value();
}
model = new InheritanceModel(InheritanceType.SINGLE_TABLE, descriminator, descriminatorValue, tableName,
schemaName);
break;
case JOINED:
// if join table
// TODOO: PRIMARY KEY JOIN COLUMN
model = new InheritanceModel(InheritanceType.JOINED, tableName, schemaName);
break;
case TABLE_PER_CLASS:
// don't override, use original ones.
model = new InheritanceModel(InheritanceType.TABLE_PER_CLASS, null, null);
break;
default:
// do nothing.
break;
}
return model;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.