auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { processInternal(annotations, roundEnv); } catch (DeepLinkProcessorException e) { error(e.getElement(), e.getMessage()); } return true; }

Target:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { processInternal(annotations, roundEnv); } catch (DeepLinkProcessorException e) { error(e.getElement(), e.getMessage()); } return false; }
Source:
public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); sb.append(remoteException.getSuppressed().toString()); if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); }

Target:
public void setRemoteException(Throwable remoteException) { StringBuilder sb = new StringBuilder(); Set<Throwable> causes = new HashSet(); while (remoteException != null) { sb.append(remoteException.toString()); StackTraceElement[] stackTraceElements = remoteException.getStackTrace(); if (stackTraceElements != null && stackTraceElements.length > 0) { for (StackTraceElement ste : stackTraceElements) { sb.append("\n\t at ").append(ste.toString()); } sb.append("\nsuppressed: "); sb.append(Arrays.toString(remoteException.getSuppressed())); if (remoteException.getCause() != null) { sb.append("\ncaused by: "); remoteException = remoteException.getCause(); if (!causes.add(remoteException)) { break; } } else { break; } } } remoteExceptionString = sb.append('\n').toString(); }
Source:
public long getMaxIdle() { return 0; }

Target:
public Long getMaxIdle() { return null; }
Source:
private void openFetchRequest() { try { if (messageAndOffsetIterator == null) { long threadId = Thread.currentThread().getId(); if (this.consumer == null) { this.consumer = consumerManager.createConsumer(threadId, split.getLeader()); } TopicPartition tp = new TopicPartition(split.getTopicName(), split.getPartitionId()); this.consumer.assign(ImmutableList.of(tp)); this.consumer.seek(tp, cursorOffset); ConsumerRecords<ByteBuffer, ByteBuffer> records = this.consumer.poll(3000); this.consumer.commitSync(); messageAndOffsetIterator = records.records(tp).iterator(); } } catch (Exception e) { if (e instanceof PrestoException) { throw e; } throw new PrestoException( KAFKA_SPLIT_ERROR, format( "Cannot read data from topic '%s', partition '%s', startOffset %s, endOffset %s, leader %s ", split.getTopicName(), split.getPartitionId(), split.getStart(), split.getEnd(), split.getLeader()), e); } }

Target:
private void openFetchRequest() { try { if (messageAndOffsetIterator == null) { String threadName = Thread.currentThread().getName(); if (consumer == null) { consumer = consumerManager.createConsumer(threadName, split.getLeader()); } TopicPartition topicPartition = new TopicPartition(split.getTopicName(), split.getPartitionId()); consumer.assign(ImmutableList.of(topicPartition)); consumer.seek(topicPartition, cursorOffset); ConsumerRecords<ByteBuffer, ByteBuffer> records = consumer.poll(POLL_TIMEOUT); messageAndOffsetIterator = records.records(topicPartition).iterator(); } } catch (Exception e) { if (e instanceof PrestoException) { throw e; } throw new PrestoException( KAFKA_SPLIT_ERROR, format( "Cannot read data from topic '%s', partition '%s', startOffset %s, endOffset %s, leader %s ", split.getTopicName(), split.getPartitionId(), split.getStart(), split.getEnd(), split.getLeader()), e); } }
Source:
public SpringBasedHttpClient() { }

Target:
public SpringBasedHttpClient() { clientParams = new HashMap<>(); restTemplate = new RestTemplate(); restTemplate.setRequestFactory(getSslAllTrustRequestFactory()); }
Source:
public void onChapterSelected(Chapter selectedChapter) { updateSelectionFor(selectedChapter.getGplusId()); }

Target:
public void onChapterSelected(Chapter selectedChapter) { updateSelectionFor(selectedChapter); }
Source:
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { Mutation m = miniBatchOp.getOperation(0); if (!codec.isEnabled(m)) { super.preBatchMutate(c, miniBatchOp); return; } Map<String,byte[]> updateAttributes = m.getAttributesMap(); PhoenixIndexMetaData indexMetaData = new PhoenixIndexMetaData(c.getEnvironment(),updateAttributes); byte[] txRollbackAttribute = m.getAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY); Collection<Pair<Mutation, byte[]>> indexUpdates = null; try (TraceScope scope = Trace.startSpan("Starting to build index updates")) { Span current = scope.getSpan(); if (current == null) { current = NullSpan.INSTANCE; } indexUpdates = getIndexUpdates(c.getEnvironment(), indexMetaData, getMutationIterator(miniBatchOp), txRollbackAttribute); IndexUtil.addLocalUpdatesToCpOperations(c, miniBatchOp, indexUpdates, m.getDurability() != Durability.SKIP_WAL); current.addTimelineAnnotation("Built index updates, doing preStep"); TracingUtils.addAnnotation(current, "index update count", indexUpdates.size()); if (!indexUpdates.isEmpty()) { this.writer.write(indexUpdates); } } catch (Throwable t) { String msg = "Failed to update index with entries:" + indexUpdates; LOG.error(msg, t); ServerUtil.throwIOException(msg, t); } }

