List of usage examples for org.apache.commons.lang3.mutable MutableBoolean setTrue
public void setTrue()
From source file:bwem.MapDrawer.java
private boolean processCommandVariants(String command, String attributName, MutableBoolean attribut) { if (command.equals("show " + attributName)) { attribut.setTrue(); return true; }//from w ww . j a v a 2s .c o m if (command.equals("hide " + attributName)) { attribut.setFalse(); return true; } if (command.equals(attributName)) { attribut.setValue(!attribut.booleanValue()); return true; } return false; }
From source file:io.codis.nedis.handler.RedisResponseDecoder.java
private Long decodeLong(ByteBuf in) throws ProtocolException { byte sign = in.readByte(); final MutableLong l; boolean negative; if (sign == '-') { negative = true;/*from w w w. j av a2s . co m*/ l = new MutableLong(0); } else { negative = false; l = new MutableLong(toDigit(sign)); } final MutableBoolean reachCR = new MutableBoolean(false); setReaderIndex(in, in.forEachByte(new ByteBufProcessor() { @Override public boolean process(byte value) throws Exception { if (value == '\r') { reachCR.setTrue(); return false; } else { if (value >= '0' && value <= '9') { l.setValue(l.longValue() * 10 + toDigit(value)); } else { throw new ProtocolException("Response is not ended by CRLF"); } return true; } } })); if (!reachCR.booleanValue()) { return null; } if (!in.isReadable()) { return null; } if (in.readByte() != '\n') { throw new ProtocolException("Response is not ended by CRLF"); } return negative ? -l.longValue() : l.longValue(); }
From source file:de.uni_potsdam.hpi.asg.logictool.helper.BDDHelper.java
public static boolean evaluateBDD(MutableBoolean result, BDD bdd, State state, Netlist netlist) { if (bdd == null) { return false; }/*from ww w . j ava 2 s. c o m*/ BDD bdd2 = bdd.and(bdd.getFactory().one()); for (Entry<Signal, Value> entry : state.getStateValues().entrySet()) { BDD sigbdd = null; switch (entry.getValue()) { case falling: case high: sigbdd = netlist.getNetlistVariableBySignal(entry.getKey()).toBDD(); break; case low: case rising: sigbdd = netlist.getNetlistVariableBySignal(entry.getKey()).toNotBDD(); break; } bdd2 = bdd2.restrictWith(sigbdd); } for (Entry<NetlistVariable, Boolean> entry : netlist.getQuasiSignals().entrySet()) { BDD sigbdd = null; if (entry.getValue()) { //true => Normally 1 sigbdd = entry.getKey().toBDD(); } else { sigbdd = entry.getKey().toNotBDD(); } bdd2 = bdd2.restrictWith(sigbdd); } if (bdd2.isOne()) { result.setTrue(); } else if (bdd2.isZero()) { result.setFalse(); } else { System.out.println(BDDHelper.getFunctionString(bdd2, netlist)); logger.error("BDD not restricted enough?!"); return false; } return true; }
From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImplTest.java
@SuppressWarnings("unchecked") @Test//from ww w . ja v a 2s . c o m public void testGetInputStreamExceptionHandling() throws Exception { final GzipCacheImpl impl = new GzipCacheImpl(); EasyMock.replay(mockAggregator, mockCacheManager); impl.setAggregator(mockAggregator); final MutableInt retLength = new MutableInt(); final CountDownLatch latch3 = new CountDownLatch(1); EasyMock.reset(mockCacheManager); EasyMock.expect(mockCacheManager.getCacheDir()).andReturn(tempdir).anyTimes(); mockCacheManager.createCacheFileAsync(EasyMock.isA(String.class), EasyMock.isA(InputStream.class), EasyMock.isA(ICacheManager.CreateCompletionCallback.class)); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { latch1.countDown(); latch2.await(); throw new IOException("test generated exception"); } }).anyTimes(); EasyMock.replay(mockCacheManager); // get input stream (should throw execption because file was deleted final MutableBoolean exceptionCaught = new MutableBoolean(false); new Thread(new Runnable() { @Override public void run() { try { InputStream is = impl.getInputStream("key", tempfile.toURI(), retLength); } catch (Exception ex) { exceptionCaught.setTrue(); } latch3.countDown(); } }).start(); latch1.await(); IGzipCache.ICacheEntry cacheEntry = impl.get("key"); latch2.countDown(); latch3.await(); Assert.assertTrue(exceptionCaught.isTrue()); Assert.assertNotNull(Whitebox.getInternalState(cacheEntry, "ex")); Assert.assertNull(impl.get("key")); }
From source file:io.codis.nedis.handler.RedisResponseDecoder.java
private String decodeString(ByteBuf in) throws ProtocolException { final StringBuilder buffer = new StringBuilder(); final MutableBoolean reachCRLF = new MutableBoolean(false); setReaderIndex(in, in.forEachByte(new ByteBufProcessor() { @Override/*from w w w . jav a 2s . co m*/ public boolean process(byte value) throws Exception { if (value == '\n') { if ((byte) buffer.charAt(buffer.length() - 1) != '\r') { throw new ProtocolException("Response is not ended by CRLF"); } else { buffer.setLength(buffer.length() - 1); reachCRLF.setTrue(); return false; } } else { buffer.append((char) value); return true; } } })); return reachCRLF.booleanValue() ? buffer.toString() : null; }
From source file:com.github.jrh3k5.mojo.flume.AbstractFlumeAgentsMojoTest.java
/** * Test the building of the agent process. * //from www . ja v a 2s .c o m * @throws Exception * If any errors occur during the test run. */ @Test public void testBuildAgentProcess() throws Exception { final File flumeDirectory = mock(File.class); final AgentProcess.Builder agentProcessBuilder = mock(AgentProcess.Builder.class); mockStatic(AgentProcess.class); when(AgentProcess.newBuilder(flumeDirectory)).thenReturn(agentProcessBuilder); final AgentProcess agentProcess = mock(AgentProcess.class); when(agentProcessBuilder.withAgent(agentName)).thenReturn(agentProcessBuilder); when(agentProcessBuilder.withConfigFile(configFile)).thenReturn(agentProcessBuilder); when(agentProcessBuilder.build()).thenReturn(agentProcess); final MutableBoolean copiedPlugins = new MutableBoolean(false); final MutableBoolean unpackedFlume = new MutableBoolean(false); final MutableBoolean wroteFlumeEnvironment = new MutableBoolean(false); final MutableBoolean removedLibs = new MutableBoolean(false); final MutableBoolean copiedLoggingProperties = new MutableBoolean(false); final List<Agent> passedAgents = new ArrayList<Agent>(); final ConcreteMojo toTest = setParameters(new ConcreteMojo() { @Override void copyFlumePlugins(Agent agent, File givenFlumeDirectory) throws IOException { passedAgents.add(agent); copiedPlugins.setTrue(); assertThat(givenFlumeDirectory).isEqualTo(flumeDirectory); } @Override File unpackFlume(Agent agent, FlumeArchiveCache archiveCache) throws IOException { passedAgents.add(agent); unpackedFlume.setTrue(); return flumeDirectory; } @Override void writeFlumeEnvironment(Agent agent, File givenFlumeDirectory) throws IOException { passedAgents.add(agent); wroteFlumeEnvironment.setTrue(); assertThat(givenFlumeDirectory).isEqualTo(flumeDirectory); } @Override void removeLibs(Agent agent, File givenFlumeDirectory) throws IOException { passedAgents.add(agent); removedLibs.setTrue(); assertThat(givenFlumeDirectory).isEqualTo(flumeDirectory); } @Override void copyLoggingProperties(Agent agent, File givenFlumeDirectory) throws IOException { passedAgents.add(agent); copiedLoggingProperties.setTrue(); assertThat(givenFlumeDirectory).isEqualTo(flumeDirectory); } }); assertThat(toTest.buildAgentProcess(agent)).isEqualTo(agentProcess); assertThat(copiedPlugins.isTrue()).isTrue(); assertThat(unpackedFlume.isTrue()).isTrue(); assertThat(wroteFlumeEnvironment.isTrue()).isTrue(); assertThat(passedAgents).hasSize(5).containsOnly(agent); }
From source file:functionaltests.RestSmartProxyTest.java
@Test(timeout = TEN_MINUTES) public void testInErrorEventsReception() throws Exception { TaskFlowJob job = createInErrorJob(); final Semaphore semaphore = new Semaphore(0); printJobXmlRepresentation(job);// w w w .j a va 2 s . c om final MutableBoolean taskHasBeenInError = new MutableBoolean(false); final MutableBoolean restartedFromErrorEventReceived = new MutableBoolean(false); SchedulerEventListenerExtended listener = new SchedulerEventListenerExtended() { @Override public void schedulerStateUpdatedEvent(SchedulerEvent eventType) { System.out.println("RestSmartProxyTest.schedulerStateUpdatedEvent " + eventType); } @Override public void jobSubmittedEvent(JobState job) { System.out.println("RestSmartProxyTest.jobSubmittedEvent"); } @Override public void jobStateUpdatedEvent(NotificationData<JobInfo> notification) { JobStatus status = notification.getData().getStatus(); System.out.println("RestSmartProxyTest.jobStateUpdatedEvent, eventType=" + notification.getEventType() + ", jobStatus=" + status); if (notification.getEventType() == SchedulerEvent.JOB_RESTARTED_FROM_ERROR) { restartedFromErrorEventReceived.setTrue(); } if (status == JobStatus.IN_ERROR) { semaphore.release(); } } @Override public void taskStateUpdatedEvent(NotificationData<TaskInfo> notification) { TaskStatus status = notification.getData().getStatus(); System.out.println("RestSmartProxyTest.taskStateUpdatedEvent, taskStatus=" + status); if (status == TaskStatus.WAITING_ON_ERROR || status == TaskStatus.IN_ERROR) { // IN_ERROR previously taskHasBeenInError.setTrue(); } } @Override public void usersUpdatedEvent(NotificationData<UserIdentification> notification) { System.out.println("RestSmartProxyTest.usersUpdatedEvent " + notification.getData()); } @Override public void pullDataFinished(String jobId, String taskName, String localFolderPath) { System.out.println("RestSmartProxyTest.pullDataFinished"); } @Override public void pullDataFailed(String jobId, String taskName, String remoteFolder_URL, Throwable t) { System.out.println("RestSmartProxyTest.pullDataFailed"); } @Override public void jobUpdatedFullDataEvent(JobState job) { System.out.println("RestSmartProxyTest.jobUpdatedFullDataEvent"); } }; restSmartProxy.addEventListener(listener); JobId jobId = restSmartProxy.submit(job, inputLocalFolder.getAbsolutePath(), pushUrl, outputLocalFolder.getAbsolutePath(), pullUrl, false, false); // the next line blocks until jobStateUpdatedEvent is called on the // listener // with job status set to IN_ERROR semaphore.acquire(); String jobIdAsString = jobId.value(); System.out.println("Restarting all In-Error tasks"); restSmartProxy.restartAllInErrorTasks(jobIdAsString); assertThat(restartedFromErrorEventReceived.booleanValue()).isTrue(); assertThat(taskHasBeenInError.booleanValue()).isTrue(); }
From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java
private boolean evaluateBDD(MutableBoolean result, BDD bdd, State state) { BDD bdd2 = bdd.and(factory.one());// w w w . jav a 2 s . co m for (Entry<Signal, Value> entry : state.getStateValues().entrySet()) { BDD sigbdd = null; switch (entry.getValue()) { case falling: case high: sigbdd = getPosBDD(entry.getKey()); break; case low: case rising: sigbdd = getNegBDD(entry.getKey()); break; } bdd2 = bdd2.restrictWith(sigbdd); } for (Entry<NetlistVariable, Boolean> entry : netlist.getQuasiSignals().entrySet()) { BDD sigbdd = null; if (entry.getValue()) { //true => Normally 1 sigbdd = getPosBDD(quasimap.get(entry.getKey())); } else { sigbdd = getNegBDD(quasimap.get(entry.getKey())); } bdd2 = bdd2.restrictWith(sigbdd); } if (bdd2.isOne()) { result.setTrue(); } else if (bdd2.isZero()) { result.setFalse(); } else { System.out.println(BDDHelper.getFunctionString(bdd2, netlist)); logger.error("BDD not restricted enough?!"); return false; } return true; }
From source file:org.apache.flink.streaming.connectors.kinesis.internals.KinesisDataFetcherTest.java
@Test public void testPeriodicWatermark() { final MutableLong clock = new MutableLong(); final MutableBoolean isTemporaryIdle = new MutableBoolean(); final List<Watermark> watermarks = new ArrayList<>(); String fakeStream1 = "fakeStream1"; StreamShardHandle shardHandle = new StreamShardHandle(fakeStream1, new Shard().withShardId(KinesisShardIdGenerator.generateFromShardOrder(0))); TestSourceContext<String> sourceContext = new TestSourceContext<String>() { @Override//from ww w .ja va2 s . c om public void emitWatermark(Watermark mark) { watermarks.add(mark); } @Override public void markAsTemporarilyIdle() { isTemporaryIdle.setTrue(); } }; HashMap<String, String> subscribedStreamsToLastSeenShardIdsUnderTest = new HashMap<>(); final KinesisDataFetcher<String> fetcher = new TestableKinesisDataFetcher<String>( Collections.singletonList(fakeStream1), sourceContext, new java.util.Properties(), new KinesisDeserializationSchemaWrapper<>( new org.apache.flink.streaming.util.serialization.SimpleStringSchema()), 1, 1, new AtomicReference<>(), new LinkedList<>(), subscribedStreamsToLastSeenShardIdsUnderTest, FakeKinesisBehavioursFactory.nonReshardedStreamsBehaviour(new HashMap<>())) { @Override protected long getCurrentTimeMillis() { return clock.getValue(); } }; Whitebox.setInternalState(fetcher, "periodicWatermarkAssigner", watermarkAssigner); SequenceNumber seq = new SequenceNumber("fakeSequenceNumber"); // register shards to subsequently emit records int shardIndex = fetcher.registerNewSubscribedShardState(new KinesisStreamShardState( KinesisDataFetcher.convertToStreamShardMetadata(shardHandle), shardHandle, seq)); StreamRecord<String> record1 = new StreamRecord<>(String.valueOf(Long.MIN_VALUE), Long.MIN_VALUE); fetcher.emitRecordAndUpdateState(record1.getValue(), record1.getTimestamp(), shardIndex, seq); Assert.assertEquals(record1, sourceContext.getCollectedOutputs().poll()); fetcher.emitWatermark(); Assert.assertTrue("potential watermark equals previous watermark", watermarks.isEmpty()); StreamRecord<String> record2 = new StreamRecord<>(String.valueOf(1), 1); fetcher.emitRecordAndUpdateState(record2.getValue(), record2.getTimestamp(), shardIndex, seq); Assert.assertEquals(record2, sourceContext.getCollectedOutputs().poll()); fetcher.emitWatermark(); Assert.assertFalse("watermark advanced", watermarks.isEmpty()); Assert.assertEquals(new Watermark(record2.getTimestamp()), watermarks.remove(0)); Assert.assertFalse("not idle", isTemporaryIdle.booleanValue()); // test idle timeout long idleTimeout = 10; // advance clock idleTimeout clock.add(idleTimeout + 1); fetcher.emitWatermark(); Assert.assertFalse("not idle", isTemporaryIdle.booleanValue()); Assert.assertTrue("not idle, no new watermark", watermarks.isEmpty()); // activate idle timeout Whitebox.setInternalState(fetcher, "shardIdleIntervalMillis", idleTimeout); fetcher.emitWatermark(); Assert.assertTrue("idle", isTemporaryIdle.booleanValue()); Assert.assertTrue("idle, no watermark", watermarks.isEmpty()); }
From source file:org.apache.pulsar.broker.loadbalance.impl.OverloadShedder.java
/** * Attempt to shed some bundles off every broker which is overloaded. * * @param loadData/*from w w w . j a v a2s .co m*/ * The load data to used to make the unloading decision. * @param conf * The service configuration. * @return A map from bundles to unload to the brokers on which they are loaded. */ public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final Map<String, Long> recentlyUnloadedBundles = loadData.getRecentlyUnloadedBundles(); // Check every broker and select loadData.getBrokerData().forEach((broker, brokerData) -> { final LocalBrokerData localData = brokerData.getLocalData(); final double currentUsage = localData.getMaxResourceUsage(); if (currentUsage < overloadThreshold) { if (log.isDebugEnabled()) { log.debug("[{}] Broker is not overloaded, ignoring at this point", broker); } return; } // We want to offload enough traffic such that this broker will go below the overload threshold // Also, add a small margin so that this broker won't be very close to the threshold edge. double percentOfTrafficToOffload = currentUsage - overloadThreshold + ADDITIONAL_THRESHOLD_PERCENT_MARGIN; double brokerCurrentThroughput = localData.getMsgThroughputIn() + localData.getMsgThroughputOut(); double minimumThroughputToOffload = brokerCurrentThroughput * percentOfTrafficToOffload; log.info( "Attempting to shed load on {}, which has max resource usage above threshold {}% > {}% -- Offloading at least {} MByte/s of traffic", broker, currentUsage, overloadThreshold, minimumThroughputToOffload / 1024 / 1024); MutableDouble trafficMarkedToOffload = new MutableDouble(0); MutableBoolean atLeastOneBundleSelected = new MutableBoolean(false); if (localData.getBundles().size() > 1) { // Sort bundles by throughput, then pick the biggest N which combined make up for at least the minimum throughput to offload loadData.getBundleData().entrySet().stream().map((e) -> { // Map to throughput value // Consider short-term byte rate to address system resource burden String bundle = e.getKey(); BundleData bundleData = e.getValue(); TimeAverageMessageData shortTermData = bundleData.getShortTermData(); double throughput = shortTermData.getMsgThroughputIn() + shortTermData.getMsgThroughputOut(); return Pair.of(bundle, throughput); }).filter(e -> { // Only consider bundles that were not already unloaded recently return !recentlyUnloadedBundles.containsKey(e.getLeft()); }).sorted((e1, e2) -> { // Sort by throughput in reverse order return Double.compare(e2.getRight(), e1.getRight()); }).forEach(e -> { if (trafficMarkedToOffload.doubleValue() < minimumThroughputToOffload || atLeastOneBundleSelected.isFalse()) { selectedBundlesCache.put(broker, e.getLeft()); trafficMarkedToOffload.add(e.getRight()); atLeastOneBundleSelected.setTrue(); } }); } else if (localData.getBundles().size() == 1) { log.warn( "HIGH USAGE WARNING : Sole namespace bundle {} is overloading broker {}. " + "No Load Shedding will be done on this broker", localData.getBundles().iterator().next(), broker); } else { log.warn("Broker {} is overloaded despite having no bundles", broker); } }); return selectedBundlesCache; }