List of usage examples for java.util HashSet isEmpty
public boolean isEmpty()
From source file:org.easysoa.registry.indicators.rest.IndicatorsController.java
private Map<String, IndicatorValue> computeIndicators(CoreSession session, String subprojectId, String visibility) throws Exception { //CoreSession session = SessionFactory.getSession(request); List<IndicatorProvider> computedProviders = new ArrayList<IndicatorProvider>(); List<IndicatorProvider> pendingProviders = new ArrayList<IndicatorProvider>(); Map<String, IndicatorValue> computedIndicators = new HashMap<String, IndicatorValue>(); //Map<String, Map<String, IndicatorValue>> indicatorsByCategory = new HashMap<String, Map<String, IndicatorValue>>(); HashSet<String> pendingRequiredIndicators = new HashSet<String>(indicatorProviders.size()); int previousComputedProvidersCount = -1; // Compute indicators in several passes, with respect to dependencies while (computedProviders.size() != previousComputedProvidersCount) { previousComputedProvidersCount = computedProviders.size(); /*for (Entry<String, List<IndicatorProvider>> indicatorProviderCategory : indicatorProviders.entrySet()) {*/ // Start or continue indicator category /*Map<String, IndicatorValue> categoryIndicators = indicatorsByCategory.get(indicatorProviderCategory.getKey()); if (categoryIndicators == null) { categoryIndicators = new HashMap<String, IndicatorValue>(); }*//*from w w w .j a va 2 s . c o m*/ // Browse all providers //for (IndicatorProvider indicatorProvider : indicatorProviderCategory.getValue()) { for (IndicatorProvider indicatorProvider : indicatorProviders) { if (!computedProviders.contains(indicatorProvider)) { // Compute indicator only if the dependencies are already computed List<String> requiredIndicators = indicatorProvider.getRequiredIndicators(); boolean allRequirementsSatisfied = true; if (requiredIndicators != null) { for (String requiredIndicator : requiredIndicators) { if (!computedIndicators.containsKey(requiredIndicator)) { allRequirementsSatisfied = false; pendingRequiredIndicators.add(requiredIndicator); break; } } } // Actual indicator calculation if (allRequirementsSatisfied) { Map<String, IndicatorValue> indicators = null; try { indicators = indicatorProvider.computeIndicators(session, subprojectId, computedIndicators, visibility); } catch (Exception e) { logger.error("Failed to compute indicator '" + indicatorProvider.toString() + "': " + e.getMessage(), e); } if (indicators != null) { //categoryIndicators.putAll(indicators); computedIndicators.putAll(indicators); pendingRequiredIndicators.removeAll(indicators.entrySet()); // just in case there had been required } computedProviders.add(indicatorProvider); pendingProviders.remove(indicatorProvider); } else { pendingProviders.add(indicatorProvider); } } } //indicatorsByCategory.put(indicatorProviderCategory.getKey(), categoryIndicators); } /*}*/ // Warn if some indicators have been left pending for (IndicatorProvider pendingProvider : pendingProviders) { logger.warn(pendingProvider.getClass().getName() + " provider dependencies could not be satisfied (" + pendingProvider.getRequiredIndicators() + ")"); } if (!pendingRequiredIndicators.isEmpty()) { logger.warn("Pending required indicators : " + pendingRequiredIndicators); } //return indicatorsByCategory; return computedIndicators; }
From source file:com.emc.storageos.volumecontroller.impl.plugins.IsilonCommunicationInterface.java
private void discoverUmanagedFileSystems(AccessProfile profile) throws BaseCollectionException { _log.debug("Access Profile Details : IpAddress : PortNumber : {}, namespace : {}", profile.getIpAddress() + profile.getPortNumber(), profile.getnamespace()); URI storageSystemId = profile.getSystemId(); StorageSystem storageSystem = _dbClient.queryObject(StorageSystem.class, storageSystemId); if (null == storageSystem) { return;/*from w ww. ja v a2 s .co m*/ } List<UnManagedFileSystem> unManagedFileSystems = new ArrayList<UnManagedFileSystem>(); List<UnManagedFileSystem> existingUnManagedFileSystems = new ArrayList<UnManagedFileSystem>(); Set<URI> allDiscoveredUnManagedFileSystems = new HashSet<URI>(); String detailedStatusMessage = "Discovery of Isilon Unmanaged FileSystem started"; long unmanagedFsCount = 0; try { IsilonApi isilonApi = getIsilonDevice(storageSystem); URIQueryResultList storagePoolURIs = new URIQueryResultList(); _dbClient.queryByConstraint( ContainmentConstraint.Factory.getStorageDeviceStoragePoolConstraint(storageSystem.getId()), storagePoolURIs); ArrayList<StoragePool> pools = new ArrayList(); Iterator<URI> poolsItr = storagePoolURIs.iterator(); while (poolsItr.hasNext()) { URI storagePoolURI = poolsItr.next(); StoragePool storagePool = _dbClient.queryObject(StoragePool.class, storagePoolURI); if (storagePool != null && !storagePool.getInactive()) { pools.add(storagePool); } } StoragePool storagePool = null; if (pools != null && !pools.isEmpty()) { storagePool = pools.get(0); } StoragePort storagePort = getStoragePortPool(storageSystem); String resumeToken = null; int totalIsilonFSDiscovered = 0; // get the associated storage port for vnas Server List<IsilonAccessZone> isilonAccessZones = isilonApi.getAccessZones(null); Map<String, NASServer> nasServers = getNASServer(storageSystem, isilonAccessZones); setDiscPathForAccess(nasServers); // Get All FileShare HashMap<String, HashSet<String>> allSMBShares = discoverAllSMBShares(storageSystem, isilonAccessZones); List<UnManagedCifsShareACL> unManagedCifsShareACLList = new ArrayList<UnManagedCifsShareACL>(); List<UnManagedCifsShareACL> oldunManagedCifsShareACLList = new ArrayList<UnManagedCifsShareACL>(); HashMap<String, HashSet<Integer>> expMap = discoverAllExports(storageSystem, isilonAccessZones); List<UnManagedNFSShareACL> unManagedNfsShareACLList = new ArrayList<UnManagedNFSShareACL>(); List<UnManagedNFSShareACL> oldunManagedNfsShareACLList = new ArrayList<UnManagedNFSShareACL>(); List<UnManagedFileExportRule> newUnManagedExportRules = new ArrayList<UnManagedFileExportRule>(); List<FileShare> discoveredFS = new ArrayList<FileShare>(); do { IsilonApi.IsilonList<FileShare> discoveredIsilonFS = discoverAllFileSystem(storageSystem, resumeToken); resumeToken = discoveredIsilonFS.getToken(); discoveredFS = discoveredIsilonFS.getList(); totalIsilonFSDiscovered += discoveredFS.size(); unManagedFileSystems = new ArrayList<UnManagedFileSystem>(); existingUnManagedFileSystems = new ArrayList<UnManagedFileSystem>(); int newFileSystemsCount = 0; int existingFileSystemsCount = 0; HashMap<String, HashMap<String, HashSet<Integer>>> exportMapTree = getExportsWithSubDirForFS( discoveredFS, expMap); for (FileShare fs : discoveredFS) { if (!checkStorageFileSystemExistsInDB(fs.getNativeGuid())) { // Create UnManaged FS String fsUnManagedFsNativeGuid = NativeGUIDGenerator .generateNativeGuidForPreExistingFileSystem(storageSystem.getSystemType(), storageSystem.getSerialNumber(), fs.getNativeId()); String fsPathName = fs.getPath(); UnManagedFileSystem unManagedFs = checkUnManagedFileSystemExistsInDB( fsUnManagedFsNativeGuid); // get the matched vNAS Server NASServer nasServer = getMatchedNASServer(nasServers, fsPathName); if (nasServer != null) { _log.info("fs path {} and nas server details {}", fs.getPath(), nasServer.toString()); if (nasServer.getStoragePorts() != null && !nasServer.getStoragePorts().isEmpty()) { storagePort = _dbClient.queryObject(StoragePort.class, URI.create(nasServer.getStoragePorts().iterator().next())); } } else { _log.info("fs path {} and vnas server not found", fs.getPath()); continue; // Skip further ingestion steps on this file share & move to next file share } boolean alreadyExist = unManagedFs == null ? false : true; unManagedFs = createUnManagedFileSystem(unManagedFs, fsUnManagedFsNativeGuid, storageSystem, storagePool, nasServer, fs); /* * Get all file exports with given file system */ HashSet<String> fsExportPaths = new HashSet<String>(); for (Entry<String, HashSet<Integer>> entry : expMap.entrySet()) { if (entry.getKey().equalsIgnoreCase(fsPathName) || entry.getKey().startsWith(fsPathName + "/")) { _log.info("filesystem path : {} and export path: {}", fs.getPath(), entry.getKey()); fsExportPaths.add(entry.getKey()); } } List<UnManagedNFSShareACL> tempUnManagedNfsShareACL = new ArrayList<UnManagedNFSShareACL>(); UnManagedNFSShareACL existingNfsACL = null; getUnmanagedNfsShareACL(unManagedFs, tempUnManagedNfsShareACL, storagePort, fs, isilonApi, fsExportPaths); if (tempUnManagedNfsShareACL != null && !tempUnManagedNfsShareACL.isEmpty()) { unManagedFs.setHasNFSAcl(true); } for (UnManagedNFSShareACL unManagedNFSACL : tempUnManagedNfsShareACL) { _log.info("Unmanaged File share acls : {}", unManagedNFSACL); String fsShareNativeId = unManagedNFSACL.getFileSystemNfsACLIndex(); _log.info("UMFS Share ACL index {}", fsShareNativeId); String fsUnManagedFileShareNativeGuid = NativeGUIDGenerator .generateNativeGuidForPreExistingFileShare(storageSystem, fsShareNativeId); _log.info("Native GUID {}", fsUnManagedFileShareNativeGuid); // set native guid, so each entry unique unManagedNFSACL.setNativeGuid(fsUnManagedFileShareNativeGuid); // Check whether the NFS share ACL was present in ViPR DB. existingNfsACL = checkUnManagedFsNfssACLExistsInDB(_dbClient, unManagedNFSACL.getNativeGuid()); if (existingNfsACL == null) { unManagedNfsShareACLList.add(unManagedNFSACL); } else { unManagedNfsShareACLList.add(unManagedNFSACL); // delete the existing acl existingNfsACL.setInactive(true); oldunManagedNfsShareACLList.add(existingNfsACL); } } // get all shares for given file system path HashSet<String> smbShareHashSet = new HashSet<String>(); for (Entry<String, HashSet<String>> entry : allSMBShares.entrySet()) { if (entry.getKey().equalsIgnoreCase(fsPathName) || entry.getKey().startsWith(fsPathName + "/")) { _log.info("filesystem path : {} and share path: {}", fs.getPath(), entry.getKey()); smbShareHashSet.addAll(entry.getValue()); } } _log.info("File System {} has shares and their size is {}", unManagedFs.getId(), smbShareHashSet.size()); if (!smbShareHashSet.isEmpty()) { List<UnManagedCifsShareACL> umfsCifsShareACL = new ArrayList<UnManagedCifsShareACL>(); // Set UnManaged ACL and also set the shares in fs object setUnmanagedCifsShareACL(unManagedFs, smbShareHashSet, umfsCifsShareACL, storagePort, fs.getName(), nasServer.getNasName(), isilonApi); if (!umfsCifsShareACL.isEmpty()) { for (UnManagedCifsShareACL unManagedCifsShareACL : umfsCifsShareACL) { _log.info("Unmanaged File share acl : {}", unManagedCifsShareACL); String fsShareNativeId = unManagedCifsShareACL.getFileSystemShareACLIndex(); _log.info("UMFS Share ACL index {}", fsShareNativeId); String fsUnManagedFileShareNativeGuid = NativeGUIDGenerator .generateNativeGuidForPreExistingFileShare(storageSystem, fsShareNativeId); _log.info("Native GUID {}", fsUnManagedFileShareNativeGuid); // set native guid, so each entry unique unManagedCifsShareACL.setNativeGuid(fsUnManagedFileShareNativeGuid); // Check whether the CIFS share ACL was present in ViPR DB. UnManagedCifsShareACL existingCifsShareACL = checkUnManagedFsCifsACLExistsInDB( _dbClient, unManagedCifsShareACL.getNativeGuid()); if (existingCifsShareACL == null) { unManagedCifsShareACLList.add(unManagedCifsShareACL); } else { unManagedCifsShareACLList.add(unManagedCifsShareACL); // delete the existing acl existingCifsShareACL.setInactive(true); oldunManagedCifsShareACLList.add(existingCifsShareACL); } } _log.info("UMFS ID {} - Size of ACL of all CIFS shares is {}", unManagedFs.getId(), umfsCifsShareACL.size()); } } // Get Export info _log.info("Getting export for {}", fs.getPath()); HashMap<String, HashSet<Integer>> expIdMap = exportMapTree.get(fs.getPath()); if (expIdMap == null) { expIdMap = new HashMap<>(); } List<UnManagedFileExportRule> unManagedExportRules = new ArrayList<UnManagedFileExportRule>(); if (!expIdMap.keySet().isEmpty()) { boolean validExportsFound = getUnManagedFSExportMap(unManagedFs, expIdMap, storagePort, fs.getPath(), nasServer.getNasName(), isilonApi); if (!validExportsFound) { // Invalid exports so ignore the FS String invalidExports = ""; for (String path : expIdMap.keySet()) { invalidExports += expIdMap.get(path); } _log.info("FS {} is ignored because it has conflicting exports {}", fs.getPath(), invalidExports); unManagedFs.setInactive(true); // Persists the inactive state before picking next UMFS!!! _dbClient.persistObject(unManagedFs); continue; } List<UnManagedFileExportRule> validExportRules = getUnManagedFSExportRules(unManagedFs, expIdMap, storagePort, fs.getPath(), nasServer.getNasName(), isilonApi); _log.info("Number of exports discovered for file system {} is {}", unManagedFs.getId(), validExportRules.size()); UnManagedFileExportRule existingRule = null; for (UnManagedFileExportRule dbExportRule : validExportRules) { _log.info("Un Managed File Export Rule : {}", dbExportRule); String fsExportRulenativeId = dbExportRule.getFsExportIndex(); _log.info("Native Id using to build Native Guid {}", fsExportRulenativeId); String fsUnManagedFileExportRuleNativeGuid = NativeGUIDGenerator .generateNativeGuidForPreExistingFileExportRule(storageSystem, fsExportRulenativeId); _log.info("Native GUID {}", fsUnManagedFileExportRuleNativeGuid); dbExportRule.setNativeGuid(fsUnManagedFileExportRuleNativeGuid); dbExportRule.setFileSystemId(unManagedFs.getId()); dbExportRule.setId(URIUtil.createId(UnManagedFileExportRule.class)); existingRule = checkUnManagedFsExportRuleExistsInDB(_dbClient, dbExportRule.getNativeGuid()); if (null == existingRule) { unManagedExportRules.add(dbExportRule); } else { existingRule.setInactive(true); _dbClient.persistObject(existingRule); unManagedExportRules.add(dbExportRule); } } // Validate Rules Compatible with ViPR - Same rules should // apply as per API SVC Validations. if (!unManagedExportRules.isEmpty()) { _log.info("Validating rules success for export {}", fs.getName()); newUnManagedExportRules.addAll(unManagedExportRules); unManagedFs.setHasExports(true); _log.info("File System {} has Exports and their size is {}", unManagedFs.getId(), newUnManagedExportRules.size()); } } if (unManagedFs.getHasExports() || unManagedFs.getHasShares()) { _log.info("FS {} is having exports/shares", fs.getPath()); unManagedFs.putFileSystemCharacterstics( UnManagedFileSystem.SupportedFileSystemCharacterstics.IS_FILESYSTEM_EXPORTED .toString(), TRUE); } else { // NO exports found _log.info("FS {} is ignored because it doesnt have exports and shares", fs.getPath()); } if (alreadyExist) { existingUnManagedFileSystems.add(unManagedFs); existingFileSystemsCount++; } else { unManagedFileSystems.add(unManagedFs); newFileSystemsCount++; } if (!newUnManagedExportRules.isEmpty()) { _log.info("Saving Number of UnManagedFileExportRule(s) {}", newUnManagedExportRules.size()); _partitionManager.updateInBatches(newUnManagedExportRules, Constants.DEFAULT_PARTITION_SIZE, _dbClient, UNMANAGED_EXPORT_RULE); newUnManagedExportRules.clear(); } // save ACLs in db if (!unManagedCifsShareACLList.isEmpty() && unManagedCifsShareACLList.size() >= MAX_UMFS_RECORD_SIZE) { _log.info("Saving Number of UnManagedCifsShareACL(s) {}", unManagedCifsShareACLList.size()); _dbClient.createObject(unManagedCifsShareACLList); unManagedCifsShareACLList.clear(); } // save old acls if (!oldunManagedCifsShareACLList.isEmpty() && oldunManagedCifsShareACLList.size() >= MAX_UMFS_RECORD_SIZE) { _log.info("Saving Number of UnManagedFileExportRule(s) {}", oldunManagedCifsShareACLList.size()); _dbClient.persistObject(oldunManagedCifsShareACLList); oldunManagedCifsShareACLList.clear(); } allDiscoveredUnManagedFileSystems.add(unManagedFs.getId()); /** * Persist 200 objects and clear them to avoid memory issue */ validateListSizeLimitAndPersist(unManagedFileSystems, existingUnManagedFileSystems, Constants.DEFAULT_PARTITION_SIZE * 2); } } _log.info("New unmanaged Isilon file systems count: {}", newFileSystemsCount); _log.info("Update unmanaged Isilon file systems count: {}", existingFileSystemsCount); if (!unManagedFileSystems.isEmpty()) { _dbClient.createObject(unManagedFileSystems); } if (!existingUnManagedFileSystems.isEmpty()) { _dbClient.updateAndReindexObject(existingUnManagedFileSystems); } } while (resumeToken != null); // save ACLs in db if (!unManagedCifsShareACLList.isEmpty()) { _log.info("Saving Number of UnManagedCifsShareACL(s) {}", unManagedCifsShareACLList.size()); _dbClient.createObject(unManagedCifsShareACLList); unManagedCifsShareACLList.clear(); } // save NFS ACLs in db if (!unManagedNfsShareACLList.isEmpty()) { _log.info("Saving Number of UnManagedNfsShareACL(s) {}", unManagedNfsShareACLList.size()); _dbClient.createObject(unManagedNfsShareACLList); unManagedNfsShareACLList.clear(); } // save old acls if (!oldunManagedCifsShareACLList.isEmpty()) { _log.info("Saving Number of UnManagedFileExportRule(s) {}", oldunManagedCifsShareACLList.size()); _dbClient.persistObject(oldunManagedCifsShareACLList); oldunManagedCifsShareACLList.clear(); } // save old acls if (!oldunManagedNfsShareACLList.isEmpty()) { _log.info("Saving Number of NFS UnManagedFileExportRule(s) {}", oldunManagedNfsShareACLList.size()); _dbClient.updateObject(oldunManagedNfsShareACLList); oldunManagedNfsShareACLList.clear(); } _log.info("Discovered {} Isilon file systems.", totalIsilonFSDiscovered); // Process those active unmanaged fs objects available in database but not in newly discovered items, to // mark them inactive. markUnManagedFSObjectsInActive(storageSystem, allDiscoveredUnManagedFileSystems); // discovery succeeds detailedStatusMessage = String.format( "Discovery completed successfully for Isilon: %s; new unmanaged file systems count: %s", storageSystemId.toString(), unmanagedFsCount); _log.info(detailedStatusMessage); } catch (Exception e) { if (storageSystem != null) { cleanupDiscovery(storageSystem); } detailedStatusMessage = String.format("Discovery failed for Isilon %s because %s", storageSystemId.toString(), e.getLocalizedMessage()); _log.error(detailedStatusMessage, e); throw new IsilonCollectionException(detailedStatusMessage); } finally { if (storageSystem != null) { try { // set detailed message storageSystem.setLastDiscoveryStatusMessage(detailedStatusMessage); _dbClient.persistObject(storageSystem); } catch (Exception ex) { _log.error("Error while persisting object to DB", ex); } } } }
From source file:org.apache.accumulo.examples.wikisearch.iterator.BooleanLogicIterator.java
private void handleAND(BooleanLogicTreeNode me) { if (log.isDebugEnabled()) { log.debug("handleAND::" + me.getContents()); }/*from w w w.j a v a 2 s .c o m*/ Enumeration<?> children = me.children(); me.setValid(true); // it's easier to prove false than true HashSet<Key> goodSet = new HashSet<Key>(); HashSet<Key> badSet = new HashSet<Key>(); while (children.hasMoreElements()) { BooleanLogicTreeNode child = (BooleanLogicTreeNode) children.nextElement(); if (child.getType() == ParserTreeConstants.JJTEQNODE || child.getType() == ParserTreeConstants.JJTANDNODE || child.getType() == ParserTreeConstants.JJTERNODE || child.getType() == ParserTreeConstants.JJTNENODE || child.getType() == ParserTreeConstants.JJTGENODE || child.getType() == ParserTreeConstants.JJTLENODE || child.getType() == ParserTreeConstants.JJTGTNODE || child.getType() == ParserTreeConstants.JJTLTNODE) { if (child.isNegated()) { if (child.hasTop()) { badSet.add(child.getTopKey()); if (goodSet.contains(child.getTopKey())) { me.setValid(false); return; } if (child.isValid()) { me.setValid(false); return; } } } else { if (child.hasTop()) { if (log.isDebugEnabled()) { log.debug("handleAND, child node: " + child.getContents()); } // if you're in the bad set, you're done. if (badSet.contains(child.getTopKey())) { if (log.isDebugEnabled()) { log.debug("handleAND, child is in bad set, setting parent false"); } me.setValid(false); return; } // if good set is empty, add it. if (goodSet.isEmpty()) { if (log.isDebugEnabled()) { log.debug("handleAND, goodSet is empty, adding child: " + child.getContents()); } goodSet.add(child.getTopKey()); } else { // must be in the good set & not in the bad set // if either fails, I'm false. if (!goodSet.contains(child.getTopKey())) { if (log.isDebugEnabled()) { log.debug( "handleAND, goodSet is not empty, and does NOT contain child, setting false. child: " + child.getContents()); } me.setValid(false); return; } else { // trim the good set to this one value // (handles the case were the initial encounters were ORs) goodSet = new HashSet<Key>(); goodSet.add(child.getTopKey()); if (log.isDebugEnabled()) { log.debug("handleAND, child in goodset, trim to this value: " + child.getContents()); } } } } else { // test if its children are all false if (child.getChildCount() > 0) { Enumeration<?> subchildren = child.children(); boolean allFalse = true; while (subchildren.hasMoreElements()) { BooleanLogicTreeNode subchild = (BooleanLogicTreeNode) subchildren.nextElement(); if (!subchild.isNegated()) { allFalse = false; break; } else if (subchild.isNegated() && subchild.hasTop()) { allFalse = false; break; } } if (!allFalse) { me.setValid(false); return; } } else { // child returned a null value and is not a negation, this in turn makes me false. me.setValid(false); return; } } } } else if (child.getType() == ParserTreeConstants.JJTORNODE) {// BooleanLogicTreeNode.NodeType.OR) { // NOTE: The OR may be an OrIterator in which case it will only produce // a single unique identifier, or it may be a pure logical construct and // be capable of producing multiple unique identifiers. // This should handle all cases. Iterator<?> iter = child.getSetIterator(); boolean goodSetEmpty = goodSet.isEmpty(); boolean matchedOne = false; boolean pureNegations = true; if (!child.isValid()) { if (log.isDebugEnabled()) { log.debug("handleAND, child is an OR and it is not valid, setting false, ALL NEGATED?: " + child.isChildrenAllNegated()); } me.setValid(false); // I'm an AND if one of my children is false, I'm false. return; } else if (child.isValid() && !child.hasTop()) { // pure negation, do nothing } else if (child.isValid() && child.hasTop()) { // I need to match one if (log.isDebugEnabled()) { log.debug("handleAND, child OR, valid and has top, means not pureNegations"); } pureNegations = false; while (iter.hasNext()) { Key i = (Key) iter.next(); if (child.isNegated()) { badSet.add(i); if (goodSet.contains(i)) { if (log.isDebugEnabled()) { log.debug("handleAND, child OR, goodSet contains bad value: " + i); } me.setValid(false); return; } } else { // if the good set is empty, then push all of my ids. if (goodSetEmpty && !badSet.contains(i)) { goodSet.add(i); matchedOne = true; } else { // I need at least one to match if (goodSet.contains(i)) { matchedOne = true; } } } } } // is the goodSet still empty? that means were were only negations // otherwise, if it's not empty and we didn't match one, false if (child.isNegated()) { // we're ok } else { if (goodSet.isEmpty() && !pureNegations) { if (log.isDebugEnabled()) { log.debug("handleAND, child OR, empty goodset && !pureNegations, set false"); } // that's bad, we weren't negated, should've pushed something in there. me.setValid(false); return; } else if (!goodSet.isEmpty() && !pureNegations) { // goodSet contains values. if (!matchedOne) { // but we didn't match any. if (log.isDebugEnabled()) { log.debug("handleAND, child OR, goodSet had values but I didn't match any, false"); } me.setValid(false); return; } // we matched something, trim the set. // i.e. two child ORs goodSet = child.getIntersection(goodSet); } } } } // end while if (goodSet.isEmpty()) { // && log.isDebugEnabled()) { if (log.isDebugEnabled()) { log.debug("handleAND-> goodSet is empty, pure negations?"); } } else { me.setTopKey(Collections.min(goodSet)); if (log.isDebugEnabled()) { log.debug("End of handleAND, this node's topKey: " + me.getTopKey()); } } }
From source file:org.apache.axis.wsdl.toJava.JavaDeployWriter.java
/** * Write out deployment instructions for given WSDL binding * * @param pw//from w w w. j a v a 2s . co m * @param bEntry * @throws IOException */ protected void writeDeployBinding(PrintWriter pw, BindingEntry bEntry) throws IOException { Binding binding = bEntry.getBinding(); String className = bEntry.getName(); if (emitter.isSkeletonWanted()) { className += "Skeleton"; } else { String customClassName = emitter.getImplementationClassName(); if (customClassName != null) className = customClassName; else className += "Impl"; } pw.println(" <parameter name=\"className\" value=\"" + className + "\"/>"); pw.println(" <parameter name=\"wsdlPortType\" value=\"" + binding.getPortType().getQName().getLocalPart() + "\"/>"); pw.println( " <parameter name=\"typeMappingVersion\" value=\"" + emitter.getTypeMappingVersion() + "\"/>"); HashSet allowedMethods = new HashSet(); String namespaceURI = binding.getQName().getNamespaceURI(); if (!emitter.isSkeletonWanted()) { Iterator operationsIterator = binding.getBindingOperations().iterator(); for (; operationsIterator.hasNext();) { BindingOperation bindingOper = (BindingOperation) operationsIterator.next(); Operation operation = bindingOper.getOperation(); OperationType type = operation.getStyle(); // These operation types are not supported. The signature // will be a string stating that fact. if ((OperationType.NOTIFICATION.equals(type)) || (OperationType.SOLICIT_RESPONSE.equals(type))) { continue; } String javaOperName = null; ServiceDesc serviceDesc = emitter.getServiceDesc(); if (emitter.isDeploy() && serviceDesc != null) { // If the emitter works in deploy mode, sync the java operation name with it of the ServiceDesc OperationDesc[] operDescs = serviceDesc .getOperationsByQName(new QName(namespaceURI, operation.getName())); if (operDescs.length == 0) { log.warn("Can't find operation in the Java Class for WSDL binding operation : " + operation.getName()); continue; } OperationDesc operDesc = operDescs[0]; if (operDesc.getMethod() == null) { log.warn("Can't find Java method for operation descriptor : " + operDesc.getName()); continue; } javaOperName = operDesc.getMethod().getName(); } else { javaOperName = JavaUtils.xmlNameToJava(operation.getName()); } allowedMethods.add(javaOperName); // We pass "" as the namespace argument because we're just // interested in the return type for now. Parameters params = symbolTable.getOperationParameters(operation, "", bEntry); if (params != null) { // TODO: Should really construct a FaultDesc here and // TODO: pass it to writeOperation, but this will take // TODO: some refactoring // Get the operation QName QName elementQName = Utils.getOperationQName(bindingOper, bEntry, symbolTable); // Get the operation's return QName and type QName returnQName = null; QName returnType = null; if (params.returnParam != null) { returnQName = params.returnParam.getQName(); returnType = Utils.getXSIType(params.returnParam); } // Get the operations faults Map faultMap = bEntry.getFaults(); ArrayList faults = null; if (faultMap != null) { faults = (ArrayList) faultMap.get(bindingOper); } // Get the operation's SOAPAction String SOAPAction = Utils.getOperationSOAPAction(bindingOper); // Write the operation metadata writeOperation(pw, javaOperName, elementQName, returnQName, returnType, params, binding.getQName(), faults, SOAPAction); } } } pw.print(" <parameter name=\"allowedMethods\" value=\""); if (allowedMethods.isEmpty()) { pw.println("*\"/>"); } else { boolean first = true; for (Iterator i = allowedMethods.iterator(); i.hasNext();) { String method = (String) i.next(); if (first) { pw.print(method); first = false; } else { pw.print(" " + method); } } pw.println("\"/>"); } Scope scope = emitter.getScope(); if (scope != null) { pw.println(" <parameter name=\"scope\" value=\"" + scope.getName() + "\"/>"); } }
From source file:imitationNLG.SFX.java
public Object[] createTrainingDatasets(ArrayList<DatasetInstance> trainingData, HashMap<String, HashSet<String>> availableAttributeActions, HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions, HashMap<Integer, HashSet<String>> nGrams) { HashMap<String, ArrayList<Instance>> predicateAttrTrainingData = new HashMap<>(); HashMap<String, HashMap<String, ArrayList<Instance>>> predicateWordTrainingData = new HashMap<>(); if (!availableWordActions.isEmpty() && !predicates.isEmpty()/* && !arguments.isEmpty()*/) { for (String predicate : predicates) { predicateAttrTrainingData.put(predicate, new ArrayList<Instance>()); predicateWordTrainingData.put(predicate, new HashMap<String, ArrayList<Instance>>()); }/* w w w. ja v a 2s .c om*/ for (DatasetInstance di : trainingData) { //System.out.println("BEGIN"); String predicate = di.getMeaningRepresentation().getPredicate(); //for (ArrayList<Action> realization : di.getEvalRealizations()) { ArrayList<Action> realization = di.getTrainRealization(); //System.out.println(realization); HashSet<String> attrValuesAlreadyMentioned = new HashSet<>(); HashSet<String> attrValuesToBeMentioned = new HashSet<>(); for (String attribute : di.getMeaningRepresentation().getAttributes().keySet()) { //int a = 0; for (String value : di.getMeaningRepresentation().getAttributes().get(attribute)) { /*if (value.startsWith("\"x")) { value = "x" + a; a++; } else if (value.startsWith("\"")) { value = value.substring(1, value.length() - 1).replaceAll(" ", "_"); }*/ attrValuesToBeMentioned.add(attribute.toLowerCase() + "=" + value.toLowerCase()); } } if (attrValuesToBeMentioned.isEmpty()) { attrValuesToBeMentioned.add("empty=empty"); } ArrayList<String> attrs = new ArrayList<>(); boolean isValueMentioned = false; String valueTBM = ""; String attrValue = ""; ArrayList<String> subPhrase = new ArrayList<>(); for (int w = 0; w < realization.size(); w++) { if (!realization.get(w).getAttribute().equals(SFX.TOKEN_PUNCT)) { if (!realization.get(w).getAttribute().equals(attrValue)) { if (!attrValue.isEmpty()) { attrValuesToBeMentioned.remove(attrValue); } Instance attrTrainingVector = SFX.this.createAttrInstance(predicate, realization.get(w).getAttribute(), attrs, new ArrayList<Action>(realization.subList(0, w)), attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableAttributeActions); if (attrTrainingVector != null) { /*System.out.println(realization.get(w).getAttribute() + " >>>> " + attrTrainingVector.getCorrectLabels()); for (String f : attrTrainingVector.getGeneralFeatureVector().keySet()) { if (f.startsWith("feature_attrValue_5gram_") || f.startsWith("feature_word_5gram_")) { System.out.println(">> " + f); } }*/ predicateAttrTrainingData.get(predicate).add(attrTrainingVector); } attrs.add(realization.get(w).getAttribute()); attrValue = realization.get(w).getAttribute(); subPhrase = new ArrayList<>(); isValueMentioned = false; valueTBM = ""; if (attrValue.contains("=")) { valueTBM = attrValue.substring(attrValue.indexOf('=') + 1); } if (valueTBM.isEmpty()) { isValueMentioned = true; } } if (!attrValue.equals(SFX.TOKEN_END)) { ArrayList<String> predictedAttributesForInstance = new ArrayList<>(); for (int i = 0; i < attrs.size() - 1; i++) { predictedAttributesForInstance.add(attrs.get(i)); } if (!attrs.get(attrs.size() - 1).equals(attrValue)) { predictedAttributesForInstance.add(attrs.get(attrs.size() - 1)); } Instance wordTrainingVector = createWordInstance(predicate, realization.get(w), predictedAttributesForInstance, new ArrayList<Action>(realization.subList(0, w)), isValueMentioned, attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableWordActions.get(predicate), nGrams, false); if (wordTrainingVector != null) { String attribute = attrValue; if (attribute.contains("=")) { attribute = attrValue.substring(0, attrValue.indexOf('=')); } if (!predicateWordTrainingData.get(predicate).containsKey(attribute)) { predicateWordTrainingData.get(predicate).put(attribute, new ArrayList<Instance>()); } /*System.out.println(realization.get(w) + " >>>> " + wordTrainingVector.getCorrectLabels()); for (String f : wordTrainingVector.getGeneralFeatureVector().keySet()) { if (f.startsWith("feature_attrValue_5gram_") || f.startsWith("feature_word_5gram_")) { System.out.println(">> " + f); } }*/ predicateWordTrainingData.get(predicate).get(attribute).add(wordTrainingVector); if (!realization.get(w).getWord().equals(SFX.TOKEN_START) && !realization.get(w).getWord().equals(SFX.TOKEN_END)) { subPhrase.add(realization.get(w).getWord()); } } if (!isValueMentioned) { if (realization.get(w).getWord().startsWith(SFX.TOKEN_X) && (valueTBM.matches("[xX][0-9]+") || valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.startsWith(SFX.TOKEN_X))) { isValueMentioned = true; } else if (!realization.get(w).getWord().startsWith(SFX.TOKEN_X) && !(valueTBM.matches("[xX][0-9]+") || valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.startsWith(SFX.TOKEN_X))) { String valueToCheck = valueTBM; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { String attribute = attrValue; if (attribute.contains("=")) { attribute = attrValue.substring(0, attrValue.indexOf('=')); } valueToCheck = attribute + ":" + valueTBM; } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments.get(valueToCheck) .keySet()) { if (endsWith(subPhrase, alignedStr)) { isValueMentioned = true; break; } } } } if (isValueMentioned) { attrValuesAlreadyMentioned.add(attrValue); attrValuesToBeMentioned.remove(attrValue); } } String mentionedAttrValue = ""; if (!realization.get(w).getWord().startsWith(SFX.TOKEN_X)) { for (String attrValueTBM : attrValuesToBeMentioned) { if (attrValueTBM.contains("=")) { String value = attrValueTBM.substring(attrValueTBM.indexOf('=') + 1); if (!(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+") || value.startsWith(SFX.TOKEN_X))) { String valueToCheck = value; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { valueToCheck = attrValueTBM.replace("=", ":"); } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments .get(valueToCheck).keySet()) { if (endsWith(subPhrase, alignedStr)) { mentionedAttrValue = attrValueTBM; break; } } } } } } } if (!mentionedAttrValue.isEmpty()) { attrValuesAlreadyMentioned.add(mentionedAttrValue); attrValuesToBeMentioned.remove(mentionedAttrValue); } } } } //} } } Object[] results = new Object[2]; results[0] = predicateAttrTrainingData; results[1] = predicateWordTrainingData; return results; }
From source file:com.android.launcher3.Launcher.java
/** * A package was uninstalled/updated. We take both the super set of packageNames * in addition to specific applications to remove, the reason being that * this can be called when a package is updated as well. In that scenario, * we only remove specific components from the workspace and hotseat, where as * package-removal should clear all items by package name. *//*from w ww .java 2 s . co m*/ @Override public void bindWorkspaceComponentsRemoved(final HashSet<String> packageNames, final HashSet<ComponentName> components, final UserHandleCompat user) { Runnable r = new Runnable() { public void run() { bindWorkspaceComponentsRemoved(packageNames, components, user); } }; if (waitUntilResume(r)) { return; } if (!packageNames.isEmpty()) { ItemInfoMatcher matcher = ItemInfoMatcher.ofPackages(packageNames, user); mWorkspace.removeItemsByMatcher(matcher); mDragController.onAppsRemoved(matcher); } if (!components.isEmpty()) { ItemInfoMatcher matcher = ItemInfoMatcher.ofComponents(components, user); mWorkspace.removeItemsByMatcher(matcher); mDragController.onAppsRemoved(matcher); } }
From source file:com.klinker.android.launcher.launcher3.Launcher.java
/** * A package was uninstalled. We take both the super set of packageNames * in addition to specific applications to remove, the reason being that * this can be called when a package is updated as well. In that scenario, * we only remove specific components from the workspace, where as * package-removal should clear all items by package name. * * @param reason if non-zero, the icons are not permanently removed, rather marked as disabled. * Implementation of the method from LauncherModel.Callbacks. *//*w w w. ja v a 2 s . c om*/ @Override public void bindComponentsRemoved(final ArrayList<String> packageNames, final ArrayList<AppInfo> appInfos, final UserHandleCompat user, final int reason) { Runnable r = new Runnable() { public void run() { bindComponentsRemoved(packageNames, appInfos, user, reason); } }; if (waitUntilResume(r)) { return; } if (reason == 0) { HashSet<ComponentName> removedComponents = new HashSet<ComponentName>(); for (AppInfo info : appInfos) { removedComponents.add(info.componentName); } if (!packageNames.isEmpty()) { mWorkspace.removeItemsByPackageName(packageNames, user); } if (!removedComponents.isEmpty()) { mWorkspace.removeItemsByComponentName(removedComponents, user); } // Notify the drag controller mDragController.onAppsRemoved(packageNames, removedComponents); } else { mWorkspace.disableShortcutsByPackageName(packageNames, user, reason); } // Update AllApps if (mAppsView != null) { mAppsView.removeApps(appInfos); } }
From source file:imitationNLG.SFX.java
public Double evaluateGeneration(HashMap<String, JAROW> classifierAttrs, HashMap<String, HashMap<String, JAROW>> classifierWords, ArrayList<DatasetInstance> trainingData, ArrayList<DatasetInstance> testingData, HashMap<String, HashSet<String>> availableAttributeActions, HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions, HashMap<Integer, HashSet<String>> nGrams, boolean printResults, int epoch) { System.out.println("Evaluate argument generation "); int totalArgDistance = 0; ArrayList<ScoredFeaturizedTranslation<IString, String>> generations = new ArrayList<>(); ArrayList<ArrayList<Action>> generationActions = new ArrayList<>(); HashMap<ArrayList<Action>, DatasetInstance> generationActionsMap = new HashMap<>(); ArrayList<ArrayList<Sequence<IString>>> finalReferences = new ArrayList<>(); ArrayList<String> predictedStrings = new ArrayList<>(); ArrayList<String> predictedStringMRs = new ArrayList<>(); ArrayList<Double> attrCoverage = new ArrayList<>(); ArrayList<ArrayList<String>> predictedAttrLists = new ArrayList<>(); HashSet<HashMap<String, HashSet<String>>> mentionedAttrs = new HashSet<HashMap<String, HashSet<String>>>(); for (DatasetInstance di : testingData) { String predicate = di.getMeaningRepresentation().getPredicate(); ArrayList<Action> predictedActionList = new ArrayList<>(); ArrayList<Action> predictedWordList = new ArrayList<>(); //PHRASE GENERATION EVALUATION String predictedAttr = ""; ArrayList<String> predictedAttrValues = new ArrayList<>(); ArrayList<String> predictedAttributes = new ArrayList<>(); HashSet<String> attrValuesToBeMentioned = new HashSet<>(); HashSet<String> attrValuesAlreadyMentioned = new HashSet<>(); HashMap<String, ArrayList<String>> valuesToBeMentioned = new HashMap<>(); for (String attribute : di.getMeaningRepresentation().getAttributes().keySet()) { for (String value : di.getMeaningRepresentation().getAttributes().get(attribute)) { attrValuesToBeMentioned.add(attribute.toLowerCase() + "=" + value.toLowerCase()); }//from w w w. j a v a 2 s. co m valuesToBeMentioned.put(attribute, new ArrayList<>(di.getMeaningRepresentation().getAttributes().get(attribute))); } if (attrValuesToBeMentioned.isEmpty()) { attrValuesToBeMentioned.add("empty=empty"); } HashSet<String> attrValuesToBeMentionedCopy = new HashSet<>(attrValuesToBeMentioned); while (!predictedAttr.equals(SFX.TOKEN_END) && predictedAttrValues.size() < maxAttrRealizationSize) { if (!predictedAttr.isEmpty()) { attrValuesToBeMentioned.remove(predictedAttr); } Instance attrTrainingVector = SFX.this.createAttrInstance(predicate, "@TOK@", predictedAttrValues, predictedActionList, attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableAttributeActions); if (attrTrainingVector != null) { Prediction predictAttr = classifierAttrs.get(predicate).predict(attrTrainingVector); if (predictAttr.getLabel() != null) { predictedAttr = predictAttr.getLabel().trim(); String predictedValue = ""; if (!predictedAttr.equals(SFX.TOKEN_END)) { predictedValue = chooseNextValue(predictedAttr, attrValuesToBeMentioned, trainingData); HashSet<String> rejectedAttrs = new HashSet<String>(); while (predictedValue.isEmpty() && !predictedAttr.equals(SFX.TOKEN_END)) { rejectedAttrs.add(predictedAttr); predictedAttr = SFX.TOKEN_END; double maxScore = -Double.MAX_VALUE; for (String attr : predictAttr.getLabel2Score().keySet()) { if (!rejectedAttrs.contains(attr) && (Double .compare(predictAttr.getLabel2Score().get(attr), maxScore) > 0)) { maxScore = predictAttr.getLabel2Score().get(attr); predictedAttr = attr; } } if (!predictedAttr.equals(SFX.TOKEN_END)) { predictedValue = chooseNextValue(predictedAttr, attrValuesToBeMentioned, trainingData); } } } if (!predictedAttr.equals(SFX.TOKEN_END)) { predictedAttr += "=" + predictedValue; } predictedAttrValues.add(predictedAttr); String attribute = predictedAttrValues.get(predictedAttrValues.size() - 1).split("=")[0]; String attrValue = predictedAttrValues.get(predictedAttrValues.size() - 1); predictedAttributes.add(attrValue); //GENERATE PHRASES if (!attribute.equals(SFX.TOKEN_END)) { if (classifierWords.get(predicate).containsKey(attribute)) { String predictedWord = ""; boolean isValueMentioned = false; String valueTBM = ""; if (attrValue.contains("=")) { valueTBM = attrValue.substring(attrValue.indexOf('=') + 1); } if (valueTBM.isEmpty()) { isValueMentioned = true; } ArrayList<String> subPhrase = new ArrayList<>(); while (!predictedWord.equals(RoboCup.TOKEN_END) && predictedWordList.size() < maxWordRealizationSize) { ArrayList<String> predictedAttributesForInstance = new ArrayList<>(); for (int i = 0; i < predictedAttributes.size() - 1; i++) { predictedAttributesForInstance.add(predictedAttributes.get(i)); } if (!predictedAttributes.get(predictedAttributes.size() - 1) .equals(attrValue)) { predictedAttributesForInstance .add(predictedAttributes.get(predictedAttributes.size() - 1)); } Instance wordTrainingVector = createWordInstance(predicate, new Action("@TOK@", attrValue), predictedAttributesForInstance, predictedActionList, isValueMentioned, attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableWordActions.get(predicate), nGrams, false); if (wordTrainingVector != null) { if (classifierWords.get(predicate) != null) { if (classifierWords.get(predicate).get(attribute) != null) { Prediction predictWord = classifierWords.get(predicate) .get(attribute).predict(wordTrainingVector); if (predictWord.getLabel() != null) { predictedWord = predictWord.getLabel().trim(); predictedActionList.add(new Action(predictedWord, attrValue)); if (!predictedWord.equals(SFX.TOKEN_END)) { subPhrase.add(predictedWord); predictedWordList.add(new Action(predictedWord, attrValue)); } } else { predictedWord = SFX.TOKEN_END; predictedActionList.add(new Action(predictedWord, attrValue)); } } else { predictedWord = SFX.TOKEN_END; predictedActionList.add(new Action(predictedWord, attrValue)); } } } if (!isValueMentioned) { if (!predictedWord.equals(SFX.TOKEN_END)) { if (predictedWord.startsWith(SFX.TOKEN_X) && (valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.matches("[xX][0-9]+") || valueTBM.startsWith(SFX.TOKEN_X))) { isValueMentioned = true; } else if (!predictedWord.startsWith(SFX.TOKEN_X) && !(valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.matches("[xX][0-9]+") || valueTBM.startsWith(SFX.TOKEN_X))) { String valueToCheck = valueTBM; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { if (attribute.contains("=")) { valueToCheck = attribute.replace("=", ":"); } else { valueToCheck = attribute + ":" + valueTBM; } } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments .get(valueToCheck).keySet()) { if (endsWith(subPhrase, alignedStr)) { isValueMentioned = true; break; } } } } } if (isValueMentioned) { attrValuesAlreadyMentioned.add(attrValue); attrValuesToBeMentioned.remove(attrValue); } } String mentionedAttrValue = ""; if (!predictedWord.startsWith(SFX.TOKEN_X)) { for (String attrValueTBM : attrValuesToBeMentioned) { if (attrValueTBM.contains("=")) { String value = attrValueTBM .substring(attrValueTBM.indexOf('=') + 1); if (!(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+") || value.startsWith(SFX.TOKEN_X))) { String valueToCheck = value; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { valueToCheck = attrValueTBM.replace("=", ":"); } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments .get(valueToCheck).keySet()) { if (endsWith(subPhrase, alignedStr)) { mentionedAttrValue = attrValueTBM; break; } } } } } } } if (!mentionedAttrValue.isEmpty()) { attrValuesAlreadyMentioned.add(attrValue); attrValuesToBeMentioned.remove(mentionedAttrValue); } } if (predictedWordList.size() >= maxWordRealizationSize && !predictedActionList .get(predictedActionList.size() - 1).getWord().equals(SFX.TOKEN_END)) { predictedWord = SFX.TOKEN_END; predictedActionList.add(new Action(predictedWord, predictedAttrValues.get(predictedAttrValues.size() - 1))); } } else { String predictedWord = SFX.TOKEN_END; predictedActionList.add(new Action(predictedWord, attrValue)); } } } else { predictedAttr = SFX.TOKEN_END; } } } ArrayList<String> predictedAttrs = new ArrayList<>(); for (String attributeValuePair : predictedAttrValues) { predictedAttrs.add(attributeValuePair.split("=")[0]); } ArrayList<Action> cleanActionList = new ArrayList<Action>(); for (Action action : predictedActionList) { if (!action.getWord().equals(SFX.TOKEN_END) && !action.getWord().equals(SFX.TOKEN_START)) { cleanActionList.add(action); } } for (int i = 0; i < cleanActionList.size(); i++) { for (ArrayList<Action> surrounds : punctPatterns.keySet()) { boolean matches = true; int m = 0; for (int s = 0; s < surrounds.size(); s++) { if (surrounds.get(s) != null) { if (i + s < cleanActionList.size()) { if (!cleanActionList.get(i + s).getWord().equals(surrounds.get(s) .getWord()) /*|| !cleanActionList.get(i).getAttribute().equals(surrounds.get(s).getAttribute())*/) { matches = false; s = surrounds.size(); } else { m++; } } else { matches = false; s = surrounds.size(); } } } if (matches && m > 0) { cleanActionList.add(i + 2, punctPatterns.get(surrounds)); } } } String predictedString = ""; ArrayList<String> predictedAttrList = new ArrayList<String>(); HashSet<String> redundants = new HashSet<String>(); for (Action action : cleanActionList) { if (action.getWord().startsWith(SFX.TOKEN_X)) { predictedString += di.getMeaningRepresentation().getDelexMap().get(action.getWord()) + " "; //predictedString += "x "; if (di.getMeaningRepresentation().getDelexMap().get(action.getWord()) == null || di.getMeaningRepresentation().getDelexMap().get(action.getWord()).equals("null")) { redundants.add(action.getWord()); } } else { predictedString += action.getWord() + " "; } if (predictedAttrList.isEmpty()) { predictedAttrList.add(action.getAttribute()); } else if (!predictedAttrList.get(predictedAttrList.size() - 1).equals(action.getAttribute())) { predictedAttrList.add(action.getAttribute()); } } predictedAttrLists.add(predictedAttrList); if (attrValuesToBeMentionedCopy.size() != 0.0) { double redundAttrs = 0.0; double missingAttrs = 0.0; for (String attr : predictedAttrList) { if (!attrValuesToBeMentionedCopy.contains(attr)) { redundAttrs += 1.0; } } for (String attr : attrValuesToBeMentionedCopy) { if (!predictedAttrList.contains(attr)) { missingAttrs += 1.0; } } double attrSize = (double) attrValuesToBeMentionedCopy.size(); attrCoverage.add((redundAttrs + missingAttrs) / attrSize); } if (predicate.startsWith("?")) { predictedString = predictedString.trim() + "?"; } else { predictedString = predictedString.trim() + "."; } predictedString = predictedString.replaceAll("\\?", " \\? ").replaceAll(":", " : ") .replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll(" ", " ").trim(); if (!mentionedAttrs.contains(di.getMeaningRepresentation().getAttributes())) { predictedStrings.add(predictedString); predictedStringMRs.add(di.getMeaningRepresentation().getMRstr()); mentionedAttrs.add(di.getMeaningRepresentation().getAttributes()); } Sequence<IString> translation = IStrings .tokenize(NISTTokenizer.tokenize(predictedString.toLowerCase())); ScoredFeaturizedTranslation<IString, String> tran = new ScoredFeaturizedTranslation<>(translation, null, 0); generations.add(tran); generationActions.add(predictedActionList); generationActionsMap.put(predictedActionList, di); ArrayList<Sequence<IString>> references = new ArrayList<>(); for (ArrayList<Action> realization : di.getEvalRealizations()) { String cleanedWords = ""; for (Action nlWord : realization) { if (!nlWord.equals(new Action(SFX.TOKEN_START, "")) && !nlWord.equals(new Action(SFX.TOKEN_END, ""))) { if (nlWord.getWord().startsWith(SFX.TOKEN_X)) { cleanedWords += di.getMeaningRepresentation().getDelexMap().get(nlWord.getWord()) + " "; } else { cleanedWords += nlWord.getWord() + " "; } } } cleanedWords = cleanedWords.trim(); if (!cleanedWords.endsWith(".")) { cleanedWords += "."; } cleanedWords = cleanedWords.replaceAll("\\?", " \\? ").replaceAll(":", " : ") .replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll(" ", " ").trim(); references.add(IStrings.tokenize(NISTTokenizer.tokenize(cleanedWords))); } finalReferences.add(references); //EVALUATE ATTRIBUTE SEQUENCE HashSet<ArrayList<String>> goldAttributeSequences = new HashSet<>(); for (DatasetInstance di2 : testingData) { if (di2.getMeaningRepresentation().getAttributes() .equals(di.getMeaningRepresentation().getAttributes())) { goldAttributeSequences.addAll(di2.getEvalMentionedAttributeSequences().values()); } } int minTotArgDistance = Integer.MAX_VALUE; for (ArrayList<String> goldArgs : goldAttributeSequences) { int totArgDistance = 0; HashSet<Integer> matchedPositions = new HashSet<>(); for (int i = 0; i < predictedAttrs.size(); i++) { if (!predictedAttrs.get(i).equals(SFX.TOKEN_START) && !predictedAttrs.get(i).equals(SFX.TOKEN_END)) { int minArgDistance = Integer.MAX_VALUE; int minArgPos = -1; for (int j = 0; j < goldArgs.size(); j++) { if (!matchedPositions.contains(j)) { if (goldArgs.get(j).equals(predictedAttrs.get(i))) { int argDistance = Math.abs(j - i); if (argDistance < minArgDistance) { minArgDistance = argDistance; minArgPos = j; } } } } if (minArgPos == -1) { totArgDistance += 100; } else { matchedPositions.add(minArgPos); totArgDistance += minArgDistance; } } } ArrayList<String> predictedCopy = (ArrayList<String>) predictedAttrs.clone(); for (String goldArg : goldArgs) { if (!goldArg.equals(SFX.TOKEN_END)) { boolean contained = predictedCopy.remove(goldArg); if (!contained) { totArgDistance += 1000; } } } if (totArgDistance < minTotArgDistance) { minTotArgDistance = totArgDistance; } } totalArgDistance += minTotArgDistance; } previousResults = generationActions; crossAvgArgDistances.add(totalArgDistance / (double) testingData.size()); NISTMetric NIST = new NISTMetric(finalReferences); BLEUMetric BLEU = new BLEUMetric(finalReferences, 4, false); BLEUMetric BLEUsmooth = new BLEUMetric(finalReferences, 4, true); Double nistScore = NIST.score(generations); Double bleuScore = BLEU.score(generations); Double bleuSmoothScore = BLEUsmooth.score(generations); double finalCoverage = 0.0; for (double c : attrCoverage) { finalCoverage += c; } finalCoverage /= (double) attrCoverage.size(); crossNIST.add(nistScore); crossBLEU.add(bleuScore); crossBLEUSmooth.add(bleuSmoothScore); System.out.println("Avg arg distance: \t" + totalArgDistance / (double) testingData.size()); System.out.println("NIST: \t" + nistScore); System.out.println("BLEU: \t" + bleuScore); System.out.println("COVERAGE: \t" + finalCoverage); System.out.println("g: " + generations); System.out.println("attr: " + predictedAttrLists); System.out.println("BLEU smooth: \t" + bleuSmoothScore); previousBLEU = bleuScore; if (printResults) { BufferedWriter bw = null; File f = null; try { f = new File("random_SFX" + dataset + "TextsAfter" + (epoch) + "_" + JDAggerForSFX.earlyStopMaxFurtherSteps + "_" + JDAggerForSFX.p + "epochsTESTINGDATA.txt"); } catch (NullPointerException e) { System.err.println("File not found." + e); } try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); } catch (FileNotFoundException e) { System.err.println("Error opening file for writing! " + e); } try { bw.write("BLEU:" + bleuScore); bw.write("\n"); } catch (IOException e) { System.err.println("Write error!"); } for (int i = 0; i < predictedStrings.size(); i++) { try { //Grafoume to String sto arxeio //SFX HOTEL TEXTS WITH LOLS -> 3 //SFX RESTAURANT TEXTS WITH LOLS -> 5 bw.write("MR;" + predictedStringMRs.get(i).replaceAll(";", ",") + ";"); if (dataset.equals("hotel")) { bw.write("LOLS_SFHOT;"); } else { bw.write("LOLS_SFRES;"); } //bw.write("@@srcdoc@@" + (i + 1)); /*String out = predictedStrings.get(i).replaceAll(" i ", " I ").replaceAll(" -ly ", "ly ").replaceAll(" s ", "s ").replaceAll("\\?", " \\? ").replaceAll(":", " : ").replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll(" ", " "); out = out.substring(0, 1).toUpperCase() + out.substring(1); bw.write(out + ";"); if (dataset.equals("hotel")) { bw.write("WEN_SFHOT;"); } else { bw.write("WEN_SFRES;"); } if (!wenDaToGen.containsKey(predictedStringMRs.get(i).trim().toLowerCase())) { System.out.println(wenDaToGen.keySet()); System.out.println(predictedStringMRs.get(i).trim().toLowerCase()); System.exit(0); } out = wenDaToGen.get(predictedStringMRs.get(i).trim().toLowerCase()).replaceAll(" i ", " I ").replaceAll(" -ly ", "ly ").replaceAll(" s ", "s ").replaceAll("\\?", " \\? ").replaceAll(":", " : ").replaceAll("\\.", " \\. ").replaceAll(",", " , ").replaceAll(" ", " "); out = out.substring(0, 1).toUpperCase() + out.substring(1); bw.write(out + ";");*/ //bw.write("@@judgeFluency@@-1"); //bw.write("@@judgeInform@@-1"); //bw.write("@@judgeQuality@@-1"); bw.write("\n"); } catch (IOException e) { System.err.println("Write error!"); } } try { bw.close(); } catch (IOException e) { System.err.println("Error closing file."); } catch (Exception e) { } } return bleuScore; }
From source file:org.unitime.timetable.action.PersonalizedExamReportAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PersonalizedExamReportForm myForm = (PersonalizedExamReportForm) form; String back = (String) request.getSession().getAttribute("loginPage"); if (back == null) back = "back"; try {/*from www . j a v a2 s. co m*/ sessionContext.checkPermission(Right.PersonalSchedule); } catch (AccessDeniedException e) { request.setAttribute("message", e.getMessage()); return mapping.findForward(back); } if (request.getParameter("q") != null) { String[] params = QueryEncoderBackend.decode(request.getParameter("q")).split(":"); if (params != null && params.length == 2) { myForm.setUid(params[0]); myForm.setSessionId(Long.valueOf(params[1])); } } String externalId = sessionContext.getUser().getExternalUserId(); String userName = sessionContext.getUser().getName(); myForm.setAdmin(sessionContext.hasPermission(Right.PersonalScheduleLookup)); myForm.setLogout(!"back".equals(back)); if (sessionContext.hasPermission(Right.PersonalScheduleLookup) && myForm.getUid() != null && !myForm.getUid().isEmpty()) { externalId = myForm.getUid(); userName = (myForm.getLname() == null || myForm.getLname().length() == 0 ? "" : " " + Constants.toInitialCase(myForm.getLname())) + (myForm.getFname() == null || myForm.getFname().length() == 0 ? "" : " " + myForm.getFname().substring(0, 1).toUpperCase()) + (myForm.getMname() == null || myForm.getMname().length() == 0 ? "" : " " + myForm.getMname().substring(0, 1).toUpperCase()); } if (externalId == null || externalId.length() == 0) { request.setAttribute("message", "No user id provided."); return mapping.findForward(back); } if ("Log Out".equals(myForm.getOp())) { SecurityContextHolder.getContext().setAuthentication(null); return mapping.findForward(back); } if ("classes".equals(back)) { if (myForm.getSessionId() == null) { myForm.setSessionId((Long) request.getSession().getAttribute("Classes.session")); } else { request.getSession().setAttribute("Classes.session", myForm.getSessionId()); } } else if ("exams".equals(back)) { if (myForm.getSessionId() == null) { myForm.setSessionId((Long) request.getSession().getAttribute("Exams.session")); } else { request.getSession().setAttribute("Exams.session", myForm.getSessionId()); } } HashSet<Session> sessions = new HashSet(); DepartmentalInstructor instructor = null; for (Iterator i = new DepartmentalInstructorDAO().getSession() .createQuery("select i from DepartmentalInstructor i where i.externalUniqueId=:externalId") .setString("externalId", translate(externalId, Source.Staff)).setCacheable(true).list() .iterator(); i.hasNext();) { DepartmentalInstructor s = (DepartmentalInstructor) i.next(); if (!canDisplay(s.getDepartment().getSession())) continue; sessions.add(s.getDepartment().getSession()); if (myForm.getSessionId() == null) { if (instructor == null || instructor.getDepartment().getSession().compareTo(s.getDepartment().getSession()) < 0) instructor = s; } else if (myForm.getSessionId().equals(s.getDepartment().getSession().getUniqueId())) { instructor = s; } } Student student = null; for (Iterator i = new StudentDAO().getSession() .createQuery("select s from Student s where s.externalUniqueId=:externalId") .setString("externalId", translate(externalId, Source.Student)).setCacheable(true).list() .iterator(); i.hasNext();) { Student s = (Student) i.next(); if (!canDisplay(s.getSession())) continue; sessions.add(s.getSession()); if (myForm.getSessionId() == null) { if (student == null || student.getSession().compareTo(s.getSession()) < 0) student = s; } else if (myForm.getSessionId().equals(s.getSession().getUniqueId())) student = s; } if (instructor == null && student == null) { if (myForm.getAdmin()) { back = "back"; myForm.setLogout(false); } else { if ("classes".equals(back)) request.setAttribute("message", "No classes found."); else if ("exams".equals(back)) request.setAttribute("message", "No examinations found."); else request.setAttribute("message", "No schedule found."); sLog.info("No matching instructor or student found for " + userName + " (" + translate(externalId, Source.Student) + "), forwarding back (" + back + ")."); return mapping.findForward(back); } } myForm.setCanExport(false); if (instructor != null && student != null && !instructor.getDepartment().getSession().equals(student.getSession())) { if (instructor.getDepartment().getSession().compareTo(student.getSession()) < 0) instructor = null; else student = null; } long t0 = System.currentTimeMillis(); if (instructor != null) { sLog.info("Requesting schedule for " + instructor.getName(DepartmentalInstructor.sNameFormatShort) + " (instructor)"); } else if (student != null) { sLog.info("Requesting schedule for " + student.getName(DepartmentalInstructor.sNameFormatShort) + " (student)"); } HashSet<ExamOwner> studentExams = new HashSet<ExamOwner>(); if (student != null) { /* for (Iterator i=student.getClassEnrollments().iterator();i.hasNext();) { StudentClassEnrollment sce = (StudentClassEnrollment)i.next(); studentExams.addAll(Exam.findAllRelated("Class_", sce.getClazz().getUniqueId())); } */ studentExams.addAll(new ExamDAO().getSession().createQuery( "select distinct o from Student s inner join s.classEnrollments ce, ExamOwner o inner join o.course co " + "inner join co.instructionalOffering io " + "inner join io.instrOfferingConfigs ioc " + "inner join ioc.schedulingSubparts ss " + "inner join ss.classes c where " + "s.uniqueId=:studentId and c=ce.clazz and (" + "(o.ownerType=" + ExamOwner.sOwnerTypeCourse + " and o.ownerId=co.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeOffering + " and o.ownerId=io.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeConfig + " and o.ownerId=ioc.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeClass + " and o.ownerId=c.uniqueId) " + ")") .setLong("studentId", student.getUniqueId()).setCacheable(true).list()); for (Iterator<ExamOwner> i = studentExams.iterator(); i.hasNext();) { Exam exam = i.next().getExam(); DepartmentStatusType type = exam.effectiveStatusType(); if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal ? DepartmentStatusType.Status.ReportExamsFinal : DepartmentStatusType.Status.ReportExamsMidterm)) i.remove(); } } HashSet<Exam> instructorExams = new HashSet<Exam>(); if (instructor != null) { instructorExams.addAll(instructor.getAllExams()); for (Iterator<Exam> i = instructorExams.iterator(); i.hasNext();) { Exam exam = i.next(); DepartmentStatusType type = exam.effectiveStatusType(); if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal ? DepartmentStatusType.Status.ReportExamsFinal : DepartmentStatusType.Status.ReportExamsMidterm)) i.remove(); } } WebTable.setOrder(sessionContext, "exams.o0", request.getParameter("o0"), 1); WebTable.setOrder(sessionContext, "exams.o1", request.getParameter("o1"), 1); WebTable.setOrder(sessionContext, "exams.o2", request.getParameter("o2"), 1); WebTable.setOrder(sessionContext, "exams.o3", request.getParameter("o3"), 1); WebTable.setOrder(sessionContext, "exams.o4", request.getParameter("o4"), 1); WebTable.setOrder(sessionContext, "exams.o5", request.getParameter("o5"), 1); WebTable.setOrder(sessionContext, "exams.o6", request.getParameter("o6"), 1); WebTable.setOrder(sessionContext, "exams.o7", request.getParameter("o7"), 1); boolean hasClasses = false; if (student != null && student.getSession().canNoRoleReportClass() && !student.getClassEnrollments().isEmpty()) { PdfWebTable table = getStudentClassSchedule(true, student); if (!table.getLines().isEmpty()) { request.setAttribute("clsschd", table.printTable(WebTable.getOrder(sessionContext, "exams.o6"))); hasClasses = true; myForm.setCanExport(true); } } if (instructor != null && instructor.getDepartment().getSession().canNoRoleReportClass()) { PdfWebTable table = getInstructorClassSchedule(true, instructor); if (!table.getLines().isEmpty()) { request.setAttribute("iclsschd", table.printTable(Math.abs(WebTable.getOrder(sessionContext, "exams.o7")))); hasClasses = true; myForm.setCanExport(true); } } if (instructor != null && sessions.size() > 1) { PdfWebTable table = getSessions(true, sessions, instructor.getName(DepartmentalInstructor.sNameFormatLastFist), instructor.getDepartment().getSession().getUniqueId()); request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0"))); } else if (student != null && sessions.size() > 1) { PdfWebTable table = getSessions(true, sessions, student.getName(DepartmentalInstructor.sNameFormatLastFist), student.getSession().getUniqueId()); request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0"))); } if (!hasClasses && instructorExams.isEmpty() && studentExams.isEmpty()) { if ("classes".equals(back)) myForm.setMessage("No classes found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if ("exams".equals(back)) myForm.setMessage("No examinations found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if (student != null || instructor != null) myForm.setMessage("No classes or examinations found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if (sessionContext.hasPermission(Right.PersonalScheduleLookup)) myForm.setMessage( "No classes or examinations found in " + SessionDAO.getInstance() .get(sessionContext.getUser().getCurrentAcademicSessionId()).getLabel() + "."); else myForm.setMessage("No classes or examinations found for " + userName + "."); sLog.info("No classes or exams found for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName)); } boolean useCache = ApplicationProperty.ExaminationCacheConflicts.isTrue(); if ("Export PDF".equals(myForm.getOp())) { sLog.info(" Generating PDF for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student.getName(DepartmentalInstructor.sNameFormatShort))); OutputStream out = ExportUtils.getPdfOutputStream(response, "schedule"); if (!instructorExams.isEmpty()) { TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (Exam exam : instructorExams) { if (exam.getAssignedPeriod() == null) continue; exams.add(new ExamAssignmentInfo(exam, useCache)); } InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out, instructor.getDepartment().getSession(), null, null, exams); ir.setM2d(true); ir.setDirect(true); ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass()); ir.printHeader(); ir.printReport(ExamInfo.createInstructorInfo(instructor), exams); ir.lastPage(); ir.close(); } else if (!studentExams.isEmpty()) { TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); TreeSet<ExamSectionInfo> sections = new TreeSet<ExamSectionInfo>(); for (ExamOwner examOwner : studentExams) { if (examOwner.getExam().getAssignedPeriod() == null) continue; ExamAssignmentInfo x = new ExamAssignmentInfo(examOwner, student, studentExams); exams.add(x); sections.addAll(x.getSectionsIncludeCrosslistedDummies()); } StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out, student.getSession(), null, null, exams); sr.setM2d(true); sr.setBtb(true); sr.setDirect(true); sr.setClassSchedule(student.getSession().canNoRoleReportClass()); sr.printHeader(); sr.printReport(student, sections); sr.lastPage(); sr.close(); } else if (hasClasses) { if (instructor != null) { InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out, instructor.getDepartment().getSession(), null, null, new TreeSet<ExamAssignmentInfo>()); ir.setM2d(true); ir.setDirect(true); ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass()); ir.printHeader(); ir.printReport(ExamInfo.createInstructorInfo(instructor), new TreeSet<ExamAssignmentInfo>()); ir.lastPage(); ir.close(); } else if (student != null) { StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out, student.getSession(), null, null, new TreeSet<ExamAssignmentInfo>()); sr.setM2d(true); sr.setBtb(true); sr.setDirect(true); sr.setClassSchedule(student.getSession().canNoRoleReportClass()); sr.printHeader(); sr.printReport(student, new TreeSet<ExamSectionInfo>()); sr.lastPage(); sr.close(); } } out.flush(); out.close(); return null; } if ("iCalendar".equals(myForm.getOp())) { Long sid = (instructor != null ? instructor.getDepartment().getSession().getUniqueId() : student.getSession().getUniqueId()); response.sendRedirect(response.encodeURL("export?q=" + QueryEncoderBackend.encode( "output=events.ics&type=person&ext=" + externalId + (sid == null ? "" : "&sid=" + sid)))); return null; } /* if ("iCalendar".equals(myForm.getOp())) { sLog.info(" Generating calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort))); try { File file = ApplicationProperties.getTempFile("schedule", "ics"); if (instructor!=null) { printInstructorSchedule(file, instructor, instructorExams); } else { printStudentSchedule(file, student, studentExams); } request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+file.getName()); } catch (Exception e) { sLog.error("Unable to generate calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort)),e); } } */ if (!studentExams.isEmpty()) { myForm.setCanExport(true); TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (ExamOwner examOwner : studentExams) exams.add(new ExamAssignmentInfo(examOwner, student, studentExams)); PdfWebTable table = getStudentExamSchedule(true, exams, student); request.setAttribute("schedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o1"))); table = getStudentConflits(true, exams, student); if (!table.getLines().isEmpty()) request.setAttribute("conf", table.printTable(WebTable.getOrder(sessionContext, "exams.o3"))); } if (!instructorExams.isEmpty()) { myForm.setCanExport(true); TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (Exam exam : instructorExams) exams.add(new ExamAssignmentInfo(exam, useCache)); PdfWebTable table = getInstructorExamSchedule(true, exams, instructor); request.setAttribute("ischedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o2"))); table = getInstructorConflits(true, exams, instructor); if (!table.getLines().isEmpty()) request.setAttribute("iconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o4"))); table = getStudentConflits(true, exams, instructor); if (!table.getLines().isEmpty()) request.setAttribute("sconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o5"))); } long t1 = System.currentTimeMillis(); sLog.info("Request processed in " + new DecimalFormat("0.00").format(((double) (t1 - t0)) / 1000.0) + " s for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName)); return mapping.findForward("show"); }
From source file:com.android.launcher3.Launcher.java
/** * Some shortcuts were updated in the background. * Implementation of the method from LauncherModel.Callbacks. * * @param updated list of shortcuts which have changed. * @param removed list of shortcuts which were deleted in the background. This can happen when * an app gets removed from the system or some of its components are no longer * available./* w w w.ja v a 2s . c o m*/ */ @Override public void bindShortcutsChanged(final ArrayList<ShortcutInfo> updated, final ArrayList<ShortcutInfo> removed, final UserHandleCompat user) { Runnable r = new Runnable() { public void run() { bindShortcutsChanged(updated, removed, user); } }; if (waitUntilResume(r)) { return; } if (!updated.isEmpty()) { mWorkspace.updateShortcuts(updated); } if (!removed.isEmpty()) { HashSet<ComponentName> removedComponents = new HashSet<>(); HashSet<ShortcutKey> removedDeepShortcuts = new HashSet<>(); for (ShortcutInfo si : removed) { if (si.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT) { removedDeepShortcuts.add(ShortcutKey.fromShortcutInfo(si)); } else { removedComponents.add(si.getTargetComponent()); } } if (!removedComponents.isEmpty()) { ItemInfoMatcher matcher = ItemInfoMatcher.ofComponents(removedComponents, user); mWorkspace.removeItemsByMatcher(matcher); mDragController.onAppsRemoved(matcher); } if (!removedDeepShortcuts.isEmpty()) { ItemInfoMatcher matcher = ItemInfoMatcher.ofShortcutKeys(removedDeepShortcuts); mWorkspace.removeItemsByMatcher(matcher); mDragController.onAppsRemoved(matcher); } } }