Target:
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { Mutation m = miniBatchOp.getOperation(0); if (!codec.isEnabled(m)) { super.preBatchMutate(c, miniBatchOp); return; } Map<String,byte[]> updateAttributes = m.getAttributesMap(); PhoenixIndexMetaData indexMetaData = new PhoenixIndexMetaData(c.getEnvironment(),updateAttributes); byte[] txRollbackAttribute = m.getAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY); Collection<Pair<Mutation, byte[]>> indexUpdates = null; try (TraceScope scope = Trace.startSpan("Starting to build index updates")) { Span current = scope.getSpan(); if (current == null) { current = NullSpan.INSTANCE; } indexUpdates = getIndexUpdates(c.getEnvironment(), indexMetaData, getMutationIterator(miniBatchOp), txRollbackAttribute); current.addTimelineAnnotation("Built index updates, doing preStep"); TracingUtils.addAnnotation(current, "index update count", indexUpdates.size()); if (!indexUpdates.isEmpty()) { this.writer.write(indexUpdates, true); } } catch (Throwable t) { String msg = "Failed to update index with entries:" + indexUpdates; LOG.error(msg, t); ServerUtil.throwIOException(msg, t); } }
Source:
protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); eye = savedInstanceState.getInt("eyeNum"); eye_setter(eye); face = savedInstanceState.getInt("faceNum"); face_setter(face); cloth = savedInstanceState.getInt("clothNum"); cloth_setter(cloth); hair = savedInstanceState.getInt("hairNum"); hair_setter(hair); }

Target:
protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); eye = savedInstanceState.getInt("eyeNum"); face = savedInstanceState.getInt("faceNum"); cloth = savedInstanceState.getInt("clothNum");; hair = savedInstanceState.getInt("hairNum"); resourceSetter(eye,getResources().getString(R.string.eye)); resourceSetter(face,getResources().getString(R.string.face)); resourceSetter(hair,getResources().getString(R.string.hair)); resourceSetter(cloth,getResources().getString(R.string.cloth)); }
Source:
public DiscountFactors discountFactors(Currency currency) { Curve curve = marketData.getValue(DiscountCurveKey.of(currency)); if (curve == null) { throw new IllegalArgumentException("Unable to find discount curve: " + currency); } return DiscountFactors.of(currency, getValuationDate(), curve); }

Target:
public DiscountFactors discountFactors(Currency currency) { Curve curve = marketData.getValue(DiscountCurveKey.of(currency)); return DiscountFactors.of(currency, getValuationDate(), curve); }
Source:
public void markJobEnded(boolean result) { if (status == ExecutionStatus.STARTED) { Date endJobTime = new Date(); endTime = endJobTime; lastUpdateTime = endJobTime; if (result) { status = ExecutionStatus.FINISHED; } else { status = ExecutionStatus.FAILED; } } }

Target:
public void markJobEnded(boolean result) { if (status == JobExecutionStatus.STARTED) { endTime = lastUpdateTime = new Date(); if (result) { status = JobExecutionStatus.FINISHED; } else { status = JobExecutionStatus.FAILED; } } }
Source:
public MorphiaSerializer(Morphia morphia) { this.morphia = morphia == null ? new Morphia() : morphia; this.geometryQueryConverter = new GeometryQueryConverter(this.morphia.getMapper()); }

Target:
public MorphiaSerializer(Morphia morphia) { Preconditions.checkNotNull(morphia); this.morphia = morphia; this.geometryQueryConverter = new GeometryQueryConverter(morphia.getMapper()); }
Source:
public Optional<RoamingGroup> findById(ID id) { RoamingGroupEntity entity = datastore.findOne(RoamingGroupEntity.class, Filter.where("_id").is(id.value)); if (entity == null) { return Optional.absent(); } List<OperatorEntity> operatorEntities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("_id").in(Lists.newArrayList(entity.operatorIDs))); return Optional.of(adapt(entity, operatorEntities)); }

Target:
public Optional<RoamingGroup> findById(ID id) { RoamingGroupEntity entity = datastore.findOne(RoamingGroupEntity.class, Filter.where("_id").is(id.value)); if (entity == null) { return Optional.absent(); } List<OperatorEntity> operatorEntities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("_id").in(entity.operatorIDs)); return Optional.of(adapt(entity, operatorEntities)); }
Source:
public static Sensor expiredWindowRecordDropSensor(final String threadId, final String taskId, final String storeType, final String storeName, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.storeLevelSensor( threadId, taskId, storeName, EXPIRED_WINDOW_RECORD_DROP, RecordingLevel.INFO ); final Version version = streamsMetrics.version(); if (version == Version.FROM_0100_TO_24) { addInvocationRateAndCountToSensor( sensor, "stream-" + storeType + "-metrics", streamsMetrics.storeLevelTagMap(threadId, taskId, storeType, storeName), EXPIRED_WINDOW_RECORD_DROP, EXPIRED_WINDOW_RECORD_DROP_RATE_DESCRIPTION, EXPIRED_WINDOW_RECORD_DROP_TOTAL_DESCRIPTION ); } return sensor; }

Target:
public static Sensor expiredWindowRecordDropSensor(final String threadId, final String taskId, final String storeType, final String storeName, final StreamsMetricsImpl streamsMetrics) { final Sensor sensor = streamsMetrics.storeLevelSensor( threadId, taskId, storeName, EXPIRED_WINDOW_RECORD_DROP, RecordingLevel.INFO ); addInvocationRateAndCountToSensor( sensor, "stream-" + storeType + "-metrics", streamsMetrics.storeLevelTagMap(threadId, taskId, storeType, storeName), EXPIRED_WINDOW_RECORD_DROP, EXPIRED_WINDOW_RECORD_DROP_RATE_DESCRIPTION, EXPIRED_WINDOW_RECORD_DROP_TOTAL_DESCRIPTION ); return sensor; }
Source:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { LOGGER.debug("Loaded Redis configuration {}", redis); final RedisConfiguration redisConfiguration = redis.getSentinel() == null ? getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }

Target:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { val redisConfiguration = redis.getSentinel() == null ? (RedisConfiguration) getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }
Source:
private CharSequence getStatementName(long lo, long hi) { CharacterStoreEntry e = portalCharacterStore.newEntry(); CharSequence statementName = null; if (hi - lo > 0 && Chars.utf8Decode(lo, hi, e)) { statementName = portalCharacterStore.toImmutable(); } return statementName; }

