/** * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding * channel bundle. */ void closeTransportManager(TransportManager transportManager) { synchronized (transportManagers) { for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator(); i.hasNext(); ) { if (i.next() == transportManager) { i.remove(); // Presumably, we have a single association for // transportManager. break; } } // Close manager try { transportManager.close(); } catch (Throwable t) { logger.warn( "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t); // The whole point of explicitly closing the // transportManagers of this Conference is to prevent memory // leaks. Hence, it does not make sense to possibly leave // TransportManagers open because a TransportManager has // failed to close. if (t instanceof InterruptedException) Thread.currentThread().interrupt(); else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } }
private int distancia_aux( Map<String, Ligacao> ligacoes, DijElem elemAct, HashMap<String, DijElem> elementos, int greycount) { Collection<Ligacao> coll = ligacoes.values(); int grey = greycount; for (Ligacao lig : coll) { DijElem target = elementos.get(lig.get_Localidaded()); if (target != null && (target.get_Vis() != _VIS_BLACK) && (target.get_Nrlocalidades() > (elemAct.get_Nrlocalidades() + 1))) { target.set_Nrlocalidades(elemAct.get_Nrlocalidades() + 1); target.set_Pai(elemAct.get_Nome()); } else if (target == null) { target = new DijElem( lig.get_Localidaded(), elemAct.get_Nrlocalidades() + 1, elemAct.get_Nome(), _VIS_GREY); grey++; elementos.put(lig.get_Localidaded(), target.clone()); } } return grey; }
private String findPrefix(Map<String, String> properties) { Map<String, Integer> prefixes = new HashMap<String, Integer>(); for (String value : properties.values()) { if (value.length() > 3) { String testPrefix = value.substring(0, 3); if (prefixes.containsKey(testPrefix)) { Integer currentValue = prefixes.get(testPrefix); prefixes.put(testPrefix, currentValue + 1); } else { prefixes.put(testPrefix, 1); } } } String probablePrefix = biggestPrefix(prefixes); return searchEntirePrefix(probablePrefix, properties.values()); }
/** Associate Advice to all n-cubes that match the passed in regular expression. */ public static void addAdvice(ApplicationID appId, String wildcard, Advice advice) { validateAppId(appId); ConcurrentMap<String, Advice> current = advices.get(appId); if (current == null) { current = new ConcurrentHashMap<>(); ConcurrentMap<String, Advice> mapRef = advices.putIfAbsent(appId, current); if (mapRef != null) { current = mapRef; } } current.put(advice.getName() + '/' + wildcard, advice); // Apply newly added advice to any fully loaded (hydrated) cubes. String regex = StringUtilities.wildcardToRegexString(wildcard); Map<String, Object> cubes = getCacheForApp(appId); for (Object value : cubes.values()) { if (value instanceof NCube) { // apply advice to hydrated cubes NCube ncube = (NCube) value; Axis axis = ncube.getAxis("method"); addAdviceToMatchedCube(advice, regex, ncube, axis); } } }
private void exportParameters() { synchronized (exported_parameters) { if (!exported_parameters_dirty) { return; } exported_parameters_dirty = false; try { TreeMap<String, String> tm = new TreeMap<String, String>(); Set<String> exported_keys = new HashSet<String>(); for (String[] entry : exported_parameters.values()) { String key = entry[0]; String value = entry[1]; exported_keys.add(key); if (value != null) { tm.put(key, value); } } for (Map.Entry<String, String> entry : imported_parameters.entrySet()) { String key = entry.getKey(); if (!exported_keys.contains(key)) { tm.put(key, entry.getValue()); } } File parent_dir = new File(SystemProperties.getUserPath()); File props = new File(parent_dir, "exported_params.properties"); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(props), "UTF-8")); try { for (Map.Entry<String, String> entry : tm.entrySet()) { pw.println(entry.getKey() + "=" + entry.getValue()); } } finally { pw.close(); } } catch (Throwable e) { e.printStackTrace(); } } }
public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(0); // reserved for future expansion (version id) out.writeShort(fieldNumber); if (header != null) writeHeader(out); if (packager != null) writePackager(out); if (direction > 0) writeDirection(out); // List keySet = new ArrayList (fields.keySet()); // Collections.sort (keySet); Iterator iter = fields.values().iterator(); while (iter.hasNext()) { ISOComponent c = (ISOComponent) iter.next(); if (c instanceof ISOMsg) { writeExternal(out, 'M', c); } else if (c instanceof ISOBinaryField) { writeExternal(out, 'B', c); } else if (c instanceof ISOAmount) { writeExternal(out, 'A', c); } else if (c instanceof ISOField) { writeExternal(out, 'F', c); } } out.writeByte('E'); }
public static void shutdown() { logger_.info("Shutting down ..."); synchronized (MessagingService.class) { /* Stop listening on any socket */ for (SelectionKey skey : listenSockets_.values()) { SelectorManager.getSelectorManager().cancel(skey); } listenSockets_.clear(); /* Shutdown the threads in the EventQueue's */ messageDeserializationExecutor_.shutdownNow(); messageSerializerExecutor_.shutdownNow(); messageDeserializerExecutor_.shutdownNow(); streamExecutor_.shutdownNow(); /* shut down the cachetables */ taskCompletionMap_.shutdown(); callbackMap_.shutdown(); /* Interrupt the selector manager thread */ SelectorManager.getSelectorManager().interrupt(); poolTable_.clear(); verbHandlers_.clear(); bShutdown_ = true; } logger_.debug("Shutdown invocation complete."); }
/** * Copia los archivos a utilizar por una aplicación, en el directorio de trabajos de tdderive, * comprime tales archivos y los divide dejando los resultados de ambas acciones en sus * directorios correspondientes. * <li>Registra los archivos de la tarea. * <li>Si se debe exportar se crea un directorio cuyo nombre será * <tt>"tarea"+MilisegundosDesde1ºEnero1970</tt>. * <li>Si se exporta, se exportan los archivos bloque por bloque, asi que aquí se indica el nombre * de cada bloque. * <li>Si no se exporta, entonces no se indican bloques, pero se indica que cada archivo está * local. * * @throws ADMINExcepcion Si error. * @throws OIExcepcion Si error. */ protected void ubicaArchivos() throws OIExcepcion, ADMINGLOExcepcion { int i = 0, idx = 0; String cNombreArchivo, cNombreComprimido, cBloque; tdutils.SplitInfo[] acBloques; PERSCoordinacion.Archivos archivoI, archivoII = null; File fArchivo = null; Iterator itr; Map mpArchivosACargar = new TreeMap(String.CASE_INSENSITIVE_ORDER); mpArchivosACargar.putAll(mpArchivos); mpArchivos.clear(); itr = mpArchivosACargar.values().iterator(); while (itr.hasNext()) { archivoI = (PERSCoordinacion.Archivos) itr.next(); cNombreArchivo = archivoI.getRutaOriginal(); fArchivo = new File(cNombreArchivo); // el archivo o directorio sí existe // se comprime en directorio de comprimidos cNombreComprimido = tarea.getComprimidosDir() + "/" + archivoI.getNombre(); try { Zip.zipFile(cNombreComprimido, cNombreArchivo); } catch (IOException ex) { throw new ADMINGLOExcepcion("No se pudo comprimir archivo.", ex); } archivoII = new PERSCoordinacion.Archivos(this.info); archivoII.setNombre(archivoI.getNombre()); archivoII.setInfoArchivo(archivoI.getInfoArchivo()); archivoII.setSiLocal(false); archivoII.setEstadoArchivo(ADMINAPPIArchivos.ARCHIVO_PRESENTE); // prepara lista de archivos a exportar mpArchivos.put(archivoII.getNombre(), archivoII); } }
/** * {@inheritDoc} * * @param ctx */ @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException { super.prepareMarshal(ctx); if (ownedVals != null) { ownedValKeys = ownedVals.keySet(); ownedValVals = ownedVals.values(); for (Map.Entry<IgniteTxKey, CacheVersionedValue> entry : ownedVals.entrySet()) { GridCacheContext cacheCtx = ctx.cacheContext(entry.getKey().cacheId()); entry.getKey().prepareMarshal(cacheCtx); entry.getValue().prepareMarshal(cacheCtx.cacheObjectContext()); } } if (retVal != null && retVal.cacheId() != 0) { GridCacheContext cctx = ctx.cacheContext(retVal.cacheId()); assert cctx != null : retVal.cacheId(); retVal.prepareMarshal(cctx); } if (filterFailedKeys != null) { for (IgniteTxKey key : filterFailedKeys) { GridCacheContext cctx = ctx.cacheContext(key.cacheId()); key.prepareMarshal(cctx); } } }
/** * Returns the file representing the Git repository directory for the given file path or any of * its parent in the filesystem. If the file doesn't exits, is not a Git repository or an error * occurred while transforming the given path into a store <code>null</code> is returned. * * @param path expected format /file/{Workspace}/{projectName}[/{path}] * @return the .git folder if found or <code>null</code> the give path cannot be resolved to a * file or it's not under control of a git repository * @throws CoreException */ public static File getGitDir(IPath path) throws CoreException { Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.GO_UP); if (gitDirs == null) return null; Collection<File> values = gitDirs.values(); if (values.isEmpty()) return null; return values.toArray(new File[] {})[0]; }
/** Metodo que escreve os clientes num ficheiro */ public void escreveLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades) throws FileNotFoundException, IOException { PrintWriter printloc = new PrintWriter(fileLocalidades); PrintWriter printlig = new PrintWriter(fileLigacoes); Collection<Localidade> coll = this.localidades.values(); for (Localidade l : coll) { printloc.print(l.get_Codigopostal() + "|" + l.get_Nome()); Map<String, Ligacao> ligacoes = l.get_Ligacoes(); int nrligacoes = ligacoes.size(); Collection<Ligacao> colllig = ligacoes.values(); for (Ligacao lig : colllig) { printloc.print("|1"); printlig.println( l.get_Codigopostal() + "|" + lig.get_Localidaded() + "|" + lig.get_Distancia() + "|" + lig.get_Taxas()); } printloc.print("\n"); nrlocalidades--; if (nrlocalidades == 0) break; } printloc.close(); printlig.close(); }
static { try { Map<String, Method> orderedMethods = new TreeMap<String, Method>(); for (Method m : MBeanServerConnection.class.getDeclaredMethods()) { orderedMethods.put(m.toGenericString(), m); } Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]); Map<String, Method> asynchMethods = new TreeMap<String, Method>(); for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) { asynchMethods.put(asynchMethod.getName(), asynchMethod); } Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length); Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length); Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length); for (int i = 0; i < methods.length; i++) { m2k.put(methods[i], (byte) i); k2m.put((byte) i, methods[i]); Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response"); if (asynchMethod == null) throw new RuntimeException( "Failed to find asynch handler for [" + methods[i].toGenericString() + "]", new Throwable()); k2am.put((byte) i, asynchMethod); } methodToKey = Collections.unmodifiableMap(m2k); keyToMethod = Collections.unmodifiableMap(k2m); keyToAsynchMethod = Collections.unmodifiableMap(k2am); } catch (Exception ex) { throw new RuntimeException(ex); } }
/** * Return the number of TdbTitles in this Tdb. * * @return the total TdbTitle count */ public int getTdbTitleCount() { int titleCount = 0; for (TdbPublisher publisher : tdbPublisherMap.values()) { titleCount += publisher.getTdbTitleCount(); } return titleCount; }
/** * Add TdbAus for like (starts with) the specified TdbAu name. * * @param tdbAuName the name of the AU to select * @param tdbAus the collection to add to * @return <code>true</code> if TdbAus were added to the collection */ public boolean getTdbAusLikeName(String tdbAuName, Collection<TdbAu> aus) { boolean added = false; for (TdbPublisher publisher : tdbPublisherMap.values()) { added |= publisher.getTdbAusLikeName(tdbAuName, aus); } return added; }
/** * Finds conference for given ID assigned by the reservation system. * * @param id identifier of the conference to find. * @return <tt>Conference</tt> for given <tt>id</tt> or <tt>null</tt> if not found. */ private Conference findConferenceForId(Number id) { for (Conference conference : conferenceMap.values()) { if (conference.getId().equals(id)) { return conference; } } return null; }
/** * For the class return all implemented interfaces including the superinterfaces of the * implementing interfaces, also iterate over for all the superclasses. For interface return all * the extended interfaces as well as superinterfaces for those extended interfaces. * * @param type type whose implemented or super interfaces are sought. * @param configuration the current configuration of the doclet. * @param sort if true, return list of interfaces sorted alphabetically. * @return List of all the required interfaces. */ public static List<Type> getAllInterfaces(Type type, Configuration configuration, boolean sort) { Map<ClassDoc, Type> results = sort ? new TreeMap<ClassDoc, Type>() : new LinkedHashMap<ClassDoc, Type>(); Type[] interfaceTypes = null; Type superType = null; if (type instanceof ParameterizedType) { interfaceTypes = ((ParameterizedType) type).interfaceTypes(); superType = ((ParameterizedType) type).superclassType(); } else if (type instanceof ClassDoc) { interfaceTypes = ((ClassDoc) type).interfaceTypes(); superType = ((ClassDoc) type).superclassType(); } else { interfaceTypes = type.asClassDoc().interfaceTypes(); superType = type.asClassDoc().superclassType(); } for (int i = 0; i < interfaceTypes.length; i++) { Type interfaceType = interfaceTypes[i]; ClassDoc interfaceClassDoc = interfaceType.asClassDoc(); if (!(interfaceClassDoc.isPublic() || (configuration == null || isLinkable(interfaceClassDoc, configuration)))) { continue; } results.put(interfaceClassDoc, interfaceType); List<Type> superInterfaces = getAllInterfaces(interfaceType, configuration, sort); for (Iterator<Type> iter = superInterfaces.iterator(); iter.hasNext(); ) { Type t = iter.next(); results.put(t.asClassDoc(), t); } } if (superType == null) return new ArrayList<Type>(results.values()); // Try walking the tree. addAllInterfaceTypes( results, superType, superType instanceof ClassDoc ? ((ClassDoc) superType).interfaceTypes() : ((ParameterizedType) superType).interfaceTypes(), false, configuration); List<Type> resultsList = new ArrayList<Type>(results.values()); if (sort) { Collections.sort(resultsList, new TypeComparator()); } return resultsList; }
private void showExternalDownloadItems() { final Map<String, FcpPersistentGet> items = persistentQueue.getDownloadRequests(); for (final FcpPersistentGet downloadRequest : items.values()) { if (!downloadModelItems.containsKey(downloadRequest.getIdentifier())) { addExternalItem(downloadRequest); } } }
public void iterateFileNames(IndexEntriesWalkerInterruptable iproc) { for (FileEntitiesHolder d : files.values()) { // iproc.process(d.getPath(), Long.toString(d.timeStamp)); if (!iproc.process(d.getPath(), d.value)) { return; } } }
/** * Adds to a collection of TdbTitles like (starts with) the specified title name across all * publishers. * * @param titleName the title name * @param titles a collection of matching titles * @return a collection of TdbTitles that match the title name */ public boolean getTdbTitlesLikeName(String titleName, Collection<TdbTitle> titles) { boolean added = false; if (titleName != null) { for (TdbPublisher publisher : tdbPublisherMap.values()) { added |= publisher.getTdbTitlesLikeName(titleName, titles); } } return added; }
/** * Removes contributions and commands that are older than CONTRIBUTION_TIMEOUT and COMMAND_TIMEOUT * respectively. */ private void removeOldStuff() { final long current = System.currentTimeMillis(); synchronized (cache) { Iterator i = cache.values().iterator(); while (i.hasNext()) { ContributionBox cb = (ContributionBox) i.next(); if (current - cb.timeStamp > CONTRIBUTION_TIMEOUT) i.remove(); } } synchronized (commands) { Iterator i = commands.values().iterator(); while (i.hasNext()) { Long t = (Long) i.next(); if (current - t.longValue() > COMMAND_TIMEOUT) i.remove(); } } }
public void clean() { myProjectBuilder.clean(); for (ModuleWrapper m : myModules.values()) { m.updateOutputStatus(); } new File(myProjectSnapshot).delete(); }
/** Add to a collection of TdbAus for this TDB that match the ISBN. */ public boolean getTdbAusByIsbn(String isbn, Collection<TdbAu> matchingTdbAus) { boolean added = false; if (isbn != null) { for (TdbPublisher tdbPublisher : tdbPublisherMap.values()) { added |= tdbPublisher.getTdbAusByIsbn(matchingTdbAus, isbn); } } return added; }
/** * Returns known contributions in an unmodifiable list. The list contains at most {@link * #MAX_CACHE_SIZE} random elements from the contribution repository. Might return the same list * when called again if there is two little time between the calls. The dynamic type of elements * is ContributionBox. It is safe to call it frequently. Threads should care of synchronization * when iterating over it. */ public synchronized List getContributions() { List o = cacheCollection; if (o == null) { o = Collections.unmodifiableList(new ArrayList(cache.values())); cacheCollection = o; } return o; }
public static void main(String[] args) throws InterruptedException { Set<String> logMessages = new HashSet<String>(); Map<String, Boolean> serviceMap = new HashMap<String, Boolean>(); serviceMap.put("OracleMTSRecoveryService", Boolean.TRUE); serviceMap.put("OracleOraDb11g_home1TNSListener", Boolean.TRUE); serviceMap.put("OracleServiceORCL", Boolean.TRUE); long wait = 0; // stop all related services. while (serviceMap.values().contains(Boolean.TRUE)) { wait = wait + 4000; for (Iterator<String> itKey = serviceMap.keySet().iterator(); itKey.hasNext(); ) { String serviceName = (String) itKey.next(); if (isServiceRunning(serviceName)) { System.out.println("stoping service " + serviceName); stopService(serviceName); Thread.sleep(wait); } else { logMessages.add("the service " + serviceName + " is off."); serviceMap.put(serviceName, Boolean.FALSE); } } } printLogs(logMessages); // stop all related services. wait = 0; logMessages = new HashSet<String>(); while (serviceMap.values().contains(Boolean.FALSE)) { wait = wait + 10000; for (Iterator<String> itKey = serviceMap.keySet().iterator(); itKey.hasNext(); ) { String serviceName = (String) itKey.next(); if (!isServiceRunning(serviceName)) { System.out.println("starting service " + serviceName); startService(serviceName); Thread.sleep(wait); } else { logMessages.add("the service " + serviceName + " is on."); serviceMap.put(serviceName, Boolean.TRUE); } } } printLogs(logMessages); System.out.println("End of the procces."); }
public void print(String prefix, PrintStream out) { super.print(prefix, out); out.println(prefix + "{"); String orgPrefix = prefix; prefix += " "; for (Tag tag : tags.values()) { tag.print(prefix, out); } out.println(orgPrefix + "}"); }
public QuickFixAction[] extractActiveFixes( final RefEntity[] refElements, final Map<RefEntity, Set<QuickFix>> actions) { if (refElements == null) return null; Map<Class, QuickFixAction> result = new java.util.HashMap<Class, QuickFixAction>(); for (RefEntity refElement : refElements) { final Set<QuickFix> localQuickFixes = actions.get(refElement); if (localQuickFixes != null) { for (QuickFix fix : localQuickFixes) { if (fix == null) continue; final Class klass = fix instanceof IntentionWrapper ? ((IntentionWrapper) fix).getAction().getClass() : fix.getClass(); final QuickFixAction quickFixAction = result.get(klass); if (quickFixAction != null) { try { String familyName = fix.getFamilyName(); familyName = familyName != null && familyName.length() > 0 ? "\'" + familyName + "\'" : familyName; ((LocalQuickFixWrapper) quickFixAction) .setText( InspectionsBundle.message( "inspection.descriptor.provider.apply.fix", familyName)); } catch (AbstractMethodError e) { // for plugin compatibility ((LocalQuickFixWrapper) quickFixAction) .setText( InspectionsBundle.message("inspection.descriptor.provider.apply.fix", "")); } } else { LocalQuickFixWrapper quickFixWrapper = new LocalQuickFixWrapper(fix, this); result.put(klass, quickFixWrapper); } } } } return result.values().isEmpty() ? null : result.values().toArray(new QuickFixAction[result.size()]); }
/** Closes the {@link #transportManagers} of this <tt>Conference</tt>. */ private void closeTransportManagers() { synchronized (transportManagers) { for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator(); i.hasNext(); ) { IceUdpTransportManager transportManager = i.next(); i.remove(); closeTransportManager(transportManager); } } }
/** * @param cls Component class. * @param <T> Component type. * @return Component class instance or {@code null} if no one plugin override this component. */ public <T> T createComponent(Class<T> cls) { for (PluginProvider plugin : plugins.values()) { PluginContext ctx = pluginContextForProvider(plugin); T comp = (T) plugin.createComponent(ctx, cls); if (comp != null) return comp; } return null; }
void loadKeyStores() { List<LockssKeyStore> lst = new ArrayList<LockssKeyStore>(keystoreMap.values()); for (LockssKeyStore lk : lst) { try { lk.load(); } catch (Exception e) { log.error("Can't load keystore " + lk.getName(), e); keystoreMap.remove(lk.getName()); } } }
@Override @NotNull public VirtualFile[] getRoots() { myRootsLock.readLock().lock(); try { Collection<VirtualFileSystemEntry> roots = myRoots.values(); return VfsUtilCore.toVirtualFileArray(roots); } finally { myRootsLock.readLock().unlock(); } }