/** Tests to see if the the randomMint method returns an empty set */ @Test public void testRandomMintZeroAmount() { IdGenerator minter = new AutoIdGenerator("", Token.DIGIT, 5); Set<Pid> randomSet = minter.randomMint(0); Assert.assertEquals(randomSet.isEmpty(), true); }
public static void fromCRAWDAD( LinkTrace links, InputStream in, double timeMul, long ticsPerSecond, long offset, IdGenerator idGen) throws IOException { StatefulWriter<LinkEvent, Link> linkWriter = links.getWriter(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { String[] elems = line.split("[ \t]+"); Integer id1 = idGen.getInternalId(elems[0]); Integer id2 = idGen.getInternalId(elems[1]); long begin = (long) (Long.parseLong(elems[2]) * timeMul) + offset; long end = (long) (Long.parseLong(elems[3]) * timeMul) + offset; linkWriter.queue(begin, new LinkEvent(id1, id2, LinkEvent.UP)); linkWriter.queue(end, new LinkEvent(id1, id2, LinkEvent.DOWN)); } linkWriter.flush(); linkWriter.setProperty(Trace.timeUnitKey, Units.toTimeUnit(ticsPerSecond)); idGen.writeTraceInfo(linkWriter); linkWriter.close(); br.close(); }
/** Tests to see if the the sequentialMint method returns an empty set */ @Test public void testSequentialMintZeroAmount() { IdGenerator minter = new AutoIdGenerator("", Token.DIGIT, 5); Set<Pid> sequentialSet = minter.sequentialMint(0); Assert.assertEquals(sequentialSet.isEmpty(), true); }
/** * Tests to see if the sequentialMint method will print the desired prefix at an arbitrary * starting value. * * @param prefix A sequence of characters that appear in the beginning of PIDs * @param sansVowel Dictates whether or not vowels are allowed * @param tokenType An enum used to configure PIDS * @param rootLength Designates the length of the id's root * @param amount The number of PIDs to be created */ @Test(dataProvider = "prefix") public void testSequentialMintPrefixWithStartingValue( String prefix, boolean sansVowel, Token tokenType, int rootLength, int amount) { // store parameters in a setting object Setting setting = new Setting(prefix, tokenType, null, rootLength, sansVowel); IdGenerator generator = new AutoIdGenerator(prefix, tokenType, rootLength); int startingValue = amount / 2; Set<Pid> sequentialSet = generator.sequentialMint(amount, startingValue); int counter = 0; Pid prev = null; Iterator<Pid> iter = sequentialSet.iterator(); while (iter.hasNext()) { // fail if the length does not match Pid current = iter.next(); PID_TEST.testPrefix(current.getName(), setting); if (prev != null && counter != startingValue) { PID_TEST.testOrder(prev, current); } counter++; prev = current; } // test to see if the amount matches the size of the generated set Assert.assertEquals(sequentialSet.size(), amount); }
/** * Tests to see if randomMint will through NotEnoughPermutation exception when the amount exceeds * the total permutations */ @Test(expectedExceptions = NotEnoughPermutationsException.class) public void testRandomNotEnoughPermutationException() { IdGenerator minter = new AutoIdGenerator("", Token.DIGIT, 5); long total = minter.getMaxPermutation(); Set<Pid> randomSet = minter.randomMint(total + 1); }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { session = request.getSession(); dbConn conn = new dbConn(); IdGenerator IG = new IdGenerator(); id = IG.current_id(); plotname = request.getParameter("plotname"); status = ""; String checker = "SELECT id FROM plots WHERE name=? OR id=?"; conn.pst = conn.conn.prepareStatement(checker); conn.pst.setString(1, plotname); conn.pst.setString(2, id); conn.rs = conn.pst.executeQuery(); if (conn.rs.next() == true) { status = "<font color=\"red\"><b>Failed </b> : Plot already exist.</font>"; } else { String inserter = "INSERT INTO plots (id,name) VALUES(?,?)"; conn.pst = conn.conn.prepareStatement(inserter); conn.pst.setString(1, id); conn.pst.setString(2, plotname); conn.pst.executeUpdate(); status = "<font color=\"green\"><b>Success : </b> Plot added successfully.</font>"; } out.println(status); } }
public static Message create(int code, MessageFlag flag) { Message message = new DefaultMessage(); message.version((byte) 1); message.code(code); message.flag(flag); message.hopByHop(IdGenerator.nextHopByHop()); message.endToEnd(IdGenerator.nextEndToEnd()); return message; }
/** * Closes this store. This will cause all buffers and channels to be closed. Requesting an * operation from after this method has been invoked is illegal and an exception will be thrown. * * <p>This method will start by invoking the {@link #closeStorage} method giving the implementing * store way to do anything that it needs to do before the fileChannel is closed. */ public void close() { if (fileChannel == null) { return; } closeStorage(); if (windowPool != null) { windowPool.close(); windowPool = null; } if ((isReadOnly() && !isBackupSlave()) || idGenerator == null || !storeOk) { releaseFileLockAndCloseFileChannel(); return; } long highId = idGenerator.getHighId(); int recordSize = -1; if (this instanceof AbstractDynamicStore) { recordSize = ((AbstractDynamicStore) this).getBlockSize(); } else if (this instanceof AbstractStore) { recordSize = ((AbstractStore) this).getRecordSize(); } idGenerator.close(); boolean success = false; IOException storedIoe = null; // hack for WINBLOWS if (!readOnly || backupSlave) { for (int i = 0; i < 10; i++) { try { fileChannel.position(highId * recordSize); ByteBuffer buffer = ByteBuffer.wrap(UTF8.encode(getTypeAndVersionDescriptor())); fileChannel.write(buffer); stringLogger.debug( "Closing " + storageFileName + ", truncating at " + fileChannel.position() + " vs file size " + fileChannel.size()); fileChannel.truncate(fileChannel.position()); fileChannel.force(false); releaseFileLockAndCloseFileChannel(); success = true; break; } catch (IOException e) { storedIoe = e; System.gc(); } } } else { releaseFileLockAndCloseFileChannel(); success = true; } if (!success) { throw new UnderlyingStorageException( "Unable to close store " + getStorageFileName(), storedIoe); } }
/** * Tests AutoIdGenerator for the presence of vowels through the randomMint method * * @param prefix A sequence of characters that appear in the beginning of PIDs * @param sansVowel Dictates whether or not vowels are allowed * @param tokenType An enum used to configure PIDS * @param rootLength Designates the length of the id's root * @param amount The number of PIDs to be created */ @Test(dataProvider = "sansVowel") public void testRandomMintSansVowels( String prefix, boolean sansVowel, Token tokenType, int rootLength, int amount) { // store parameters in a setting object Setting setting = new Setting(prefix, tokenType, null, rootLength, sansVowel); IdGenerator generator = new AutoIdGenerator(prefix, tokenType, rootLength); Set<Pid> randomSet = generator.randomMint(amount); for (Pid id : randomSet) { PID_TEST.testTokenType(id.getName(), setting); } // test to see if the amount matches the size of the generated set Assert.assertEquals(randomSet.size(), amount); }
Connector addConnector(VNode node, Connector c) { String localId = c.getLocalId(); if (connectorIdGenerator.getIds().contains(localId)) { throw new IllegalArgumentException( "Cannot add connector: id \"" + localId + "\" already in use"); } Connector result = new ConnectorImpl(node, c); connectors.add(result); connectorIdGenerator.addId(localId); return result; }
@Test public void testBasic() { assertEquals("", IdGenerator.generate("", "")); assertEquals("", IdGenerator.generate(null, "")); assertEquals("", IdGenerator.generate("", null)); assertEquals("", IdGenerator.generate(null, null)); assertEquals("a", IdGenerator.generate("a", null)); assertEquals("a", IdGenerator.generate("a", "")); assertEquals("b", IdGenerator.generate("", "b")); assertEquals("b", IdGenerator.generate(null, "b")); assertEquals("a" + IdGenerator.SEPARATOR + "b", IdGenerator.generate("a", "b")); }
// read all defense missile from given defense destructor protected void readDefenseDestructorFromGivenDestructor(Element destructor) { NamedNodeMap attributes = destructor.getAttributes(); String id = ""; String type; Attr attr = (Attr) attributes.item(0); String name = attr.getNodeName(); // if it's iron dome if (name.equals("id")) { id = attr.getNodeValue(); // update id's in the war IdGenerator.updateIronDomeId(id); // add to war war.addIronDome(id); NodeList destructdMissiles = destructor.getElementsByTagName("destructdMissile"); readDefensDestructoreMissiles(destructdMissiles, id); // if it's launcher destructor } else { if (name.equals("type")) { type = attr.getNodeValue(); // add to war id = war.addDefenseLauncherDestructor(type); NodeList destructedLanuchers = destructor.getElementsByTagName("destructedLanucher"); readDefensDestructoreMissiles(destructedLanuchers, id); } } }
@Override public Document generateIdIfAbsentFromDocument(final Document document) { if (!documentHasId(document)) { document.put(ID_FIELD_NAME, idGenerator.generate()); } return document; }
@Test public void testHazelcastInstances() { assertNotNull(map1); assertNotNull(map2); assertNotNull(multiMap); assertNotNull(queue); assertNotNull(topic); assertNotNull(set); assertNotNull(list); assertNotNull(executorService); assertNotNull(idGenerator); assertNotNull(atomicLong); assertNotNull(atomicReference); assertNotNull(countDownLatch); assertNotNull(semaphore); assertNotNull(lock); assertEquals("map1", map1.getName()); assertEquals("map2", map2.getName()); assertEquals("testMultimap", multiMap.getName()); assertEquals("testQ", queue.getName()); assertEquals("testTopic", topic.getName()); assertEquals("set", set.getName()); assertEquals("list", list.getName()); assertEquals("idGenerator", idGenerator.getName()); assertEquals("atomicLong", atomicLong.getName()); assertEquals("atomicReference", atomicReference.getName()); assertEquals("countDownLatch", countDownLatch.getName()); assertEquals("semaphore", semaphore.getName()); }
public Server() { id = IdGenerator.getInstance().getId(); spreadGroup = new SpreadGroup(); GroupConnection.getInstance().getConnection().add(listener); knownServers = new HashMap<>(); waitingOperations = new LinkedBlockingDeque<>(); }
/* (non-Javadoc) * @see org.collectionspace.JSONStore#retrieveJson(java.lang.String) */ public JSONObject retrieveJSON(String filePath, JSONObject restrictions) throws ExistException, UnderlyingStorageException, UnimplementedException { // XXX hack: support views properly String XXXCHOP = "/view"; String XXXCHOP2 = "/refs"; if (filePath.endsWith(XXXCHOP)) filePath = filePath.substring(0, filePath.length() - XXXCHOP.length()); if (filePath.endsWith(XXXCHOP2)) return new JSONObject(); if (idRequest(filePath)) return id.retrieveJSON(filePath, restrictions); File jsonFile = fileFromPath(filePath); if (!jsonFile.exists()) { throw new ExistException("No such file: " + filePath); } try { FileReader r = new FileReader(jsonFile); String data = IOUtils.toString(r); r.close(); JSONObject jsonObject = new JSONObject(data); return jsonObject; } catch (IOException ioe) { return new JSONObject(); // XXX } catch (JSONException je) { return new JSONObject(); // XXX } }
public static XMLFragmentMapping getInstance( FragmentMapping fm, XMLElementResolverFactory resolverFac) { logger.debug("Resolving fragment-mapping: " + fm); XMLResolver<FragmentMapping, XMLFragmentMapping> fmResolver = resolverFac.getResolver(FragmentMapping.class, XMLFragmentMapping.class); if (fmResolver == null) throw new ReuseRuntimeException( "No XMLResolver found for " + FragmentMapping.class + ", " + XMLFragmentMapping.class); IdGenerator<XMLFragmentMapping> fmIdGenerator = resolverFac.getIdGenerator(XMLFragmentMapping.class); if (fmIdGenerator == null) throw new ReuseRuntimeException("No IdGenerator found for " + XMLFragmentMapping.class); if (fmResolver.isBound(fm)) { XMLFragmentMapping resolved = fmResolver.resolve(fm); logger.debug("Cache hit for fragment-mapping: " + fm + ", in cache: " + resolved); return resolved; } // TFragmentizer2.printFragmentMapping(fm); Set<Operator> ops = fm.getOperators(); Set<XMLOperator> xmlOps = new HashSet<XMLOperator>(); for (Operator op : ops) { XMLOperator xmlOp = XMLOperator.getInstance(op, resolverFac); xmlOps.add(xmlOp); } XMLFragmentMapping xmlFm = new XMLFragmentMapping(); String id = fm.getId(); // if no id is set -> generate one if (id == null) { id = fmIdGenerator.generateId(xmlFm); } xmlFm.setId(id); xmlFm.setOperators(xmlOps); fmResolver.bind(fm, xmlFm); logger.debug("Resolved fragment-mapping: " + fm + " to: " + xmlFm); return xmlFm; }
/** @return The highest possible id in use, -1 if no id in use. */ public long getHighestPossibleIdInUse() { if (idGenerator != null) { return idGenerator.getHighId() - 1; } else { // If we ask for this before we've recovered we can only make a best-effort guess // about the highest possible id in use. return figureOutHighestIdInUse(); } }
/** * Return the highest id in use. * * @return The highest id in use. */ public long getHighId() { long genHighId = idGenerator != null ? idGenerator.getHighId() : -1; long updateHighId = highestUpdateRecordId; if (updateHighId > genHighId) { return updateHighId; } return genHighId; }
public BibtexEntry makeBibtexEntry() { BibtexEntry e = new BibtexEntry(IdGenerator.next(), BibtexEntryTypes.INCOLLECTION); e.setField("title", "Marine finfish larviculture in Europe"); e.setField("bibtexkey", "shields01"); e.setField("year", "2001"); e.setField("author", "Kevin Shields"); return e; }
/** * Constructs the consumer which will read from the given destination and is a child of the given * context. * * @param destination the destination that this consumer will read from * @param hazelcastMQContext the parent context of this consumer */ DefaultHazelcastMQConsumer(String destination, DefaultHazelcastMQContext hazelcastMQContext) { super(); this.destination = destination; this.receiveLock = new ReentrantLock(); this.receiveCondition = receiveLock.newCondition(); this.closed = false; this.active = false; this.hazelcastMQContext = hazelcastMQContext; this.config = hazelcastMQContext.getHazelcastMQInstance().getConfig(); HazelcastInstance hazelcast = this.hazelcastMQContext.getHazelcastMQInstance().getConfig().getHazelcastInstance(); IdGenerator idGenerator = hazelcast.getIdGenerator("hazelcastmqconsumer"); this.id = "hazelcastmqconsumer-" + String.valueOf(idGenerator.newId()); }
public void deleteJSON(String filePath) throws ExistException, UnimplementedException, UnderlyingStorageException { if (idRequest(filePath)) id.deleteJSON(filePath); File jsonFile = fileFromPath(filePath); if (!jsonFile.exists()) { throw new ExistException("No such file: " + filePath); } jsonFile.delete(); }
public User createUser(String username, String password) { if (userRepository.usernameExists(username)) { throw new ServiceException("Username is already taken"); } String id = idGenerator.generate(); User user = new User(id, username, password); userRepository.add(user); return user; }
// read all defense destructors and their missiles from XML protected void readDefenseDestructors() { ; NodeList destructors = root.getElementsByTagName("destructor"); int destructorsSize = destructors.getLength(); for (int i = 0; i < destructorsSize; i++) { Element destructor = (Element) destructors.item(i); readDefenseDestructorFromGivenDestructor(destructor); } // update the id's in the war IdGenerator.updateFinalIronDomeId(); }
/** * Accumulates available regulation capacity for a given TariffSubscription. This is basically a * data structure that holds two numbers: an amount of up-regulation capacity (non-negative), and an * amount of down-regulation capacity (non-positive). The subscription is also included to simplify * log analysis; in cases where no subscription is involved, this value should be null. * * @author John Collins */ @Domain public class RegulationCapacity { protected static Logger log = LogManager.getLogger(RegulationCapacity.class.getName()); long id = IdGenerator.createId(); // ignore small numbers private static double epsilon = 1e-10; private double upRegulationCapacity = 0.0; private double downRegulationCapacity = 0.0; /** * Creates a new RegulationAccumulator instance specifying the amounts of regulating capacity * available for up-regulation and down-regulation. Values are expressed with respect to the * balancing market; a negative value means power is delivered to the customer (down-regulation), * and a positive value means power is delivered to the balancing market (up-regulation). */ public RegulationCapacity( TariffSubscription subscription, double upRegulationCapacity, double downRegulationCapacity) { super(); if (upRegulationCapacity < 0.0) { if (upRegulationCapacity < -epsilon) log.warn("upRegulationCapacity " + upRegulationCapacity + " < 0.0"); upRegulationCapacity = 0.0; } if (downRegulationCapacity > 0.0) { if (downRegulationCapacity > epsilon) log.warn("downRegulationCapacity " + downRegulationCapacity + " > 0.0"); downRegulationCapacity = 0.0; } this.upRegulationCapacity = upRegulationCapacity; this.downRegulationCapacity = downRegulationCapacity; } public long getId() { return id; } /** Returns the available up-regulation capacity in kWh. Value is non-negative. */ public double getUpRegulationCapacity() { return upRegulationCapacity; } /** Returns the available down-regulation capacity in kWh. Value is non-positive. */ public double getDownRegulationCapacity() { return downRegulationCapacity; } }
public String autocreateJSON(String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException { if ("id".equals(filePath)) id.autocreateJSON("", jsonObject); while (true) { int tail = rnd.nextInt(Integer.MAX_VALUE); String filename = filePath + "/" + tail; try { set(filename, jsonObject, true); return Integer.toString(tail); } catch (ExistException e) { // Try again } } }
// read enemy launchers and their missiles form XML protected void readEnemyLaunchers() { NodeList launchers = root.getElementsByTagName("launcher"); for (int i = 0; i < launchers.getLength(); i++) { Element tempLauncher = (Element) launchers.item(i); String idLauncher = tempLauncher.getAttribute("id"); boolean isHidden = Boolean.parseBoolean(tempLauncher.getAttribute("isHidden")); // add to the war war.addEnemyLauncher(idLauncher, isHidden); IdGenerator.updateEnemyLauncherId(idLauncher); NodeList missiles = tempLauncher.getElementsByTagName("missile"); // read all missiles readMissilesForGivenLauncher(missiles, idLauncher); } // update the id's in the war IdGenerator.updateFinalEnemyMissileId(); IdGenerator.updateFinalEnemyLauncherId(); }
/** * Tests the AutoIdGenerator for the presence of vowels through the sequentialMint method. * * @param prefix A sequence of characters that appear in the beginning of PIDs * @param sansVowel Dictates whether or not vowels are allowed * @param tokenType An enum used to configure PIDS * @param rootLength Designates the length of the id's root * @param amount The number of PIDs to be created */ @Test(dataProvider = "sansVowel") public void testSequentialMintSansVowels( String prefix, boolean sansVowel, Token tokenType, int rootLength, int amount) { // store parameters in a setting object Setting setting = new Setting(prefix, tokenType, null, rootLength, sansVowel); IdGenerator generator = new AutoIdGenerator(prefix, tokenType, rootLength); Set<Pid> sequentialSet = generator.sequentialMint(amount); Pid prev = null; Iterator<Pid> iter = sequentialSet.iterator(); while (iter.hasNext()) { // fail if the length does not match Pid current = iter.next(); PID_TEST.testTokenType(current.getName(), setting); if (prev != null) { PID_TEST.testOrder(prev, current); } prev = current; } Assert.assertEquals(sequentialSet.size(), amount); }
@Test public void testCiteKeyAndID() { BibEntry be = new BibEntry(); Assert.assertFalse(be.hasCiteKey()); be.setField("author", "Albert Einstein"); be.setField(BibEntry.KEY_FIELD, "Einstein1931"); Assert.assertTrue(be.hasCiteKey()); Assert.assertEquals("Einstein1931", be.getCiteKey()); Assert.assertEquals("Albert Einstein", be.getField("author")); be.clearField("author"); Assert.assertNull(be.getField("author")); String id = IdGenerator.next(); be.setId(id); Assert.assertEquals(id, be.getId()); }
private static BibtexEntry getTestEntry() { if (PreviewPrefsTab.entry != null) { return PreviewPrefsTab.entry; } PreviewPrefsTab.entry = new BibtexEntry(IdGenerator.next(), BibtexEntryType.getType("article")); PreviewPrefsTab.entry.setField(BibtexFields.KEY_FIELD, "conceicao1997"); PreviewPrefsTab.entry.setField( "author", "Luis E. C. Conceic{\\~a}o and Terje van der Meeren and Johan A. J. Verreth and M S. Evjen and D. F. Houlihan and H. J. Fyhn"); PreviewPrefsTab.entry.setField( "title", "Amino acid metabolism and protein turnover in larval turbot (Scophthalmus maximus) fed natural zooplankton or Artemia"); PreviewPrefsTab.entry.setField("year", "1997"); PreviewPrefsTab.entry.setField("journal", "Marine Biology"); PreviewPrefsTab.entry.setField("month", "January"); PreviewPrefsTab.entry.setField("number", "2"); PreviewPrefsTab.entry.setField("volume", "123"); PreviewPrefsTab.entry.setField("pdf", "conceicao1997.pdf"); PreviewPrefsTab.entry.setField("pages", "255--265"); PreviewPrefsTab.entry.setField( "keywords", "energetics, artemia, metabolism, amino acid, turbot"); PreviewPrefsTab.entry.setField( "url", "http://ejournals.ebsco.com/direct.asp?ArticleID=TYY4NT82XA9H7R8PFPPV"); PreviewPrefsTab.entry.setField( "abstract", "Abstract The present paper studied the influence of different food regimes " + "on the free amino acid (FAA) pool, the rate of protein turnover, the flux of amino acids, and " + "their relation to growth of larval turbot (Scophthalmus maximus L.) from first feeding until " + "metamorphosis. The amino acid profile of protein was stable during the larval period although " + "some small, but significant, differences were found. Turbot larvae had proteins which were rich " + "in leucine and aspartate, and poor in glutamate, suggesting a high leucine requirement. The " + "profile of the FAA pool was highly variable and quite different from the amino acid profile in " + "protein. The proportion of essential FAA decreased with development. High contents of free tyrosine " + "and phenylalanine were found on Day 3, while free taurine was present at high levels throughout " + "the experimental period. Larval growth rates were positively correlated with taurine levels, " + "suggesting a dietary dependency for taurine and/or sulphur amino acids.\n\nReduced growth rates in " + "Artemia-fed larvae were associated with lower levels of free methionine, indicating that this diet " + "is deficient in methionine for turbot larvae. Leucine might also be limiting turbot growth as the " + "different diet organisms had lower levels of this amino acid in the free pool than was found in the " + "larval protein. A previously presented model was used to describe the flux of amino acids in growing " + "turbot larvae. The FAA pool was found to be small and variable. It was estimated that the daily dietary " + "amino acid intake might be up to ten times the larval FAA pool. In addition, protein synthesis and " + "protein degradation might daily remove and return, respectively, the equivalent of up to 20 and 10 " + "times the size of the FAA pool. In an early phase (Day 11) high growth rates were associated with a " + "relatively low protein turnover, while at a later stage (Day 17), a much higher turnover was observed."); return PreviewPrefsTab.entry; }