Target:
private CharSequence getStatementName(long lo, long hi) throws BadProtocolException { CharacterStoreEntry e = portalCharacterStore.newEntry(); CharSequence statementName = null; if (hi - lo > 0) { if (Chars.utf8Decode(lo, hi, e)) { statementName = portalCharacterStore.toImmutable(); } else { LOG.error().$("invalid UTF8 bytes in statement name").$(); throw BadProtocolException.INSTANCE; } } return statementName; }
Source:
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c) || Object.class == c) { return c.cast(getValue(jsonObj)); } else if (Enum.class.isAssignableFrom(c)) { try { String value = String.class.cast(getValue(jsonObj)); value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; return c.cast(c.getMethod("valueOf", String.class).invoke(null, value)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); } } else if (JsonSerializable.class.isAssignableFrom(c)) { return (T) ModelBridgeInternal.instantiateJsonSerializable((ObjectNode) jsonObj, c); } else if (containsJsonSerializable(c)) { return ModelBridgeInternal.instantiateByJsonString(Utils.toJson(Utils.getSimpleObjectMapper(), (ObjectNode) jsonObj), c); } else { JsonSerializable.checkForValidPOJO(c); try { return this.getMapper().treeToValue(jsonObj, c); } catch (IOException e) { throw new IllegalStateException("Failed to get POJO.", e); } } } return null; }

Target:
public <T> T getObject(String propertyName, Class<T> c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) || Boolean.class.isAssignableFrom(c) || Object.class == c) { return c.cast(getValue(jsonObj)); } else if (Enum.class.isAssignableFrom(c)) { try { String value = String.class.cast(getValue(jsonObj)); value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; return c.cast(c.getMethod("valueOf", String.class).invoke(null, value)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); } } else if (JsonSerializable.class.isAssignableFrom(c)) { return (T) ModelBridgeInternal.instantiateJsonSerializable((ObjectNode) jsonObj, c); } else if (containsJsonSerializable(c)) { return ModelBridgeInternal.instantiateByObjectNode((ObjectNode) jsonObj, c); } else { JsonSerializable.checkForValidPOJO(c); try { return this.getMapper().treeToValue(jsonObj, c); } catch (IOException e) { throw new IllegalStateException("Failed to get POJO.", e); } } } return null; }
Source:
void rebuildTokenMap() { lock.lock(); try { if (tokenMap == null) return; Token.Factory factory = getTokenFactory(partitioner); if (factory == null) return; this.tokenMap = TokenMap.build( factory, tokenMap.primaryToTokens, keyspaces.values(), tokenMap.ring, tokenMap.tokenRanges, tokenMap.tokenToPrimary); } finally { lock.unlock(); } }

Target:
void rebuildTokenMap() { lock.lock(); try { if (tokenMap == null) return; this.tokenMap = TokenMap.build( tokenMap.factory, tokenMap.primaryToTokens, keyspaces.values(), tokenMap.ring, tokenMap.tokenRanges, tokenMap.tokenToPrimary); } finally { lock.unlock(); } }
Source:
public int onBite(IVampire biter) { float perc = biter instanceof IVampirePlayer ? 0.2F : 0.08F; if (getLevel() == 0) { int amt = player.getFoodStats().getFoodLevel(); int sucked = (int) (amt * perc); player.getFoodStats().setFoodLevel(amt - sucked); player.addExhaustion(1000F); if (!player.isPotionActive(ModPotions.sanguinare) && Helper.canTurnPlayer(biter, player) && Helper.canBecomeVampire(player)) { PotionSanguinare.addRandom(player, true); } return sucked; } int amt = this.getBloodStats().getBloodLevel(); int sucked = (int) (amt * perc); bloodStats.removeBlood(sucked, true); sync(this.bloodStats.writeUpdate(new NBTTagCompound()), true); feedCounter = 30; return sucked; }

Target:
public int onBite(IVampire biter) { float perc = biter instanceof IVampirePlayer ? 0.2F : 0.08F; if (getLevel() == 0) { int amt = player.getFoodStats().getFoodLevel(); int sucked = (int) Math.ceil((amt * perc)); player.getFoodStats().setFoodLevel(amt - sucked); player.addExhaustion(1000F); if (!player.isPotionActive(ModPotions.sanguinare) && Helper.canTurnPlayer(biter, player) && Helper.canBecomeVampire(player)) { PotionSanguinare.addRandom(player, true); } return sucked; } int amt = this.getBloodStats().getBloodLevel(); int sucked = (int) Math.ceil((amt * perc)); bloodStats.removeBlood(sucked, true); sync(this.bloodStats.writeUpdate(new NBTTagCompound()), true); return sucked; }
Source:
private Path getLocalTempFile(String s) throws IOException { Path projectRoot = Paths.get("."); Path tempDirectory = Files.createTempDirectory(projectRoot, this.getClass().getSimpleName() + "-test-"); Path relativeTempDirectory = projectRoot.relativize(tempDirectory); Path tempFile = Files.createTempFile(relativeTempDirectory, "test", s); tempFile.toFile().deleteOnExit(); tempDirectory.toFile().deleteOnExit(); return tempFile; }

Target:
private Path getLocalTempFile(String s) throws IOException { Path projectRoot = Paths.get("."); Path tempDirectory = Files.createTempDirectory(projectRoot, this.getClass().getSimpleName() + "-test-"); Path relativeTempDirectory = projectRoot.relativize(tempDirectory); Path tempFile = Files.createTempFile(relativeTempDirectory, "test", s); tempDirectory.toFile().deleteOnExit(); tempFile.toFile().deleteOnExit(); return tempFile; }
Source:
public Collection<ManagedConversation> getConversations() { return new HashSet<ManagedConversation>(getConversationMap().values()); }

