code
stringlengths 73
34.1k
| label
stringclasses 1
value |
---|---|
public OTMConnection acquireConnection(PBKey pbKey)
{
TransactionFactory txFactory = getTransactionFactory();
return txFactory.acquireConnection(pbKey);
} | java |
public void sendMessageToAgents(String[] agent_name, String msgtype,
Object message_content, Connector connector) {
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("performative", msgtype);
hm.put(SFipa.CONTENT, message_content);
IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];
for (int i = 0; i < agent_name.length; i++) {
ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);
}
((IMessageService) connector.getMessageService()).deliverMessage(hm,
"fipa", ici);
} | java |
public void sendMessageToAgentsWithExtraProperties(String[] agent_name,
String msgtype, Object message_content,
ArrayList<Object> properties, Connector connector) {
HashMap<String, Object> hm = new HashMap<String, Object>();
hm.put("performative", msgtype);
hm.put(SFipa.CONTENT, message_content);
for (Object property : properties) {
// Logger logger = Logger.getLogger("JadexMessenger");
// logger.info("Sending message with extra property: "+property.get(0)+", with value "+property.get(1));
hm.put((String) ((Tuple) property).get(0), ((Tuple) property).get(1));
}
IComponentIdentifier[] ici = new IComponentIdentifier[agent_name.length];
for (int i = 0; i < agent_name.length; i++) {
ici[i] = (IComponentIdentifier) connector.getAgentID(agent_name[i]);
}
((IMessageService) connector.getMessageService()).deliverMessage(hm,
"fipa", ici);
} | java |
public void lock(Object obj, int lockMode) throws LockNotGrantedException
{
if (log.isDebugEnabled()) log.debug("lock object was called on tx " + this + ", object is " + obj.toString());
checkOpen();
RuntimeObject rtObject = new RuntimeObject(obj, this);
lockAndRegister(rtObject, lockMode, isImplicitLocking(), getRegistrationList());
// if(isImplicitLocking()) moveToLastInOrderList(rtObject.getIdentity());
} | java |
protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException
{
/*
arminw:
if broker isn't in PB-tx, start tx
*/
if (!getBroker().isInTransaction())
{
if (log.isDebugEnabled()) log.debug("call beginTransaction() on PB instance");
broker.beginTransaction();
}
// Notify objects of impending commits.
performTransactionAwareBeforeCommit();
// Now perfom the real work
objectEnvelopeTable.writeObjects(isFlush);
// now we have to perform the named objects
namedRootsMap.performDeletion();
namedRootsMap.performInsert();
namedRootsMap.afterWriteCleanup();
} | java |
protected synchronized void doClose()
{
try
{
LockManager lm = getImplementation().getLockManager();
Enumeration en = objectEnvelopeTable.elements();
while (en.hasMoreElements())
{
ObjectEnvelope oe = (ObjectEnvelope) en.nextElement();
lm.releaseLock(this, oe.getIdentity(), oe.getObject());
}
//remove locks for objects which haven't been materialized yet
for (Iterator it = unmaterializedLocks.iterator(); it.hasNext();)
{
lm.releaseLock(this, it.next());
}
// this tx is no longer interested in materialization callbacks
unRegisterFromAllIndirectionHandlers();
unRegisterFromAllCollectionProxies();
}
finally
{
/**
* MBAIRD: Be nice and close the table to release all refs
*/
if (log.isDebugEnabled())
log.debug("Close Transaction and release current PB " + broker + " on tx " + this);
// remove current thread from LocalTxManager
// to avoid problems for succeeding calls of the same thread
implementation.getTxManager().deregisterTx(this);
// now cleanup and prepare for reuse
refresh();
}
} | java |
protected void refresh()
{
if (log.isDebugEnabled())
log.debug("Refresh this transaction for reuse: " + this);
try
{
// we reuse ObjectEnvelopeTable instance
objectEnvelopeTable.refresh();
}
catch (Exception e)
{
if (log.isDebugEnabled())
{
log.debug("error closing object envelope table : " + e.getMessage());
e.printStackTrace();
}
}
cleanupBroker();
// clear the temporary used named roots map
// we should do that, because same tx instance
// could be used several times
broker = null;
clearRegistrationList();
unmaterializedLocks.clear();
txStatus = Status.STATUS_NO_TRANSACTION;
} | java |
public void abort()
{
/*
do nothing if already rolledback
*/
if (txStatus == Status.STATUS_NO_TRANSACTION
|| txStatus == Status.STATUS_UNKNOWN
|| txStatus == Status.STATUS_ROLLEDBACK)
{
log.info("Nothing to abort, tx is not active - status is " + TxUtil.getStatusString(txStatus));
return;
}
// check status of tx
if (txStatus != Status.STATUS_ACTIVE && txStatus != Status.STATUS_PREPARED &&
txStatus != Status.STATUS_MARKED_ROLLBACK)
{
throw new IllegalStateException("Illegal state for abort call, state was '" + TxUtil.getStatusString(txStatus) + "'");
}
if(log.isEnabledFor(Logger.INFO))
{
log.info("Abort transaction was called on tx " + this);
}
try
{
try
{
doAbort();
}
catch(Exception e)
{
log.error("Error while abort transaction, will be skipped", e);
}
// used in managed environments, ignored in non-managed
this.implementation.getTxManager().abortExternalTx(this);
try
{
if(hasBroker() && getBroker().isInTransaction())
{
getBroker().abortTransaction();
}
}
catch(Exception e)
{
log.error("Error while do abort used broker instance, will be skipped", e);
}
}
finally
{
txStatus = Status.STATUS_ROLLEDBACK;
// cleanup things, e.g. release all locks
doClose();
}
} | java |
public Object getObjectByIdentity(Identity id)
throws PersistenceBrokerException
{
checkOpen();
ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(id);
if (envelope != null)
{
return (envelope.needsDelete() ? null : envelope.getObject());
}
else
{
return getBroker().getObjectByIdentity(id);
}
} | java |
private void lockAndRegisterReferences(ClassDescriptor cld, Object sourceObject, int lockMode, List registeredObjects) throws LockNotGrantedException
{
if (implicitLocking)
{
Iterator i = cld.getObjectReferenceDescriptors(true).iterator();
while (i.hasNext())
{
ObjectReferenceDescriptor rds = (ObjectReferenceDescriptor) i.next();
Object refObj = rds.getPersistentField().get(sourceObject);
if (refObj != null)
{
boolean isProxy = ProxyHelper.isProxy(refObj);
RuntimeObject rt = isProxy ? new RuntimeObject(refObj, this, false) : new RuntimeObject(refObj, this);
if (!registrationList.contains(rt.getIdentity()))
{
lockAndRegister(rt, lockMode, registeredObjects);
}
}
}
}
} | java |
public void afterMaterialization(IndirectionHandler handler, Object materializedObject)
{
try
{
Identity oid = handler.getIdentity();
if (log.isDebugEnabled())
log.debug("deferred registration: " + oid);
if(!isOpen())
{
log.error("Proxy object materialization outside of a running tx, obj=" + oid);
try{throw new Exception("Proxy object materialization outside of a running tx, obj=" + oid);}catch(Exception e)
{
e.printStackTrace();
}
}
ClassDescriptor cld = getBroker().getClassDescriptor(materializedObject.getClass());
RuntimeObject rt = new RuntimeObject(materializedObject, oid, cld, false, false);
lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());
}
catch (Throwable t)
{
log.error("Register materialized object with this tx failed", t);
throw new LockNotGrantedException(t.getMessage());
}
unregisterFromIndirectionHandler(handler);
} | java |
public void afterLoading(CollectionProxyDefaultImpl colProxy)
{
if (log.isDebugEnabled()) log.debug("loading a proxied collection a collection: " + colProxy);
Collection data = colProxy.getData();
for (Iterator iterator = data.iterator(); iterator.hasNext();)
{
Object o = iterator.next();
if(!isOpen())
{
log.error("Collection proxy materialization outside of a running tx, obj=" + o);
try{throw new Exception("Collection proxy materialization outside of a running tx, obj=" + o);}
catch(Exception e)
{e.printStackTrace();}
}
else
{
Identity oid = getBroker().serviceIdentity().buildIdentity(o);
ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));
RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));
lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());
}
}
unregisterFromCollectionProxy(colProxy);
} | java |
protected boolean isTransient(ClassDescriptor cld, Object obj, Identity oid)
{
// if the Identity is transient we assume a non-persistent object
boolean isNew = oid != null && oid.isTransient();
/*
detection of new objects is costly (select of ID in DB to check if object
already exists) we do:
a. check if the object has nullified PK field
b. check if the object is already registered
c. lookup from cache and if not found, last option select on DB
*/
if(!isNew)
{
final PersistenceBroker pb = getBroker();
if(cld == null)
{
cld = pb.getClassDescriptor(obj.getClass());
}
isNew = pb.serviceBrokerHelper().hasNullPKField(cld, obj);
if(!isNew)
{
if(oid == null)
{
oid = pb.serviceIdentity().buildIdentity(cld, obj);
}
final ObjectEnvelope mod = objectEnvelopeTable.getByIdentity(oid);
if(mod != null)
{
// already registered object, use current state
isNew = mod.needsInsert();
}
else
{
// if object was found cache, assume it's old
// else make costly check against the DB
isNew = pb.serviceObjectCache().lookup(oid) == null
&& !pb.serviceBrokerHelper().doesExist(cld, oid, obj);
}
}
}
return isNew;
} | java |
private License getLicense(final String licenseId) {
License result = null;
final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);
if (matchingLicenses.isEmpty()) {
result = DataModelFactory.createLicense("#" + licenseId + "# (to be identified)", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);
result.setUnknown(true);
} else {
if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {
LOG.warn(String.format("%s matches multiple licenses %s. " +
"Please run the report showing multiple matching on licenses",
licenseId, matchingLicenses.toString()));
}
result = mapper.getLicense(matchingLicenses.iterator().next());
}
return result;
} | java |
private String[] getHeaders() {
final List<String> headers = new ArrayList<>();
if(decorator.getShowSources()){
headers.add(SOURCE_FIELD);
}
if(decorator.getShowSourcesVersion()){
headers.add(SOURCE_VERSION_FIELD);
}
if(decorator.getShowTargets()){
headers.add(TARGET_FIELD);
}
if(decorator.getShowTargetsDownloadUrl()){
headers.add(DOWNLOAD_URL_FIELD);
}
if(decorator.getShowTargetsSize()){
headers.add(SIZE_FIELD);
}
if(decorator.getShowScopes()){
headers.add(SCOPE_FIELD);
}
if(decorator.getShowLicenses()){
headers.add(LICENSE_FIELD);
}
if(decorator.getShowLicensesLongName()){
headers.add(LICENSE_LONG_NAME_FIELD);
}
if(decorator.getShowLicensesUrl()){
headers.add(LICENSE_URL_FIELD);
}
if(decorator.getShowLicensesComment()){
headers.add(LICENSE_COMMENT_FIELD);
}
return headers.toArray(new String[headers.size()]);
} | java |
public InputStream getStream(String url, RasterLayer layer) throws IOException {
if (layer instanceof ProxyLayerSupport) {
ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
if (proxyLayer.isUseCache() && null != cacheManagerService) {
Object cachedObject = cacheManagerService.get(proxyLayer, CacheCategory.RASTER, url);
if (null != cachedObject) {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_GET_FROM_CACHE);
return new ByteArrayInputStream((byte[]) cachedObject);
} else {
testRecorder.record(TEST_RECORDER_GROUP, TEST_RECORDER_PUT_IN_CACHE);
InputStream stream = super.getStream(url, proxyLayer);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int b;
while ((b = stream.read()) >= 0) {
os.write(b);
}
cacheManagerService.put(proxyLayer, CacheCategory.RASTER, url, os.toByteArray(),
getLayerEnvelope(proxyLayer));
return new ByteArrayInputStream((byte[]) os.toByteArray());
}
}
}
return super.getStream(url, layer);
} | java |
private Envelope getLayerEnvelope(ProxyLayerSupport layer) {
Bbox bounds = layer.getLayerInfo().getMaxExtent();
return new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY());
} | java |
private static String buildErrorMsg(List<String> dependencies, String message) {
final StringBuilder buffer = new StringBuilder();
boolean isFirstElement = true;
for (String dependency : dependencies) {
if (!isFirstElement) {
buffer.append(", ");
}
// check if it is an instance of Artifact - add the gavc else append the object
buffer.append(dependency);
isFirstElement = false;
}
return String.format(message, buffer.toString());
} | java |
protected Query buildPrefetchQuery(Collection ids)
{
CollectionDescriptor cds = getCollectionDescriptor();
QueryByCriteria query = buildPrefetchQuery(ids, cds.getForeignKeyFieldDescriptors(getItemClassDescriptor()));
// check if collection must be ordered
if (!cds.getOrderBy().isEmpty())
{
Iterator iter = cds.getOrderBy().iterator();
while (iter.hasNext())
{
query.addOrderBy((FieldHelper) iter.next());
}
}
return query;
} | java |
protected void associateBatched(Collection owners, Collection children)
{
CollectionDescriptor cds = getCollectionDescriptor();
PersistentField field = cds.getPersistentField();
PersistenceBroker pb = getBroker();
Class ownerTopLevelClass = pb.getTopLevelClass(getOwnerClassDescriptor().getClassOfObject());
Class collectionClass = cds.getCollectionClass(); // this collection type will be used:
HashMap ownerIdsToLists = new HashMap(owners.size());
IdentityFactory identityFactory = pb.serviceIdentity();
// initialize the owner list map
for (Iterator it = owners.iterator(); it.hasNext();)
{
Object owner = it.next();
ownerIdsToLists.put(identityFactory.buildIdentity(getOwnerClassDescriptor(), owner), new ArrayList());
}
// build the children lists for the owners
for (Iterator it = children.iterator(); it.hasNext();)
{
Object child = it.next();
// BRJ: use cld for real class, relatedObject could be Proxy
ClassDescriptor cld = getDescriptorRepository().getDescriptorFor(ProxyHelper.getRealClass(child));
Object[] fkValues = cds.getForeignKeyValues(child, cld);
Identity ownerId = identityFactory.buildIdentity(null, ownerTopLevelClass, fkValues);
List list = (List) ownerIdsToLists.get(ownerId);
if (list != null)
{
list.add(child);
}
}
// connect children list to owners
for (Iterator it = owners.iterator(); it.hasNext();)
{
Object result;
Object owner = it.next();
Identity ownerId = identityFactory.buildIdentity(owner);
List list = (List) ownerIdsToLists.get(ownerId);
if ((collectionClass == null) && field.getType().isArray())
{
int length = list.size();
Class itemtype = field.getType().getComponentType();
result = Array.newInstance(itemtype, length);
for (int j = 0; j < length; j++)
{
Array.set(result, j, list.get(j));
}
}
else
{
ManageableCollection col = createCollection(cds, collectionClass);
for (Iterator it2 = list.iterator(); it2.hasNext();)
{
col.ojbAdd(it2.next());
}
result = col;
}
Object value = field.get(owner);
if ((value instanceof CollectionProxyDefaultImpl) && (result instanceof Collection))
{
((CollectionProxyDefaultImpl) value).setData((Collection) result);
}
else
{
field.set(owner, result);
}
}
} | java |
protected ManageableCollection createCollection(CollectionDescriptor desc, Class collectionClass)
{
Class fieldType = desc.getPersistentField().getType();
ManageableCollection col;
if (collectionClass == null)
{
if (ManageableCollection.class.isAssignableFrom(fieldType))
{
try
{
col = (ManageableCollection)fieldType.newInstance();
}
catch (Exception e)
{
throw new OJBRuntimeException("Cannot instantiate the default collection type "+fieldType.getName()+" of collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject());
}
}
else if (fieldType.isAssignableFrom(RemovalAwareCollection.class))
{
col = new RemovalAwareCollection();
}
else if (fieldType.isAssignableFrom(RemovalAwareList.class))
{
col = new RemovalAwareList();
}
else if (fieldType.isAssignableFrom(RemovalAwareSet.class))
{
col = new RemovalAwareSet();
}
else
{
throw new MetadataException("Cannot determine a default collection type for collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject());
}
}
else
{
try
{
col = (ManageableCollection)collectionClass.newInstance();
}
catch (Exception e)
{
throw new OJBRuntimeException("Cannot instantiate the collection class "+collectionClass.getName()+" of collection "+desc.getAttributeName()+" in type "+desc.getClassDescriptor().getClassNameOfObject());
}
}
return col;
} | java |
@Api
public void setFeatureModel(FeatureModel featureModel) throws LayerException {
this.featureModel = featureModel;
if (null != getLayerInfo()) {
featureModel.setLayerInfo(getLayerInfo());
}
filterService.registerFeatureModel(featureModel);
} | java |
public void update(Object feature) throws LayerException {
Session session = getSessionFactory().getCurrentSession();
session.update(feature);
} | java |
private void enforceSrid(Object feature) throws LayerException {
Geometry geom = getFeatureModel().getGeometry(feature);
if (null != geom) {
geom.setSRID(srid);
getFeatureModel().setGeometry(feature, geom);
}
} | java |
private Envelope getBoundsLocal(Filter filter) throws LayerException {
try {
Session session = getSessionFactory().getCurrentSession();
Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());
CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);
Criterion c = (Criterion) filter.accept(visitor, criteria);
if (c != null) {
criteria.add(c);
}
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<?> features = criteria.list();
Envelope bounds = new Envelope();
for (Object f : features) {
Envelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();
if (!geomBounds.isNull()) {
bounds.expandToInclude(geomBounds);
}
}
return bounds;
} catch (HibernateException he) {
throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()
.getDataSourceName(), filter.toString());
}
} | java |
public Object getBean(String name) {
Bean bean = beans.get(name);
if (null == bean) {
return null;
}
return bean.object;
} | java |
public void setBean(String name, Object object) {
Bean bean = beans.get(name);
if (null == bean) {
bean = new Bean();
beans.put(name, bean);
}
bean.object = object;
} | java |
public Object remove(String name) {
Bean bean = beans.get(name);
if (null != bean) {
beans.remove(name);
bean.destructionCallback.run();
return bean.object;
}
return null;
} | java |
public void registerDestructionCallback(String name, Runnable callback) {
Bean bean = beans.get(name);
if (null == bean) {
bean = new Bean();
beans.put(name, bean);
}
bean.destructionCallback = callback;
} | java |
public void clear() {
for (Bean bean : beans.values()) {
if (null != bean.destructionCallback) {
bean.destructionCallback.run();
}
}
beans.clear();
} | java |
private String parseLayerId(HttpServletRequest request) {
StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
String token = "";
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
}
return token;
} | java |
private WmsLayer getLayer(String layerId) {
RasterLayer layer = configurationService.getRasterLayer(layerId);
if (layer instanceof WmsLayer) {
return (WmsLayer) layer;
}
return null;
} | java |
private byte[] createErrorImage(int width, int height, Exception e) throws IOException {
String error = e.getMessage();
if (null == error) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
error = result.toString();
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.RED);
g.drawString(error, ERROR_MESSAGE_X, height / 2);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", out);
out.flush();
byte[] result = out.toByteArray();
out.close();
return result;
} | java |
public static String formatConnectionEstablishmentMessage(final String connectionName, final String host, final String connectionReason) {
return CON_ESTABLISHMENT_FORMAT.format(new Object[] { connectionName, host, connectionReason });
} | java |
public static String formatConnectionTerminationMessage(final String connectionName, final String host, final String connectionReason, final String terminationReason) {
return CON_TERMINATION_FORMAT.format(new Object[] { connectionName, host, connectionReason, terminationReason });
} | java |
public String findPlatformFor(String jdbcSubProtocol, String jdbcDriver)
{
String platform = (String)jdbcSubProtocolToPlatform.get(jdbcSubProtocol);
if (platform == null)
{
platform = (String)jdbcDriverToPlatform.get(jdbcDriver);
}
return platform;
} | java |
public static void validate(final License license) {
// A license should have a name
if(license.getName() == null ||
license.getName().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("License name should not be empty!")
.build());
}
// A license should have a long name
if(license.getLongName() == null ||
license.getLongName().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("License long name should not be empty!")
.build());
}
// If there is a regexp, it should compile
if(license.getRegexp() != null &&
!license.getRegexp().isEmpty()){
try{
Pattern.compile(license.getRegexp());
}
catch (PatternSyntaxException e){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("License regexp does not compile!").build());
}
Pattern regex = Pattern.compile("[&%//]");
if(regex.matcher(license.getRegexp()).find()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("License regexp does not compile!").build());
}
}
} | java |
public static void validate(final Module module) {
if (null == module) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Module cannot be null!")
.build());
}
if(module.getName() == null ||
module.getName().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Module name cannot be null or empty!")
.build());
}
if(module.getVersion()== null ||
module.getVersion().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Module version cannot be null or empty!")
.build());
}
// Check artifacts
for(final Artifact artifact: DataUtils.getAllArtifacts(module)){
validate(artifact);
}
// Check dependencies
for(final Dependency dependency: DataUtils.getAllDependencies(module)){
validate(dependency.getTarget());
}
} | java |
public static void validate(final Organization organization) {
if(organization.getName() == null ||
organization.getName().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Organization name cannot be null or empty!")
.build());
}
} | java |
public static void validate(final ArtifactQuery artifactQuery) {
final Pattern invalidChars = Pattern.compile("[^A-Fa-f0-9]");
if(artifactQuery.getUser() == null ||
artifactQuery.getUser().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Mandatory field [user] missing")
.build());
}
if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Invalid [stage] value (supported 0 | 1)")
.build());
}
if(artifactQuery.getName() == null ||
artifactQuery.getName().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Mandatory field [name] missing, it should be the file name")
.build());
}
if(artifactQuery.getSha256() == null ||
artifactQuery.getSha256().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Mandatory field [sha256] missing")
.build());
}
if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Invalid file checksum value")
.build());
}
if(artifactQuery.getType() == null ||
artifactQuery.getType().isEmpty()){
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
.entity("Mandatory field [type] missing")
.build());
}
} | java |
protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException
{
long result;
// lookup sequence name
String sequenceName = calculateSequenceName(field);
try
{
result = buildNextSequence(field.getClassDescriptor(), sequenceName);
}
catch (Throwable e)
{
// maybe the sequence was not created
try
{
log.info("Create DB sequence key '"+sequenceName+"'");
createSequence(field.getClassDescriptor(), sequenceName);
}
catch (Exception e1)
{
throw new SequenceManagerException(
SystemUtils.LINE_SEPARATOR +
"Could not grab next id, failed with " + SystemUtils.LINE_SEPARATOR +
e.getMessage() + SystemUtils.LINE_SEPARATOR +
"Creation of new sequence failed with " +
SystemUtils.LINE_SEPARATOR + e1.getMessage() + SystemUtils.LINE_SEPARATOR
, e1);
}
try
{
result = buildNextSequence(field.getClassDescriptor(), sequenceName);
}
catch (Throwable e1)
{
throw new SequenceManagerException("Could not grab next id, sequence seems to exist", e);
}
}
return result;
} | java |
protected Collection provideStateManagers(Collection pojos)
{
PersistenceCapable pc;
int [] fieldNums;
Iterator iter = pojos.iterator();
Collection result = new ArrayList();
while (iter.hasNext())
{
// obtain a StateManager
pc = (PersistenceCapable) iter.next();
Identity oid = new Identity(pc, broker);
StateManagerInternal smi = pmi.getStateManager(oid, pc.getClass());
// fetch attributes into StateManager
JDOClass jdoClass = Helper.getJDOClass(pc.getClass());
fieldNums = jdoClass.getManagedFieldNumbers();
FieldManager fm = new OjbFieldManager(pc, broker);
smi.replaceFields(fieldNums, fm);
smi.retrieve();
// get JDO PersistencecCapable instance from SM and add it to result collection
Object instance = smi.getObject();
result.add(instance);
}
return result;
} | java |
public final Object copy(final Object toCopy, PersistenceBroker broker)
{
return clone(toCopy, IdentityMapFactory.getIdentityMap(), new HashMap());
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
public void releaseDbResources()
{
Iterator it = m_rsIterators.iterator();
while (it.hasNext())
{
((OJBIterator) it.next()).releaseDbResources();
}
} | java |
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 |
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 |
public Class getSearchClass()
{
Object obj = getExampleObject();
if (obj instanceof Identity)
{
return ((Identity) obj).getObjectsTopLevelClass();
}
else
{
return obj.getClass();
}
} | java |
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 |
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 |
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 |
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 |
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 |
public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException
{
return getKeyValues(cld, oid, true);
} | java |
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 |
public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException
{
return getKeyValues(cld, objectOrProxy, true);
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public boolean unlink(Object source, String attributeName, Object target)
{
return linkOrUnlink(false, source, attributeName, false);
} | java |
public void unlink(Object obj, ObjectReferenceDescriptor ord, boolean insert)
{
linkOrUnlink(false, obj, ord, insert);
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
@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 |
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 |
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 |
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 |
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 |
void unbind(String key)
{
NamedEntry entry = new NamedEntry(key, null, false);
localUnbind(key);
addForDeletion(entry);
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public Object get(Object key)
{
purge();
Entry entry = getEntry(key);
if (entry == null) return null;
return entry.getValue();
} | java |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.