/** {@inheritDoc} */ @Override public Map<K, V> peekAll( @Nullable Collection<? extends K> keys, @Nullable GridPredicate<? super GridCacheEntry<K, V>>[] filter) { if (keys == null || keys.isEmpty()) return emptyMap(); final Collection<K> skipped = new GridLeanSet<K>(); final Map<K, V> map = peekAll0(keys, filter, skipped); if (map.size() + skipped.size() != keys.size()) { map.putAll( dht.peekAll( F.view( keys, new P1<K>() { @Override public boolean apply(K k) { return !map.containsKey(k) && !skipped.contains(k); } }), filter)); } return map; }
public List<ShelvedChangeList> importChangeLists( final Collection<VirtualFile> files, final Consumer<VcsException> exceptionConsumer) { final List<ShelvedChangeList> result = new ArrayList<ShelvedChangeList>(files.size()); try { final FilesProgress filesProgress = new FilesProgress(files.size(), "Processing "); for (VirtualFile file : files) { filesProgress.updateIndicator(file); final String description = file.getNameWithoutExtension().replace('_', ' '); final File patchPath = getPatchPath(description); final ShelvedChangeList list = new ShelvedChangeList( patchPath.getPath(), description, new SmartList<ShelvedBinaryFile>(), file.getTimeStamp()); try { final List<TextFilePatch> patchesList = loadPatches(myProject, file.getPath(), new CommitContext()); if (!patchesList.isEmpty()) { FileUtil.copy(new File(file.getPath()), patchPath); // add only if ok to read patch myShelvedChangeLists.add(list); result.add(list); } } catch (IOException e) { exceptionConsumer.consume(new VcsException(e)); } catch (PatchSyntaxException e) { exceptionConsumer.consume(new VcsException(e)); } } } finally { notifyStateChanged(); } return result; }
/** @throws Exception If failed. */ public void testCreateFileColocated() throws Exception { GridGgfsPath path = new GridGgfsPath("/colocated"); UUID uuid = UUID.randomUUID(); GridUuid affKey; long idx = 0; while (true) { affKey = new GridUuid(uuid, idx); if (grid(0).mapKeyToNode(DATA_CACHE_NAME, affKey).id().equals(grid(0).localNode().id())) break; idx++; } try (GridGgfsOutputStream out = fs.create(path, 1024, true, affKey, 0, 1024, null)) { // Write 5M, should be enough to test distribution. for (int i = 0; i < 15; i++) out.write(new byte[1024 * 1024]); } GridGgfsFile info = fs.info(path); Collection<GridGgfsBlockLocation> affNodes = fs.affinity(path, 0, info.length()); assertEquals(1, affNodes.size()); Collection<UUID> nodeIds = F.first(affNodes).nodeIds(); assertEquals(1, nodeIds.size()); assertEquals(grid(0).localNode().id(), F.first(nodeIds)); }
/** * Deletes a very specific mapping from the replica catalog. The LFN must be matches, the PFN, and * all PFN attributes specified in the replica catalog entry. More than one entry could * theoretically be removed. Upon removal of an entry, all attributes associated with the PFN also * evaporate (cascading deletion). * * @param lfn is the logical directory in the tuple. * @param tuple is a description of the PFN and its attributes. * @return the number of removed entries, either 0 or 1. */ public int delete(String lfn, ReplicaCatalogEntry tuple) { int result = 0; if (lfn == null || tuple == null) { return result; } Collection c = (Collection) mLFNMap.get(lfn); if (c == null) { return result; } List l = new ArrayList(); for (Iterator i = c.iterator(); i.hasNext(); ) { ReplicaCatalogEntry rce = (ReplicaCatalogEntry) i.next(); if (!matchMe(rce, tuple)) { l.add(rce); } } // anything removed? if (l.size() != c.size()) { result = c.size() - l.size(); mLFNMap.put(lfn, l); } // done return result; }
public static void testDetermineMergeParticipantsAndMergeCoords4() { Address a = Util.createRandomAddress(), b = Util.createRandomAddress(), c = Util.createRandomAddress(), d = Util.createRandomAddress(); org.jgroups.util.UUID.add(a, "A"); org.jgroups.util.UUID.add(b, "B"); org.jgroups.util.UUID.add(c, "C"); org.jgroups.util.UUID.add(d, "D"); View v1 = View.create(a, 1, a, b); View v2 = View.create(c, 1, c, d); Map<Address, View> map = new HashMap<>(); map.put(a, v1); map.put(b, v1); map.put(d, v2); StringBuilder sb = new StringBuilder("map:\n"); for (Map.Entry<Address, View> entry : map.entrySet()) sb.append(entry.getKey() + ": " + entry.getValue() + "\n"); System.out.println(sb); Collection<Address> merge_participants = Util.determineMergeParticipants(map); System.out.println("merge_participants = " + merge_participants); assert merge_participants.size() == 3; assert merge_participants.contains(a) && merge_participants.contains(c) && merge_participants.contains(d); Collection<Address> merge_coords = Util.determineMergeCoords(map); System.out.println("merge_coords = " + merge_coords); assert merge_coords.size() == 2; assert merge_coords.contains(a) && merge_coords.contains(c); }
/** * @param in Object input. * @return Read collection. * @throws IOException If failed. * @throws ClassNotFoundException If failed. */ private Collection<Object> readFieldsCollection(ObjectInput in) throws IOException, ClassNotFoundException { assert fields; int size = in.readInt(); if (size == -1) return null; Collection<Object> res = new ArrayList<>(size); for (int i = 0; i < size; i++) { int size0 = in.readInt(); Collection<Object> col = new ArrayList<>(size0); for (int j = 0; j < size0; j++) col.add(in.readObject()); assert col.size() == size0; res.add(col); } assert res.size() == size; return res; }
/** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); if (writes != null) unmarshalTx(writes, false, ctx, ldr); if (reads != null) unmarshalTx(reads, false, ctx, ldr); if (grpLockKeyBytes != null && grpLockKey == null) grpLockKey = ctx.marshaller().unmarshal(grpLockKeyBytes, ldr); if (dhtVerKeys != null && dhtVers == null) { assert dhtVerVals != null; assert dhtVerKeys.size() == dhtVerVals.size(); Iterator<IgniteTxKey> keyIt = dhtVerKeys.iterator(); Iterator<GridCacheVersion> verIt = dhtVerVals.iterator(); dhtVers = U.newHashMap(dhtVerKeys.size()); while (keyIt.hasNext()) { IgniteTxKey key = keyIt.next(); key.finishUnmarshal(ctx.cacheContext(key.cacheId()), ldr); dhtVers.put(key, verIt.next()); } } if (txNodesBytes != null) txNodes = ctx.marshaller().unmarshal(txNodesBytes, ldr); }
/** * Restart of the application server : * * <p>All running services are stopped. LookupManager is flushed. * * <p>Client code that started us should notice the special return value and restart us. */ protected final void doExecute(AdminCommandContext context) { try { // unfortunately we can't rely on constructors with HK2... if (registry == null) throw new NullPointerException( new LocalStringsImpl(getClass()) .get("restart.server.internalError", "registry was not set")); init(context); if (!verbose) { // do it now while we still have the Logging service running... reincarnate(); } // else we just return a special int from System.exit() Collection<Module> modules = registry.getModules("com.sun.enterprise.osgi-adapter"); if (modules.size() == 1) { final Module mgmtAgentModule = modules.iterator().next(); mgmtAgentModule.stop(); } else context.getLogger().warning(strings.get("restart.server.badNumModules", modules.size())); } catch (Exception e) { context.getLogger().severe(strings.get("restart.server.failure", e)); } int ret = RESTART_NORMAL; if (debug != null) ret = debug ? RESTART_DEBUG_ON : RESTART_DEBUG_OFF; System.exit(ret); }
// Returns true iff all items in subset are in superset, treating null and // empty collections as // the same. public static <T> boolean isSubset(Collection<T> subset, Collection<T> superset) { if ((superset == null) || (superset.size() == 0)) { return ((subset == null) || (subset.size() == 0)); } HashSet<T> hash = new HashSet<T>(superset); for (T t : subset) { if (!hash.contains(t)) { return false; } } return true; }
public double splitQuality(int question) { double classEntropy = findEntropy(students); Collection<String[]> right = findAnswers(question, true); Collection<String[]> wrong = findAnswers(question, false); double splitEntropy = (right.size() * findEntropy(right) + wrong.size() * findEntropy(wrong)) / ((double) students.size()); // System.out.println("question " + question); // System.out.println("ce " + classEntropy + " se " + splitEntropy); // System.out.println("se " + right.size() + " ws " + wrong.size()); // System.out.println("correct " + correct); return classEntropy - splitEntropy; }
private void ConnectKnowledgeBaseBtnMouseClicked( java.awt.event.MouseEvent evt) { // GEN-FIRST:event_ConnectKnowledgeBaseBtnMouseClicked String sPrjFile = ProjectNameTF.getText().trim(); String sLocationURI = sURI + "Location"; Collection errors = new ArrayList(); Date d1 = new Date(); long l1 = d1.getTime(); prj = Project.loadProjectFromFile(sPrjFile, errors); owlModel = (OWLModel) prj.getKnowledgeBase(); kb = prj.getKnowledgeBase(); URI uri = prj.getActiveRootURI(); Collection colNumberOfInstance = kb.getInstances(); lNumberOfInstance = colNumberOfInstance.size(); Date d2 = new Date(); long l2 = d2.getTime(); lLoadedTime = (l2 - l1); theLogger.info("Connected to MySQL in " + lLoadedTime + " ms"); theLogger.info("KB has " + lNumberOfInstance + " instances"); LoggingAreaTA.append("Project has " + lNumberOfInstance + " in total\n"); LoggingAreaTA.append("Project is loaded in " + lLoadedTime + " ms\n"); } // GEN-LAST:event_ConnectKnowledgeBaseBtnMouseClicked
/** * JUnit. * * @throws Exception If failed. */ public void testGetAndIncrement() throws Exception { Collection<Long> res = new HashSet<>(); String seqName = UUID.randomUUID().toString(); for (int i = 0; i < GRID_CNT; i++) { Set<Long> retVal = compute(grid(i).cluster().forLocal()).call(new GetAndIncrementJob(seqName, RETRIES)); for (Long l : retVal) assert !res.contains(l) : "Value already was used " + l; res.addAll(retVal); } assert res.size() == GRID_CNT * RETRIES; int gapSize = 0; for (long i = 0; i < GRID_CNT * RETRIES; i++) { if (!res.contains(i)) gapSize++; else gapSize = 0; assert gapSize <= BATCH_SIZE + 1 : "Gap above id " + i + " is " + gapSize + " more than batch size: " + (BATCH_SIZE + 1); } }
/** {@inheritDoc} */ @Override protected Collection<E> dequeue0(int cnt) { WindowHolder tup = ref.get(); AtomicInteger size = tup.size(); Collection<T> evts = tup.collection(); Collection<E> resCol = new ArrayList<>(cnt); while (true) { int curSize = size.get(); if (curSize > 0) { if (size.compareAndSet(curSize, curSize - 1)) { E res = pollInternal(evts, tup.set()); if (res != null) { resCol.add(res); if (resCol.size() >= cnt) return resCol; } else { size.incrementAndGet(); return resCol; } } } else return resCol; } }
public void logFilePaths(PrintStream stream, Collection<String> paths) { List<String> strings = new ArrayList<String>(paths.size()); for (String path : paths) { strings.add(FileUtil.toSystemIndependentName(getRelativePath(path))); } logMany(stream, strings); }
public void makeSnapshots(Collection<InetAddress> endpoints) { try { snapshotLatch = new CountDownLatch(endpoints.size()); IAsyncCallback callback = new IAsyncCallback() { @Override public boolean isLatencyForSnitch() { return false; } @Override public void response(Message msg) { RepairJob.this.snapshotLatch.countDown(); } }; for (InetAddress endpoint : endpoints) MessagingService.instance() .sendRR( new SnapshotCommand(tablename, cfname, sessionName, false), endpoint, callback); snapshotLatch.await(); snapshotLatch = null; } catch (InterruptedException e) { throw new RuntimeException(e); } }
/** {@inheritDoc} */ @SuppressWarnings("TypeMayBeWeakened") @Nullable private Collection<byte[]> marshalFieldsCollection( @Nullable Collection<Object> col, GridCacheContext<K, V> ctx) throws GridException { assert ctx != null; if (col == null) return null; Collection<List<Object>> col0 = new ArrayList<>(col.size()); for (Object o : col) { List<GridIndexingEntity<?>> list = (List<GridIndexingEntity<?>>) o; List<Object> list0 = new ArrayList<>(list.size()); for (GridIndexingEntity<?> ent : list) { if (ent.bytes() != null) list0.add(ent.bytes()); else { if (ctx.deploymentEnabled()) prepareObject(ent.value(), ctx); list0.add(CU.marshal(ctx, ent.value())); } } col0.add(list0); } return marshalCollection(col0, ctx); }
/** INTERNAL: Transform the object-level value into a database-level value */ public Object getFieldValue(Object objectValue, AbstractSession session) { DatabaseMapping mapping = getMapping(); Object fieldValue = objectValue; if ((mapping != null) && (mapping.isDirectToFieldMapping() || mapping.isDirectCollectionMapping())) { // CR#3623207, check for IN Collection here not in mapping. if (objectValue instanceof Collection) { // This can actually be a collection for IN within expressions... however it would be better // for expressions to handle this. Collection values = (Collection) objectValue; Vector fieldValues = new Vector(values.size()); for (Iterator iterator = values.iterator(); iterator.hasNext(); ) { Object value = iterator.next(); if (!(value instanceof Expression)) { value = getFieldValue(value, session); } fieldValues.add(value); } fieldValue = fieldValues; } else { if (mapping.isDirectToFieldMapping()) { fieldValue = ((AbstractDirectMapping) mapping).getFieldValue(objectValue, session); } else if (mapping.isDirectCollectionMapping()) { fieldValue = ((DirectCollectionMapping) mapping).getFieldValue(objectValue, session); } } } return fieldValue; }
/** {@inheritDoc} */ @SuppressWarnings("TypeMayBeWeakened") @Nullable private Collection<Object> unmarshalFieldsCollection( @Nullable Collection<byte[]> byteCol, GridCacheContext<K, V> ctx, ClassLoader ldr) throws GridException { assert ctx != null; assert ldr != null; Collection<Object> col = unmarshalCollection(byteCol, ctx, ldr); Collection<Object> col0 = null; if (col != null) { col0 = new ArrayList<>(col.size()); for (Object o : col) { List<Object> list = (List<Object>) o; List<Object> list0 = new ArrayList<>(list.size()); for (Object obj : list) list0.add(obj != null ? ctx.marshaller().unmarshal((byte[]) obj, ldr) : null); col0.add(list0); } } return col0; }
/** Check if the getSubBuilders properly predicts the output. */ public static void testSubBuilders() throws Exception { Workspace ws = Workspace.getWorkspace(new File("test/ws")); Project project = ws.getProject("p4-sub"); Collection<? extends Builder> bs = project.getSubBuilders(); assertNotNull(bs); assertEquals(3, bs.size()); Set<String> names = new HashSet<String>(); for (Builder b : bs) { names.add(b.getBsn()); } assertTrue(names.contains("p4-sub.a")); assertTrue(names.contains("p4-sub.b")); assertTrue(names.contains("p4-sub.c")); File[] files = project.build(); assertTrue(project.check()); System.err.println(Processor.join(project.getErrors(), "\n")); System.err.println(Processor.join(project.getWarnings(), "\n")); assertEquals(0, project.getErrors().size()); assertEquals(0, project.getWarnings().size()); assertNotNull(files); assertEquals(3, files.length); for (File file : files) { Jar jar = new Jar(file); Manifest m = jar.getManifest(); assertTrue(names.contains(m.getMainAttributes().getValue("Bundle-SymbolicName"))); } }
/** {@inheritDoc} */ @Override public Map<K, V> peekAll( @Nullable Collection<? extends K> keys, @Nullable Collection<GridCachePeekMode> modes) throws GridException { if (keys == null || keys.isEmpty()) return emptyMap(); final Collection<K> skipped = new GridLeanSet<K>(); final Map<K, V> map = !modes.contains(PARTITIONED_ONLY) ? peekAll0(keys, modes, ctx.tm().localTxx(), skipped) : new GridLeanMap<K, V>(0); if (map.size() != keys.size() && !modes.contains(NEAR_ONLY)) { map.putAll( dht.peekAll( F.view( keys, new P1<K>() { @Override public boolean apply(K k) { return !map.containsKey(k) && !skipped.contains(k); } }), modes)); } return map; }
@Test public void testEchoedRow() throws IOException, ExecutionException, InterruptedException { // This test check that EchoedRow doesn't skipp rows: see CASSANDRA-2653 Keyspace keyspace = Keyspace.open(KEYSPACE1); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Standard2"); // disable compaction while flushing cfs.disableAutoCompaction(); // Insert 4 keys in two sstables. We need the sstables to have 2 rows // at least to trigger what was causing CASSANDRA-2653 for (int i = 1; i < 5; i++) { DecoratedKey key = Util.dk(String.valueOf(i)); RowMutation rm = new RowMutation(KEYSPACE1, key.key); rm.add( "Standard2", ByteBufferUtil.bytes(String.valueOf(i)), ByteBufferUtil.EMPTY_BYTE_BUFFER, i); rm.apply(); if (i % 2 == 0) cfs.forceBlockingFlush(); } Collection<SSTableReader> toCompact = cfs.getSSTables(); assert toCompact.size() == 2; // Reinserting the same keys. We will compact only the previous sstable, but we need those new // ones // to make sure we use EchoedRow, otherwise it won't be used because purge can be done. for (int i = 1; i < 5; i++) { DecoratedKey key = Util.dk(String.valueOf(i)); RowMutation rm = new RowMutation(KEYSPACE1, key.key); rm.add( "Standard2", ByteBufferUtil.bytes(String.valueOf(i)), ByteBufferUtil.EMPTY_BYTE_BUFFER, i); rm.apply(); } cfs.forceBlockingFlush(); SSTableReader tmpSSTable = null; for (SSTableReader sstable : cfs.getSSTables()) if (!toCompact.contains(sstable)) tmpSSTable = sstable; assert tmpSSTable != null; // Force compaction on first sstables. Since each row is in only one sstable, we will be using // EchoedRow. Util.compact(cfs, toCompact); assertEquals(2, cfs.getSSTables().size()); // Now, we remove the sstable that was just created to force the use of EchoedRow (so that it // doesn't hide the problem) cfs.markObsolete(Collections.singleton(tmpSSTable), OperationType.UNKNOWN); assertEquals(1, cfs.getSSTables().size()); // Now assert we do have the 4 keys assertEquals(4, Util.getRangeSlice(cfs).size()); }
public void startServer() throws Exception { while (true) { Socket s = server.accept(); cClient.add(new ClientConn(s)); ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort()); ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n"); } }
/** * Returns the index of each elem in a List. * * @param elements The list of items * @return An array of indices */ public int[] indices(Collection<E> elements) { int[] indices = new int[elements.size()]; int i = 0; for (E elem : elements) { indices[i++] = indexOf(elem); } return indices; }
private void BriefInfoBtnMouseClicked( java.awt.event.MouseEvent evt) { // GEN-FIRST:event_BriefInfoBtnMouseClicked // TODO add your handling code here: Collection colNumberOfInstance = kb.getInstances(); long lNumberOfInstance = colNumberOfInstance.size(); LoggingAreaTA.append("Project has " + lNumberOfInstance + " in total"); LoggingAreaTA.append("Project is loaded in " + lLoadedTime + " ms"); } // GEN-LAST:event_BriefInfoBtnMouseClicked
/** * Converts a collection of Dependency objects to a list of corresponding Artifact objects. * * @param deps The collection of dependencies to convert. * @return A list of Artifact instances. */ private List<Artifact> dependenciesToArtifacts(final Collection<Dependency> deps) { final List<Artifact> artifacts = new ArrayList<Artifact>(deps.size()); for (Dependency dep : deps) { artifacts.add(dependencyToArtifact(dep)); } return artifacts; }
/** * Removes all mappings for an LFN from the replica catalog. * * @param lfn is the logical directory to remove all mappings for. * @return the number of removed entries. */ public int remove(String lfn) { Collection c = (Collection) mLFNMap.remove(lfn); if (c == null) { return 0; } else { return c.size(); } }
public static File[] toFileArray(Collection fileObjects) { Set files = new HashSet(fileObjects.size() * 4 / 3 + 1); for (Iterator i = fileObjects.iterator(); i.hasNext(); ) { files.add(FileUtil.toFile((FileObject) i.next())); } files.remove(null); return (File[]) files.toArray(new File[files.size()]); }
public void serializeHistoryCursor( Collection<TrackHistory> historyCursor, HttpServletResponse httpServletResponse) { try { final ServletOutputStream httpOutputStream = httpServletResponse.getOutputStream(); final BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(httpOutputStream)); outputStream.write("{"); outputStream.write("\"count\":"); outputStream.write("" + historyCursor.size()); if (historyCursor.size() > 0) { Gson gson = new Gson(); outputStream.write(","); outputStream.write("\"tracks\":["); for (Iterator<TrackHistory> iterator = historyCursor.iterator(); iterator.hasNext(); ) { TrackHistory next = iterator.next(); outputStream.write(gson.toJson(toWebTrack(next))); if (iterator.hasNext()) { outputStream.write(","); } outputStream.flush(); } /* while (historyCursor.hasNext()) { outputStream.write(gson.toJson(toWebTrack(historyCursor.next()))); if (historyCursor.hasNext()) { outputStream.write(","); } outputStream.flush(); } */ outputStream.write("]"); } outputStream.write("}"); outputStream.flush(); outputStream.close(); httpOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
/** {@inheritDoc} */ @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException { super.finishUnmarshal(ctx, ldr); if (ownedValKeys != null && ownedVals == null) { ownedVals = U.newHashMap(ownedValKeys.size()); assert ownedValKeys.size() == ownedValVals.size(); Iterator<IgniteTxKey> keyIter = ownedValKeys.iterator(); Iterator<CacheVersionedValue> valIter = ownedValVals.iterator(); while (keyIter.hasNext()) { IgniteTxKey key = keyIter.next(); GridCacheContext cctx = ctx.cacheContext(key.cacheId()); CacheVersionedValue val = valIter.next(); key.finishUnmarshal(cctx, ldr); val.finishUnmarshal(cctx, ldr); ownedVals.put(key, val); } } if (retVal != null && retVal.cacheId() != 0) { GridCacheContext cctx = ctx.cacheContext(retVal.cacheId()); assert cctx != null : retVal.cacheId(); retVal.finishUnmarshal(cctx, ldr); } if (filterFailedKeys != null) { for (IgniteTxKey key : filterFailedKeys) { GridCacheContext cctx = ctx.cacheContext(key.cacheId()); key.finishUnmarshal(cctx, ldr); } } }
private static Project testBuildAll(String dependsOn, int count) throws Exception { Workspace ws = new Workspace(new File("test/ws")); Project all = ws.getProject("build-all"); all.setProperty("-dependson", dependsOn); all.prepare(); Collection<Project> dependson = all.getDependson(); assertEquals(count, dependson.size()); return all; }