Target:
public Collection<ManagedConversation> getConversations() { Map<String, ManagedConversation> conversations = getConversationMap(); synchronized (conversations) { return new HashSet<ManagedConversation>(conversations.values()); } }
Source:
private boolean isUserGiverOfResponse(FeedbackQuestionAttributes question, FeedbackResponseAttributes response, String userEmail, CourseRoster roster) { if (question.giverType == FeedbackParticipantType.TEAMS) { if (roster.isStudentsInSameTeam(response.giver, userEmail)) { return true; } } else { if (response.giver.equals(userEmail)) { return true; } } return false; }

Target:
private boolean isUserGiverOfResponse(FeedbackQuestionAttributes question, FeedbackResponseAttributes response, String userEmail, CourseRoster roster) { return question.giverType == FeedbackParticipantType.TEAMS && roster.isStudentsInSameTeam(response.giver, userEmail) || question.giverType != FeedbackParticipantType.TEAMS && response.giver.equals(userEmail); }
Source:
protected Map<Locator, MetricData> getDatapointsForRange( List<Locator> locators, Range range, String columnFamily, Granularity granularity ) { Map<Locator, List<ResultSetFuture>> locatorToFuturesMap = new HashMap<Locator, List<ResultSetFuture>>(); Map<Locator, DAbstractMetricIO> locatorIOMap = new HashMap<Locator, DAbstractMetricIO>(); for (Locator locator : locators) { try { String rType = metadataCache.get( locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase() ); DAbstractMetricIO io = getIO( rType, granularity ); locatorIOMap.put( locator, io ); List<ResultSetFuture> selectFutures = io.selectForLocatorAndRange( columnFamily, locator, range ); List<ResultSetFuture> existing = locatorToFuturesMap.get(locator); if (existing == null) { existing = new ArrayList<ResultSetFuture>(); locatorToFuturesMap.put(locator, existing); } existing.addAll(selectFutures); } catch (CacheException ex) { Instrumentation.markReadError(); LOG.error(String.format("Error looking up locator %s in cache", locator), ex); } } return resultSetsToMetricData(locatorToFuturesMap, locatorIOMap, granularity); }

Target:
public Map<Locator, MetricData> getDatapointsForRange( List<Locator> locators, Range range, String columnFamily, Granularity granularity ) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext( columnFamily ); try { Map<Locator, List<ResultSetFuture>> locatorToFuturesMap = new HashMap<Locator, List<ResultSetFuture>>(); Map<Locator, DAbstractMetricIO> locatorIOMap = new HashMap<Locator, DAbstractMetricIO>(); for (Locator locator : locators) { try { String rType = metadataCache.get( locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase() ); DAbstractMetricIO io = getIO( rType, granularity ); locatorIOMap.put( locator, io ); List<ResultSetFuture> selectFutures = io.selectForLocatorAndRange( columnFamily, locator, range ); List<ResultSetFuture> existing = locatorToFuturesMap.get(locator); if (existing == null) { existing = new ArrayList<ResultSetFuture>(); locatorToFuturesMap.put(locator, existing); } existing.addAll(selectFutures); } catch (CacheException ex) { Instrumentation.markReadError(); LOG.error(String.format("Error looking up locator %s in cache", locator), ex); } } return resultSetsToMetricData(locatorToFuturesMap, locatorIOMap, granularity); } finally { ctx.stop(); } }
Source:
public ResourceSet<?> setPageSize(final int pageSize) { reader.pageSize(pageSize); return this; }

Target:
public ResourceSet<E> setPageSize(final int pageSize) { reader.pageSize(pageSize); return this; }
Source:
public synchronized Tuple peek() throws SQLException { try { init(); return next; } catch (IOException e) { throw SQLExceptionInfo.getNewInfoObject(SQLExceptionCodeEnum.IO_EXCEPTION).genWrappedException(e); } }

Target:
public synchronized Tuple peek() throws SQLException { try { init(); return next; } catch (IOException e) { throw new PhoenixIOException(e); } }
Source:
public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) return; new Thread("Cleanup " + keyspace) { @Override public void run() { try { LOGGER.info("Starting cleanup on keyspace {}", keyspace); keyspaceStarted(); List<String> cfNames = jmxConnect.getColumnFamilyNames(keyspace); for (String cfName : cfNames) { int status = jmxConnect.getStorageServiceProxy().forceKeyspaceCleanup(keyspace, cfName); CompactionManager.AllSSTableOpStatus s = CompactionManager.AllSSTableOpStatus.SUCCESSFUL; for (CompactionManager.AllSSTableOpStatus st : CompactionManager.AllSSTableOpStatus.values()) { if (st.statusCode == status) s = st; } LOGGER.info("Cleanup of {}.{} returned with {}", keyspace, cfName, s); } keyspaceFinished("SUCCESS", keyspace); } catch (Exception e) { LOGGER.error("Failed to cleanup keyspace " + keyspace, e); keyspaceFinished("FAILURE", keyspace); } finally { startNextKeyspace(); } } }.start(); LOGGER.info("Submitted cleanup for keyspace {}", keyspace); }

Target:
public void startNextKeyspace() { final String keyspace = super.nextKeyspace(); if (keyspace == null) { return; } cleanupFuture = executorService.submit(new Runnable() { @Override public void run() { try { LOGGER.info("Starting cleanup on keyspace {}", keyspace); keyspaceStarted(); List<String> cfNames = jmxConnect.getColumnFamilyNames(keyspace); for (String cfName : cfNames) { int status = jmxConnect.getStorageServiceProxy().forceKeyspaceCleanup(keyspace, cfName); CompactionManager.AllSSTableOpStatus s = CompactionManager.AllSSTableOpStatus.SUCCESSFUL; for (CompactionManager.AllSSTableOpStatus st : CompactionManager.AllSSTableOpStatus.values()) { if (st.statusCode == status) { s = st; } } LOGGER.info("Cleanup of {}.{} returned with {}", keyspace, cfName, s); } keyspaceFinished("SUCCESS", keyspace); } catch (Exception e) { LOGGER.error("Failed to cleanup keyspace " + keyspace, e); keyspaceFinished("FAILURE", keyspace); } finally { startNextKeyspace(); } } }); LOGGER.info("Submitted cleanup for keyspace {}", keyspace); }
Source:
@Override public void run(JsonNode jNode) { String cacheName = jNode.get("cacheName").asText(); long size = jNode.get("size").asLong(); int dataSize = jNode.get("dataSize").asInt(); markInitialized(); try (IgniteDataStreamer<UUID, byte[]> dataStreamer = ignite.dataStreamer(cacheName)) { for (long j = 0L; j <= size; j++) dataStreamer.addData(UUID.randomUUID(), new byte[dataSize]); } markFinished(); }

