code
stringlengths
73
34.1k
label
stringclasses
1 value
public IGoal[] getAgentGoals(final String agent_name, Connector connector) { ((IExternalAccess) connector.getAgentsExternalAccess(agent_name)) .scheduleStep(new IComponentStep<Plan>() { public IFuture<Plan> execute(IInternalAccess ia) { IBDIInternalAccess bia = (IBDIInternalAccess) ia; goals = bia.getGoalbase().getGoals(); return null; } }).get(new ThreadSuspendable()); return goals; }
java
public void localBegin() { if (this.isInLocalTransaction) { throw new TransactionInProgressException("Connection is already in transaction"); } Connection connection = null; try { connection = this.getConnection(); } catch (LookupException e) { /** * must throw to notify user that we couldn't start a connection */ throw new PersistenceBrokerException("Can't lookup a connection", e); } if (log.isDebugEnabled()) log.debug("localBegin was called for con " + connection); // change autoCommit state only if we are not in a managed environment // and it is enabled by user if(!broker.isManaged()) { if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE) { if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'"); platform.changeAutoCommitState(jcd, connection, false); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call"); } this.isInLocalTransaction = true; }
java
public void localCommit() { if (log.isDebugEnabled()) log.debug("commit was called"); if (!this.isInLocalTransaction) { throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()"); } try { if(!broker.isManaged()) { if (batchCon != null) { batchCon.commit(); } else if (con != null) { con.commit(); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Connection.commit() call"); } } catch (SQLException e) { log.error("Commit on underlying connection failed, try to rollback connection", e); this.localRollback(); throw new TransactionAbortedException("Commit on connection failed", e); } finally { this.isInLocalTransaction = false; restoreAutoCommitState(); this.releaseConnection(); } }
java
public void localRollback() { log.info("Rollback was called, do rollback on current connection " + con); if (!this.isInLocalTransaction) { throw new PersistenceBrokerException("Not in transaction, cannot abort"); } try { //truncate the local transaction this.isInLocalTransaction = false; if(!broker.isManaged()) { if (batchCon != null) { batchCon.rollback(); } else if (con != null && !con.isClosed()) { con.rollback(); } } else { if(log.isEnabledFor(Logger.INFO)) log.info( "Found managed environment setting in PB, will ignore rollback call on connection, this should be done by JTA"); } } catch (SQLException e) { log.error("Rollback on the underlying connection failed", e); } finally { try { restoreAutoCommitState(); } catch(OJBRuntimeException ignore) { // Ignore or log exception } releaseConnection(); } }
java
protected void restoreAutoCommitState() { try { if(!broker.isManaged()) { if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE && originalAutoCommitState == true && con != null && !con.isClosed()) { platform.changeAutoCommitState(jcd, con, true); } } else { if(log.isDebugEnabled()) log.debug( "Found managed environment setting in PB, will skip Platform.changeAutoCommitState(...) call"); } } catch (SQLException e) { // should never be reached throw new OJBRuntimeException("Restore of connection autocommit state failed", e); } }
java
public boolean isAlive(Connection conn) { try { return con != null ? !con.isClosed() : false; } catch (SQLException e) { log.error("IsAlive check failed, running connection was invalid!!", e); return false; } }
java
public static void registerAgent(Agent agent, String serviceName, String serviceType) throws FIPAException{ DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType(serviceType); sd.setName(serviceName); //NOTE El serviceType es un string que define el tipo de servicio publicado en el DF por el Agente X. // He escogido crear nombres en clave en jade.common.Definitions para este campo. //NOTE El serviceName es el nombre efectivo del servicio. // Esto es lo que el usuario va a definir en MockConfiguration.DFNameService y no el tipo como estaba puesto. // sd.setType(agentType); // sd.setName(agent.getLocalName()); //Add services?? // Sets the agent description dfd.setName(agent.getAID()); dfd.addServices(sd); // Register the agent DFService.register(agent, dfd); }
java
public static InterceptorFactory getInstance() { if (instance == null) { instance = new InterceptorFactory(); OjbConfigurator.getInstance().configure(instance); } return instance; }
java
public void registerDropPasteWorker(DropPasteWorkerInterface worker) { this.dropPasteWorkerSet.add(worker); defaultDropTarget.setDefaultActions( defaultDropTarget.getDefaultActions() | worker.getAcceptableActions(defaultDropTarget.getComponent()) ); }
java
public void removeDropPasteWorker(DropPasteWorkerInterface worker) { this.dropPasteWorkerSet.remove(worker); java.util.Iterator it = this.dropPasteWorkerSet.iterator(); int newDefaultActions = 0; while (it.hasNext()) newDefaultActions |= ((DropPasteWorkerInterface)it.next()).getAcceptableActions(defaultDropTarget.getComponent()); defaultDropTarget.setDefaultActions(newDefaultActions); }
java
public static String serialize(final Object obj) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.writeValueAsString(obj); }
java
public static Organization unserializeOrganization(final String organization) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(organization, Organization.class); }
java
public static Module unserializeModule(final String module) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(module, Module.class); }
java
public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){}); }
java
public Object get(String name, ObjectFactory<?> factory) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); Object result = context.getBean(name); if (null == result) { result = factory.getObject(); context.setBean(name, result); } return result; }
java
public Object remove(String name) { ThreadScopeContext context = ThreadScopeContextHolder.getContext(); return context.remove(name); }
java
public static void addItemsHandled(String handledItemsType, int handledItemsNumber) { JobLogger jobLogger = (JobLogger) getInstance(); if (jobLogger == null) { return; } jobLogger.addItemsHandledInstance(handledItemsType, handledItemsNumber); }
java
protected DataSource getDataSource(JdbcConnectionDescriptor jcd) throws LookupException { final PBKey key = jcd.getPBKey(); DataSource ds = (DataSource) dsMap.get(key); if (ds == null) { // Found no pool for PBKey try { synchronized (poolSynch) { // Setup new object pool ObjectPool pool = setupPool(jcd); poolMap.put(key, pool); // Wrap the underlying object pool as DataSource ds = wrapAsDataSource(jcd, pool); dsMap.put(key, ds); } } catch (Exception e) { log.error("Could not setup DBCP DataSource for " + jcd, e); throw new LookupException(e); } } return ds; }
java
protected ObjectPool setupPool(JdbcConnectionDescriptor jcd) { log.info("Create new ObjectPool for DBCP connections:" + jcd); try { ClassHelper.newInstance(jcd.getDriver()); } catch (InstantiationException e) { log.fatal("Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } catch (IllegalAccessException e) { log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } catch (ClassNotFoundException e) { log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!" , e); } // Get the configuration for the connection pool GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig(); // Get the additional abandoned configuration AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); // Create the ObjectPool that serves as the actual pool of connections. final ObjectPool connectionPool = createConnectionPool(conf, ac); // Create a DriverManager-based ConnectionFactory that // the connectionPool will use to create Connection instances final org.apache.commons.dbcp.ConnectionFactory connectionFactory; connectionFactory = createConnectionFactory(jcd); // Create PreparedStatement object pool (if any) KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd); // Set validation query and auto-commit mode final String validationQuery; final boolean defaultAutoCommit; final boolean defaultReadOnly = false; validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery(); defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // final PoolableConnectionFactory poolableConnectionFactory; poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, ac); return poolableConnectionFactory.getPool(); }
java
protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd, ObjectPool connectionPool) { final boolean allowConnectionUnwrap; if (jcd == null) { allowConnectionUnwrap = false; } else { final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties(); final String allowConnectionUnwrapParam; allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED); allowConnectionUnwrap = allowConnectionUnwrapParam != null && Boolean.valueOf(allowConnectionUnwrapParam).booleanValue(); } final PoolingDataSource dataSource; dataSource = new PoolingDataSource(connectionPool); dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap); if(jcd != null) { final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) { final LoggerWrapperPrintWriter loggerPiggyBack; loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR); dataSource.setLogWriter(loggerPiggyBack); } } return dataSource; }
java
public void setAlias(String alias) { m_alias = alias; String attributePath = (String)getAttribute(); boolean allPathsAliased = true; m_userAlias = new UserAlias(alias, attributePath, allPathsAliased); }
java
final void begin() { if (this.properties.isDateRollEnforced()) { final Thread thread = new Thread(this, "Log4J Time-based File-roll Enforcer"); thread.setDaemon(true); thread.start(); this.threadRef = thread; } }
java
public Map<String, ClientWidgetInfo> securityClone(Map<String, ClientWidgetInfo> widgetInfo) { Map<String, ClientWidgetInfo> res = new HashMap<String, ClientWidgetInfo>(); for (Map.Entry<String, ClientWidgetInfo> entry : widgetInfo.entrySet()) { ClientWidgetInfo value = entry.getValue(); if (!(value instanceof ServerSideOnlyInfo)) { res.put(entry.getKey(), value); } } return res; }
java
public ClientLayerInfo securityClone(ClientLayerInfo original) { // the data is explicitly copied as this assures the security is considered when copying. if (null == original) { return null; } ClientLayerInfo client = null; String layerId = original.getServerLayerId(); if (securityContext.isLayerVisible(layerId)) { client = (ClientLayerInfo) SerializationUtils.clone(original); client.setWidgetInfo(securityClone(original.getWidgetInfo())); client.getLayerInfo().setExtraInfo(securityCloneLayerExtraInfo(original.getLayerInfo().getExtraInfo())); if (client instanceof ClientVectorLayerInfo) { ClientVectorLayerInfo vectorLayer = (ClientVectorLayerInfo) client; // set statuses vectorLayer.setCreatable(securityContext.isLayerCreateAuthorized(layerId)); vectorLayer.setUpdatable(securityContext.isLayerUpdateAuthorized(layerId)); vectorLayer.setDeletable(securityContext.isLayerDeleteAuthorized(layerId)); // filter feature info FeatureInfo featureInfo = vectorLayer.getFeatureInfo(); List<AttributeInfo> originalAttr = featureInfo.getAttributes(); List<AttributeInfo> filteredAttr = new ArrayList<AttributeInfo>(); featureInfo.setAttributes(filteredAttr); for (AttributeInfo ai : originalAttr) { if (securityContext.isAttributeReadable(layerId, null, ai.getName())) { filteredAttr.add(ai); } } } } return client; }
java
public String getKeyValue(String key){ String keyName = keysMap.get(key); if (keyName != null){ return keyName; } return ""; //key wasn't defined in keys properties file }
java
public static void serialize(final File folder, final String content, final String fileName) throws IOException { if (!folder.exists()) { folder.mkdirs(); } final File output = new File(folder, fileName); try ( final FileWriter writer = new FileWriter(output); ) { writer.write(content); writer.flush(); } catch (Exception e) { throw new IOException("Failed to serialize the notification in folder " + folder.getPath(), e); } }
java
public static String read(final File file) throws IOException { final StringBuilder sb = new StringBuilder(); try ( final FileReader fr = new FileReader(file); final BufferedReader br = new BufferedReader(fr); ) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } return sb.toString(); }
java
public static Long getSize(final File file){ if ( file!=null && file.exists() ){ return file.length(); } return null; }
java
public static void touch(final File folder , final String fileName) throws IOException { if(!folder.exists()){ folder.mkdirs(); } final File touchedFile = new File(folder, fileName); // The JVM will only 'touch' the file if you instantiate a // FileOutputStream instance for the file in question. // You don't actually write any data to the file through // the FileOutputStream. Just instantiate it and close it. try ( FileOutputStream doneFOS = new FileOutputStream(touchedFile); ) { // Touching the file } catch (FileNotFoundException e) { throw new FileNotFoundException("Failed to the find file." + e); } }
java
private void init(final List<DbLicense> licenses) { licensesRegexp.clear(); for (final DbLicense license : licenses) { if (license.getRegexp() == null || license.getRegexp().isEmpty()) { licensesRegexp.put(license.getName(), license); } else { licensesRegexp.put(license.getRegexp(), license); } } }
java
public DbLicense getLicense(final String name) { final DbLicense license = repoHandler.getLicense(name); if (license == null) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity("License " + name + " does not exist.").build()); } return license; }
java
public void deleteLicense(final String licName) { final DbLicense dbLicense = getLicense(licName); repoHandler.deleteLicense(dbLicense.getName()); final FiltersHolder filters = new FiltersHolder(); final LicenseIdFilter licenseIdFilter = new LicenseIdFilter(licName); filters.addFilter(licenseIdFilter); for (final DbArtifact artifact : repoHandler.getArtifacts(filters)) { repoHandler.removeLicenseFromArtifact(artifact, licName, this); } }
java
public DbLicense resolve(final String licenseId) { for (final Entry<String, DbLicense> regexp : licensesRegexp.entrySet()) { try { if (licenseId.matches(regexp.getKey())) { return regexp.getValue(); } } catch (PatternSyntaxException e) { LOG.error("Wrong pattern for the following license " + regexp.getValue().getName(), e); continue; } } if(LOG.isWarnEnabled()) { LOG.warn(String.format("No matching pattern for license %s", licenseId)); } return null; }
java
public Set<DbLicense> resolveLicenses(List<String> licStrings) { Set<DbLicense> result = new HashSet<>(); licStrings .stream() .map(this::getMatchingLicenses) .forEach(result::addAll); return result; }
java
private void verityLicenseIsConflictFree(final DbLicense newComer) { if(newComer.getRegexp() == null || newComer.getRegexp().isEmpty()) { return; } final DbLicense existing = repoHandler.getLicense(newComer.getName()); final List<DbLicense> licenses = repoHandler.getAllLicenses(); if(null == existing) { licenses.add(newComer); } else { existing.setRegexp(newComer.getRegexp()); } final Optional<Report> reportOp = ReportsRegistry.findById(MULTIPLE_LICENSE_MATCHING_STRINGS); if (reportOp.isPresent()) { final Report reportDef = reportOp.get(); ReportRequest reportRequest = new ReportRequest(); reportRequest.setReportId(reportDef.getId()); Map<String, String> params = new HashMap<>(); // // TODO: Make the organization come as an external parameter from the client side. // This may have impact on the UI, as when the user will update a license he will // have to specify which organization he's editing the license for (in case there // are more organizations defined in the collection). // params.put("organization", "Axway"); reportRequest.setParamValues(params); final RepositoryHandler wrapped = wrapperBuilder .start(repoHandler) .replaceGetMethod("getAllLicenses", licenses) .build(); final ReportExecution execution = reportDef.execute(wrapped, reportRequest); List<String[]> data = execution.getData(); final Optional<String[]> first = data .stream() .filter(strings -> strings[2].contains(newComer.getName())) .findFirst(); if(first.isPresent()) { final String[] strings = first.get(); final String message = String.format( "Pattern conflict for string entry %s matching multiple licenses: %s", strings[1], strings[2]); LOG.info(message); throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(message) .build()); } else { if(!data.isEmpty() && !data.get(0)[2].isEmpty()) { LOG.info("There are remote conflicts between existing licenses and artifact strings"); } } } else { if(LOG.isWarnEnabled()) { LOG.warn(String.format("Cannot find report by id %s", MULTIPLE_LICENSE_MATCHING_STRINGS)); } } }
java
public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){ final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); return getModuleDependencies(module, filters, 1, new ArrayList<String>()); }
java
public DependencyReport getDependencyReport(final String moduleId, final FiltersHolder filters) { final DbModule module = moduleHandler.getModule(moduleId); final DbOrganization organization = moduleHandler.getOrganization(module); filters.setCorporateFilter(new CorporateFilter(organization)); final DependencyReport report = new DependencyReport(moduleId); final List<String> done = new ArrayList<String>(); for(final DbModule submodule: DataUtils.getAllSubmodules(module)){ done.add(submodule.getId()); } addModuleToReport(report, module, filters, done, 1); return report; }
java
public final boolean roll(final LoggingEvent loggingEvent) { for (int i = 0; i < this.fileRollables.length; i++) { if (this.fileRollables[i].roll(loggingEvent)) { return true; } } return false; }
java
public boolean isPartOf(GetVectorTileRequest request) { if (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; } if (code != null ? !code.equals(request.code) : request.code != null) { return false; } if (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; } if (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; } if (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; } if (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; } if (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; } if (paintGeometries && !request.paintGeometries) { return false; } if (paintLabels && !request.paintLabels) { return false; } return true; }
java
@PostConstruct protected void checkPluginDependencies() throws GeomajasException { if ("true".equals(System.getProperty("skipPluginDependencyCheck"))) { return; } if (null == declaredPlugins) { return; } // start by going through all plug-ins to build a map of versions for plug-in keys // includes verification that each key is only used once Map<String, String> versions = new HashMap<String, String>(); for (PluginInfo plugin : declaredPlugins.values()) { String name = plugin.getVersion().getName(); String version = plugin.getVersion().getVersion(); // check for multiple plugin with same name but different versions (duplicates allowed for jar+source dep) if (null != version) { String otherVersion = versions.get(name); if (null != otherVersion) { if (!version.startsWith(EXPR_START)) { if (!otherVersion.startsWith(EXPR_START) && !otherVersion.equals(version)) { throw new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_INVALID_DUPLICATE, name, version, versions.get(name)); } versions.put(name, version); } } else { versions.put(name, version); } } } // Check dependencies StringBuilder message = new StringBuilder(); String backendVersion = versions.get("Geomajas"); for (PluginInfo plugin : declaredPlugins.values()) { String name = plugin.getVersion().getName(); message.append(checkVersion(name, "Geomajas back-end", plugin.getBackendVersion(), backendVersion)); List<PluginVersionInfo> dependencies = plugin.getDependencies(); if (null != dependencies) { for (PluginVersionInfo dependency : plugin.getDependencies()) { String depName = dependency.getName(); message.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName))); } } dependencies = plugin.getOptionalDependencies(); if (null != dependencies) { for (PluginVersionInfo dependency : dependencies) { String depName = dependency.getName(); String availableVersion = versions.get(depName); if (null != availableVersion) { message.append(checkVersion(name, depName, dependency.getVersion(), versions.get(depName))); } } } } if (message.length() > 0) { throw new GeomajasException(ExceptionCode.DEPENDENCY_CHECK_FAILED, message.toString()); } recorder.record(GROUP, VALUE); }
java
String checkVersion(String pluginName, String dependency, String requestedVersion, String availableVersion) { if (null == availableVersion) { return "Dependency " + dependency + " not found for " + pluginName + ", version " + requestedVersion + " or higher needed.\n"; } if (requestedVersion.startsWith(EXPR_START) || availableVersion.startsWith(EXPR_START)) { return ""; } Version requested = new Version(requestedVersion); Version available = new Version(availableVersion); if (requested.getMajor() != available.getMajor()) { return "Dependency " + dependency + " is provided in a incompatible API version for plug-in " + pluginName + ", which requests version " + requestedVersion + ", but version " + availableVersion + " supplied.\n"; } if (requested.after(available)) { return "Dependency " + dependency + " too old for " + pluginName + ", version " + requestedVersion + " or higher needed, but version " + availableVersion + " supplied.\n"; } return ""; }
java
public void check(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { ensureNoTableInfoIfNoRepositoryInfo(classDef, checkLevel); checkModifications(classDef, checkLevel); checkExtents(classDef, checkLevel); ensureTableIfNecessary(classDef, checkLevel); checkFactoryClassAndMethod(classDef, checkLevel); checkInitializationMethod(classDef, checkLevel); checkPrimaryKey(classDef, checkLevel); checkProxyPrefetchingLimit(classDef, checkLevel); checkRowReader(classDef, checkLevel); checkObjectCache(classDef, checkLevel); checkProcedures(classDef, checkLevel); }
java
private void ensureNoTableInfoIfNoRepositoryInfo(ClassDescriptorDef classDef, String checkLevel) { if (!classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_REPOSITORY_INFO, true)) { classDef.setProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, "false"); } }
java
private void checkModifications(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } HashMap features = new HashMap(); FeatureDescriptorDef def; for (Iterator it = classDef.getFields(); it.hasNext();) { def = (FeatureDescriptorDef)it.next(); features.put(def.getName(), def); } for (Iterator it = classDef.getReferences(); it.hasNext();) { def = (FeatureDescriptorDef)it.next(); features.put(def.getName(), def); } for (Iterator it = classDef.getCollections(); it.hasNext();) { def = (FeatureDescriptorDef)it.next(); features.put(def.getName(), def); } // now checking the modifications Properties mods; String modName; String propName; for (Iterator it = classDef.getModificationNames(); it.hasNext();) { modName = (String)it.next(); if (!features.containsKey(modName)) { throw new ConstraintException("Class "+classDef.getName()+" contains a modification for an unknown feature "+modName); } def = (FeatureDescriptorDef)features.get(modName); if (def.getOriginal() == null) { throw new ConstraintException("Class "+classDef.getName()+" contains a modification for a feature "+modName+" that is not inherited but defined in the same class"); } // checking modification mods = classDef.getModification(modName); for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();) { propName = (String)propIt.next(); if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName)) { throw new ConstraintException("The modification of attribute "+propName+" in class "+classDef.getName()+" is not applicable to the feature "+modName); } } } }
java
private void checkExtents(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } HashMap processedClasses = new HashMap(); InheritanceHelper helper = new InheritanceHelper(); ClassDescriptorDef curExtent; boolean canBeRemoved; for (Iterator it = classDef.getExtentClasses(); it.hasNext();) { curExtent = (ClassDescriptorDef)it.next(); canBeRemoved = false; if (classDef.getName().equals(curExtent.getName())) { throw new ConstraintException("The class "+classDef.getName()+" specifies itself as an extent-class"); } else if (processedClasses.containsKey(curExtent)) { canBeRemoved = true; } else { try { if (!helper.isSameOrSubTypeOf(curExtent, classDef.getName(), false)) { throw new ConstraintException("The class "+classDef.getName()+" specifies an extent-class "+curExtent.getName()+" that is not a sub-type of it"); } // now we check whether we already have an extent for a base-class of this extent-class for (Iterator processedIt = processedClasses.keySet().iterator(); processedIt.hasNext();) { if (helper.isSameOrSubTypeOf(curExtent, ((ClassDescriptorDef)processedIt.next()).getName(), false)) { canBeRemoved = true; break; } } } catch (ClassNotFoundException ex) { // won't happen because we don't use lookup of the actual classes } } if (canBeRemoved) { it.remove(); } processedClasses.put(curExtent, null); } }
java
private void checkInitializationMethod(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (!CHECKLEVEL_STRICT.equals(checkLevel)) { return; } String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATION_METHOD); if (initMethodName == null) { return; } Class initClass; Method initMethod; try { initClass = InheritanceHelper.getClass(classDef.getName()); } catch (ClassNotFoundException ex) { throw new ConstraintException("The class "+classDef.getName()+" was not found on the classpath"); } try { initMethod = initClass.getDeclaredMethod(initMethodName, new Class[0]); } catch (NoSuchMethodException ex) { initMethod = null; } catch (Exception ex) { throw new ConstraintException("Exception while checking the class "+classDef.getName()+": "+ex.getMessage()); } if (initMethod == null) { try { initMethod = initClass.getMethod(initMethodName, new Class[0]); } catch (NoSuchMethodException ex) { throw new ConstraintException("No suitable initialization-method "+initMethodName+" found in class "+classDef.getName()); } catch (Exception ex) { throw new ConstraintException("Exception while checking the class "+classDef.getName()+": "+ex.getMessage()); } } // checking modifiers int mods = initMethod.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isAbstract(mods)) { throw new ConstraintException("The initialization-method "+initMethodName+" in class "+classDef.getName()+" must be a concrete instance method"); } }
java
private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) && classDef.getPrimaryKeys().isEmpty()) { LogHelper.warn(true, getClass(), "checkPrimaryKey", "The class "+classDef.getName()+" has no primary key"); } }
java
private void checkRowReader(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (!CHECKLEVEL_STRICT.equals(checkLevel)) { return; } String rowReaderName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_ROW_READER); if (rowReaderName == null) { return; } try { InheritanceHelper helper = new InheritanceHelper(); if (!helper.isSameOrSubTypeOf(rowReaderName, ROW_READER_INTERFACE)) { throw new ConstraintException("The class "+rowReaderName+" specified as row-reader of class "+classDef.getName()+" does not implement the interface "+ROW_READER_INTERFACE); } } catch (ClassNotFoundException ex) { throw new ConstraintException("Could not find the class "+ex.getMessage()+" on the classpath while checking the row-reader class "+rowReaderName+" of class "+classDef.getName()); } }
java
private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (!CHECKLEVEL_STRICT.equals(checkLevel)) { return; } ObjectCacheDef objCacheDef = classDef.getObjectCache(); if (objCacheDef == null) { return; } String objectCacheName = objCacheDef.getName(); if ((objectCacheName == null) || (objectCacheName.length() == 0)) { throw new ConstraintException("No class specified for the object-cache of class "+classDef.getName()); } try { InheritanceHelper helper = new InheritanceHelper(); if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE)) { throw new ConstraintException("The class "+objectCacheName+" specified as object-cache of class "+classDef.getName()+" does not implement the interface "+OBJECT_CACHE_INTERFACE); } } catch (ClassNotFoundException ex) { throw new ConstraintException("Could not find the class "+ex.getMessage()+" on the classpath while checking the object-cache class "+objectCacheName+" of class "+classDef.getName()); } }
java
private void checkProcedures(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } ProcedureDef procDef; String type; String name; String fieldName; String argName; for (Iterator it = classDef.getProcedures(); it.hasNext();) { procDef = (ProcedureDef)it.next(); type = procDef.getName(); name = procDef.getProperty(PropertyHelper.OJB_PROPERTY_NAME); if ((name == null) || (name.length() == 0)) { throw new ConstraintException("The "+type+"-procedure in class "+classDef.getName()+" doesn't have a name"); } fieldName = procDef.getProperty(PropertyHelper.OJB_PROPERTY_RETURN_FIELD_REF); if ((fieldName != null) && (fieldName.length() > 0)) { if (classDef.getField(fieldName) == null) { throw new ConstraintException("The "+type+"-procedure "+name+" in class "+classDef.getName()+" references an unknown or non-persistent return field "+fieldName); } } for (CommaListIterator argIt = new CommaListIterator(procDef.getProperty(PropertyHelper.OJB_PROPERTY_ARGUMENTS)); argIt.hasNext();) { argName = argIt.getNext(); if (classDef.getProcedureArgument(argName) == null) { throw new ConstraintException("The "+type+"-procedure "+name+" in class "+classDef.getName()+" references an unknown argument "+argName); } } } ProcedureArgumentDef argDef; for (Iterator it = classDef.getProcedureArguments(); it.hasNext();) { argDef = (ProcedureArgumentDef)it.next(); type = argDef.getProperty(PropertyHelper.OJB_PROPERTY_TYPE); if ("runtime".equals(type)) { fieldName = argDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELD_REF); if ((fieldName != null) && (fieldName.length() > 0)) { if (classDef.getField(fieldName) == null) { throw new ConstraintException("The "+type+"-argument "+argDef.getName()+" in class "+classDef.getName()+" references an unknown or non-persistent return field "+fieldName); } } } } }
java
OTMConnection getConnection() { if (m_connection == null) { OTMConnectionRuntimeException ex = new OTMConnectionRuntimeException("Connection is null."); sendEvents(ConnectionEvent.CONNECTION_ERROR_OCCURRED, ex, null); } return m_connection; }
java
private Integer getReleaseId() { final String[] versionParts = stringVersion.split("-"); if(isBranch() && versionParts.length >= 3){ return Integer.valueOf(versionParts[2]); } else if(versionParts.length >= 2){ return Integer.valueOf(versionParts[1]); } return 0; }
java
public int compare(final Version other) throws IncomparableException{ // Cannot compare branch versions and others if(!isBranch().equals(other.isBranch())){ throw new IncomparableException(); } // Compare digits final int minDigitSize = getDigitsSize() < other.getDigitsSize()? getDigitsSize(): other.getDigitsSize(); for(int i = 0; i < minDigitSize ; i++){ if(!getDigit(i).equals(other.getDigit(i))){ return getDigit(i).compareTo(other.getDigit(i)); } } // If not the same number of digits and the first digits are equals, the longest is the newer if(!getDigitsSize().equals(other.getDigitsSize())){ return getDigitsSize() > other.getDigitsSize()? 1: -1; } if(isBranch() && !getBranchId().equals(other.getBranchId())){ return getBranchId().compareTo(other.getBranchId()); } // if the digits are the same, a snapshot is newer than a release if(isSnapshot() && other.isRelease()){ return 1; } if(isRelease() && other.isSnapshot()){ return -1; } // if both versions are releases, compare the releaseID if(isRelease() && other.isRelease()){ return getReleaseId().compareTo(other.getReleaseId()); } return 0; }
java
public void calculateSize(PdfContext context) { float width = 0; float height = 0; for (PrintComponent<?> child : children) { child.calculateSize(context); float cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX(); float ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY(); switch (getConstraint().getFlowDirection()) { case LayoutConstraint.FLOW_NONE: width = Math.max(width, cw); height = Math.max(height, ch); break; case LayoutConstraint.FLOW_X: width += cw; height = Math.max(height, ch); break; case LayoutConstraint.FLOW_Y: width = Math.max(width, cw); height += ch; break; default: throw new IllegalStateException("Unknown flow direction " + getConstraint().getFlowDirection()); } } if (getConstraint().getWidth() != 0) { width = getConstraint().getWidth(); } if (getConstraint().getHeight() != 0) { height = getConstraint().getHeight(); } setBounds(new Rectangle(0, 0, width, height)); }
java
public void setChildren(List<PrintComponent<?>> children) { this.children = children; // needed for Json unmarshall !!!! for (PrintComponent<?> child : children) { child.setParent(this); } }
java
public void remove(Identity oid) { //processQueue(); if(oid != null) { removeTracedIdentity(oid); objectTable.remove(buildKey(oid)); if(log.isDebugEnabled()) log.debug("Remove object " + oid); } }
java
public List<DbComment> getComments(String entityId, String entityType) { return repositoryHandler.getComments(entityId, entityType); }
java
public void store(String gavc, String action, String commentText, DbCredential credential, String entityType) { DbComment comment = new DbComment(); comment.setEntityId(gavc); comment.setEntityType(entityType); comment.setDbCommentedBy(credential.getUser()); comment.setAction(action); if(!commentText.isEmpty()) { comment.setDbCommentText(commentText); } comment.setDbCreatedDateTime(new Date()); repositoryHandler.store(comment); }
java
private boolean relevant(File currentLogFile, GregorianCalendar lastRelevantDate) { String fileName=currentLogFile.getName(); Pattern p = Pattern.compile(APPENER_DATE_DEFAULT_PATTERN); Matcher m = p.matcher(fileName); if(m.find()){ int year=Integer.parseInt(m.group(1)); int month=Integer.parseInt(m.group(2)); int dayOfMonth=Integer.parseInt(m.group(3)); GregorianCalendar fileDate=new GregorianCalendar(year, month, dayOfMonth); fileDate.add(Calendar.MONTH,-1); //Because of Calendar save the month such that January is 0 return fileDate.compareTo(lastRelevantDate)>0; } else{ return false; } }
java
private GregorianCalendar getLastReleventDate(GregorianCalendar currentDate) { int age=this.getProperties().getMaxFileAge(); GregorianCalendar result=new GregorianCalendar(currentDate.get(Calendar.YEAR),currentDate.get(Calendar.MONTH),currentDate.get(Calendar.DAY_OF_MONTH)); result.add(Calendar.DAY_OF_MONTH, -age); return result; }
java
private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef) { String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN); ColumnDef columnDef = tableDef.getColumn(name); if (columnDef == null) { columnDef = new ColumnDef(name); tableDef.addColumn(columnDef); } if (!fieldDef.isNested()) { columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName()); } columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE)); columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID)); if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false)) { columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, "true"); columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, "true"); } else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true)) { columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, "true"); } if ("database".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT))) { columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, "true"); } columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint()); if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION)) { columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION)); } if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION)) { columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION)); } return columnDef; }
java
private List getColumns(List fields) { ArrayList columns = new ArrayList(); for (Iterator it = fields.iterator(); it.hasNext();) { FieldDescriptorDef fieldDef = (FieldDescriptorDef)it.next(); columns.add(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)); } return columns; }
java
private boolean containsCollectionAndMapsToDifferentTable(CollectionDescriptorDef origCollDef, TableDef origTableDef, ClassDescriptorDef classDef) { if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) && !origTableDef.getName().equals(classDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE))) { CollectionDescriptorDef curCollDef = classDef.getCollection(origCollDef.getName()); if ((curCollDef != null) && !curCollDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_IGNORE, false)) { return true; } } return false; }
java
private String getHierarchyTable(ClassDescriptorDef classDef) { ArrayList queue = new ArrayList(); String tableName = null; queue.add(classDef); while (!queue.isEmpty()) { ClassDescriptorDef curClassDef = (ClassDescriptorDef)queue.get(0); queue.remove(0); if (curClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true)) { if (tableName != null) { if (!tableName.equals(curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE))) { return null; } } else { tableName = curClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE); } } for (Iterator it = curClassDef.getExtentClasses(); it.hasNext();) { curClassDef = (ClassDescriptorDef)it.next(); if (curClassDef.getReference("super") == null) { queue.add(curClassDef); } } } return tableName; }
java
private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef) { IndexDef indexDef = tableDef.getIndex(indexDescDef.getName()); if (indexDef == null) { indexDef = new IndexDef(indexDescDef.getName(), indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false)); tableDef.addIndex(indexDef); } try { String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS); ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames); FieldDescriptorDef fieldDef; for (Iterator it = fields.iterator(); it.hasNext();) { fieldDef = (FieldDescriptorDef)it.next(); indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN)); } } catch (NoSuchFieldException ex) { // won't happen if we already checked the constraints } }
java
private void addTable(TableDef table) { table.setOwner(this); _tableDefs.put(table.getName(), table); }
java
public static Class getClass(String name) throws ClassNotFoundException { try { return Class.forName(name); } catch (ClassNotFoundException ex) { throw new ClassNotFoundException(name); } }
java
public void cache(Identity oid, Object obj) { if (oid != null && obj != null) { ObjectCache cache = getCache(oid, obj, METHOD_CACHE); if (cache != null) { cache.cache(oid, obj); } } }
java
public Object lookup(Identity oid) { Object ret = null; if (oid != null) { ObjectCache cache = getCache(oid, null, METHOD_LOOKUP); if (cache != null) { ret = cache.lookup(oid); } } return ret; }
java
public void remove(Identity oid) { if (oid == null) return; ObjectCache cache = getCache(oid, null, METHOD_REMOVE); if (cache != null) { cache.remove(oid); } }
java
public static ResourceBundle getCurrentResourceBundle(String locale) { try { if (null != locale && !locale.isEmpty()) { return getCurrentResourceBundle(LocaleUtils.toLocale(locale)); } } catch (IllegalArgumentException ex) { // do nothing } return getCurrentResourceBundle((Locale) null); }
java
private String getPropertyName(Expression expression) { if (!(expression instanceof PropertyName)) { throw new IllegalArgumentException("Expression " + expression + " is not a PropertyName."); } String name = ((PropertyName) expression).getPropertyName(); if (name.endsWith(FilterService.ATTRIBUTE_ID)) { // replace by Hibernate id property, always refers to the id, even if named differently name = name.substring(0, name.length() - FilterService.ATTRIBUTE_ID.length()) + HIBERNATE_ID; } return name; }
java
private Object getLiteralValue(Expression expression) { if (!(expression instanceof Literal)) { throw new IllegalArgumentException("Expression " + expression + " is not a Literal."); } return ((Literal) expression).getValue(); }
java
private String parsePropertyName(String orgPropertyName, Object userData) { // try to assure the correct separator is used String propertyName = orgPropertyName.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR); // split the path (separator is defined in the HibernateLayerUtil) String[] props = propertyName.split(HibernateLayerUtil.SEPARATOR_REGEXP); String finalName; if (props.length > 1 && userData instanceof Criteria) { // the criteria API requires an alias for each join table !!! String prevAlias = null; for (int i = 0; i < props.length - 1; i++) { String alias = props[i] + "_alias"; if (!aliases.contains(alias)) { Criteria criteria = (Criteria) userData; if (i == 0) { criteria.createAlias(props[0], alias); } else { criteria.createAlias(prevAlias + "." + props[i], alias); } aliases.add(alias); } prevAlias = alias; } finalName = prevAlias + "." + props[props.length - 1]; } else { finalName = propertyName; } return finalName; }
java
public void afterCompletion(int status) { if(afterCompletionCall) return; log.info("Method afterCompletion was called"); try { switch(status) { case Status.STATUS_COMMITTED: if(log.isDebugEnabled()) { log.debug("Method afterCompletion: Do commit internal odmg-tx, status of JTA-tx is " + TxUtil.getStatusString(status)); } commit(); break; default: log.error("Method afterCompletion: Do abort call on internal odmg-tx, status of JTA-tx is " + TxUtil.getStatusString(status)); abort(); } } finally { afterCompletionCall = true; log.info("Method afterCompletion finished"); } }
java
public void beforeCompletion() { // avoid redundant calls if(beforeCompletionCall) return; log.info("Method beforeCompletion was called"); int status = Status.STATUS_UNKNOWN; try { JTATxManager mgr = (JTATxManager) getImplementation().getTxManager(); status = mgr.getJTATransaction().getStatus(); // ensure proper work, check all possible status // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary if(status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLEDBACK || status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_UNKNOWN || status == Status.STATUS_NO_TRANSACTION) { log.error("Synchronization#beforeCompletion: Can't prepare for commit, because tx status was " + TxUtil.getStatusString(status) + ". Do internal cleanup only."); } else { if(log.isDebugEnabled()) { log.debug("Synchronization#beforeCompletion: Prepare for commit"); } // write objects to database prepareCommit(); } } catch(Exception e) { log.error("Synchronization#beforeCompletion: Error while prepare for commit", e); if(e instanceof LockNotGrantedException) { throw (LockNotGrantedException) e; } else if(e instanceof TransactionAbortedException) { throw (TransactionAbortedException) e; } else if(e instanceof ODMGRuntimeException) { throw (ODMGRuntimeException) e; } else { throw new ODMGRuntimeException("Method beforeCompletion() fails, status of JTA-tx was " + TxUtil.getStatusString(status) + ", message: " + e.getMessage()); } } finally { beforeCompletionCall = true; setInExternTransaction(false); internalCleanup(); } }
java
private void internalCleanup() { if(hasBroker()) { PersistenceBroker broker = getBroker(); if(log.isDebugEnabled()) { log.debug("Do internal cleanup and close the internal used connection without" + " closing the used broker"); } ConnectionManagerIF cm = broker.serviceConnectionManager(); if(cm.isInLocalTransaction()) { /* arminw: in managed environment this call will be ignored because, the JTA transaction manager control the connection status. But to make connectionManager happy we have to complete the "local tx" of the connectionManager before release the connection */ cm.localCommit(); } cm.releaseConnection(); } }
java
public void checkpoint(ObjectEnvelope mod) throws org.apache.ojb.broker.PersistenceBrokerException { mod.doUpdate(); }
java
@Api public void setUrl(String url) throws LayerException { try { this.url = url; Map<String, Object> params = new HashMap<String, Object>(); params.put("url", url); DataStore store = DataStoreFactory.create(params); setDataStore(store); } catch (IOException ioe) { throw new LayerException(ioe, ExceptionCode.INVALID_SHAPE_FILE_URL, url); } }
java
private void beginInternTransaction() { if (log.isDebugEnabled()) log.debug("beginInternTransaction was called"); J2EETransactionImpl tx = (J2EETransactionImpl) super.currentTransaction(); if (tx == null) tx = newInternTransaction(); if (!tx.isOpen()) { // start the transaction tx.begin(); tx.setInExternTransaction(true); } }
java
private J2EETransactionImpl newInternTransaction() { if (log.isDebugEnabled()) log.debug("obtain new intern odmg-transaction"); J2EETransactionImpl tx = new J2EETransactionImpl(this); try { getConfigurator().configure(tx); } catch (ConfigurationException e) { throw new OJBRuntimeException("Cannot create new intern odmg transaction", e); } return tx; }
java
protected void associateBatched(Collection owners, Collection children) { ObjectReferenceDescriptor ord = getObjectReferenceDescriptor(); ClassDescriptor cld = getOwnerClassDescriptor(); Object owner; Object relatedObject; Object fkValues[]; Identity id; PersistenceBroker pb = getBroker(); PersistentField field = ord.getPersistentField(); Class topLevelClass = pb.getTopLevelClass(ord.getItemClass()); HashMap childrenMap = new HashMap(children.size()); for (Iterator it = children.iterator(); it.hasNext(); ) { relatedObject = it.next(); childrenMap.put(pb.serviceIdentity().buildIdentity(relatedObject), relatedObject); } for (Iterator it = owners.iterator(); it.hasNext(); ) { owner = it.next(); fkValues = ord.getForeignKeyValues(owner,cld); if (isNull(fkValues)) { field.set(owner, null); continue; } id = pb.serviceIdentity().buildIdentity(null, topLevelClass, fkValues); relatedObject = childrenMap.get(id); field.set(owner, relatedObject); } }
java
public boolean existsElement(String predicate) throws org.odmg.QueryInvalidException { DList results = (DList) this.query(predicate); if (results == null || results.size() == 0) return false; else return true; }
java
public Iterator select(String predicate) throws org.odmg.QueryInvalidException { return this.query(predicate).iterator(); }
java
public Object selectElement(String predicate) throws org.odmg.QueryInvalidException { return ((DList) this.query(predicate)).get(0); }
java
public static boolean sameLists(String list1, String list2) { return new CommaListIterator(list1).equals(new CommaListIterator(list2)); }
java
public static void startTimer(final String type) { TransactionLogger instance = getInstance(); if (instance == null) { return; } instance.components.putIfAbsent(type, new Component(type)); instance.components.get(type).startTimer(); }
java
public static void pauseTimer(final String type) { TransactionLogger instance = getInstance(); if (instance == null) { return; } instance.components.get(type).pauseTimer(); }
java
public static ComponentsMultiThread getComponentsMultiThread() { TransactionLogger instance = getInstance(); if (instance == null) { return null; } return instance.componentsMultiThread; }
java
public static Collection<Component> getComponentsList() { TransactionLogger instance = getInstance(); if (instance == null) { return null; } return instance.components.values(); }
java
public static String getFlowContext() { TransactionLogger instance = getInstance(); if (instance == null) { return null; } return instance.flowContext; }
java
protected static boolean createLoggingAction(final Logger logger, final Logger auditor, final TransactionLogger instance) { TransactionLogger oldInstance = getInstance(); if (oldInstance == null || oldInstance.finished) { if(loggingKeys == null) { synchronized (TransactionLogger.class) { if (loggingKeys == null) { logger.info("Initializing 'LoggingKeysHandler' class"); loggingKeys = new LoggingKeysHandler(keysPropStream); } } } initInstance(instance, logger, auditor); setInstance(instance); return true; } return false; // Really not sure it can happen - since we arrive here in a new thread of transaction I think it's ThreadLocal should be empty. But leaving this code just in case... }
java
protected void addPropertiesStart(String type) { putProperty(PropertyKey.Host.name(), IpUtils.getHostName()); putProperty(PropertyKey.Type.name(), type); putProperty(PropertyKey.Status.name(), Status.Start.name()); }
java
protected void writePropertiesToLog(Logger logger, Level level) { writeToLog(logger, level, getMapAsString(this.properties, separator), null); if (this.exception != null) { writeToLog(this.logger, Level.ERROR, "Error:", this.exception); } }
java
private static void initInstance(final TransactionLogger instance, final Logger logger, final Logger auditor) { instance.logger = logger; instance.auditor = auditor; instance.components = new LinkedHashMap<>(); instance.properties = new LinkedHashMap<>(); instance.total = new Component(TOTAL_COMPONENT); instance.total.startTimer(); instance.componentsMultiThread = new ComponentsMultiThread(); instance.flowContext = FlowContextFactory.serializeNativeFlowContext(); }
java
private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) { if (level == Level.ERROR) { logger.error(pattern, exception); } else if (level == Level.INFO) { logger.info(pattern); } else if (level == Level.DEBUG) { logger.debug(pattern); } }
java
private static void addTimePerComponent(HashMap<String, Long> mapComponentTimes, Component component) { Long currentTimeOfComponent = 0L; String key = component.getComponentType(); if (mapComponentTimes.containsKey(key)) { currentTimeOfComponent = mapComponentTimes.get(key); } //when transactions are run in parallel, we should log the longest transaction only to avoid that //for ex 'Total time' would be 100ms and transactions in parallel to hornetQ will be 2000ms Long maxTime = Math.max(component.getTime(), currentTimeOfComponent); mapComponentTimes.put(key, maxTime); }
java
public static String convertToSQL92(char escape, char multi, char single, String pattern) throws IllegalArgumentException { if ((escape == '\'') || (multi == '\'') || (single == '\'')) { throw new IllegalArgumentException("do not use single quote (') as special char!"); } StringBuilder result = new StringBuilder(pattern.length() + 5); int i = 0; while (i < pattern.length()) { char chr = pattern.charAt(i); if (chr == escape) { // emit the next char and skip it if (i != (pattern.length() - 1)) { result.append(pattern.charAt(i + 1)); } i++; // skip next char } else if (chr == single) { result.append('_'); } else if (chr == multi) { result.append('%'); } else if (chr == '\'') { result.append('\''); result.append('\''); } else { result.append(chr); } i++; } return result.toString(); }
java
public String getSQL92LikePattern() throws IllegalArgumentException { if (escape.length() != 1) { throw new IllegalArgumentException("Like Pattern --> escape char should be of length exactly 1"); } if (wildcardSingle.length() != 1) { throw new IllegalArgumentException("Like Pattern --> wildcardSingle char should be of length exactly 1"); } if (wildcardMulti.length() != 1) { throw new IllegalArgumentException("Like Pattern --> wildcardMulti char should be of length exactly 1"); } return LikeFilterImpl.convertToSQL92(escape.charAt(0), wildcardMulti.charAt(0), wildcardSingle.charAt(0), isMatchingCase(), pattern); }
java
public boolean evaluate(Object feature) { // Checks to ensure that the attribute has been set if (attribute == null) { return false; } // Note that this converts the attribute to a string // for comparison. Unlike the math or geometry filters, which // require specific types to function correctly, this filter // using the mandatory string representation in Java // Of course, this does not guarantee a meaningful result, but it // does guarantee a valid result. // LOGGER.finest("pattern: " + pattern); // LOGGER.finest("string: " + attribute.getValue(feature)); // return attribute.getValue(feature).toString().matches(pattern); Object value = attribute.evaluate(feature); if (null == value) { return false; } Matcher matcher = getMatcher(); matcher.reset(value.toString()); return matcher.matches(); }
java