code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public boolean isServerAvailable(){
final Client client = getClient();
final ClientResponse response = client.resource(serverURL).get(ClientResponse.class);
if(ClientResponse.Status.OK.getStatusCode() == response.getStatus()){
return true;
}
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, "Failed to reach the targeted Grapes server", response.getStatus()));
}
client.destroy();
return false;
} | Checks if the dependency server is available
@return true if the server is reachable, false otherwise |
public void postBuildInfo(final String moduleName, final String moduleVersion, final Map<String, String> buildInfo, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getBuildInfoPath(moduleName, moduleVersion));
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, buildInfo);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST buildInfo";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Post a build info to the server
@param moduleName String
@param moduleVersion String
@param buildInfo Map<String,String>
@param user String
@param password String
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public void postModule(final Module module, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.moduleResourcePath());
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, module);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST module";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Post a module to the server
@param module
@param user
@param password
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));
final ClientResponse response = resource.delete(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = String.format(FAILED_TO_GET_MODULE, "to delete module", name, version);
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Delete a module from Grapes server
@param name
@param version
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public Module getModule(final String name, final String version) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));
final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = String.format(FAILED_TO_GET_MODULE, "get module details", name, version);
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(Module.class);
} | Send a get module request
@param name
@param version
@return the targeted module
@throws GrapesCommunicationException |
public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {
final Client client = getClient();
WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());
for(final Map.Entry<String,String> queryParam: filters.entrySet()){
resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());
}
final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get filtered modules.";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(new GenericType<List<Module>>(){});
} | Get a list of modules regarding filters
@param filters Map<String,String>
@return List<Module>
@throws GrapesCommunicationException |
public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version));
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = String.format(FAILED_TO_GET_MODULE, "promote module", name, version);
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Promote a module in the Grapes server
@param name
@param version
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public PromotionEvaluationReport getModulePromotionReport(final String name, final String version) throws GrapesCommunicationException {
return getModulePromotionReportRaw(name, version, false, PromotionEvaluationReport.class);
} | Check if a module can be promoted in the Grapes server
@param name
@param version
@return a boolean which is true only if the module can be promoted
@throws GrapesCommunicationException |
public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST artifact";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Post an artifact to the Grapes server
@param artifact The artifact to post
@param user The user posting the information
@param password The user password
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public void deleteArtifact(final String gavc, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactPath(gavc));
final ClientResponse response = resource.delete(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to DELETE artifact " + gavc;
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Delete an artifact in the Grapes server
@param gavc
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());
final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get artifacts";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(ArtifactList.class);
} | Send a get artifacts request
@param hasLicense
@return list of artifact
@throws GrapesCommunicationException |
public void postDoNotUseArtifact(final String gavc, final Boolean doNotUse, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getDoNotUseArtifact(gavc));
final ClientResponse response = resource.queryParam(ServerAPI.DO_NOT_USE, doNotUse.toString())
.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to post do not use artifact";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Post boolean flag "DO_NOT_USE" to an artifact
@param gavc
@param doNotUse
@param user
@param password
@throws GrapesCommunicationException |
public List<String> getArtifactVersions(final String gavc) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactVersions(gavc));
final ClientResponse response = resource
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = FAILED_TO_GET_CORPORATE_FILTERS;
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(new GenericType<List<String>>(){});
} | Returns the artifact available versions
@param gavc String
@return List<String> |
public void addLicense(final String gavc, final String licenseId, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactLicensesPath(gavc));
final ClientResponse response = resource.queryParam(ServerAPI.LICENSE_ID_PARAM, licenseId).post(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to add license " + licenseId + " to artifact " + gavc;
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Add a license to an artifact
@param gavc
@param licenseId
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to POST license";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Post a license to the server
@param license
@param user
@param password
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public void approveLicense(final String licenseId, final Boolean approve, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getLicensePath(licenseId));
final ClientResponse response = resource.queryParam(ServerAPI.APPROVED_PARAM, approve.toString()).post(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to approve license " + licenseId;
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Approve or reject a license
@param licenseId
@param approve
@throws GrapesCommunicationException
@throws javax.naming.AuthenticationException |
public List<Dependency> getModuleAncestors(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactAncestors(moduleName, moduleVersion));
final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true")
.queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true")
.queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true")
.queryParam(ServerAPI.SCOPE_TEST_PARAM, "true")
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors", moduleName, moduleVersion);
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(new GenericType<List<Dependency>>(){});
} | Return the list of module ancestors
@param moduleName
@param moduleVersion
@return List<Dependency>
@throws GrapesCommunicationException |
public List<Dependency> getModuleDependencies(final String moduleName, final String moduleVersion, final Boolean fullRecursive, final Boolean corporate, final Boolean thirdParty) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactDependencies(moduleName, moduleVersion));
final ClientResponse response = resource.queryParam(ServerAPI.SCOPE_COMPILE_PARAM, "true")
.queryParam(ServerAPI.SCOPE_PROVIDED_PARAM, "true")
.queryParam(ServerAPI.SCOPE_RUNTIME_PARAM, "true")
.queryParam(ServerAPI.SCOPE_TEST_PARAM, "true")
.queryParam(ServerAPI.RECURSIVE_PARAM, fullRecursive.toString())
.queryParam(ServerAPI.SHOW_CORPORATE_PARAM, corporate.toString())
.queryParam(ServerAPI.SHOW_THIRPARTY_PARAM, thirdParty.toString())
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = String.format(FAILED_TO_GET_MODULE, "get module ancestors ", moduleName, moduleVersion);
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(new GenericType<List<Dependency>>(){});
} | Return the list of module dependencies
@param moduleName
@param moduleVersion
@param fullRecursive
@param corporate
@param thirdParty
@return List<Dependency>
@throws GrapesCommunicationException |
public Organization getModuleOrganization(final String moduleName, final String moduleVersion) throws GrapesCommunicationException {
final Client client = getClient();
final WebResource resource = client.resource(serverURL).path(RequestUtils.getModuleOrganizationPath(moduleName, moduleVersion));
final ClientResponse response = resource
.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
client.destroy();
if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){
final String message = "Failed to get module's organization";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
return response.getEntity(Organization.class);
} | Returns the organization of a given module
@return Organization |
public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName));
final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery);
client.destroy();
if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
final String message = "Failed to create a delivery";
if(LOG.isErrorEnabled()) {
LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
}
throw new GrapesCommunicationException(message, response.getStatus());
}
} | Create an Product delivery
@throws AuthenticationException, GrapesCommunicationException, IOException |
public void commit(ObjectEnvelope mod) throws org.apache.ojb.broker.PersistenceBrokerException
{
mod.doInsert();
mod.setModificationState(StateOldClean.getInstance());
} | commit the associated transaction |
public Object lookup(Identity oid)
{
CacheEntry entry = null;
SoftReference ref = (SoftReference) objectTable.get(oid);
if (ref != null)
{
entry = (CacheEntry) ref.get();
if (entry == null || entry.lifetime < System.currentTimeMillis())
{
objectTable.remove(oid); // Soft-referenced Object reclaimed by GC
// timeout, so set null
entry = null;
}
}
return entry != null ? entry.object : null;
} | Lookup object with Identity oid in objectTable.
Returns null if no matching id is found |
public void cleanup(boolean reuse, boolean wasInsert)
{
if(currentImage != null)
{
performImageCleanup(currentImage, reuse);
}
if(beforeImage != null)
{
// we always free all resources of the old image
performImageCleanup(beforeImage, false);
}
if(reuse)
{
refreshObjectImage(wasInsert);
}
else
{
myObj = null;
}
} | This method should be called before transaction ends
to allow cleanup of used resources, e.g. remove proxy listener objects
to avoid invoke of registered objects after tx end. |
public Identity refreshIdentity()
{
Identity oldOid = getIdentity();
this.oid = getBroker().serviceIdentity().buildIdentity(myObj);
return oldOid;
} | Replace the current with a new generated identity object and
returns the old one. |
private Map buildObjectImage(PersistenceBroker broker) throws PersistenceBrokerException
{
Map imageMap = new HashMap();
ClassDescriptor cld = broker.getClassDescriptor(getObject().getClass());
//System.out.println("++++ build image: " + getObject());
// register 1:1 references in image
buildImageForSingleReferences(imageMap, cld);
// put object values to image map
buildImageForFields(imageMap, cld);
// register 1:n and m:n references in image
buildImageForCollectionReferences(imageMap, cld);
return imageMap;
} | buildObjectImage() will return the image of the Object. |
private void prepareInitialState(boolean isNewObject)
{
// determine appropriate modification state
ModificationState initialState;
if(isNewObject)
{
// if object is not already persistent it must be marked as new
// it must be marked as dirty because it must be stored even if it will not modified during tx
initialState = StateNewDirty.getInstance();
}
else if(isDeleted(oid))
{
// if object is already persistent it will be marked as old.
// it is marked as dirty as it has been deleted during tx and now it is inserted again,
// possibly with new field values.
initialState = StateOldDirty.getInstance();
}
else
{
// if object is already persistent it will be marked as old.
// it is marked as clean as it has not been modified during tx already
initialState = StateOldClean.getInstance();
}
// remember it:
modificationState = initialState;
} | Sets the initial MoificationState of the wrapped object myObj. The initial state will be StateNewDirty if myObj
is not persisten already. The state will be set to StateOldClean if the object is already persistent. |
public boolean isDeleted(Identity id)
{
ObjectEnvelope envelope = buffer.getByIdentity(id);
return (envelope != null && envelope.needsDelete());
} | Checks if the object with the given identity has been deleted
within the transaction.
@param id The identity
@return true if the object has been deleted
@throws PersistenceBrokerException |
public void setModificationState(ModificationState newModificationState)
{
if(newModificationState != modificationState)
{
if(log.isDebugEnabled())
{
log.debug("object state transition for object " + this.oid + " ("
+ modificationState + " --> " + newModificationState + ")");
// try{throw new Exception();}catch(Exception e)
// {
// e.printStackTrace();
// }
}
modificationState = newModificationState;
}
} | set the Modification state to a new value. Used during state transitions.
@param newModificationState org.apache.ojb.server.states.ModificationState |
public boolean hasChanged(PersistenceBroker broker)
{
if(hasChanged == null)
{
Map current = null;
try
{
current = getCurrentImage();
}
catch(Exception e)
{
log.warn("Could not verify object changes, mark dirty: " + getIdentity(), e);
}
if(beforeImage != null && current != null)
{
Iterator it = beforeImage.entrySet().iterator();
hasChanged = Boolean.FALSE;
while(it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next();
Image imageBefore = (Image) entry.getValue();
Image imageCurrent = (Image) current.get(entry.getKey());
if(imageBefore.modified(imageCurrent))
{
hasChanged = Boolean.TRUE;
break;
}
}
}
else
{
hasChanged = Boolean.TRUE;
}
if(log.isDebugEnabled())
{
log.debug("State detection for " + getIdentity() + " --> object "
+ (hasChanged.booleanValue() ? "has changed" : "unchanged"));
}
}
return hasChanged.booleanValue();
} | For internal use only! Only call immediately before commit to guarantee
that all changes can be detected (because this method cache the detected "change state"
thus on eager call changes could be ignored). Checks whether object and internal clone
differ and returns <em>true</em> if so, returns <em>false</em> else.
@return boolean The result. |
void markReferenceElements(PersistenceBroker broker)
{
// these cases will be handled by ObjectEnvelopeTable#cascadingDependents()
// if(getModificationState().needsInsert() || getModificationState().needsDelete()) return;
Map oldImage = getBeforeImage();
Map newImage = getCurrentImage();
Iterator iter = newImage.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
// we only interested in references
if(key instanceof ObjectReferenceDescriptor)
{
Image oldRefImage = (Image) oldImage.get(key);
Image newRefImage = (Image) entry.getValue();
newRefImage.performReferenceDetection(oldRefImage);
}
}
} | Mark new or deleted reference elements
@param broker |
@Override
public void launchPlatform() {
logger.fine("Launching Jade Platform...");
this.runtime = Runtime.instance();
// TODO make this configurable
Profile p = new ProfileImpl();
p.setParameter(Profile.GUI, TRUE);
p.setParameter(Profile.NO_MTP, TRUE);
p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);
p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);
p.setParameter(Profile.LOCAL_PORT, MAIN_PORT);
p.setParameter(Profile.AGENTS, AGENTS);
p.setParameter(Profile.SERVICES, SERVICES);
this.mainContainer = this.runtime.createMainContainer(p);
logger.fine("Main container launched");
this.createdAgents = new HashMap<String, AgentController>();
this.platformContainers = new HashMap<String, ContainerController>();
this.platformContainers.put("Main-Container", mainContainer);
this.createAgent(BEAST_MESSENGER,
"es.upm.dit.gsi.beast.platform.jade.agent.MessengerAgent");
} | /*
(non-Javadoc)
@see es.upm.dit.gsi.beast.platform.Connector#launchPlatform() |
@Override
public void stopPlatform() {
try {
for (Entry<String, AgentController> e : this.createdAgents
.entrySet()) {
AgentController ac = e.getValue();
ac.kill();
}
for (Entry<String, ContainerController> e : this.platformContainers
.entrySet()) {
ContainerController cc = e.getValue();
cc.kill();
}
this.mainContainer.kill();
this.runtime.shutDown();
} catch (Exception e) {
logger.warning("Warning shuting down JADE platform: "
+ e.getMessage());
}
} | /* (non-Javadoc)
@see es.upm.dit.gsi.beast.platform.Connector#stopPlatform() |
@Override
public void createAgent(String agent_name, String path) {
logger.fine("Creating agent " + agent_name + " in Main Container");
Object reference = new Object();
Object empty[] = new Object[1];
empty[0] = reference;
try {
AgentController agentController = mainContainer.createNewAgent(
agent_name, path, empty);
this.createdAgents.put(agent_name, agentController);
agentController.start();
logger.fine("Agent " + agent_name
+ " created and started in Main Container");
try {
Thread.sleep(MILLIS_TO_WAIT_FOR_AGENT_STARTING);
} catch (InterruptedException e) {
logger.warning("It was not possible to wait for agent starting... Maybe, the agent is not completely started yet.");
}
} catch (StaleProxyException e) {
logger.warning("Exception creating or starting agent in MainContainer... "
+ e);
}
// Register the agent
} | /*
(non-Javadoc)
@see
es.upm.dit.gsi.beast.platform.Connector#createAgent(java.lang.String,
java.lang.String) |
public void createContainer(String container) {
ContainerController controller = this.platformContainers.get(container);
if (controller == null) {
// TODO make this configurable
Profile p = new ProfileImpl();
p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);
p.setParameter(Profile.MAIN_HOST, MAIN_HOST);
p.setParameter(Profile.MAIN_PORT, MAIN_PORT);
p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);
int port = Integer.parseInt(MAIN_PORT);
port = port + 1 + this.platformContainers.size();
p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));
p.setParameter(Profile.CONTAINER_NAME, container);
logger.fine("Creating container " + container + "...");
ContainerController agentContainer = this.runtime
.createAgentContainer(p);
this.platformContainers.put(container, agentContainer);
logger.fine("Container " + container + " created successfully.");
} else {
logger.fine("Container " + container + " is already created.");
}
} | Create a container in the platform
@param container
The name of the container |
public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)
{
return aQuery;
} | Default implementation returns unmodified original Query
@see org.apache.ojb.broker.accesslayer.QueryCustomizer#customizeQuery |
public String getAttribute(String attributeName, String defaultValue)
{
String result = defaultValue;
if (m_attributeList!=null)
{
result = (String)m_attributeList.get(attributeName);
if (result==null)
{
result = defaultValue;
}
}
return result;
} | /* (non-Javadoc)
@see org.apache.ojb.broker.metadata.AttributeContainer#getAttribute(java.lang.String, java.lang.String) |
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {
if (null == filter) {
filter = Filter.INCLUDE;
}
List<Object> filteredList = new ArrayList<Object>();
try {
synchronized (featuresById) {
for (Object feature : featuresById.values()) {
if (filter.evaluate(feature)) {
filteredList.add(feature);
}
}
}
} catch (Exception e) { // NOSONAR
throw new LayerException(e, ExceptionCode.FILTER_EVALUATION_PROBLEM, filter, getId());
}
// Sorting of elements.
if (comparator != null) {
Collections.sort(filteredList, comparator);
}
if (maxResultSize > 0) {
int fromIndex = Math.max(0, offset);
int toIndex = Math.min(offset + maxResultSize, filteredList.size());
toIndex = Math.max(fromIndex, toIndex);
return filteredList.subList(fromIndex, toIndex).iterator();
} else {
return filteredList.iterator();
}
} | This implementation does not support the 'offset' and 'maxResultSize' parameters. |
public Envelope getBounds(Filter queryFilter) throws LayerException {
Iterator<?> it = getElements(queryFilter, 0, 0);
// start with null envelope
Envelope bounds = new Envelope();
while (it.hasNext()) {
Object o = it.next();
Geometry g = featureModel.getGeometry(o);
bounds.expandToInclude(g.getEnvelopeInternal());
}
return bounds;
} | Retrieve the bounds of the specified features.
@return the bounds of the specified features |
public void setTileUrls(List<String> tileUrls) {
this.tileUrls = tileUrls;
if (null != urlStrategy) {
urlStrategy.setUrls(tileUrls);
}
} | Set possible tile URLs.
@param tileUrls tile URLs |
public void postConstruct(GeoService geoService, DtoConverterService converterService) throws GeomajasException {
if (null == layerInfo) {
layerInfo = new RasterLayerInfo();
}
layerInfo.setCrs(TiledRasterLayerService.MERCATOR);
crs = geoService.getCrs2(TiledRasterLayerService.MERCATOR);
layerInfo.setTileWidth(tileSize);
layerInfo.setTileHeight(tileSize);
Bbox bbox = new Bbox(-TiledRasterLayerService.HALF_EQUATOR_IN_METERS,
-TiledRasterLayerService.HALF_EQUATOR_IN_METERS, TiledRasterLayerService.EQUATOR_IN_METERS,
TiledRasterLayerService.EQUATOR_IN_METERS);
layerInfo.setMaxExtent(bbox);
maxBounds = converterService.toInternal(bbox);
resolutions = new double[maxZoomLevel + 1];
double powerOfTwo = 1;
for (int zoomLevel = 0; zoomLevel <= maxZoomLevel; zoomLevel++) {
double resolution = (TiledRasterLayerService.EQUATOR_IN_METERS) / (tileSize * powerOfTwo);
resolutions[zoomLevel] = resolution;
powerOfTwo *= 2;
}
} | Finish initialization of state object.
@param geoService geo service
@param converterService converter service
@throws GeomajasException oops |
public synchronized void addListener(MaterializationListener listener)
{
if (_listeners == null)
{
_listeners = new ArrayList();
}
// add listener only once
if (!_listeners.contains(listener))
{
_listeners.add(listener);
}
} | Adds a materialization listener.
@param listener
The listener to add |
protected void beforeMaterialization()
{
if (_listeners != null)
{
MaterializationListener listener;
for (int idx = _listeners.size() - 1; idx >= 0; idx--)
{
listener = (MaterializationListener) _listeners.get(idx);
listener.beforeMaterialization(this, _id);
}
}
} | Calls beforeMaterialization on all registered listeners in the reverse
order of registration. |
protected void afterMaterialization()
{
if (_listeners != null)
{
MaterializationListener listener;
// listeners may remove themselves during the afterMaterialization
// callback.
// thus we must iterate through the listeners vector from back to
// front
// to avoid index problems.
for (int idx = _listeners.size() - 1; idx >= 0; idx--)
{
listener = (MaterializationListener) _listeners.get(idx);
listener.afterMaterialization(this, _realSubject);
}
}
} | Calls afterMaterialization on all registered listeners in the reverse
order of registration. |
protected TemporaryBrokerWrapper getBroker() throws PBFactoryException
{
PersistenceBrokerInternal broker;
boolean needsClose = false;
if (getBrokerKey() == null)
{
/*
arminw:
if no PBKey is set we throw an exception, because we don't
know which PB (connection) should be used.
*/
throw new OJBRuntimeException("Can't find associated PBKey. Need PBKey to obtain a valid" +
"PersistenceBroker instance from intern resources.");
}
// first try to use the current threaded broker to avoid blocking
broker = PersistenceBrokerThreadMapping.currentPersistenceBroker(getBrokerKey());
// current broker not found, create a intern new one
if ((broker == null) || broker.isClosed())
{
broker = (PersistenceBrokerInternal) PersistenceBrokerFactory.createPersistenceBroker(getBrokerKey());
/** Specifies whether we obtained a fresh broker which we have to close after we used it */
needsClose = true;
}
return new TemporaryBrokerWrapper(broker, needsClose);
} | Gets the persistence broker used by this indirection handler.
If no PBKey is available a runtime exception will be thrown.
@return a PersistenceBroker |
public Object invoke(Object proxy, Method method, Object[] args)
{
Object subject;
String methodName = method.getName();
try
{
// [andrew clute]
// short-circuit any calls to a finalize methjod if the subject
// has not been retrieved yet
if ("finalize".equals(methodName) && _realSubject == null)
{
return null;
}
// [andrew clute]
// When trying to serialize a proxy, we need to determine how to
// handle it
if ("writeReplace".equals(methodName))
{
if (_realSubject == null)
{
// Unmaterialized proxies are replaced by simple
// serializable
// objects that can be unserialized without classloader
// issues
return generateSerializableProxy();
} else
{
// Materiliazed objects should be passed back as they might
// have
// been mutated
return getRealSubject();
}
}
// [tomdz]
// Previously the hashcode of the identity would have been used
// but this requires a compatible hashCode implementation in the
// proxied object (which is somewhat unlikely, even the default
// hashCode implementation does not fulfill this requirement)
// for those that require this behavior, a custom indirection
// handler can be used, or the hashCode of the identity
/*
* if ("hashCode".equals(methodName)) { return new
* Integer(_id.hashCode()); }
*/
// [tomdz]
// this would handle toString differently for non-materialized
// proxies
// (to avoid materialization due to logging)
// however toString should be a normal business method which
// materializes the proxy
// if this is not desired, then the ProxyHandler.toString(Object)
// method
// should be used instead (e.g. for logging within OJB)
/*
* if ((realSubject == null) && "toString".equals(methodName)) {
* return "unmaterialized proxy for " + id; }
*/
// BRJ: make sure that the object to be compared is a real object
// otherwise equals may return false.
if ("equals".equals(methodName) && args[0] != null)
{
TemporaryBrokerWrapper tmp = getBroker();
try
{
args[0] = tmp.broker.getProxyFactory().getRealObject(args[0]);
}
finally
{
tmp.close();
}
}
if ("getIndirectionHandler".equals(methodName) && args[0] != null)
{
return this;
}
subject = getRealSubject();
//kuali modification start
try {
method.setAccessible(true);
} catch (SecurityException ex) {
LoggerFactory.getLogger(IndirectionHandler.class).warn(
"Error calling setAccessible for method " + method.getName(), ex);
}
//kuali modification end
return method.invoke(subject, args);
// [olegnitz] I've changed the following strange lines
// to the above one. Why was this done in such complicated way?
// Is it possible that subject doesn't implement the method's
// interface?
// Method m = subject.getClass().getMethod(method.getName(),
// method.getParameterTypes());
// return m.invoke(subject, args);
} catch (Exception ex)
{
throw new PersistenceBrokerException("Error invoking method " + method.getName(), ex);
}
} | [Copied from {@link java.lang.reflect.InvocationHandler}]:<br/>
Processes a method invocation on a proxy instance and returns the result.
This method will be invoked on an invocation handler when a method is
invoked on a proxy instance that it is associated with.
@param proxy
The proxy instance that the method was invoked on
@param method
The <code>Method</code> instance corresponding to the
interface method invoked on the proxy instance. The declaring
class of the <code>Method</code> object will be the
interface that the method was declared in, which may be a
superinterface of the proxy interface that the proxy class
inherits the method through.
@param args
An array of objects containing the values of the arguments
passed in the method invocation on the proxy instance, or
<code>null</code> if interface method takes no arguments.
Arguments of primitive types are wrapped in instances of the
appropriate primitive wrapper class, such as
<code>java.lang.Integer</code> or
<code>java.lang.Boolean</code>.
@return The value to return from the method invocation on the proxy
instance. If the declared return type of the interface method is
a primitive type, then the value returned by this method must be
an instance of the corresponding primitive wrapper class;
otherwise, it must be a type assignable to the declared return
type. If the value returned by this method is <code>null</code>
and the interface method's return type is primitive, then a
<code>NullPointerException</code> will be thrown by the method
invocation on the proxy instance. If the value returned by this
method is otherwise not compatible with the interface method's
declared return type as described above, a
<code>ClassCastException</code> will be thrown by the method
invocation on the proxy instance.
@throws PersistenceBrokerException
The exception to throw from the method invocation on the
proxy instance. The exception's type must be assignable
either to any of the exception types declared in the
<code>throws</code> clause of the interface method or to
the unchecked exception types
<code>java.lang.RuntimeException</code> or
<code>java.lang.Error</code>. If a checked exception is
thrown by this method that is not assignable to any of the
exception types declared in the <code>throws</code> clause
of the interface method, then an
{@link java.lang.reflect.UndeclaredThrowableException}
containing the exception that was thrown by this method will
be thrown by the method invocation on the proxy instance.
@see java.lang.reflect.UndeclaredThrowableException |
public Object getRealSubject() throws PersistenceBrokerException
{
if (_realSubject == null)
{
beforeMaterialization();
_realSubject = materializeSubject();
afterMaterialization();
}
return _realSubject;
} | Returns the proxies real subject. The subject will be materialized if
necessary.
@return The subject |
protected synchronized Object materializeSubject() throws PersistenceBrokerException
{
TemporaryBrokerWrapper tmp = getBroker();
try
{
Object realSubject = tmp.broker.getObjectByIdentity(_id);
if (realSubject == null)
{
LoggerFactory.getLogger(IndirectionHandler.class).warn(
"Can not materialize object for Identity " + _id + " - using PBKey " + getBrokerKey());
}
return realSubject;
} catch (Exception ex)
{
throw new PersistenceBrokerException(ex);
} finally
{
tmp.close();
}
} | Retrieves the real subject from the underlying RDBMS. Override this
method if the object is to be materialized in a specific way.
@return The real subject of the proxy |
public DSet difference(DSet otherSet)
{
DSetImpl result = new DSetImpl(getPBKey());
Iterator iter = this.iterator();
while (iter.hasNext())
{
Object candidate = iter.next();
if (!otherSet.contains(candidate))
{
result.add(candidate);
}
}
return result;
} | Create a new <code>DSet</code> object that contains the elements of this
collection minus the elements in <code>otherSet</code>.
@param otherSet A set containing elements that should not be in the result set.
@return A newly created <code>DSet</code> instance that contains the elements
of this set minus those elements in <code>otherSet</code>. |
public boolean properSubsetOf(org.odmg.DSet otherSet)
{
return (this.size() > 0 && this.size() < otherSet.size() && this.subsetOf(otherSet));
} | Determine whether this set is a proper subset of the set referenced by
<code>otherSet</code>.
@param otherSet Another set.
@return True if this set is a proper subset of the set referenced by
<code>otherSet</code>, otherwise false. |
public boolean properSupersetOf(org.odmg.DSet otherSet)
{
return (otherSet.size() > 0 && otherSet.size() < this.size() && this.supersetOf(otherSet));
} | Determine whether this set is a proper superset of the set referenced by
<code>otherSet</code>.
@param otherSet Another set.
@return True if this set is a proper superset of the set referenced by
<code>otherSet</code>, otherwise false. |
public DCollection query(String predicate) throws org.odmg.QueryInvalidException
{
// 1.build complete OQL statement
String oql = "select all from java.lang.Object where " + predicate;
TransactionImpl tx = getTransaction();
OQLQuery predicateQuery = tx.getImplementation().newOQLQuery();
PBCapsule capsule = new PBCapsule(tx.getImplementation().getCurrentPBKey(), tx);
PersistenceBroker broker = capsule.getBroker();
try
{
predicateQuery.create(oql);
Query pQ = ((OQLQueryImpl) predicateQuery).getQuery();
Criteria pCrit = pQ.getCriteria();
Criteria allElementsCriteria = this.getPkCriteriaForAllElements(broker);
// join selection of elements with predicate criteria:
pCrit.addAndCriteria(allElementsCriteria);
Class clazz = this.getElementsExtentClass(broker);
Query q = new QueryByCriteria(clazz, pCrit);
if (log.isDebugEnabled()) log.debug(q.toString());
// 2. perfom query
return (DSetImpl) broker.getCollectionByQuery(DSetImpl.class, q);
}
catch (PersistenceBrokerException e)
{
throw new ODMGRuntimeException(e.getMessage());
}
finally
{
capsule.destroy();
}
} | Evaluate the boolean query predicate for each element of the collection and
return a new collection that contains each element that evaluated to true.
@param predicate An OQL boolean query predicate.
@return A new collection containing the elements that evaluated true for the predicate.
@exception org.odmg.QueryInvalidException The query predicate is invalid. |
public DSet union(DSet otherSet)
{
DSetImpl result = new DSetImpl(getPBKey());
result.addAll(this);
result.addAll(otherSet);
return result;
} | Create a new <code>DSet</code> object that is the set union of this
<code>DSet</code> object and the set referenced by <code>otherSet</code>.
@param otherSet The other set to be used in the union operation.
@return A newly created <code>DSet</code> instance that contains the union of the two sets. |
public void ojbAdd(Object anObject)
{
DSetEntry entry = prepareEntry(anObject);
entry.setPosition(elements.size());
elements.add(entry);
} | add a single Object to the Collection. This method is used during reading Collection elements
from the database. Thus it is is save to cast anObject to the underlying element type of the
collection. |
@Override
public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
final ThrowableInformation information = event.getThrowableInformation();
if (information != null) {
final String[] stringRep = information.getThrowableStrRep();
int length = 0;
if (option == null) {
length = stringRep.length;
} else if ("full".equals(option)) {
length = stringRep.length;
} else if ("short".equals(option)) {
length = -1;
} else if ("none".equals(option)) {
return;
} else {
length = stringRep.length;
}
toAppendTo.append("\n[Exception: ");
if (length == -1) {
toAppendTo.append(generateAbbreviatedExceptionMessage(information.getThrowable()));
} else {
for (int i = 0; i < length; i++) {
final String string = stringRep[i];
toAppendTo.append(string).append('\n');
}
}
toAppendTo.append("]");
}
} | {@inheritDoc} |
private String generateAbbreviatedExceptionMessage(final Throwable throwable) {
final StringBuilder builder = new StringBuilder();
builder.append(": ");
builder.append(throwable.getClass().getCanonicalName());
builder.append(": ");
builder.append(throwable.getMessage());
Throwable cause = throwable.getCause();
while (cause != null) {
builder.append('\n');
builder.append("Caused by: ");
builder.append(cause.getClass().getCanonicalName());
builder.append(": ");
builder.append(cause.getMessage());
// make sure the exception cause is not itself to prevent infinite
// looping
assert (cause != cause.getCause());
cause = (cause == cause.getCause() ? null : cause.getCause());
}
return builder.toString();
} | Method generates abbreviated exception message.
@param message
Original log message
@param throwable
The attached throwable
@return Abbreviated exception message |
@PostConstruct
protected void postConstruct() throws GeomajasException {
if (null != crsDefinitions) {
for (CrsInfo crsInfo : crsDefinitions.values()) {
try {
CoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());
String code = crsInfo.getKey();
crsCache.put(code, CrsFactory.getCrs(code, crs));
} catch (FactoryException e) {
throw new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());
}
}
}
if (null != crsTransformDefinitions) {
for (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {
String key = getTransformKey(crsTransformInfo);
transformCache.put(key, getCrsTransform(key, crsTransformInfo));
}
}
GeometryFactory factory = new GeometryFactory();
EMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));
EMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));
EMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));
EMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));
EMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!
EMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!
EMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));
} | Finish service initialization.
@throws GeomajasException oops |
public int getSridFromCrs(String crs) {
int crsInt;
if (crs.indexOf(':') != -1) {
crsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));
} else {
try {
crsInt = Integer.parseInt(crs);
} catch (NumberFormatException e) {
crsInt = 0;
}
}
return crsInt;
} | Isn't there a method for this in GeoTools?
@param crs
CRS string in the form of 'EPSG:<srid>'.
@return SRID as integer. |
public Envelope transform(Envelope source, CoordinateReferenceSystem sourceCrs, CoordinateReferenceSystem targetCrs)
throws GeomajasException {
if (sourceCrs == targetCrs) { // NOPMD
// only works when the caching of the CRSs works
return source;
}
CrsTransform crsTransform = geoService.getCrsTransform(sourceCrs, targetCrs);
return geoService.transform(source, crsTransform);
} | Transform a {@link Envelope} from the source to the target CRS.
@param source source geometry
@param sourceCrs source CRS
@param targetCrs target CRS
@return transformed source, now in target CRS
@throws GeomajasException building the transformation or doing the transformation is not possible |
public Envelope extendPoint(Coordinate coordinate, CoordinateReferenceSystem crs,
double width, double height) throws GeomajasException {
double halfCrsWidth = EXTEND_MAPUNIT_TEST_LENGTH;
double halfCrsHeight = EXTEND_MAPUNIT_TEST_LENGTH;
double x = coordinate.x;
double y = coordinate.y;
for (int i = EXTEND_MAX_ITERATIONS; i > 0; i--) {
try {
Coordinate test;
test = new Coordinate(x + halfCrsWidth, y);
double deltaX = JTS.orthodromicDistance(coordinate, test, crs);
test = new Coordinate(x, y + halfCrsHeight);
double deltaY = JTS.orthodromicDistance(coordinate, test, crs);
if (Math.abs(deltaX - width / 2) < DISTANCE_PRECISION &&
Math.abs(deltaY - height / 2) < DISTANCE_PRECISION) {
break;
}
halfCrsWidth = halfCrsWidth / deltaX * width / 2;
halfCrsHeight = halfCrsHeight / deltaY * height / 2;
} catch (TransformException te) {
throw new GeomajasException(te, ExceptionCode.GEOMETRY_TRANSFORMATION_FAILED, crs);
}
}
return new Envelope(x - halfCrsWidth, x + halfCrsWidth, y - halfCrsHeight, y + halfCrsHeight);
} | Build an area around a point with given width and height in meters.
<p/>
The calculation tries to get the size right up to mm precision, but it may be less precise as the number of
attempts to reach the precision are limited.
@param coordinate center for result envelope.
@param crs crs for coordinate
@param width width in meters
@param height height in meters
@return envelope width requested size (up to mm precision) centered on point
@throws GeomajasException transformation problems |
public void configure(Configuration pConfig) throws ConfigurationException
{
if (pConfig instanceof PBPoolConfiguration)
{
PBPoolConfiguration conf = (PBPoolConfiguration) pConfig;
this.setMaxActive(conf.getMaxActive());
this.setMaxIdle(conf.getMaxIdle());
this.setMaxWait(conf.getMaxWaitMillis());
this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());
this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli());
this.setWhenExhaustedAction(conf.getWhenExhaustedAction());
}
else
{
LoggerFactory.getDefaultLogger().error(this.getClass().getName() +
" cannot read configuration properties, use default.");
}
} | Read in the configuration properties. |
protected void log(String aLevel, Object obj, Throwable t)
{
buffer.append(BRAKE_OPEN).append(getName()).append(BRAKE_CLOSE).append(aLevel);
if (obj != null && obj instanceof Throwable)
{
try
{
buffer.append(((Throwable) obj).getMessage()).append(EOL);
((Throwable) obj).printStackTrace();
}
catch (Throwable ignored)
{
/*logging should be failsafe*/
}
}
else
{
try
{
buffer.append(obj).append(EOL);
}
catch(Exception e)
{
// ignore
}
}
if (t != null)
{
try
{
buffer.append(t.getMessage()).append(EOL);
buffer.append(ExceptionUtils.getFullStackTrace(t)).append(EOL);
}
catch (Throwable ignored)
{
/*logging should be failsafe*/
}
}
if(!errorLog && (aLevel.equals(STR_ERROR) || aLevel.equals(STR_FATAL)))
{
errorLog = true;
}
} | Log all statements in a {@link StringBuffer}. |
public Object sqlToJava(Object source) throws ConversionException
{
if (source == null)
{
return null;
}
if (!(source instanceof String))
{
throw new ConversionException("Object is not a String it is a"
+ source.getClass().getName());
}
if (source.toString().equals(NULLVALUE))
{
return null;
}
if (source.toString().equals(EMPTYCOLLEC))
{
return new ArrayList();
}
List v = new ArrayList();
String input = source.toString();
int pos = input.indexOf("#");
while (pos >= 0)
{
if (pos == 0)
{
v.add("");
}
else
{
v.add(Integer.valueOf(input.substring(0, pos)));
}
if (pos + 1 > input.length())
{
//# at end causes outof bounds
break;
}
input = input.substring(pos + 1, input.length());
pos = input.indexOf("#");
}
return v;
} | /* (non-Javadoc)
@see org.apache.ojb.broker.accesslayer.conversions.FieldConversion#sqlToJava(java.lang.Object) |
public OTMConnection acquireConnection(PBKey pbKey)
{
TransactionFactory txFactory = getTransactionFactory();
return txFactory.acquireConnection(pbKey);
} | Obtain an OTMConnection for the given persistence broker key |
public Transaction getTransaction(OTMConnection conn)
{
TransactionFactory txFactory = getTransactionFactory();
Transaction tx = txFactory.getTransactionForConnection(conn);
tx.setKit(this);
return tx;
} | Obtain the transaction which <code>conn</code> is currently
bound to. |
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);
} | This method sends the same message to many agents.
@param agent_name
The id of the agents that receive the message
@param msgtype
@param message_content
The content of the message
@param connector
The connector to get the external access |
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);
} | This method works as the one above, adding some properties to the message
@param agent_name
The id of the agents that receive the message
@param msgtype
@param message_content
The content of the message
@param properties
to be added to the message
@param connector
The connector to get the external access |
public boolean isOpen()
{
return (getStatus() == Status.STATUS_ACTIVE ||
getStatus() == Status.STATUS_MARKED_ROLLBACK ||
getStatus() == Status.STATUS_PREPARED ||
getStatus() == Status.STATUS_PREPARING ||
getStatus() == Status.STATUS_COMMITTING);
} | Determine whether the transaction is open or not. A transaction is open if
a call has been made to <code>begin</code> , but a subsequent call to
either <code>commit</code> or <code>abort</code> has not been made.
@return True if the transaction is open, otherwise false. |
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());
} | Upgrade the lock on the given object to the given lock mode. The call has
no effect if the object's current lock is already at or above that level of
lock mode.
@param obj object to acquire a lock on.
@param lockMode lock mode to acquire. The lock modes
are <code>READ</code> , <code>UPGRADE</code> , and <code>WRITE</code> .
@exception LockNotGrantedException Description of Exception |
public void lockAndRegister(RuntimeObject rtObject, int lockMode, List registeredObjects)
{
lockAndRegister(rtObject, lockMode, isImplicitLocking(), registeredObjects);
} | Lock and register the specified object, make sure that when cascading locking and register
is enabled to specify a List to register the already processed object Identiy. |
public synchronized void lockAndRegister(RuntimeObject rtObject, int lockMode, boolean cascade, List registeredObjects)
{
if(log.isDebugEnabled()) log.debug("Lock and register called for " + rtObject.getIdentity());
// if current object was already locked, do nothing
// avoid endless loops when circular object references are used
if(!registeredObjects.contains(rtObject.getIdentity()))
{
if(cascade)
{
// if implicite locking is enabled, first add the current object to
// list of registered objects to avoid endless loops on circular objects
registeredObjects.add(rtObject.getIdentity());
// lock and register 1:1 references first
//
// If implicit locking is used, we have materialize the main object
// to lock the referenced objects too
lockAndRegisterReferences(rtObject.getCld(), rtObject.getObjMaterialized(), lockMode, registeredObjects);
}
try
{
// perform the lock on the object
// we don't need to lock new objects
if(!rtObject.isNew())
{
doSingleLock(rtObject.getCld(), rtObject.getObj(), rtObject.getIdentity(), lockMode);
}
// after we locked the object, register it to detect status and changes while tx
doSingleRegister(rtObject, lockMode);
}
catch (Throwable t)
{
//log.error("Locking of obj " + rtObject.getIdentity() + " failed", t);
// if registering of object fails release lock on object, because later we don't
// get a change to do this.
implementation.getLockManager().releaseLock(this, rtObject.getIdentity(), rtObject.getObj());
if(t instanceof LockNotGrantedException)
{
throw (LockNotGrantedException) t;
}
else
{
log.error("Unexpected failure while locking", t);
throw new LockNotGrantedException("Locking failed for "
+ rtObject.getIdentity()+ ", nested exception is: [" + t.getClass().getName()
+ ": " + t.getMessage() + "]");
}
}
if(cascade)
{
// perform locks and register 1:n and m:n references
// If implicit locking is used, we have materialize the main object
// to lock the referenced objects too
lockAndRegisterCollections(rtObject.getCld(), rtObject.getObjMaterialized(), lockMode, registeredObjects);
}
}
} | Lock and register the specified object, make sure that when cascading locking and register
is enabled to specify a List to register the already processed object Identiy. |
void doSingleLock(ClassDescriptor cld, Object obj, Identity oid, int lockMode) throws LockNotGrantedException
{
LockManager lm = implementation.getLockManager();
if (cld.isAcceptLocks())
{
if (lockMode == Transaction.READ)
{
if (log.isDebugEnabled()) log.debug("Do READ lock on object: " + oid);
if(!lm.readLock(this, oid, obj))
{
throw new LockNotGrantedException("Can not lock for READ: " + oid);
}
}
else if (lockMode == Transaction.WRITE)
{
if (log.isDebugEnabled()) log.debug("Do WRITE lock on object: " + oid);
if(!lm.writeLock(this, oid, obj))
{
throw new LockNotGrantedException("Can not lock for WRITE: " + oid);
}
}
else if (lockMode == Transaction.UPGRADE)
{
if (log.isDebugEnabled()) log.debug("Do UPGRADE lock on object: " + oid);
if(!lm.upgradeLock(this, oid, obj))
{
throw new LockNotGrantedException("Can not lock for UPGRADE: " + oid);
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("Class '" + cld.getClassNameOfObject() + "' doesn't accept locks" +
" (accept-locks=false) when implicite locked, so OJB skip this object: " + oid);
}
}
} | Only lock the specified object, represented by
the {@link RuntimeObject} instance.
@param cld The {@link org.apache.ojb.broker.metadata.ClassDescriptor}
of the object to acquire a lock on.
@param oid The {@link org.apache.ojb.broker.Identity} of the object to lock.
@param lockMode lock mode to acquire. The lock modes
are <code>READ</code> , <code>UPGRADE</code> , and <code>WRITE</code>.
@exception LockNotGrantedException Description of Exception |
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();
}
} | Close a transaction and do all the cleanup associated with it. |
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;
} | cleanup tx and prepare for reuse |
public boolean tryLock(Object obj, int lockMode)
{
if (log.isDebugEnabled()) log.debug("Try to lock object was called on tx " + this);
checkOpen();
try
{
lock(obj, lockMode);
return true;
}
catch (LockNotGrantedException ex)
{
return false;
}
} | Upgrade the lock on the given object to the given lock mode. Method <code>
tryLock</code> is the same as <code>lock</code> except it returns a boolean
indicating whether the lock was granted instead of generating an exception.
@param obj Description of Parameter
@param lockMode Description of Parameter
@return Description of the Returned Value
</code>, <code>UPGRADE</code> , and <code>WRITE</code> .
@return true if the lock has been acquired, otherwise false. |
public void commit()
{
checkOpen();
try
{
prepareCommit();
checkForCommit();
txStatus = Status.STATUS_COMMITTING;
if (log.isDebugEnabled()) log.debug("Commit transaction " + this);
// now do real commit on broker
if(hasBroker()) getBroker().commitTransaction();
// Now, we notify everything the commit is done.
performTransactionAwareAfterCommit();
doClose();
txStatus = Status.STATUS_COMMITTED;
}
catch(Exception ex)
{
log.error("Error while commit objects, do abort tx " + this + ", " + ex.getMessage(), ex);
txStatus = Status.STATUS_MARKED_ROLLBACK;
abort();
if(!(ex instanceof ODMGRuntimeException))
{
throw new TransactionAbortedExceptionOJB("Can't commit objects: " + ex.getMessage(), ex);
}
else
{
throw (ODMGRuntimeException) ex;
}
}
} | Commit and close the transaction. Calling <code>commit</code> commits to
the database all persistent object modifications within the transaction and
releases any locks held by the transaction. A persistent object
modification is an update of any field of an existing persistent object, or
an update or creation of a new named object in the database. If a
persistent object modification results in a reference from an existing
persistent object to a transient object, the transient object is moved to
the database, and all references to it updated accordingly. Note that the
act of moving a transient object to the database may create still more
persistent references to transient objects, so its referents must be
examined and moved as well. This process continues until the database
contains no references to transient objects, a condition that is guaranteed
as part of transaction commit. Committing a transaction does not remove
from memory transient objects created during the transaction.
The updateObjectList contains a list of all objects for which this transaction
has write privledge to. We need to update these objects. |
protected void prepareCommit() throws TransactionAbortedException, LockNotGrantedException
{
if (txStatus == Status.STATUS_MARKED_ROLLBACK)
{
throw new TransactionAbortedExceptionOJB("Prepare Transaction: tx already marked for rollback");
}
if (txStatus != Status.STATUS_ACTIVE)
{
throw new IllegalStateException("Prepare Transaction: tx status is not 'active', status is " + TxUtil.getStatusString(txStatus));
}
try
{
txStatus = Status.STATUS_PREPARING;
doWriteObjects(false);
txStatus = Status.STATUS_PREPARED;
}
catch (RuntimeException e)
{
log.error("Could not prepare for commit", e);
txStatus = Status.STATUS_MARKED_ROLLBACK;
throw e;
}
} | Prepare does the actual work of moving the changes at the object level
into storage (the underlying rdbms for instance). prepare Can be called multiple times, and
does not release locks.
@throws TransactionAbortedException if the transaction has been aborted
for any reason.
@throws IllegalStateException Method called if transaction is
not in the proper state to perform this operation
@throws TransactionNotInProgressException if the transaction is closed. |
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();
}
} | Abort and close the transaction. Calling abort abandons all persistent
object modifications and releases the associated locks. Aborting a
transaction does not restore the state of modified transient objects |
public synchronized void begin()
{
checkForBegin();
if (log.isDebugEnabled()) log.debug("Begin transaction was called on tx " + this);
// initialize the ObjectEnvelope table
objectEnvelopeTable = new ObjectEnvelopeTable(this);
// register transaction
implementation.getTxManager().registerTx(this);
// mark tx as active (open)
txStatus = Status.STATUS_ACTIVE;
} | Start a transaction. Calling <code>begin</code> multiple times on the same
transaction object, without an intervening call to <code>commit</code> or
<code>abort</code> , causes the exception <code>
TransactionInProgressException</code> to be thrown on the second and
subsequent calls. Operations executed before a transaction has been opened,
or before reopening after a transaction is aborted or committed, have
undefined results; these may throw a <code>
TransactionNotInProgressException</code> exception. |
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);
}
} | Get object by identity. First lookup among objects registered in the
transaction, then in persistent storage.
@param id The identity
@return The object
@throws PersistenceBrokerException |
void doSingleRegister(RuntimeObject rtObject, int lockMode)
throws LockNotGrantedException, PersistenceBrokerException
{
if(log.isDebugEnabled()) log.debug("Register object " + rtObject.getIdentity());
Object objectToRegister = rtObject.getObj();
/*
if the object is a Proxy there are two options:
1. The proxies real subject has already been materialized:
we take this real subject as the object to register and proceed
as if it were a ordinary object.
2. The real subject has not been materialized: Then there is nothing
to be registered now!
Of course we might just materialize the real subject to have something
to register. But this would make proxies useless for ODMG as proxies would
get materialized even if their real subjects were not used by the
client app.
Thus we register the current transaction as a Listener to the IndirectionHandler
of the Proxy.
Only when the IndirectionHandler performs the materialization of the real subject
at some later point in time it invokes callbacks on all it's listeners.
Using this callback we can defer the registering until it's really needed.
*/
if(rtObject.isProxy())
{
IndirectionHandler handler = rtObject.getHandler();
if(handler == null)
{
throw new OJBRuntimeException("Unexpected error, expect an proxy object as indicated: " + rtObject);
}
if (handler.alreadyMaterialized())
{
objectToRegister = handler.getRealSubject();
}
else
{
registerToIndirectionHandler(handler);
registerUnmaterializedLocks(rtObject.getObj());
// all work is done, so set to null
objectToRegister = null;
}
}
// no Proxy and is not null, register real object
if (objectToRegister != null)
{
ObjectEnvelope envelope = objectEnvelopeTable.getByIdentity(rtObject.getIdentity());
// if we found an envelope, object is already registered --> we do nothing
// than refreshing the object!
if ((envelope == null))
{
// register object itself
envelope = objectEnvelopeTable.get(rtObject.getIdentity(), objectToRegister, rtObject.isNew());
}
else
{
/*
arminw:
if an different instance of the same object was locked again
we should replace the old instance with new one to make
accessible the changed fields
*/
envelope.refreshObjectIfNeeded(objectToRegister);
}
/*
arminw:
For better performance we check if this object has already a write lock
in this case we don't need to acquire a write lock on commit
*/
if(lockMode == Transaction.WRITE)
{
// signal ObjectEnvelope that a WRITE lock is already acquired
envelope.setWriteLocked(true);
}
}
} | Registers the object (without locking) with this transaction. This method
expects that the object was already locked, no check is done!!! |
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);
}
}
}
}
} | we only use the registrationList map if the object is not a proxy. During the
reference locking, we will materialize objects and they will enter the registered for
lock map. |
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);
} | this callback is invoked after an Object is materialized
within an IndirectionHandler.
this callback allows to defer registration of objects until
it's really neccessary.
@param handler the invoking handler
@param materializedObject the materialized Object |
public PersistenceBrokerInternal getBrokerInternal()
{
if (broker == null || broker.isClosed())
{
checkOpen();
try
{
checkForDB();
broker = PersistenceBrokerFactoryFactory.instance().createPersistenceBroker(curDB.getPBKey());
}
catch (PBFactoryException e)
{
log.error("Cannot obtain PersistenceBroker from PersistenceBrokerFactory, " +
"found PBKey was " + curDB.getPBKey(), e);
throw new PersistenceBrokerException(e);
}
}
return broker;
} | Gets the broker associated with the transaction.
MBAIRD: only return the associated broker if the transaction is open,
if it's closed, throw a TransactionNotInProgressException. If we allow
brokers to be reaquired by an already closed transaction, there is a
very good chance the broker will be leaked as the doClose() method of
transactionImpl will never be called and thus the broker will never
be closed and returned to the pool.
@return Returns a PersistenceBroker
@throws TransactionNotInProgressException is the transaction is not open; |
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);
} | Remove colProxy from list of pending collections and
register its contents with the transaction. |
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;
} | Detect new objects. |
public void setCascadingDelete(Class target, String referenceField, boolean doCascade)
{
ClassDescriptor cld = getBroker().getClassDescriptor(target);
ObjectReferenceDescriptor ord = cld.getObjectReferenceDescriptorByName(referenceField);
if(ord == null)
{
ord = cld.getCollectionDescriptorByName(referenceField);
}
if(ord == null)
{
throw new CascadeSettingException("Invalid reference field name '" + referenceField
+ "', can't find 1:1, 1:n or m:n relation with that name in " + target);
}
runtimeCascadeDeleteMap.put(ord, (doCascade ? Boolean.TRUE : Boolean.FALSE));
} | Allows to change the <em>cascading delete</em> behavior of the specified reference
of the target class while this transaction is in use.
@param target The class to change cascading delete behavior of the references.
@param referenceField The field name of the 1:1, 1:n or 1:n reference.
@param doCascade If <em>true</em> cascading delete is enabled, <em>false</em> disabled. |
public void setCascadingDelete(Class target, boolean doCascade)
{
ClassDescriptor cld = getBroker().getClassDescriptor(target);
List extents = cld.getExtentClasses();
Boolean result = doCascade ? Boolean.TRUE : Boolean.FALSE;
setCascadingDelete(cld, result);
if(extents != null && extents.size() > 0)
{
for(int i = 0; i < extents.size(); i++)
{
Class extent = (Class) extents.get(i);
ClassDescriptor tmp = getBroker().getClassDescriptor(extent);
setCascadingDelete(tmp, result);
}
}
} | Allows to change the <em>cascading delete</em> behavior of all references of the
specified class while this transaction is in use - if the specified class is an
interface, abstract class or class with "extent" classes the cascading flag will
be propagated.
@param target The class to change cascading delete behavior of all references.
@param doCascade If <em>true</em> cascading delete is enabled, <em>false</em> disabled. |
protected boolean cascadeDeleteFor(ObjectReferenceDescriptor ord)
{
boolean result;
Boolean runtimeSetting = (Boolean) runtimeCascadeDeleteMap.get(ord);
if(runtimeSetting == null)
{
/*
arminw: Here we use the auto-delete flag defined in metadata
*/
result = ord.getCascadingDelete() == ObjectReferenceDescriptor.CASCADE_OBJECT;
}
else
{
result = runtimeSetting.booleanValue();
}
return result;
} | Returns <em>true</em> if cascading delete is enabled for the specified
single or collection descriptor. |
public Table getTable(){
final Table table = new Table(getHeaders());
// Create row(s) per dependency
for(final Dependency dependency: dependencies){
final List<String> licenseIds = dependency.getTarget().getLicenses();
// A dependency can have many rows if it has many licenses
if(licenseIds.isEmpty()){
table.addRow(getDependencyCells(dependency, DataModelFactory.createLicense("","","","","")));
}
else{
for(final String licenseId: dependency.getTarget().getLicenses()){
final License license = getLicense(licenseId);
table.addRow(getDependencyCells(dependency, license));
}
}
}
return table;
} | Generate a table that contains the dependencies information with the column that match the configured filters
@return Table |
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;
} | Returns a licenses regarding its Id and a fake on if no license exist with such an Id
@param licenseId String
@return License |
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()]);
} | Init the headers of the table regarding the filters
@return String[] |
private String[] getDependencyCells(final Dependency dependency, final License license) {
final List<String> cells = new ArrayList<>();
if(decorator.getShowSources()){
cells.add(dependency.getSourceName());
}
if(decorator.getShowSourcesVersion()){
cells.add(dependency.getSourceVersion());
}
if(decorator.getShowTargets()){
cells.add(dependency.getTarget().getGavc());
}
if(decorator.getShowTargetsDownloadUrl()){
cells.add(dependency.getTarget().getDownloadUrl());
}
if(decorator.getShowTargetsSize()){
cells.add(dependency.getTarget().getSize());
}
if(decorator.getShowScopes()){
cells.add(dependency.getScope().name());
}
if(decorator.getShowLicenses()){
cells.add(license.getName());
}
if(decorator.getShowLicensesLongName()){
cells.add(license.getLongName());
}
if(decorator.getShowLicensesUrl()){
cells.add(license.getUrl());
}
if(decorator.getShowLicensesComment()){
cells.add(license.getComments());
}
return cells.toArray(new String[cells.size()]);
} | Retrieve the require information (regarding filters) of a dependency
@param dependency Dependency
@param license License
@return String[] |
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);
} | Get the contents from the request URL.
@param url URL to get the response from
@param layer the raster layer
@return {@link InputStream} with the content
@throws IOException cannot get content |
private Envelope getLayerEnvelope(ProxyLayerSupport layer) {
Bbox bounds = layer.getLayerInfo().getMaxExtent();
return new Envelope(bounds.getX(), bounds.getMaxX(), bounds.getY(), bounds.getMaxY());
} | Return the max bounds of the layer as envelope.
@param layer the layer to get envelope from
@return Envelope the envelope |
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());
} | Get the error message with the dependencies appended
@param dependencies - the list with dependencies to be attached to the message
@param message - the custom error message to be displayed to the user
@return String |
protected Query[] buildPrefetchQueries(Collection owners, Collection children)
{
ClassDescriptor cld = getOwnerClassDescriptor();
Class topLevelClass = getBroker().getTopLevelClass(cld.getClassOfObject());
BrokerHelper helper = getBroker().serviceBrokerHelper();
Collection queries = new ArrayList(owners.size());
Collection idsSubset = new HashSet(owners.size());
Object[] fkValues;
Object owner;
Identity id;
Iterator iter = owners.iterator();
while (iter.hasNext())
{
owner = iter.next();
fkValues = helper.extractValueArray(helper.getKeyValues(cld, owner));
id = getBroker().serviceIdentity().buildIdentity(null, topLevelClass, fkValues);
idsSubset.add(id);
if (idsSubset.size() == pkLimit)
{
queries.add(buildPrefetchQuery(idsSubset));
idsSubset.clear();
}
}
if (idsSubset.size() > 0)
{
queries.add(buildPrefetchQuery(idsSubset));
}
return (Query[]) queries.toArray(new Query[queries.size()]);
} | Build the multiple queries for one relationship because of limitation of IN(...)
@param owners Collection containing all objects of the ONE side |
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;
} | Build the query to perform a batched read get orderBy settings from CollectionDescriptor
@param ids Collection containing all identities of objects of the ONE side |
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);
}
}
} | associate the batched Children with their owner object loop over children |
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;
} | Create a collection object of the given collection type. If none has been given,
OJB uses RemovalAwareList, RemovalAwareSet, or RemovalAwareCollection depending
on the field type.
@param desc The collection descriptor
@param collectionClass The collection class specified in the collection-descriptor
@return The collection object |
@Api
@Override
public void setLayerInfo(VectorLayerInfo layerInfo) throws LayerException {
super.setLayerInfo(layerInfo);
if (null != featureModel) {
featureModel.setLayerInfo(getLayerInfo());
}
} | Set the layer configuration.
@param layerInfo
layer information
@throws LayerException
oops
@since 1.7.1 |
Subsets and Splits