Target:
@Override public void run(JsonNode jNode) { String cacheName = jNode.get("cacheName").asText(); int amount = jNode.get("amount").asInt(); int dataSize = jNode.get("dataSize").asInt(); markInitialized(); try (IgniteDataStreamer<UUID, byte[]> dataStreamer = ignite.dataStreamer(cacheName)) { for (int i = 0; i < amount; i++) dataStreamer.addData(UUID.randomUUID(), new byte[dataSize]); } markFinished(); }
Source:
public void testConversionToFrameworkFormat() { if (Util.SDK_INT < 16) { return; } byte[] initData1 = new byte[] {1, 2, 3}; byte[] initData2 = new byte[] {4, 5, 6}; List<byte[]> initData = new ArrayList<>(); initData.add(initData1); initData.add(initData2); testConversionToFrameworkFormatV16(MediaFormat.createVideoFormat( null, MediaFormat.NO_VALUE, "video/xyz", 5000, 102400, 1000L, 1280, 720, initData)); testConversionToFrameworkFormatV16(MediaFormat.createVideoFormat( null, MediaFormat.NO_VALUE, "video/xyz", 5000, MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, 1280, 720, null)); testConversionToFrameworkFormatV16(MediaFormat.createAudioFormat( null, MediaFormat.NO_VALUE, "audio/xyz", 500, 128, 1000L, 5, 44100, initData, null)); testConversionToFrameworkFormatV16(MediaFormat.createAudioFormat( null, MediaFormat.NO_VALUE, "audio/xyz", 500, MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, 5, 44100, null, null)); testConversionToFrameworkFormatV16( MediaFormat.createTextFormat(null, MediaFormat.NO_VALUE, "text/xyz", MediaFormat.NO_VALUE, 1000L, "eng")); testConversionToFrameworkFormatV16( MediaFormat.createTextFormat(null, MediaFormat.NO_VALUE, "text/xyz", MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, null)); }

Target:
public void testConversionToFrameworkFormat() { if (Util.SDK_INT < 16) { return; } byte[] initData1 = new byte[] {1, 2, 3}; byte[] initData2 = new byte[] {4, 5, 6}; List<byte[]> initData = new ArrayList<>(); initData.add(initData1); initData.add(initData2); testConversionToFrameworkFormatV16(MediaFormat.createVideoFormat( null, "video/xyz", 5000, 102400, 1000L, 1280, 720, initData)); testConversionToFrameworkFormatV16(MediaFormat.createVideoFormat( null, "video/xyz", 5000, MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, 1280, 720, null)); testConversionToFrameworkFormatV16(MediaFormat.createAudioFormat( null, "audio/xyz", 500, 128, 1000L, 5, 44100, initData, null)); testConversionToFrameworkFormatV16(MediaFormat.createAudioFormat( null, "audio/xyz", 500, MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, 5, 44100, null, null)); testConversionToFrameworkFormatV16( MediaFormat.createTextFormat(null, "text/xyz", MediaFormat.NO_VALUE, 1000L, "eng")); testConversionToFrameworkFormatV16( MediaFormat.createTextFormat(null, "text/xyz", MediaFormat.NO_VALUE, C.UNKNOWN_TIME_US, null)); }
Source:
public File getFile() { try { return springResource.getFile(); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); return null; } }

Target:
public File getFile() { try { return springResource.getFile(); } catch (final Exception e) { throw new TechnicalException(e); } }
Source:
public ClusterLevel makeClusterLevel(String version) { ClusterLevel level = new ClusterLevel(); level.setId(version); if (!isFiltered()) { CpuTypes cpuTypes = new CpuTypes(); for (ServerCpu serverCpu : getServerCpuList(version)) { CpuType cpuType = new CpuType(); cpuType.setName(serverCpu.getCpuName()); cpuType.setLevel(serverCpu.getLevel()); cpuType.setArchitecture(CPUMapper.map(serverCpu.getArchitecture(), null)); cpuTypes.getCpuTypes().add(cpuType); } level.setCpuTypes(cpuTypes); } Permits permits = new Permits(); for (ActionGroup actionGroup : getActionGroups()) { Permit permit = PermitMapper.map(actionGroup, null); permits.getPermits().add(permit); } level.setPermits(permits); ClusterFeatures features = new ClusterFeatures(); getAdditionalFeatureList(version).forEach(clusterFeature -> { org.ovirt.engine.api.model.ClusterFeature feature = ClusterFeaturesMapper.map(clusterFeature, null); features.getClusterFeatures().add(feature); }); level.setClusterFeatures(features); return LinkHelper.addLinks(level); }

