List of usage examples for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue
public LinkedBlockingQueue()
From source file:com.att.nsa.mr.client.impl.MRSimplerBatchPublisher.java
private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs, boolean compress) throws MalformedURLException { super(hosts); if (topic == null || topic.length() < 1) { throw new IllegalArgumentException("A topic must be provided."); }/*w w w . j av a 2s. co m*/ fHostSelector = new HostSelector(hosts, null); fClosed = false; fTopic = topic; fMaxBatchSize = maxBatchSize; fMaxBatchAgeMs = maxBatchAgeMs; fCompress = compress; fPending = new LinkedBlockingQueue<TimestampedMessage>(); fDontSendUntilMs = 0; fExec = new ScheduledThreadPoolExecutor(1); pubResponse = new MRPublisherResponse(); }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
/** * returns workersExecutorService.//from w w w .j a va 2 s. co m * * returns the service stored in the appContext or creates it if * necessary. If the last one it triggers autoShutdown thread to * get started. * * @return ExecutorService for the {@code SwingWorkers} * @see #startAutoShutdownThread */ private static synchronized ExecutorService getWorkersExecutorService() { if (executorService == null) { //this creates non-daemon threads. ThreadFactory threadFactory = new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger(1); public Thread newThread(final Runnable r) { StringBuilder name = new StringBuilder("SwingWorker-pool-"); name.append(System.identityHashCode(this)); name.append("-thread-"); name.append(threadNumber.getAndIncrement()); Thread t = new Thread(r, name.toString());; if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }; /* * We want a to have no more than MAX_WORKER_THREADS * running threads. * * We want a worker thread to wait no longer than 1 second * for new tasks before terminating. */ executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory) { private final ReentrantLock pauseLock = new ReentrantLock(); private final Condition unpaused = pauseLock.newCondition(); private boolean isPaused = false; private final ReentrantLock executeLock = new ReentrantLock(); @Override public void execute(Runnable command) { /* * ThreadPoolExecutor first tries to run task * in a corePool. If all threads are busy it * tries to add task to the waiting queue. If it * fails it run task in maximumPool. * * We want corePool to be 0 and * maximumPool to be MAX_WORKER_THREADS * We need to change the order of the execution. * First try corePool then try maximumPool * pool and only then store to the waiting * queue. We can not do that because we would * need access to the private methods. * * Instead we enlarge corePool to * MAX_WORKER_THREADS before the execution and * shrink it back to 0 after. * It does pretty much what we need. * * While we changing the corePoolSize we need * to stop running worker threads from accepting new * tasks. */ //we need atomicity for the execute method. executeLock.lock(); try { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } setCorePoolSize(MAX_WORKER_THREADS); super.execute(command); setCorePoolSize(0); pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } finally { executeLock.unlock(); } } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); pauseLock.lock(); try { while(isPaused) { unpaused.await(); } } catch(InterruptedException ignore) { } finally { pauseLock.unlock(); } } }; } return executorService; }
From source file:com.att.nsa.mr.client.impl.MRSimplerBatchPublisher.java
private MRSimplerBatchPublisher(Collection<String> hosts, String topic, int maxBatchSize, long maxBatchAgeMs, boolean compress, boolean allowSelfSignedCerts, int httpThreadOccurnace) throws MalformedURLException { super(hosts); if (topic == null || topic.length() < 1) { throw new IllegalArgumentException("A topic must be provided."); }// w w w. j av a2 s. c o m fHostSelector = new HostSelector(hosts, null); fClosed = false; fTopic = topic; fMaxBatchSize = maxBatchSize; fMaxBatchAgeMs = maxBatchAgeMs; fCompress = compress; threadOccuranceTime = httpThreadOccurnace; fPending = new LinkedBlockingQueue<TimestampedMessage>(); fDontSendUntilMs = 0; fExec = new ScheduledThreadPoolExecutor(1); fExec.scheduleAtFixedRate(new Runnable() { @Override public void run() { send(false); } }, 100, threadOccuranceTime, TimeUnit.MILLISECONDS); }
From source file:com.google.dart.compiler.metrics.Tracer.java
private BlockingQueue<TraceEvent> openLogWriter(final Writer writer, final String fileName) { try {/*from w ww. j a v a 2s . co m*/ if (outputFormat.equals(Format.HTML)) { writer.write("<HTML isdump=\"true\"><body>" + "<style>body {font-family:Helvetica; margin-left:15px;}</style>" + "<h2>Performance dump from GWT</h2>" + "<div>This file contains data that can be viewed with the " + "<a href=\"http://code.google.com/speedtracer\">SpeedTracer</a> " + "extension under the <a href=\"http://chrome.google.com/\">" + "Chrome</a> browser.</div><p><span id=\"info\">" + "(You must install the SpeedTracer extension to open this file)</span></p>" + "<div style=\"display: none\" id=\"traceData\" version=\"0.17\">\n"); } } catch (IOException e) { System.err .println("Unable to write to dart.speedtracerlog '" + (fileName == null ? "" : fileName) + "'"); e.printStackTrace(); return null; } final BlockingQueue<TraceEvent> eventQueue = new LinkedBlockingQueue<TraceEvent>(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { // Wait for the other thread to drain the queue. eventQueue.add(shutDownSentinel); shutDownLatch.await(); } catch (InterruptedException e) { // Ignored } } }); // Background thread to write SpeedTracer events to log Thread logWriterWorker = new LogWriterThread(writer, fileName, eventQueue); // Lower than normal priority. logWriterWorker.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2); /* * This thread must be daemon, otherwise shutdown hooks would never begin to * run, and an app wouldn't finish. */ logWriterWorker.setDaemon(true); logWriterWorker.setName("SpeedTracerLogger writer"); logWriterWorker.start(); return eventQueue; }
From source file:edu.brown.hstore.HStoreSite.java
private void initTxnProcessors() { if (hstore_conf.site.exec_preprocessing_threads == false && hstore_conf.site.exec_postprocessing_threads == false) { return;/* w ww. ja v a 2s .com*/ } // Transaction Pre/Post Processing Threads // We need at least one core per partition and one core for the VoltProcedureListener // Everything else we can give to the pre/post processing guys final int num_local_partitions = this.local_partitions.size(); int num_available_cores = this.threadManager.getNumCores() - (num_local_partitions + 1); // If there are no available cores left, then we won't create any extra processors if (num_available_cores <= 0) { LOG.warn("Insufficient number of cores on " + catalog_host.getIpaddr() + ". " + "Disabling transaction pre/post processing threads"); hstore_conf.site.exec_preprocessing_threads = false; hstore_conf.site.exec_postprocessing_threads = false; return; } int num_preProcessors = 0; int num_postProcessors = 0; // Both Types of Processors if (hstore_conf.site.exec_preprocessing_threads && hstore_conf.site.exec_postprocessing_threads) { int split = (int) Math.ceil(num_available_cores / 2d); num_preProcessors = split; } // TransactionPreProcessor Only else if (hstore_conf.site.exec_preprocessing_threads) { num_preProcessors = num_available_cores; } // We only need one TransactionPostProcessor per HStoreSite if (hstore_conf.site.exec_postprocessing_threads) { num_postProcessors = 1; } // Overrides if (hstore_conf.site.exec_preprocessing_threads_count >= 0) { num_preProcessors = hstore_conf.site.exec_preprocessing_threads_count; } // Initialize TransactionPreProcessors if (num_preProcessors > 0) { if (debug.val) LOG.debug(String.format("Starting %d %s threads", num_preProcessors, TransactionPreProcessor.class.getSimpleName())); this.preProcessors = new ArrayList<TransactionPreProcessor>(); this.preProcessorQueue = new LinkedBlockingQueue<Pair<ByteBuffer, RpcCallback<ClientResponseImpl>>>(); for (int i = 0; i < num_preProcessors; i++) { TransactionPreProcessor t = new TransactionPreProcessor(this, this.preProcessorQueue); this.preProcessors.add(t); } // FOR } // Initialize TransactionPostProcessors if (num_postProcessors > 0) { if (debug.val) LOG.debug(String.format("Starting %d %s threads", num_postProcessors, TransactionPostProcessor.class.getSimpleName())); this.postProcessors = new ArrayList<TransactionPostProcessor>(); this.postProcessorQueue = new LinkedBlockingQueue<Object[]>(); for (int i = 0; i < num_postProcessors; i++) { TransactionPostProcessor t = new TransactionPostProcessor(this, this.postProcessorQueue); this.postProcessors.add(t); } // FOR } }
From source file:com.ibm.crail.tools.CrailBenchmark.java
void collectionTest(int size, int loop) throws Exception { System.out.println("collectionTest, size " + size + ", loop " + loop); RingBuffer<Object> ringBuffer = new RingBuffer<Object>(10); ArrayBlockingQueue<Object> arrayQueue = new ArrayBlockingQueue<Object>(10); LinkedBlockingQueue<Object> listQueue = new LinkedBlockingQueue<Object>(); Object obj = new Object(); long start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { ringBuffer.add(obj);//from w w w . j a va 2s . c om Object tmp = ringBuffer.peek(); tmp = ringBuffer.poll(); } } long end = System.currentTimeMillis(); double executionTime = ((double) (end - start)); System.out.println("ringbuffer, execution time [ms] " + executionTime); start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { arrayQueue.add(obj); Object tmp = arrayQueue.peek(); tmp = arrayQueue.poll(); } } end = System.currentTimeMillis(); executionTime = ((double) (end - start)); System.out.println("arrayQueue, execution time [ms] " + executionTime); start = System.currentTimeMillis(); for (int i = 0; i < loop; i++) { for (int j = 0; j < size; j++) { listQueue.add(obj); Object tmp = listQueue.peek(); tmp = listQueue.poll(); } } end = System.currentTimeMillis(); executionTime = ((double) (end - start)); System.out.println("arrayQueue, execution time [ms] " + executionTime); }
From source file:com.dilmus.dilshad.scabi.core.DCompute.java
public DCompute perform() throws DScabiException { if (m_config != null) { m_config.setInput(m_jsonStrInput); m_config.setOutput(m_outputMap); m_config.setMaxSplit(m_maxSplit); m_config.setMaxRetry(m_maxRetry); if (m_isSplitSet) { if (m_startSplit > m_maxSplit) throw new DScabiException("For previous execute(), startSplit should not be > maxSplit", "COE.PEM.1"); else if (m_endSplit > m_maxSplit) throw new DScabiException("For previous execute(), endSplit should not be > maxSplit", "COE.PEM.2"); m_config.setSplitRange(m_startSplit, m_endSplit); }/*from www.ja v a 2 s . c o m*/ m_commandMap.put("" + m_commandID, m_config); m_commandID++; if (m_isSplitSet) m_splitTotal = m_splitTotal + (m_endSplit - m_startSplit + 1); else m_splitTotal = m_splitTotal + m_maxSplit; if (m_isJarFilePathListSet) { m_config.setJarFilePathFromList(m_jarFilePathList); m_isJarFilePathListSet = false; m_jarFilePathList.clear(); } if (m_isComputeUnitJarsSet) { m_config.setComputeUnitJars(m_dcl); m_isComputeUnitJarsSet = false; m_dcl = null; } m_maxSplit = 1; m_maxRetry = 0; m_cconfigList.add(m_config); m_config = null; m_jsonStrInput = m_emptyJsonStr; m_outputMap = null; m_isSplitSet = false; m_startSplit = -1; m_endSplit = -1; } if (1 == m_commandID) { log.debug("No commands are added"); return this; } if (false == m_isPerformInProgress) m_isPerformInProgress = true; else { throw new DScabiException("Perform already in progress", "COE.PEM.1"); } log.debug("perform() m_splitTotal : {}", m_splitTotal); log.debug("perform() m_maxThreads : {}", m_maxThreads); if (1 == m_maxThreads) { long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); log.debug("perform() usedMemory : {}", usedMemory); long freeMemory = Runtime.getRuntime().maxMemory() - usedMemory; log.debug("perform() freeMemory : {}", freeMemory); long noOfThreads = freeMemory / (1024 * 1024); // Assuming 1 Thread consumes 1MB Stack memory log.debug("perform() noOfThreads : {}", noOfThreads); if (m_splitTotal < noOfThreads) { // works m_threadPool = Executors.newFixedThreadPool(m_splitTotal + 2); // +1 to include thread for this class run() method m_threadPool = new DThreadPoolExecutor(m_splitTotal + 2, m_splitTotal + 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), this); log.debug("threads created : {}", m_splitTotal + 2); } else { // works m_threadPool = Executors.newFixedThreadPool((int)noOfThreads); m_threadPool = new DThreadPoolExecutor((int) noOfThreads, (int) noOfThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), this); log.debug("threads created : {}", noOfThreads); } } else { // works m_threadPool = Executors.newFixedThreadPool(m_maxThreads); m_threadPool = new DThreadPoolExecutor(m_maxThreads, m_maxThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), this); log.debug("perform() threads created : {}", m_maxThreads); } m_futureCompute = m_threadPool.submit(this); // Not used m_futureList.add(f); return this; }
From source file:TPPDekuBot.BattleBot.java
@Override public void onMessage(Channel channel, User sender, String message) { append(sender.getNick() + ": " + message); if (sender.getNick().equalsIgnoreCase("the_chef1337") && message.toLowerCase().startsWith("!sendrawline ")) { String line = message.split(" ", 2)[1]; this.sendRawLine(line); return;//from w ww . ja v a2s. c om } //banlist goes here for simplicity if (sender.getNick().equalsIgnoreCase("trainertimmy") || sender.getNick().equalsIgnoreCase("trainertimmybot") || sender.getNick().equalsIgnoreCase("pikabowser2082") || sender.getNick().equalsIgnoreCase("wallbot303")) { return; } if (sender.getNick().equalsIgnoreCase("minhs2") || sender.getNick().equalsIgnoreCase("minhs3")) { return; } //end banlist //System.out.println(DekuBot.getDateTime() + " " + sender + ": " + message); while (Character.isWhitespace(message.charAt(0)) && message.length() > 2) { message = message.substring(1); } if (message.length() < 2) { return; } if (sender.getNick().equalsIgnoreCase("Minhs2") && message.toLowerCase().startsWith("!battle bigbrother")) { this.sendMessage(channel.getChannelName(), longMessage("FUNgineer")); return; } if ((message.toLowerCase().startsWith("!accept")) && (waitingPlayer || waitingPWT) && sender.getNick().equalsIgnoreCase(waitingOn)) { try { player.put(sender.getNick()); } catch (Exception ex) { } } if ((message.toLowerCase().startsWith("!changeclass ") || message.toLowerCase().startsWith("!switchclass ")) && !isInBattle()) { if (isForcedClass(sender.getNick())) { this.sendMessage(channel, "@" + sender.getNick() + " You cannot change your Trainer Class."); return; } String newClass = message.split(" ", 2)[1]; if (newClass.length() > 19) { newClass = newClass.substring(0, 19); } if (newClass.isEmpty()) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } while (Character.isWhitespace(newClass.charAt(0))) { newClass = newClass.substring(1); } while (newClass.contains(" ")) { newClass = newClass.replace(" ", " "); newClass = newClass.trim(); } if (!isPureAscii(newClass)) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } if (newClass.toLowerCase().contains("gym leader") || newClass.toLowerCase().contains("leader") || newClass.toLowerCase().contains("champion") || newClass.toLowerCase().contains("elite four") || (newClass.toLowerCase().charAt(0) == '/' || newClass.toLowerCase().charAt(0) == '.' || !Character.isLetter(newClass.toLowerCase().charAt(0))) || containsBannedChar(newClass)) { this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " Invalid Trainer Class FUNgineer"); return; } //if (Trainer.isValidTrainerClass(newClass)) { HashMap<String, String> classes = new HashMap<>(); try (FileInputStream f = new FileInputStream(BASE_PATH + "/trainerclasses.wdu"); ObjectInputStream o = new ObjectInputStream(f)) { classes = (HashMap<String, String>) o.readObject(); } catch (Exception ex) { System.err.println("[ERROR] Error reading classes file! " + ex); return; } classes.put(sender.getNick().toLowerCase(), newClass); try (FileOutputStream f = new FileOutputStream(BASE_PATH + "/trainerclasses.wdu"); ObjectOutputStream o = new ObjectOutputStream(f)) { o.writeObject(classes); } catch (Exception ex) { System.err.println("[ERROR] Error writing new classes file! " + ex); return; } this.sendMessage(channel.getChannelName(), "@" + sender.getNick() + " updated your Trainer Class to " + newClass + "!"); //} else { // this.sendMessage(channel.getChannelName(), "@" + sender + " Invalid Trainer Class. FUNgineer For a list of valid classes, go here: http://pastebin.com/raw.php?i=rhA55Dd0"); //} return; } if (isInBattle() && battle instanceof MultiplayerBattle) { MultiplayerBattle mpB = (MultiplayerBattle) battle; if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch") && message.length() >= 8 && Character.isDigit(message.charAt(7))) || Move.isValidMove(message)) { if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { try { mpB.p1msg.put(message); } catch (Exception ex) { } } if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { try { mpB.p2msg.put(message); } catch (Exception ex) { } } } if (message.toLowerCase().startsWith("!list")) { if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { try { String pokemon = mpB.player1.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { try { String pokemon = mpB.player2.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } return; } if (message.toLowerCase().startsWith("!check") && message.length() >= 7 && Character.isDigit(message.charAt(6))) { int check = Integer.parseInt(message.charAt(6) + ""); if (sender.getNick().equalsIgnoreCase(mpB.getPlayer1())) { Pokemon p = mpB.player1.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } else if (sender.getNick().equalsIgnoreCase(mpB.getPlayer2())) { Pokemon p = mpB.player2.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } } if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof MultiplayerBattle) && (sender.getNick().equalsIgnoreCase(mpB.getPlayer1()) || sender.getNick().equalsIgnoreCase(mpB.getPlayer2()))) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon."); } } if (isInBattle() && battle instanceof PWTBattle) { PWTBattle mpB = (PWTBattle) battle; if (message.toLowerCase().startsWith("!run") || (message.toLowerCase().startsWith("!switch") && message.length() >= 8 && Character.isDigit(message.charAt(7))) || Move.isValidMove(message)) { if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { try { mpB.p1msg.put(message); } catch (Exception ex) { } } if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { try { mpB.p2msg.put(message); } catch (Exception ex) { } } } if (message.toLowerCase().startsWith("!list")) { if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { try { String pokemon = mpB.player1.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { try { String pokemon = mpB.player2.getPokemonList(); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Your pokemon are: " + pokemon); } catch (Exception ex) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " You have no other Pokemon in your party!"); } } return; } if (message.toLowerCase().startsWith("!check") && message.length() >= 7 && Character.isDigit(message.charAt(6))) { int check = Integer.parseInt(message.charAt(6) + ""); if (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) { Pokemon p = mpB.player1.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } else if (sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { Pokemon p = mpB.player2.getPokemon(check); this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Status of " + p.getName() + " (" + p.getType1() + ((p.getType2() != Type.NONE) ? "/" + p.getType2() : "") + "): " + p.getStat(Stats.HP) + " out of " + p.getMaxHP() + "hp left. Has these moves: " + p.getMove1().getName() + ", " + p.getMove2().getName() + ", " + p.getMove3().getName() + ", " + p.getMove4().getName()); } } if (message.toLowerCase().startsWith("!help") && (isInBattle() && battle instanceof PWTBattle) && (sender.getNick().equalsIgnoreCase(mpB.player1.getTrainerName())) || sender.getNick().equalsIgnoreCase(mpB.player2.getTrainerName())) { this.sendMessage(channel.getChannelName(), "/w " + sender.getNick() + " Type !list to see a list of your Pokemon. Type !checkx where x is the number of the Pokemon from !list to see it's moves. Type !switchx where x is number of the Pokemon from !list to switch to a Pokemon."); } } if (isInBattle() && battle instanceof SafariBattle) { SafariBattle sB = (SafariBattle) battle; if (sender.getNick().equalsIgnoreCase(sB.user.getTrainerName())) { if (message.toLowerCase().startsWith("!rock") || message.toLowerCase().startsWith("!bait") || message.toLowerCase().startsWith("!ball") || message.toLowerCase().startsWith("!run")) { if (this.getOutgoingQueueSize() == 0) { sB.msg.add(message.split(" ", 2)[0].toLowerCase()); } } } } if (!isInBattle() && !waitingPlayer && !waitingPWT) { if (message.startsWith("!safari")) { Thread t = new Thread(() -> { int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; int id = new SecureRandom().nextInt(718 - 1 + 1) + 1; System.err.println("Attempting Pokemon ID " + id + " level " + level); SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level)); battle = sB; sB.doBattle(this, channel.getChannelName()); System.err.println("Now out of Safari Battle"); battle = null; }); t.start(); } } if (!isInBattle() && !waitingPlayer && !waitingPWT) { if (message.startsWith("!pwt")) { this.sendMessage(channel, sender.getNick() + " has started a new Random Pokemon World Tournament! Type !join to join. The PWT will start in 60 seconds."); //this.sendMessage(channel,"Debug mode for PWT activated, wait 60 sec"); pwtQueue.add(sender.getNick().toLowerCase()); music.play(new File(ROOT_PATH + "\\pwt\\pwt-lobby.mp3")); waitingPWT = true; Thread t = new Thread(() -> { try { ArrayList<Trainer> randoms = new ArrayList<>(); Thread tet = new Thread(() -> { outer: while (waitingPWT) { Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL); if (randoms.isEmpty()) { randoms.add(rand); System.err.println("Added " + rand + " " + rand.getPokemon()); continue; } for (Trainer el : randoms) { if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) { continue outer; } } randoms.add(rand); System.err.println("Added " + rand + " " + rand.getPokemon()); } }); tet.start(); Thread.sleep(60000); // while (randoms.size() < 7) { // outer: // while (waitingPWT) { // Trainer rand = PWTournament.generateTrainer(PWTType.RANDOM, PWTClass.NORMAL); // if (randoms.isEmpty()) { // randoms.add(rand); // System.err.println("Added " + rand + " " + rand.getPokemon()); // continue; // } // for (Trainer el : randoms) { // if (el.getTrainerName().equalsIgnoreCase(rand.getTrainerName())) { // continue outer; // } // } // randoms.add(rand); // System.err.println("Added " + rand + " " + rand.getPokemon()); // } // } waitingPWT = false; inPWT = true; this.sendMessage(channel, "The " + PWTType.RANDOM + " Pokemon World Tournament is starting! Stand by while I generate Pokemon... the first match will begin soon!"); ArrayList<Trainer> pwtList = new ArrayList<>(); for (String el : pwtQueue) { ArrayList<Pokemon> p = Trainer.generatePokemon(3, 50); Trainer te = new Trainer(el, Trainer.getTrainerClass(el), Region.getRandomRegion(), p, false); pwtList.add(te); } Collections.shuffle(pwtList); PWTournament pwt = new PWTournament(PWTType.RANDOM, PWTClass.NORMAL, pwtList, randoms); pwt.arrangeBracket(); pwt.doTourney(this, channel.getChannelName()); pwtQueue = new ArrayList<>(); waitingPWT = false; inPWT = false; } catch (Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```An error occurred in the PWT!!\n" + sw.toString() + "```"); pwtQueue = new ArrayList<>(); waitingPWT = false; inPWT = false; } }); t.start(); } } if (!isInBattle() && waitingPWT) { if (message.toLowerCase().startsWith("!join") && pwtQueue.size() < 4) { if (!pwtQueue.contains(sender.getNick().toLowerCase())) { pwtQueue.add(sender.getNick().toLowerCase()); this.sendMessage(channel, sender.getNick() + " has been added to the PWT! Type !join to join."); return; } } } if (message.toLowerCase().startsWith("!help") && !isInBattle()) { this.sendMessage(channel.getChannelName(), "https://github.com/robomaeyhem/WowBattleBot (scroll down to see the Readme)"); } if (message.toLowerCase().startsWith("!randbat @") || message.toLowerCase().startsWith("!randombattle @")) { if (isInBattle() || waitingPlayer || waitingPWT) { return; } //if ((message.toLowerCase().startsWith("!challenge @") || message.toLowerCase().startsWith("!multibattle @")) && !inMultiBattle && !inPokemonBattle && !inSafariBattle) { final String messageFinal = message; Thread t = new Thread(() -> { try { String target = messageFinal.split("@", 2)[1].split(" ", 2)[0]; if (target.isEmpty() || target.contains("/") || target.contains(".")) { this.sendMessage(channel, "FUNgineer"); return; } int pkmAmt = 1; try { pkmAmt = Integer.parseInt(messageFinal.split("@", 2)[1].split(" ", 2)[1].split(" ", 2)[0]); } catch (Exception ex2) { pkmAmt = 1; } if (pkmAmt < 1) { pkmAmt = 1; } if (pkmAmt > 6) { pkmAmt = 6; } if (target.equalsIgnoreCase(sender.getNick())) { this.sendMessage(channel.getChannelName(), "You cannot challenge yourself FUNgineer"); return; } if (target.equalsIgnoreCase("frunky5") || target.equalsIgnoreCase("23forces") || target.equalsIgnoreCase("groudonger")) { } else if (target.equalsIgnoreCase("wow_deku_onehand") || target.equalsIgnoreCase("wow_battlebot_onehand") || User.isBot(target) || target.equalsIgnoreCase("killermapper")) { this.sendMessage(channel.getChannelName(), "FUNgineer"); return; } if (!waitingPlayer) { waitingPlayer = true; waitingOn = target; this.sendMessage(channel.getChannelName(), "Challenging " + target + "..."); int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; while (level < 20) { level = new SecureRandom().nextInt(100 - 20 + 1) + 20; } boolean isHere = false; for (User el : this.getUsers(channel.getChannelName())) { if (target.equalsIgnoreCase(el.getNick())) { isHere = true; break; } } if (!isHere) { append(sender.getNick() + " SENDING INVITE"); BattleBot.sendAnInvite(target, "_keredau_1423645868201", oAuth); } this.sendWhisper(target, "You have been challenged to a Pokemon Battle by " + sender.getNick() + "! To accept, go to the Battle Dungeon and type !accept. You have one minute."); String player2 = player.poll(60, TimeUnit.SECONDS); if (player2 == null) { this.sendMessage(channel.getChannelName(), target + " did not respond to the challenge BibleThump"); waitingPlayer = false; waitingOn = ""; return; } waitingPlayer = false; waitingOn = ""; this.sendMessage(channel.getChannelName(), "Generating Pokemon, give me a minute..."); System.err.println("Going into Multiplayer Battle"); MultiplayerBattle mpB = new MultiplayerBattle(this, sender.getNick(), target, level, pkmAmt); battle = mpB; mpB.doBattle(channel.getChannelName()); battle = null; System.err.println("Now out of Multiplayer Battle"); } } catch (Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "\n```"); waitingPlayer = false; battle = null; } }); t.start(); } if (message.toLowerCase().startsWith("!test ") && sender.getNick().equalsIgnoreCase("the_chef1337")) { String test = message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0]; if (!test.equalsIgnoreCase("pwt") && !Character.isDigit(message.charAt(6))) { final String senderFinal = "the_chef1337"; Thread t = new Thread(() -> { try { pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = senderFinal; System.err.println("Going into Pokemon Battle"); PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), false, false, sender.getNick(), true); System.err.println("Now out of Pokemon Battle"); pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = ""; battle = null; } catch (Exception ex) { personInBattle = ""; pokemonMessages = new LinkedBlockingQueue<>(); this.sendMessage(channel.getChannelName(), "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW"); System.err.println("[POKEMON] Uh oh " + ex); ex.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "```"); battle = null; } }); t.start(); } else if (message.toLowerCase().split("!test ", 2)[1].split(" ", 2)[0].equalsIgnoreCase("pwt")) { Trainer t = new Trainer("Cynthia", "Sinnoh Champion", Region.SINNOH, Trainer.generatePokemon(3, 50), true); Trainer m = new Trainer("23forces", "Elite Four", Region.getRandomRegion(), Trainer.generatePokemon(3, 50), true); //String name, String trnClass, Region region, ArrayList<Pokemon> pokemon, boolean ai this.sendMessage(channel, PWTRound.FIRST_ROUND.getText() + "match of the " + PWTType.RANDOM + " tournament! This match is between " + t + " and " + m + "!"); PWTBattle b = new PWTBattle(this, m, t, PWTType.RANDOM, PWTClass.NORMAL, PWTRound.FIRST_ROUND); battle = b; Thread th = new Thread(() -> { try { this.music.play(PWTBattle.determineMusic(b)); b.doBattle(channel.getChannelName()); battle = null; } catch (Exception ex) { ex.printStackTrace(); } }); th.start(); } else { final int finalId = Integer.parseInt(message.split("!test ", 2)[1].split(" ", 2)[0]); Thread t = new Thread(() -> { int level = new SecureRandom().nextInt(100 - 20 + 1) + 20; int id = finalId; System.err.println("Attempting Pokemon ID " + id + " level " + level); SafariBattle sB = new SafariBattle(this, sender.getNick(), new Pokemon(id, level)); battle = sB; sB.doBattle(this, channel.getChannelName()); System.err.println("Now out of Safari Battle"); battle = null; }); t.start(); } } if (message.toLowerCase().startsWith("!battle") && !waitingPlayer && !waitingPWT && !isInBattle()) { boolean bigbrother = false, fromChef = false; if (message.contains("BigBrother") || sender.getNick().equalsIgnoreCase("dewgong98") || sender.getNick().equalsIgnoreCase("mad_king98") || sender.getNick().equalsIgnoreCase("Starmiewaifu")) { bigbrother = true; if (sender.getNick().equalsIgnoreCase("the_chef1337")) { fromChef = true; } } final boolean bbrother = bigbrother; final boolean fChef = fromChef; if (sender.getNick().equalsIgnoreCase("twitchplaysleaderboard")) { return; } else { final String senderFinal = sender.getNick(); if (!isInBattle() && !waitingPlayer && !waitingPWT) { Thread t = new Thread(() -> { try { pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = senderFinal; System.err.println("Going into Pokemon Battle"); PokemonBattle a = new PokemonBattle(this, channel.getChannelName(), bbrother, fChef, sender.getNick(), false); System.err.println("Now out of Pokemon Battle"); pokemonMessages = new LinkedBlockingQueue<>(); personInBattle = ""; battle = null; } catch (Exception ex) { personInBattle = ""; pokemonMessages = new LinkedBlockingQueue<>(); this.sendMessage(channel.getChannelName(), "Something fucked up OneHand this battle is now over both Pokemon exploded violently KAPOW"); System.err.println("[POKEMON] Uh oh " + ex); ex.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); music.sendMessage(music.getChannel(), music.CHEF.mention() + " ```" + sw.toString() + "```"); battle = null; } }); t.start(); } } } if (message.toLowerCase().startsWith("!run")) { if (!channel.getChannelName().equals("#_keredau_1423645868201")) { return; } if (isInBattle() && battle instanceof PokemonBattle) { if (sender.getNick().equalsIgnoreCase(personInBattle)) { // if (DekuBot.containsOtherChar(message)) { // this.sendMessage(channel.getChannelName(), sender + "... TriHard"); // return; // } personInBattle = ""; pokemonMessages.add("run"); } } } if (message.toLowerCase().startsWith("!move1") || message.toLowerCase().startsWith("!move2") || message.toLowerCase().startsWith("!move3") || message.toLowerCase().startsWith("!move4")) { if (sender.getNick().equalsIgnoreCase("wow_deku_onehand")) { return; } if (!channel.getChannelName().equals("#_keredau_1423645868201")) { return; } if (isInBattle() && battle instanceof PokemonBattle) { if (sender.getNick().equalsIgnoreCase(personInBattle)) { pokemonMessages.add("" + message.charAt(5)); } } } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * TODO: add same functionality & checks as in HTTPDemon.parseMultipart * * parse multi-part form data for formfields, see also original * implementation in HTTPDemon.parseMultipart * * For file data the parameter for the formfield contains the filename and a * additional parameter with appendix [fieldname]$file conteins the upload content * (e.g. <input type="file" name="upload"> upload="local/filename" upload$file=[content]) * * @param request/*from w w w. j av a2s .co m*/ * @param args found fields/values are added to the map */ protected void parseMultipart(final HttpServletRequest request, final serverObjects args) throws IOException { // reject too large uploads if (request.getContentLength() > SIZE_FILE_THRESHOLD) throw new IOException("FileUploadException: uploaded file too large = " + request.getContentLength()); // check if we have enough memory if (!MemoryControl.request(request.getContentLength() * 3, false)) { throw new IOException("not enough memory available for request. request.getContentLength() = " + request.getContentLength() + ", MemoryControl.available() = " + MemoryControl.available()); } ServletFileUpload upload = new ServletFileUpload(DISK_FILE_ITEM_FACTORY); upload.setFileSizeMax(SIZE_FILE_THRESHOLD); try { // Parse the request to get form field items List<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator<FileItem> i = fileItems.iterator(); final BlockingQueue<Map.Entry<String, byte[]>> files = new LinkedBlockingQueue<>(); while (i.hasNext()) { FileItem item = i.next(); if (item.isFormField()) { // simple text if (item.getContentType() == null || !item.getContentType().contains("charset")) { // old yacy clients use their local default charset, on most systems UTF-8 (I hope ;) args.add(item.getFieldName(), item.getString(StandardCharsets.UTF_8.name())); } else { // use default encoding (given as header or ISO-8859-1) args.add(item.getFieldName(), item.getString()); } } else { // read file upload args.add(item.getFieldName(), item.getName()); // add the filename to the parameters InputStream filecontent = null; try { filecontent = item.getInputStream(); files.put(new AbstractMap.SimpleEntry<String, byte[]>(item.getFieldName(), FileUtils.read(filecontent))); } catch (IOException e) { ConcurrentLog.info("FILEHANDLER", e.getMessage()); } finally { if (filecontent != null) try { filecontent.close(); } catch (IOException e) { ConcurrentLog.info("FILEHANDLER", e.getMessage()); } } } } if (files.size() <= 1) { // TODO: should include additonal checks to limit parameter.size below rel. large SIZE_FILE_THRESHOLD for (Map.Entry<String, byte[]> job : files) { // add the file content to parameter fieldname$file String n = job.getKey(); byte[] v = job.getValue(); String filename = args.get(n); if (filename != null && filename.endsWith(".gz")) { // transform this value into base64 String b64 = Base64Order.standardCoder.encode(v); args.put(n + "$file", b64); args.remove(n); args.put(n, filename + ".base64"); } else { args.put(n + "$file", v); // the byte[] is transformed into UTF8. You cannot push binaries here } } } else { // do this concurrently (this would all be superfluous if serverObjects could store byte[] instead only String) int t = Math.min(files.size(), Runtime.getRuntime().availableProcessors()); final Map.Entry<String, byte[]> POISON = new AbstractMap.SimpleEntry<>(null, null); Thread[] p = new Thread[t]; for (int j = 0; j < t; j++) { files.put(POISON); p[j] = new Thread("YaCyDefaultServlet.parseMultipart-" + j) { @Override public void run() { Map.Entry<String, byte[]> job; try { while ((job = files.take()) != POISON) { String n = job.getKey(); byte[] v = job.getValue(); String filename = args.get(n); String b64 = Base64Order.standardCoder.encode(v); synchronized (args) { args.put(n + "$file", b64); args.remove(n); args.put(n, filename + ".base64"); } } } catch (InterruptedException e) { } } }; p[j].start(); } for (int j = 0; j < t; j++) p[j].join(); } } catch (Exception ex) { ConcurrentLog.info("FILEHANDLER", ex.getMessage()); } }
From source file:com.mirth.connect.server.controllers.DonkeyEngineController.java
@Override public synchronized List<ChannelFuture> submitTasks(List<ChannelTask> tasks, ChannelTaskHandler handler) { List<ChannelFuture> futures = new ArrayList<ChannelFuture>(); /*// w w w . j av a 2 s . c o m * If no handler is given then use the default handler to that at least errors will be * logged out. */ if (handler == null) { handler = new LoggingTaskHandler(); } for (ChannelTask task : tasks) { ExecutorService engineExecutor = engineExecutors.get(task.getChannelId()); if (engineExecutor == null) { engineExecutor = new ThreadPoolExecutor(0, 1, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); engineExecutors.put(task.getChannelId(), engineExecutor); } task.setHandler(handler); try { futures.add(task.submitTo(engineExecutor)); } catch (RejectedExecutionException e) { /* * This can happen if a channel was halted, in which case we don't want to perform * whatever task this was anyway. */ handler.taskErrored(task.getChannelId(), task.getMetaDataId(), e); } } return futures; }