Target:
public ClusterLevel makeClusterLevel(String version) { ClusterLevel level = new ClusterLevel(); level.setId(version); if (!isFiltered()) { CpuTypes cpuTypes = new CpuTypes(); for (ServerCpu serverCpu : getServerCpuList(version)) { CpuType cpuType = new CpuType(); cpuType.setName(serverCpu.getCpuName()); cpuType.setLevel(serverCpu.getLevel()); cpuType.setArchitecture(CPUMapper.map(serverCpu.getArchitecture(), null)); cpuTypes.getCpuTypes().add(cpuType); } level.setCpuTypes(cpuTypes); } Permits permits = new Permits(); for (ActionGroup actionGroup : getActionGroups()) { Permit permit = PermitMapper.map(actionGroup, null); permits.getPermits().add(permit); } level.setPermits(permits); return LinkHelper.addLinks(level); }
Source:
private Triple<String, Date, String> getRef(GHRef ref, GHRepository repository) { final Date epochStart = new Date(0); Date branchDate = new Date(0); String refName = ref.getRef(); String sha = null; boolean toIgnore = false; if (refName.startsWith("refs/heads/")) { refName = StringUtils.removeStart(refName, "refs/heads/"); } else if (refName.startsWith("refs/tags/")) { refName = StringUtils.removeStart(refName, "refs/tags/"); } else if (refName.startsWith("refs/pull/")) { toIgnore = true; } if (!toIgnore) { try { sha = ref.getObject().getSha(); if (ref.getObject().getType().equals("tag")) { GHTagObject tagObject = repository.getTagObject(sha); sha = tagObject.getObject().getSha(); } else if (ref.getObject().getType().equals("branch")) { GHBranch branch = repository.getBranch(refName); sha = branch.getSHA1(); } GHCommit commit = repository.getCommit(sha); branchDate = commit.getCommitDate(); if (branchDate.before(epochStart)) { branchDate = epochStart; } } catch (IOException e) { LOG.info("unable to retrieve commit date for branch " + refName); } return Triple.of(refName, branchDate, sha); } else { return null; } }

Target:
private Triple<String, Date, String> getRef(GHRef ref, GHRepository repository) { final Date epochStart = new Date(0); Date branchDate = new Date(0); String refName = ref.getRef(); String sha = null; boolean toIgnore = false; if (refName.startsWith("refs/heads/")) { refName = StringUtils.removeStart(refName, "refs/heads/"); } else if (refName.startsWith("refs/tags/")) { refName = StringUtils.removeStart(refName, "refs/tags/"); } else if (refName.startsWith("refs/pull/")) { toIgnore = true; } if (!toIgnore) { try { sha = ref.getObject().getSha(); if (ref.getObject().getType().equals("tag")) { GHTagObject tagObject = repository.getTagObject(sha); sha = tagObject.getObject().getSha(); } else if (ref.getObject().getType().equals("branch")) { GHBranch branch = repository.getBranch(refName); sha = branch.getSHA1(); } GHCommit commit = repository.getCommit(sha); branchDate = commit.getCommitDate(); if (branchDate.before(epochStart)) { branchDate = epochStart; } } catch (IOException e) { LOG.error("unable to retrieve commit date for branch " + refName); } return Triple.of(refName, branchDate, sha); } else { return null; } }
Source:
public boolean shutdown() { }

Target:
public boolean shutdown() { return true; }
Source:
public boolean match(Object selection) { if (selection instanceof EditPart) { if (selection instanceof PapyrusLabelEditPart && ((EditPart) selection).getParent() instanceof org.eclipse.gmf.runtime.diagram.ui.editparts.BorderedBorderItemEditPart) { return true; } } return false; }

Target:
public boolean match(Object selection) { boolean match = false; if (selection instanceof EditPart) { if (selection instanceof PapyrusLabelEditPart && ((EditPart) selection).getParent() instanceof org.eclipse.gmf.runtime.diagram.ui.editparts.BorderedBorderItemEditPart) { match = true; } } return match; }
Source:
private static String getStringProperty(final String name, final String def) { try { return System.getProperty("samjdk." + name, def); } catch (final java.security.AccessControlException error) { return def; } }

Target:
private static String getStringProperty(final String name, final String def) { try { return System.getProperty("samjdk." + name, def); } catch (final java.security.AccessControlException error) { log.warn(error,"java Security Manager forbids 'System.getProperty(\"" + name + "\")' , returning default value: " + def ); return def; } }
Source:
public void write(Object object) throws IOException { String content; if (object == null) return; result.totalCount++; if (writeSchema == null) { writeSchema = ((IndexedRecord) object).getSchema(); } GenericIndexedRecordConverter factory = new GenericIndexedRecordConverter(); factory.setSchema(writeSchema); IndexedRecord inputRecord = factory.convertToAvro((IndexedRecord) object); Field msgContent = writeSchema.getField(AzureStorageQueueProperties.FIELD_MESSAGE_CONTENT); int ttl = props.timeToLiveInSeconds.getValue(); int visibility = props.initialVisibilityDelayInSeconds.getValue(); if (msgContent == null) { LOGGER.error(i18nMessages.getMessage("error.VacantMessage")); if (props.dieOnError.getValue()) { throw new ComponentException(new Exception(i18nMessages.getMessage("error.VacantMessage"))); } } else { content = (String) inputRecord.get(msgContent.pos()); CloudQueueMessage msg = new CloudQueueMessage(content); msg.setMessageContent(content); messagesBuffer.add(new QueueMessage(msg, ttl, visibility)); } if (messagesBuffer.size() >= MAX_MSG_TO_ENQUEUE) { sendParallelMessages(); } }

Target:
public void write(Object object) throws IOException { String content; if (object == null) return; result.totalCount++; if (writeSchema == null) { writeSchema = ((IndexedRecord) object).getSchema(); } GenericIndexedRecordConverter factory = new GenericIndexedRecordConverter(); factory.setSchema(writeSchema); IndexedRecord inputRecord = factory.convertToAvro((IndexedRecord) object); Field msgContent = writeSchema.getField(AzureStorageQueueProperties.FIELD_MESSAGE_CONTENT); int ttl = props.timeToLiveInSeconds.getValue(); int visibility = props.initialVisibilityDelayInSeconds.getValue(); if (msgContent == null) { LOGGER.error(i18nMessages.getMessage("error.VacantMessage")); if (props.dieOnError.getValue()) { throw new ComponentException(new Exception(i18nMessages.getMessage("error.VacantMessage"))); } } else { content = (String) inputRecord.get(msgContent.pos()); messagesBuffer.add(new QueueMessage(new CloudQueueMessage(content), ttl, visibility)); } if (messagesBuffer.size() >= MAX_MSG_TO_ENQUEUE) { sendParallelMessages(); } }
Source:
private static String normalizeJUnitOutput(String input) { Scanner scn = new Scanner(input); int index = 1; String res = ""; while (scn.hasNextLine()) { String line = scn.nextLine(); if (line.startsWith(index + ") ")) { res += line + "\n" + scn.nextLine() + "\n"; index++; } } scn.close(); return res; }

Target:
private static Map<String, String> normalizeJUnitOutput(String input) { BufferedReader bufReader = new BufferedReader(new StringReader(input)); String line; String methodName = null; Map<String, String> resultMap = new HashMap<String, String>(); StringBuilder result = new StringBuilder(); try { int index = 1; while ((line = bufReader.readLine()) != null) { String indexStr = index + ") "; if (line.startsWith(indexStr)) { if (methodName != null) { resultMap.put(methodName, result.toString()); result.setLength(0); } methodName = line; index += 1; } else if (line.isEmpty()) { resultMap.put(methodName, result.toString()); break; } else if (methodName != null) { int lParenIndex = line.indexOf('('); if (lParenIndex >= 0) { line = line.substring(0, lParenIndex); } result.append(line + "\n"); } } bufReader.close(); } catch (IOException e) { System.err.println("I/O error reading line from trace."); e.printStackTrace(); System.exit(1); return null; } return resultMap; }
Source:
public void increment( int typeId ) { if ( typeId >= counts.length ) { counts = Arrays.copyOf( counts, max( counts.length * 2, typeId ) ); } counts[typeId]++; if ( typeId > highestTypeId ) { highestTypeId = typeId; } }

Target:
public void increment( int typeId ) { if ( typeId >= counts.length ) { counts = Arrays.copyOf( counts, max( counts.length * 2, typeId + 1 ) ); } counts[typeId]++; if ( typeId > highestTypeId ) { highestTypeId = typeId; } }
Source:
public ResultSetFuture executeAsync(final Statement statement) { if (cluster.isClosed()) { throw new IllegalStateException("Parent cluster is closed. This session is no longer valid."); } if (isInit) { DefaultResultSetFuture future = new DefaultResultSetFuture( this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); new RequestHandler(this, future, statement).sendRequest(); return future; } else { final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture(); this.initAsync() .addListener( new Runnable() { @Override public void run() { DefaultResultSetFuture actualFuture = new DefaultResultSetFuture( SessionManager.this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); execute(actualFuture, statement); chainedFuture.setSource(actualFuture); } }, executor()); return chainedFuture; } }

Target:
public ResultSetFuture executeAsync(final Statement statement) { if (isInit) { DefaultResultSetFuture future = new DefaultResultSetFuture( this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); execute(future, statement); return future; } else { final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture(); this.initAsync() .addListener( new Runnable() { @Override public void run() { DefaultResultSetFuture actualFuture = new DefaultResultSetFuture( SessionManager.this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); execute(actualFuture, statement); chainedFuture.setSource(actualFuture); } }, executor()); return chainedFuture; } }
Source:
@Override public Optional<org.spongepowered.api.map.color.MapColor.Base> getById(String id) { checkNotNull(id, "id"); return Optional.ofNullable(this.mapColorMappings.get(id.toLowerCase(Locale.ENGLISH))); }

Target:
public Optional<org.spongepowered.api.map.color.MapColor.Base> getById(String id) { checkNotNull(id, "id"); return Optional.ofNullable(mapColorMappings.get(id.toLowerCase(Locale.ENGLISH))); }
Source:
public Schema modelFromProperty(Schema object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); if (obj != null) { example = obj.toString(); } Schema items; ArraySchema model = new ArraySchema(); model.setDescription(description); model.setExample(example); if (object.getAdditionalProperties() != null && object.getAdditionalProperties() instanceof Schema) { items = (Schema) object.getAdditionalProperties(); model.setItems(items); } return model; }

Target:
public Schema modelFromProperty(Schema object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); if (obj != null) { example = obj.toString(); } ArraySchema model = new ArraySchema(); model.setDescription(description); model.setExample(example); if (object.getAdditionalProperties() != null && object.getAdditionalProperties() instanceof Schema) { model.setItems((Schema) object.getAdditionalProperties()); } return model; }
Source:
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { if (isTaskSideMetaData(job)) { return toParquetSplits(super.getSplits(job, numSplits)); } List<Footer> footers = getFooters(job); List<ParquetInputSplit> splits = realInputFormat.getSplits(job, footers); if (splits == null) { return null; } InputSplit[] resultSplits = new InputSplit[splits.size()]; int i = 0; for (ParquetInputSplit split : splits) { resultSplits[i++] = new ParquetInputSplitWrapper(split); } return resultSplits; }

Target:
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { if (isTaskSideMetaData(job)) { return super.getSplits(job, numSplits); } List<Footer> footers = getFooters(job); List<ParquetInputSplit> splits = realInputFormat.getSplits(job, footers); if (splits == null) { return null; } InputSplit[] resultSplits = new InputSplit[splits.size()]; int i = 0; for (ParquetInputSplit split : splits) { resultSplits[i++] = new ParquetInputSplitWrapper(split); } return resultSplits; }
Source:
public Map<Long, Set<TObject>> chronologize(String key, long record, long start, long end, Map<Long, Set<TObject>> context) { Set<TObject> set = Iterables.getLast(context.values(), Sets.<TObject> newLinkedHashSet()); for (Iterator<Write> it = iterator(); it.hasNext();) { Write write = it.next(); long writeTimeStamp = write.getVersion(); if(writeTimeStamp >= start && writeTimeStamp <= end) { Text writtenKey = write.getKey(); long writtenRecordId = write.getRecord().longValue(); Action action = write.getType(); if(writtenKey.toString().equals(key) && writtenRecordId == record) { set = Sets.newLinkedHashSet(set); Value newValue = write.getValue(); if(action == Action.ADD) { set.add(newValue.getTObject()); } else if(action == Action.REMOVE) { set.remove(newValue.getTObject()); } context.put(writeTimeStamp, set); } } } return context; }

Target:
public Map<Long, Set<TObject>> chronologize(String key, long record, long start, long end, Map<Long, Set<TObject>> context) { Set<TObject> set = Iterables.getLast(context.values(), Sets.<TObject> newLinkedHashSet()); for (Iterator<Write> it = iterator(); it.hasNext();) { Write write = it.next(); long timestamp = write.getVersion(); if(timestamp >= end){ break; } else{ Text writeKey = write.getKey(); long writeRecord = write.getRecord().longValue(); Action action = write.getType(); if(writeKey.toString().equals(key) && writeRecord == record) { set = Sets.newLinkedHashSet(set); Value writeValue = write.getValue(); if(action == Action.ADD) { set.add(writeValue.getTObject()); } else if(action == Action.REMOVE) { set.remove(writeValue.getTObject()); } if(timestamp >= start && !set.isEmpty()) context.put(timestamp, set); } } } return context; }
Source:
public void stop(String workspaceId, Map<String, String> options) throws NotFoundException, InfrastructureException, ConflictException { RuntimeState state = runtimes.get(workspaceId); if (state == null) { throw new NotFoundException("Workspace with id '" + workspaceId + "' is not running."); } if (!state.status.equals(RUNNING)) { throw new ConflictException( format("Could not start workspace '%s' because its state is '%s'", workspaceId, state.status)); } runtimes.replace(workspaceId, new RuntimeState(state.runtime, STOPPING)); eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.RUNNING) .withStatus(WorkspaceStatus.STOPPING)); try { state.runtime.stop(options); runtimes.remove(workspaceId); eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.STOPPING) .withStatus(STOPPED)); } catch (InfrastructureException e) { runtimes.remove(workspaceId); eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.STOPPING) .withStatus(STOPPED) .withError("Error occurs on workspace runtime stop. Error: " + e.getMessage())); } }

Target:
public void stop(String workspaceId, Map<String, String> options) throws NotFoundException, InfrastructureException, ConflictException { RuntimeState state = runtimes.get(workspaceId); if (state == null) { throw new NotFoundException("Workspace with id '" + workspaceId + "' is not running."); } if (!state.status.equals(RUNNING)) { throw new ConflictException( format("Could not stop workspace '%s' because its state is '%s'", workspaceId, state.status)); } if (!runtimes.replace(workspaceId, state, new RuntimeState(state.runtime, STOPPING))) { RuntimeState newState = runtimes.get(workspaceId); WorkspaceStatus status = newState != null ? newState.status : STOPPED; throw new ConflictException( format("Could not stop workspace '%s' because its state is '%s'", workspaceId, status)); } eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.RUNNING) .withStatus(WorkspaceStatus.STOPPING)); try { state.runtime.stop(options); runtimes.remove(workspaceId); eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.STOPPING) .withStatus(STOPPED)); } catch (InfrastructureException e) { runtimes.remove(workspaceId); eventService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withPrevStatus(WorkspaceStatus.STOPPING) .withStatus(STOPPED) .withError("Error occurs on workspace runtime stop. Error: " + e.getMessage())); } }
Source:
private void calculateState(Route route) { boolean failureLimitReached = isThresholdExceeded(); if (state.get() == STATE_CLOSED) { if (failureLimitReached) { LOG.debug("opening circuit..."); openCircuit(route); } } else if (state.get() == STATE_HALF_OPEN) { if (failureLimitReached) { LOG.debug("opening circuit..."); openCircuit(route); } else { LOG.debug("closing circuit..."); closeCircuit(route); } } else if (state.get() == STATE_OPEN) { long elapsedTimeSinceOpened = System.currentTimeMillis() - openedAt; if (halfOpenAfter <= elapsedTimeSinceOpened) { LOG.debug("checking an open circuit..."); if (halfOpenHandler != null) { if (halfOpenHandler.isReadyToBeClosed()) { LOG.debug("closing circuit..."); closeCircuit(route); } else { LOG.debug("opening circuit..."); openCircuit(route); } } else { LOG.debug("half opening circuit..."); halfOpenCircuit(route); } } } }

Target:
private void calculateState(Route route) { boolean failureLimitReached = isThresholdExceeded(); if (state.get() == STATE_CLOSED) { if (failureLimitReached) { LOG.debug("Opening circuit..."); openCircuit(route); } } else if (state.get() == STATE_HALF_OPEN) { if (failureLimitReached) { LOG.debug("Opening circuit..."); openCircuit(route); } else { LOG.debug("Closing circuit..."); closeCircuit(route); } } else if (state.get() == STATE_OPEN) { long elapsedTimeSinceOpened = System.currentTimeMillis() - openedAt; if (halfOpenAfter <= elapsedTimeSinceOpened) { LOG.debug("Checking an open circuit..."); if (halfOpenHandler != null) { if (halfOpenHandler.isReadyToBeClosed()) { LOG.debug("Closing circuit..."); closeCircuit(route); } else { LOG.debug("Opening circuit..."); openCircuit(route); } } else { LOG.debug("Half opening circuit..."); halfOpenCircuit(route); } } } }