auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static ExceptionSupplier<CredentialSource, ConfigXMLParseException> createCredentialStoreSupplier(final XMLLocation location, final String storeName, final String alias, final String clearText, final Map<String, ExceptionSupplier<CredentialStore, ConfigXMLParseException>> credentialStoresMap) { return () -> { if (storeName != null) { final ExceptionSupplier<CredentialStore, ConfigXMLParseException> supplier = credentialStoresMap.get(storeName); if (supplier == null) { throw xmlLog.xmlCredentialStoreNameNotDefined(location, storeName); } final CredentialStore credentialStore = supplier.get(); return new CredentialStoreCredentialSource(credentialStore, alias); } else if (clearText != null) { return new CredentialSource() { @Override public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { return SupportLevel.SUPPORTED; } @Override public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { return credentialType.cast(new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, clearText.toCharArray()))); } }; } else { throw xmlLog.xmlInvalidCredentialStoreRef(location); } }; }

Target:
private static ExceptionSupplier<CredentialSource, ConfigXMLParseException> createCredentialStoreSupplier(final XMLLocation location, final String storeName, final String alias, final String clearText, final Map<String, ExceptionSupplier<CredentialStore, ConfigXMLParseException>> credentialStoresMap) { return () -> { if (storeName != null) { final ExceptionSupplier<CredentialStore, ConfigXMLParseException> supplier = credentialStoresMap.get(storeName); if (supplier == null) { throw xmlLog.xmlCredentialStoreNameNotDefined(location, storeName); } final CredentialStore credentialStore = supplier.get(); return new CredentialStoreCredentialSource(credentialStore, alias); } else if (clearText != null) { final PasswordCredential passwordCredential = new PasswordCredential(ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, clearText.toCharArray())); return IdentityCredentials.NONE.withCredential(passwordCredential); } else { throw xmlLog.xmlInvalidCredentialStoreRef(location); } }; }
Source:
public SyslogReceivingChannelAdapterFactoryBean(Protocol protocol) { this.protocol = protocol; }

Target:
public SyslogReceivingChannelAdapterFactoryBean(Protocol protocol) { Assert.notNull(protocol, "'protocol' cannot be null"); this.protocol = protocol; }
Source:
public T getNullable() { T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }

Target:
private T getNullable() { T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }
Source:
public void testLoadString() throws Exception { if (! myFileIsBinary) { String ionText; try { ionText = PrivateUtils.utf8FileToString(myTestFile); } catch (IonException e) { final CharBuffer buffer = CharBuffer.allocate(1204); final CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); final FileReader fileReader = new FileReader(myTestFile); while(fileReader.read(buffer) != -1){ assert utf8Encoder.canEncode(buffer); } return; } try { @SuppressWarnings("unused") IonDatagram dg = loader().load(ionText); fail("Expected IonException"); } catch (IonException e) { } } }

Target:
public void testLoadString() throws Exception { if (! myFileIsBinary) { String ionText; try { ionText = PrivateUtils.utf8FileToString(myTestFile); } catch (IonException e) { final CharBuffer buffer = CharBuffer.allocate(1024); final CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); final FileReader fileReader = new FileReader(myTestFile); while(fileReader.read(buffer) != -1){ assert utf8Encoder.canEncode(buffer); } return; } try { @SuppressWarnings("unused") IonDatagram dg = loader().load(ionText); fail("Expected IonException"); } catch (IonException e) { } } }
Source:
public static void validateNotSingleJobInstance(String definition, Collection<String> jobInstances) { JobSpecification jobSpecification = null; try { JobParser parser = new JobParser(); jobSpecification = parser.parse(definition); } catch (Exception e) { return; } if (jobSpecification.getJobReferences().size() == 1) { String jobName = jobSpecification.getJobReferences().get(0).getName(); if (jobInstances.contains(jobName)) { throw new IllegalStateException(String.format( "Job Instance specified %s must use transitions. Or just " + "launch the job instance directly", jobName)); } } }

Target:
public static void validateNotSingleJobInstance(String definition, Collection<String> jobInstances) { JobSpecification jobSpecification = null; try { JobParser parser = new JobParser(); jobSpecification = parser.parse(definition); } catch (JobSpecificationException e) { return; } if (jobSpecification.getJobReferences().size() == 1) { String jobName = jobSpecification.getJobReferences().get(0).getName(); if (jobInstances.contains(jobName)) { throw new IllegalStateException(String.format( "Job Instance specified %s must use transitions. Or just " + "launch the job instance directly", jobName)); } } }
Source:
public void tearDown() throws Exception { System.setProperty("BUCKET", ""); System.setProperty("CONNECTIONS", ""); System.setProperty("ENABLED", ""); System.setProperty("ALLOW_ENV_PARAMETRIZATION", ""); }

Target:
public void tearDown() throws Exception { System.clearProperty("BUCKET"); System.clearProperty("CONNECTIONS"); System.clearProperty("ENABLED"); System.clearProperty("ALLOW_ENV_PARAMETRIZATION"); }
Source:
public void testConvertToInterleavedStorageCommand() { ConvertToInterleavedStorageCommand cmd = new ConvertToInterleavedStorageCommand(); Assert.assertTrue(cmd.apply(bkFlags, new String[] { "" })); }

Target:
public void testConvertToInterleavedStorageCommand() { ConvertToInterleavedStorageCommand cmd = new ConvertToInterleavedStorageCommand(); Assert.assertTrue(cmd.apply(bkFlags, new String[] { "" })); try { verifyNew(ServerConfiguration.class).withArguments(eq(conf)); verifyNew(LedgerDirsManager.class, times(2)) .withArguments(eq(conf), any(File[].class), any(DiskChecker.class)); verifyNew(DbLedgerStorage.class, times(1)).withNoArguments(); verifyNew(InterleavedLedgerStorage.class, times(1)).withNoArguments(); verify(dbStorage, times(1)).initialize(eq(conf), eq(null), any(LedgerDirsManager.class), any(LedgerDirsManager.class), eq(null), any(CheckpointSource.class), any(Checkpointer.class), eq(NullStatsLogger.INSTANCE), eq(PooledByteBufAllocator.DEFAULT)); verify(interleavedLedgerStorage, times(1)) .initialize(eq(conf), eq(null), any(LedgerDirsManager.class), any(LedgerDirsManager.class), eq(null), any(CheckpointSource.class), any(Checkpointer.class), eq(NullStatsLogger.INSTANCE), eq(PooledByteBufAllocator.DEFAULT)); verify(dbStorage, times(1)).getActiveLedgersInRange(anyLong(), anyLong()); verify(dbStorage, times(10)).readMasterKey(anyLong()); verify(interleavedLedgerStorage, times(10)).setMasterKey(anyLong(), any()); verify(dbStorage, times(10)).getLastEntryInLedger(anyLong()); verify(dbStorage, times(10)).getLocation(anyLong(), anyLong()); verify(dbStorage, times(1)).shutdown(); verify(interleavedLedgerCache, times(1)).flushLedger(true); verify(interleavedLedgerStorage, times(1)).flush(); verify(interleavedLedgerStorage, times(1)).shutdown(); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } }
Source:
public T set(final int index, final T element) { try { return this.origin.set(index, element); } catch (final IndexOutOfBoundsException ex) { throw new IllegalArgumentException(this.message, ex); } }

Target:
public T set(final int index, final T element) { try { return this.origin.set(index, element); } catch (final IndexOutOfBoundsException ex) { throw this.wrapException(ex); } }
Source:
private static FunctionMetadata methodToFunctionMetadata(ScalarTranslationHeader header, Method method) { requireNonNull(header, "header is null"); SqlType annotatedReturnType = method.getAnnotation(SqlType.class); checkArgument(annotatedReturnType != null, format("Method [%s] is missing @SqlType annotation", method)); TypeSignature returnType = parseTypeSignature(annotatedReturnType.value(), ImmutableSet.of()); ImmutableList.Builder<TypeSignature> argumentTypes = new ImmutableList.Builder<>(); for (Parameter parameter : method.getParameters()) { Annotation[] annotations = parameter.getAnnotations(); SqlType type = Stream.of(annotations) .filter(SqlType.class::isInstance) .map(SqlType.class::cast) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Method [%s] is missing @SqlType annotation for parameter", method))); TypeSignature typeSignature = parseTypeSignature(type.value(), ImmutableSet.of()); argumentTypes.add(typeSignature); } if (header.getOperatorType().isPresent()) { return new FunctionMetadata(header.getOperatorType().get(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } else { return new FunctionMetadata(header.getName(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } }

Target:
private static FunctionMetadata methodToFunctionMetadata(ScalarTranslationHeader header, Method method) { requireNonNull(header, "header is null"); SqlType annotatedReturnType = method.getAnnotation(SqlType.class); checkArgument(annotatedReturnType != null, format("Method [%s] is missing @SqlType annotation", method)); TypeSignature returnType = parseTypeSignature(annotatedReturnType.value(), ImmutableSet.of()); ImmutableList.Builder<TypeSignature> argumentTypes = new ImmutableList.Builder<>(); for (Parameter parameter : method.getParameters()) { Annotation[] annotations = parameter.getAnnotations(); SqlType type = Stream.of(annotations) .filter(SqlType.class::isInstance) .map(SqlType.class::cast) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Method [%s] is missing @SqlType annotation for parameter", method))); TypeSignature typeSignature = parseTypeSignature(type.value(), ImmutableSet.of()); argumentTypes.add(typeSignature); } if (header.getOperatorType().isPresent()) { return new FunctionMetadata(header.getOperatorType().get(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); } return new FunctionMetadata(header.getName(), argumentTypes.build(), returnType, SCALAR, header.isDeterministic(), header.isCalledOnNullInput()); }
Source:
Pair<String, String> doWork(Map<String, String> statsWrappersJSON) throws IOException { StatsSnapshot partitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); Map<String, Long> partitionTimestampMap = new HashMap<>(); StatsSnapshot rawPartitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); for (Map.Entry<String, String> statsWrapperJSON : statsWrappersJSON.entrySet()) { if (statsWrapperJSON != null) { StatsWrapper snapshotWrapper = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); StatsWrapper snapshotWrapperCopy = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); combineRaw(rawPartitionSnapshot, snapshotWrapper); combine(partitionSnapshot, snapshotWrapperCopy, statsWrapperJSON.getKey(), partitionTimestampMap); } } logger.info("Reduced raw snapshot {}", mapper.writeValueAsString(rawPartitionSnapshot)); logger.info("Reduced snapshot {}", mapper.writeValueAsString(partitionSnapshot)); StatsSnapshot reducedRawSnapshot = reduce(rawPartitionSnapshot); StatsSnapshot reducedSnapshot = reduce(partitionSnapshot); return new Pair<>(mapper.writeValueAsString(reducedRawSnapshot), mapper.writeValueAsString(reducedSnapshot)); }

Target:
Pair<String, String> doWork(Map<String, String> statsWrappersJSON) throws IOException { StatsSnapshot partitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); Map<String, Long> partitionTimestampMap = new HashMap<>(); StatsSnapshot rawPartitionSnapshot = new StatsSnapshot(0L, new HashMap<String, StatsSnapshot>()); for (Map.Entry<String, String> statsWrapperJSON : statsWrappersJSON.entrySet()) { if (statsWrapperJSON != null) { StatsWrapper snapshotWrapper = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); StatsWrapper snapshotWrapperCopy = mapper.readValue(statsWrapperJSON.getValue(), StatsWrapper.class); combineRaw(rawPartitionSnapshot, snapshotWrapper); combine(partitionSnapshot, snapshotWrapperCopy, statsWrapperJSON.getKey(), partitionTimestampMap); } } if (logger.isTraceEnabled()) { logger.trace("Combined raw snapshot {}", mapper.writeValueAsString(rawPartitionSnapshot)); logger.trace("Combined snapshot {}", mapper.writeValueAsString(partitionSnapshot)); } StatsSnapshot reducedRawSnapshot = reduce(rawPartitionSnapshot); StatsSnapshot reducedSnapshot = reduce(partitionSnapshot); if (logger.isTraceEnabled()) { logger.trace("Reduced raw snapshot {}", mapper.writeValueAsString(reducedRawSnapshot)); logger.trace("Reduced snapshot {}", mapper.writeValueAsString(reducedSnapshot)); } return new Pair<>(mapper.writeValueAsString(reducedRawSnapshot), mapper.writeValueAsString(reducedSnapshot)); }
Source:
public boolean shouldIgnore() { return coreFeature.getStorageConfiguration().isVCS() || coreFeature.getStorageConfiguration().isVCSMySQL(); }

Target:
public boolean shouldIgnore() { return !coreFeature.getStorageConfiguration().isVCS() || coreFeature.getStorageConfiguration().isVCSMySQL(); }
Source:
default DataStore getDataStore(MetaDataStore metaDataStore, AggregationDataStore aggregationDataStore, EntityManagerFactory entityManagerFactory) { CancelSession cancelSession = new CancelSession(entityManagerFactory.get().unwrap(Session.class)); DataStore jpaDataStore = new JpaDataStore( () -> { return entityManagerFactory.createEntityManager(); }, (em -> { return new NonJtaTransaction(em, cancelSession); })); DataStore dataStore = new MultiplexManager(jpaDataStore, metaDataStore, aggregationDataStore); return dataStore; }

Target:
default DataStore getDataStore(MetaDataStore metaDataStore, AggregationDataStore aggregationDataStore, EntityManagerFactory entityManagerFactory) { DataStore jpaDataStore = new JpaDataStore( () -> { return entityManagerFactory.createEntityManager(); }, (em) -> { return new NonJtaTransaction(em, TXCANCEL); }); DataStore dataStore = new MultiplexManager(jpaDataStore, metaDataStore, aggregationDataStore); return dataStore; }
Source:
protected void modified(Map<String, Object> config) { if (config == null) return; final Object value = config.get("provider"); if (value instanceof String) { providerName = (String) value; } }

Target:
protected void modified(Map<String, Object> config) { applyConfig(config); }
Source:
NodeCursor( Read read ) { super( -1 ); this.read = read; this.labelCursor = read.labelCursor(); }

Target:
NodeCursor( Read read ) { super( NO_ID ); this.read = read; this.labelCursor = read.labelCursor(); }
Source:
public static Set<DistributionModuleGroup> getModuleGroups(String distribution, String version) { Set<DistributionModuleGroup> hs = new HashSet<>(); DistributionModuleGroup dmgSpark16 = new DistributionModuleGroup( CDH5100Constant.SPARK_KAFKA_CLIENT_MRREQUIRED_MODULE_GROUP.getModuleName(), true, new NestedComponentCondition(new MultiComponentCondition( new SparkStreamingLinkedNodeCondition(distribution, version, SparkStreamingConstant.KAFKA_SPARKCONFIGURATION_LINKEDPARAMETER).getCondition(), BooleanOperator.AND, spark16Condition))); hs.add(dmgSpark16); DistributionModuleGroup dmgSpark21 = new DistributionModuleGroup( CDH5100Constant.SPARK2_KAFKA_CLIENT_MRREQUIRED_MODULE_GROUP.getModuleName(), true, new NestedComponentCondition( new MultiComponentCondition( new SparkStreamingLinkedNodeCondition(distribution, version, SparkStreamingConstant.KAFKA_SPARKCONFIGURATION_LINKEDPARAMETER).getCondition(), BooleanOperator.AND, spark21Condition))); hs.add(dmgSpark16); hs.add(dmgSpark21); return hs; }

Target:
public static Set<DistributionModuleGroup> getModuleGroups(String distribution, String version) { Set<DistributionModuleGroup> hs = new HashSet<>(); DistributionModuleGroup dmgSpark16 = new DistributionModuleGroup( CDH5100Constant.SPARK_KAFKA_CLIENT_MRREQUIRED_MODULE_GROUP.getModuleName(), true, new NestedComponentCondition(new MultiComponentCondition( new SparkStreamingLinkedNodeCondition(distribution, version, SparkStreamingConstant.KAFKA_SPARKCONFIGURATION_LINKEDPARAMETER).getCondition(), BooleanOperator.AND, spark16Condition))); hs.add(dmgSpark16); DistributionModuleGroup dmgSpark21 = new DistributionModuleGroup( CDH5100Constant.SPARK2_KAFKA_CLIENT_MRREQUIRED_MODULE_GROUP.getModuleName(), true, new NestedComponentCondition( new MultiComponentCondition( new SparkStreamingLinkedNodeCondition(distribution, version, SparkStreamingConstant.KAFKA_SPARKCONFIGURATION_LINKEDPARAMETER).getCondition(), BooleanOperator.AND, spark21Condition))); hs.add(dmgSpark21); return hs; }
Source:
protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "whitespace" + File.separator + "IteratorPad" + File.separator + filename); }

Target:
protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "whitespace" + File.separator + "iteratorpad" + File.separator + filename); }
Source:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (m_category != "" ? "." + m_category : ""); }

Target:
private String getStorageKey(boolean perInstance) { return (perInstance ? m_instance : "") + (!m_category.equals("") ? "." + m_category : ""); }
Source:
public void testLongParseDefaultSuccess() { Long num = NumberParser.parseLong("Non Long", 1L); assertTrue(num == 1L); num = NumberParser.parseLong("0", 1L); assertTrue(num == 0L); }

Target:
public void testLongParseDefaultSuccess() { long num = NumberParser.parseLong("Non Long", 1L); assertEquals(1L, num); }
Source:
private void processChunking(NHttpClientConnection conn, MessageContext requestMsgCtx) throws IOException, AxisFault { String disableChunking = (String) requestMsgCtx.getProperty(PassThroughConstants.DISABLE_CHUNKING); String forceHttp10 = (String) requestMsgCtx.getProperty(PassThroughConstants.FORCE_HTTP_1_0); if ("true".equals(disableChunking) || "true".equals(forceHttp10)) { if (requestMsgCtx.getEnvelope().getBody().getFirstElement() == null) { BasicHttpEntity entity = (BasicHttpEntity) ((BasicHttpEntityEnclosingRequest) request).getEntity(); try { RelayUtils.buildMessage(requestMsgCtx); this.hasEntityBody = true; Pipe pipe = (Pipe) requestMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { pipe.attachConsumer(conn); this.connect(pipe); if (Boolean.TRUE.equals(requestMsgCtx.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) { ByteArrayOutputStream out = new ByteArrayOutputStream(); MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx); formatter.writeTo(requestMsgCtx, format, out, false); OutputStream _out = pipe.getOutputStream(); IOUtils.write(out.toByteArray(), _out); entity.setContentLength(new Long(out.toByteArray().length)); entity.setChunked(false); } } } catch (XMLStreamException e) { e.printStackTrace(); } } } }

Target:
private void processChunking(NHttpClientConnection conn, MessageContext requestMsgCtx) throws IOException, AxisFault { String disableChunking = (String) requestMsgCtx.getProperty(PassThroughConstants.DISABLE_CHUNKING); String forceHttp10 = (String) requestMsgCtx.getProperty(PassThroughConstants.FORCE_HTTP_1_0); if (log.isDebugEnabled()) { log.debug("Process Chungking (disableChunking : " + disableChunking + ", forceHttp10 : " + forceHttp10 + ")"); } if (("true".equals(disableChunking) || "true".equals(forceHttp10)) && (requestMsgCtx.getEnvelope().getBody().getFirstElement() == null)) { if (log.isDebugEnabled()) { log.debug("Envelope Body is empty"); } BasicHttpEntity entity = (BasicHttpEntity) ((BasicHttpEntityEnclosingRequest) request).getEntity(); try { RelayUtils.buildMessage(requestMsgCtx); this.hasEntityBody = true; Pipe pipe = (Pipe) requestMsgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { pipe.attachConsumer(conn); this.connect(pipe); if (Boolean.TRUE.equals( requestMsgCtx.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) { ByteArrayOutputStream out = new ByteArrayOutputStream(); MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx); formatter.writeTo(requestMsgCtx, format, out, false); IOUtils.write(out.toByteArray(), pipe.getOutputStream()); if (log.isDebugEnabled()) { log.debug("Set ContentLength : " + new Long(out.toByteArray().length)); } entity.setContentLength(new Long(out.toByteArray().length)); entity.setChunked(false); } } } catch (XMLStreamException e) { log.error("Error while process chunking", e); } } }
Source:
private static void validateFormatOptions(ReadableConfig tableOptions) { final boolean hasQuoteCharacter = tableOptions.getOptional(QUOTE_CHARACTER).isPresent(); final boolean isDisabledQuoteCharacter = tableOptions.get(DISABLE_QUOTE_CHARACTER); if (isDisabledQuoteCharacter && hasQuoteCharacter){ throw new ValidationException( "Format cannot define a quote character and disabled quote character at the same time."); } validateCharacterVal(tableOptions, FIELD_DELIMITER); validateCharacterVal(tableOptions, QUOTE_CHARACTER); validateCharacterVal(tableOptions, ESCAPE_CHARACTER); }

Target:
private static void validateFormatOptions(ReadableConfig tableOptions) { final boolean hasQuoteCharacter = tableOptions.getOptional(QUOTE_CHARACTER).isPresent(); final boolean isDisabledQuoteCharacter = tableOptions.get(DISABLE_QUOTE_CHARACTER); if (isDisabledQuoteCharacter && hasQuoteCharacter){ throw new ValidationException( "Format cannot define a quote character and disabled quote character at the same time."); } validateCharacterVal(tableOptions, FIELD_DELIMITER); validateCharacterVal(tableOptions, ARRAY_ELEMENT_DELIMITER); validateCharacterVal(tableOptions, QUOTE_CHARACTER); validateCharacterVal(tableOptions, ESCAPE_CHARACTER); tableOptions.getOptional(LINE_DELIMITER).ifPresent(delimiter -> { Set<String> allowedValues = new HashSet<>(Arrays.asList("\r", "\n", "\r\n", "")); if (!allowedValues.contains(delimiter)) { throw new ValidationException( String.format("Invalid value for option '%s.%s'. Supported values are %s, but was: %s", IDENTIFIER, LINE_DELIMITER.key(), "[\\r, \\n, \\r\\n, \"\"]", delimiter)); } }); }
Source:
@Override public void flush() { flush(FlushMode.IDLE); }

Target:
public void flush() { flush(FlushMode.IDLE); }
Source:
public void load(NBTTagCompound nbt) { super.load(nbt); if(nbt.hasKey("process")) { process.load(nbt.getCompoundTag("process")); } if(host.world().isRemote) { if(nbt.hasKey("node")) { NBTTagCompound nodeNBT = nbt.getCompoundTag("node"); if(nodeNBT.hasKey("address")) { clientAddress = nodeNBT.getString("address"); getHandler().setProcess(clientAddress, process, System.currentTimeMillis()); } } } else { if(nbt.hasKey("bbuffer")) { buildBuffer = Instruction.fromNBT(nbt.getTagList("bbuffer", Constants.NBT.TAG_COMPOUND)); buildDelay = 0; for (Instruction inst : buildBuffer) { if(inst instanceof Delay) { buildDelay += ((Delay)inst).delay; } } } if(nbt.hasKey("nbuffer")) { nextBuffer = Instruction.fromNBT(nbt.getTagList("bbuffer", Constants.NBT.TAG_COMPOUND)); nextDelay = 0; for (Instruction inst : nextBuffer) { if(inst instanceof Delay) { nextDelay += ((Delay)inst).delay; } } } if(nbt.hasKey("volume")) { soundVolume = nbt.getByte("volume"); } } }

Target:
public void load(NBTTagCompound nbt) { super.load(nbt); if(nbt.hasKey("process")) { process.load(nbt.getCompoundTag("process")); } if(host.world().isRemote) { if(nbt.hasKey("node")) { NBTTagCompound nodeNBT = nbt.getCompoundTag("node"); if(nodeNBT.hasKey("address")) { clientAddress = nodeNBT.getString("address"); SyncHandler.getHandler().setProcess(clientAddress, process, System.currentTimeMillis()); } } } else { if(nbt.hasKey("bbuffer")) { buildBuffer = Instruction.fromNBT(nbt.getTagList("bbuffer", Constants.NBT.TAG_COMPOUND)); buildDelay = 0; for (Instruction inst : buildBuffer) { if(inst instanceof Delay) { buildDelay += ((Delay)inst).delay; } } } if(nbt.hasKey("nbuffer")) { nextBuffer = Instruction.fromNBT(nbt.getTagList("nbuffer", Constants.NBT.TAG_COMPOUND)); nextDelay = 0; for (Instruction inst : nextBuffer) { if(inst instanceof Delay) { nextDelay += ((Delay)inst).delay; } } } if(nbt.hasKey("volume")) { soundVolume = nbt.getByte("volume"); } } }
Source:
public String validate(String validationType, String value){ if( "nonempty".equalsIgnoreCase(validationType)){ if( isEmpty(value) ) return i18n.text("required_field_empty_msg"); } else if("isDate".equalsIgnoreCase(validationType)){ if( isDate( value)) return SUCCESS; else return "must be in valid date format mm/dd/yyyy."; } else if( validationType.indexOf("datatype:") == 0 ) { String datatypeURI = validationType.substring(9); String errorMsg = validateAgainstDatatype( value, datatypeURI ); if ( errorMsg == null ) { return SUCCESS; } else { return errorMsg; } } else if ("httpUrl".equalsIgnoreCase(validationType)){ if(! value.startsWith("http://") && ! value.startsWith("https://") ){ return "This URL must start with http:// or https://"; }else{ return SUCCESS; } } else if( "dateNotPast".equalsIgnoreCase(validationType)){ Calendar c = Calendar.getInstance(); Calendar inputC = Calendar.getInstance(); String yearParamStr, monthParamStr, dayParamStr; int yearDash = value.indexOf("-"); int monthDash = value.lastIndexOf("-"); if(yearDash != -1 && yearDash != monthDash) { yearParamStr = value.substring(0, yearDash); monthParamStr = value.substring(yearDash + 1, monthDash); dayParamStr = value.substring(monthDash + 1, value.length()); inputC.set(Integer.parseInt(yearParamStr), Integer.parseInt(monthParamStr) - 1, Integer.parseInt(dayParamStr)); if(inputC.before(c)) { return i18n.text("data_not_past_msg"); } else { return SUCCESS; } } } return null; }

Target:
public String validate(String validationType, String value){ if( "nonempty".equalsIgnoreCase(validationType)){ if( isEmpty(value) ) return i18n.text(REQUIRED_FIELD_EMPTY_MSG); } else if("isDate".equalsIgnoreCase(validationType)){ if( isDate( value)) return SUCCESS; else return "must be in valid date format mm/dd/yyyy."; } else if( validationType.indexOf("datatype:") == 0 ) { String datatypeURI = validationType.substring(9); String errorMsg = validateAgainstDatatype( value, datatypeURI ); if ( errorMsg == null ) { return SUCCESS; } else { return errorMsg; } } else if ("httpUrl".equalsIgnoreCase(validationType)){ if(! value.startsWith("http://") && ! value.startsWith("https://") ){ return "This URL must start with http:// or https://"; }else{ return SUCCESS; } } else if( "dateNotPast".equalsIgnoreCase(validationType)){ Calendar c = Calendar.getInstance(); Calendar inputC = Calendar.getInstance(); String yearParamStr, monthParamStr, dayParamStr; int yearDash = value.indexOf("-"); int monthDash = value.lastIndexOf("-"); if(yearDash != -1 && yearDash != monthDash) { yearParamStr = value.substring(0, yearDash); monthParamStr = value.substring(yearDash + 1, monthDash); dayParamStr = value.substring(monthDash + 1, value.length()); inputC.set(Integer.parseInt(yearParamStr), Integer.parseInt(monthParamStr) - 1, Integer.parseInt(dayParamStr)); if(inputC.before(c)) { return i18n.text(DATA_NOT_PAST_MSG); } else { return SUCCESS; } } } return null; }
Source:
public static SupportStatus getServerSupportStatus() { if (supportStatus == null) { for (String clazz : dangerousServerClasses) { try { Class.forName(clazz); return supportStatus = SupportStatus.DANGEROUS; } catch (final ClassNotFoundException ignored) { } } try { Class.forName("net.minecraftforge.common.MinecraftForge"); return supportStatus = SupportStatus.UNSTABLE; } catch (final ClassNotFoundException ignored) { } if (ReflUtil.getNMSClass("MinecraftServer") == null) { return supportStatus = SupportStatus.UNSTABLE; } if (!supportedVersions.contains(getServerBukkitVersion())) { return supportStatus = SupportStatus.OUTDATED; } return supportStatus = PaperLib.isPaper() ? SupportStatus.FULL : SupportStatus.LIMITED; } return supportStatus; }

Target:
public static SupportStatus getServerSupportStatus() { if (supportStatus == null) { for (Map.Entry<String, SupportStatus> entry : unsupportedServerClasses.entrySet()) { final boolean inverted = entry.getKey().contains("!"); final String clazz = entry.getKey().replace("!", ""); try { Class.forName(clazz); if (!inverted) { return supportStatus = entry.getValue(); } } catch (final ClassNotFoundException ignored) { if (inverted) { return supportStatus = entry.getValue(); } } } if (!supportedVersions.contains(getServerBukkitVersion())) { return supportStatus = SupportStatus.OUTDATED; } return supportStatus = PaperLib.isPaper() ? SupportStatus.FULL : SupportStatus.LIMITED; } return supportStatus; }
Source:
public String deploy(Artifact artifact) throws CarbonDeploymentException { logger.info("Deploying : " + artifact.getName()); if (artifact.getName().contains("sample1.txt")) { sample1Deployed = false; } else if (artifact.getName().contains("sample2.txt")) { sample2Deployed = false; } throw new CarbonDeploymentException("Error while deploying : " + artifact.getName()); }

Target:
public String deploy(Artifact artifact) throws CarbonDeploymentException { logger.info("Deploying : " + artifact.getName()); if (artifact.getName() != null && artifact.getName().contains("sample1.txt")) { sample1Deployed = false; } else if (artifact.getName() != null && artifact.getName().contains("sample2.txt")) { sample2Deployed = false; } throw new CarbonDeploymentException("Error while deploying : " + artifact.getName()); }
Source:
private Response handleInternal(final CacheRpcCommand cmd, final ComponentRegistry cr) throws Throwable { CommandsFactory commandsFactory = cr.getCommandsFactory(); commandsFactory.initializeReplicableCommand(cmd, true); try { if (trace) log.tracef("Calling perform() on %s", cmd); ResponseGenerator respGen = cr.getResponseGenerator(); if(cmd instanceof CancellableCommand){ cancelService.register(Thread.currentThread(), ((CancellableCommand)cmd).getUUID()); } Object retval = cmd.perform(null); Response response = retval instanceof Response ? (Response) retval : respGen.getResponse(cmd, retval); log.tracef("About to send back response %s for command %s", response, cmd); return response; } catch (Exception e) { log.error("Exception executing command", e); return new ExceptionResponse(e); } finally { if(cmd instanceof CancellableCommand){ cancelService.unregister(((CancellableCommand)cmd).getUUID()); } } }

Target:
private Response handleInternal(final CacheRpcCommand cmd, final ComponentRegistry cr) throws Throwable { try { if (trace) log.tracef("Calling perform() on %s", cmd); ResponseGenerator respGen = cr.getResponseGenerator(); if(cmd instanceof CancellableCommand){ cancelService.register(Thread.currentThread(), ((CancellableCommand)cmd).getUUID()); } Object retval = cmd.perform(null); Response response = respGen.getResponse(cmd, retval); log.tracef("About to send back response %s for command %s", response, cmd); return response; } catch (Exception e) { log.error("Exception executing command", e); return new ExceptionResponse(e); } finally { if(cmd instanceof CancellableCommand){ cancelService.unregister(((CancellableCommand)cmd).getUUID()); } } }
Source:
public Response updateFlow(@PathParam("id") String id, AuthenticationFlowRepresentation flow) { auth.realm().requireManageRealm(); AuthenticationFlowRepresentation existingFlow = getFlow(id); if (flow.getAlias() == null || flow.getAlias().isEmpty()) { return ErrorResponse.exists("Failed to update flow with empty alias name"); } AuthenticationFlowModel checkFlow = realm.getFlowByAlias(flow.getAlias()); if (checkFlow != null) { if (!checkFlow.getDescription().equals(flow.getDescription()) && checkFlow.getId().equals(flow.getId())) { checkFlow.setDescription(flow.getDescription()); } else { return ErrorResponse.exists("Flow alias name already exists"); } } else { checkFlow = realm.getAuthenticationFlowById(flow.getId()); checkFlow.setAlias(flow.getAlias()); if (!flow.getDescription().equals(checkFlow.getDescription())) { checkFlow.setDescription(flow.getDescription()); } } flow.setId(existingFlow.getId()); realm.updateAuthenticationFlow(RepresentationToModel.toModel(flow)); adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(flow).success(); return Response.accepted(flow).build(); }

Target:
public Response updateFlow(@PathParam("id") String id, AuthenticationFlowRepresentation flow) { auth.realm().requireManageRealm(); AuthenticationFlowRepresentation existingFlow = getFlow(id); if (flow.getAlias() == null || flow.getAlias().isEmpty()) { return ErrorResponse.exists("Failed to update flow with empty alias name"); } AuthenticationFlowModel checkFlow = realm.getAuthenticationFlowById(id); if (checkFlow == null) { session.getTransactionManager().setRollbackOnly(); throw new NotFoundException("Illegal execution"); } if (realm.getFlowByAlias(flow.getAlias()) != null && !checkFlow.getAlias().equals(flow.getAlias())) { return ErrorResponse.exists("Flow alias name already exists"); } if (!checkFlow.getAlias().equals(flow.getAlias())) { checkFlow.setAlias(flow.getAlias()); } if (!checkFlow.getDescription().equals(flow.getDescription())) { checkFlow.setDescription(flow.getDescription()); } flow.setId(existingFlow.getId()); realm.updateAuthenticationFlow(RepresentationToModel.toModel(flow)); adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(flow).success(); return Response.accepted(flow).build(); }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof NumberItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only NumberItems are allowed - please check your *.items configuration"); } if (bindingConfig.length() != 4) { throw new BindingConfigParseException( "The configured address must consist of just 2 bytes housecode"); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof NumberItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only NumberItems are allowed - please check your *.items configuration"); } }
Source:
public boolean isActionAllowed(String action) { EMap<String, ActionInfo> actionsAvailable = getActions(); if (actionsAvailable != null) { ActionInfo actionInfo = actionsAvailable.get(action); if (actionInfo != null) { return true; } } return false; }

Target:
public boolean isActionAllowed(String action) { EMap<String, ActionInfo> actionsAvailable = getActions(); if (actionsAvailable != null) { ActionInfo actionInfo = actionsAvailable.get(action); if (actionInfo != null) { if (action.equals(ActionConstants.REBASE.getName())) { return true; } return actionInfo.isEnabled(); } } return false; }
Source:
public void writeTo(BufferedSink sink) { int readCount; Iterator<OnDatatransferProgressListener> it; try { mChannel.position(mOffset); long size = mFile.length(); if (size == 0) { size = -1; } long maxCount = Math.min(mOffset + mChunkSize, mChannel.size()); while (mChannel.position() < maxCount) { Log_OC.v("Sink buffer size: " + sink.buffer().size()); readCount = mChannel.read(mBuffer); Log_OC.v("Read " + readCount + " bytes from file channel to " + mBuffer.toString()); sink.buffer().write(mBuffer.array(), 0, readCount); sink.flush(); Log_OC.v("Write " + readCount + " bytes to sink buffer with size " + sink.buffer().size()); mBuffer.clear(); if (mTransferred < maxCount) { mTransferred += readCount; } synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readCount, mTransferred, size, mFile.getAbsolutePath()); } } } Log_OC.v("Chunk with size $mChunkSize written in request body"); } catch (Exception exception) { Log_OC.e(exception.getMessage()); } }

Target:
public void writeTo(BufferedSink sink) { int readCount; Iterator<OnDatatransferProgressListener> it; try { mChannel.position(mOffset); long size = mFile.length(); if (size == 0) { size = -1; } long maxCount = Math.min(mOffset + mChunkSize, mChannel.size()); while (mChannel.position() < maxCount) { Log_OC.v("Sink buffer size: " + sink.buffer().size()); readCount = mChannel.read(mBuffer); Log_OC.v("Read " + readCount + " bytes from file channel to " + mBuffer.toString()); sink.buffer().write(mBuffer.array(), 0, readCount); sink.flush(); Log_OC.v("Write " + readCount + " bytes to sink buffer with size " + sink.buffer().size()); mBuffer.clear(); if (mTransferred < maxCount) { mTransferred += readCount; } synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readCount, mTransferred, size, mFile.getAbsolutePath()); } } } Log_OC.v("Chunk with size " + mChunkSize + " written in request body"); } catch (Exception exception) { Log_OC.e(exception.getMessage()); } }
Source:
private void considerAddingAConsumer() { synchronized(consumersMonitor) { if (this.consumers.size() < this.maxConcurrentConsumers) { long now = System.currentTimeMillis(); if (this.lastConsumerStarted + 10000 < now) { if (logger.isDebugEnabled()) { logger.debug("Starting a new consumer"); } this.addAndStartConsumers(1); this.lastConsumerStarted = now; } } } }

Target:
private void considerAddingAConsumer() { synchronized(consumersMonitor) { if (this.consumers != null && this.maxConcurrentConsumers != null && this.consumers.size() < this.maxConcurrentConsumers) { long now = System.currentTimeMillis(); if (this.lastConsumerStarted + startConsumerMinInterval < now) { if (logger.isDebugEnabled()) { logger.debug("Starting a new consumer"); } this.addAndStartConsumers(1); this.lastConsumerStarted = now; } } } }
Source:
public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(catalogName, "connectorId is null"); requireNonNull(config, "requiredConfig is null"); requireNonNull(context, "context is null"); try { Bootstrap app = new Bootstrap(new JsonModule(), new AccumuloModule(catalogName, context.getTypeManager())); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(AccumuloConnector.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }

Target:
public Connector create(String catalogName, Map<String, String> config, ConnectorContext context) { requireNonNull(catalogName, "catalogName is null"); requireNonNull(config, "requiredConfig is null"); requireNonNull(context, "context is null"); try { Bootstrap app = new Bootstrap(new JsonModule(), new AccumuloModule(catalogName, context.getTypeManager())); Injector injector = app .strictConfig() .doNotInitializeLogging() .setRequiredConfigurationProperties(config) .initialize(); return injector.getInstance(AccumuloConnector.class); } catch (Exception e) { throwIfUnchecked(e); throw new RuntimeException(e); } }
Source:
BibEntry getEntryByDOI(String doi) { for (BibEntry b : databaseContext.getEntries()) { Optional<String> o = b.getField(StandardField.DOI); if (o.isPresent() && o.get().equals(doi)) { return b; } } return null; }

Target:
Optional<BibEntry> getEntryByDOI(String doi) { return databaseContext.getEntries().stream(). filter(entry -> doi.equals(entry.getField(StandardField.DOI).orElse(""))).findFirst(); }
Source:
public void printClassWithoutJavaDocButWithComment() { String code = " public class A { \n CompilationUnit cu = JavaParser.parse(code); PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavaDoc(false); String content = cu.toString(ignoreJavaDoc); assertEquals("public class A {\n }

Target:
public void printClassWithoutJavaDocButWithComment() { String code = String.format(" public class A { %s CompilationUnit cu = JavaParser.parse(code); PrettyPrinterConfiguration ignoreJavaDoc = new PrettyPrinterConfiguration().setPrintJavaDoc(false); String content = cu.toString(ignoreJavaDoc); assertEquals(String.format("public class A {%s }
Source:
private void createMetadataArtifact(AbstractFile aFile, Map<String, String> metadata) { String moduleName = KeywordSearchIngestModule.class.getName(); Collection<BlackboardAttribute> attributes = new ArrayList<>(); Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); for (Map.Entry<String, String> entry : metadata.entrySet()) { if (METADATA_TYPES_MAP.containsKey(entry.getKey())) { BlackboardAttribute bba = checkAttribute(entry.getKey(), entry.getValue()); if (bba != null) { attributes.add(bba); } } } if (!attributes.isEmpty()) { try { BlackboardArtifact bbart = aFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_METADATA); bbart.addAttributes(attributes); bbartifacts.add(bbart); } catch (TskCoreException ex) { logger.log(Level.WARNING, String.format("Error creatinkg or adding artifact."), ex); return; } if (!bbartifacts.isEmpty()) { try{ Case.getCurrentCaseThrows().getSleuthkitCase().getBlackboard().postArtifacts(bbartifacts, moduleName); } catch (NoCurrentCaseException | Blackboard.BlackboardException ex) { logger.log(Level.WARNING, "Unable to post blackboard artifacts", ex); return; } } } }

Target:
private void createMetadataArtifact(AbstractFile aFile, Map<String, String> metadata) { String moduleName = KeywordSearchIngestModule.class.getName(); Collection<BlackboardAttribute> attributes = new ArrayList<>(); Collection<BlackboardArtifact> bbartifacts = new ArrayList<>(); for (Map.Entry<String, String> entry : metadata.entrySet()) { if (METADATA_TYPES_MAP.containsKey(entry.getKey())) { BlackboardAttribute bba = checkAttribute(entry.getKey(), entry.getValue()); if (bba != null) { attributes.add(bba); } } } if (!attributes.isEmpty()) { try { BlackboardArtifact bbart = aFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_METADATA); bbart.addAttributes(attributes); bbartifacts.add(bbart); } catch (TskCoreException ex) { logger.log(Level.WARNING, String.format("Error creating or adding metadata artifact for file %s.", aFile.getParentPath() + aFile.getName()), ex); return; } if (!bbartifacts.isEmpty()) { try{ Case.getCurrentCaseThrows().getSleuthkitCase().getBlackboard().postArtifacts(bbartifacts, moduleName); } catch (NoCurrentCaseException | Blackboard.BlackboardException ex) { logger.log(Level.WARNING, String.format("Unable to post blackboard artifacts for file $s.", aFile.getParentPath() + aFile.getName()) , ex); return; } } } }
Source:
public StandaloneDeployer addDomain(File domain) throws MojoFailureException { try { log.debug(String.format("Deploying domain : %s", domain)); mule.deployDomain(domain.getAbsolutePath()); return this; } catch (MuleControllerException e) { log.error("Couldn't deploy domain: " + domain); throw new MojoFailureException("Couldn't deploy domain: " + domain); } }

Target:
public StandaloneDeployer addDomain(File domain) throws DeploymentException { checkNotNull(domain, "Domain cannot be null"); try { log.debug(String.format("Deploying domain : %s", domain)); mule.deployDomain(domain.getAbsolutePath()); return this; } catch (MuleControllerException e) { log.error("Couldn't deploy domain: " + domain); throw new DeploymentException("Couldn't deploy domain: " + domain); } }
Source:
public void writeFloat(final double value) throws IOException { prepareValue(); if (value == ((double) ((float) value))) { updateLength(5); buffer.writeUInt8(FLOAT_TYPE | 4); buffer.writeUInt32(floatToRawIntBits((float) value)); } else { updateLength(9); buffer.writeUInt8(FLOAT_TYPE | 8); buffer.writeUInt64(doubleToRawLongBits(value)); } finishValue(); }

Target:
public void writeFloat(final double value) throws IOException { prepareValue(); if (isFloatBinary32Enabled && value == ((double) ((float) value))) { updateLength(5); buffer.writeUInt8(FLOAT_TYPE | 4); buffer.writeUInt32(floatToRawIntBits((float) value)); } else { updateLength(9); buffer.writeUInt8(FLOAT_TYPE | 8); buffer.writeUInt64(doubleToRawLongBits(value)); } finishValue(); }
Source:
public void testFinalQueryInfoSetOnAbort() throws Exception { try (DistributedQueryRunner queryRunner = createQueryRunner(TEST_SESSION)) { QueryId queryId = startQuery("SELECT COUNT(*) FROM tpch.sf1000.lineitem", queryRunner); SettableFuture<QueryInfo> futureFinalQueryInfo = SettableFuture.create(); queryRunner.getCoordinator().addFinalQueryInfoListener(queryId, futureFinalQueryInfo::set); Thread.sleep(1_000); queryRunner.getCoordinator().getQueryManager().cancelQuery(queryId); QueryInfo finalQueryInfo = tryGetFutureValue(futureFinalQueryInfo, 10, SECONDS) .orElseThrow(() -> new AssertionError("Final query info never set")); assertTrue(finalQueryInfo.isFinalQueryInfo()); } }

Target:
public void testFinalQueryInfoSetOnAbort() throws Exception { try (DistributedQueryRunner queryRunner = createQueryRunner(TEST_SESSION)) { QueryId queryId = startQuery("SELECT COUNT(*) FROM tpch.sf1000.lineitem", queryRunner); SettableFuture<QueryInfo> finalQueryInfoFuture = SettableFuture.create(); queryRunner.getCoordinator().addFinalQueryInfoListener(queryId, finalQueryInfoFuture::set); Thread.sleep(1_000); queryRunner.getCoordinator().getQueryManager().cancelQuery(queryId); QueryInfo finalQueryInfo = tryGetFutureValue(finalQueryInfoFuture, 10, SECONDS) .orElseThrow(() -> new AssertionError("Final query info never set")); assertTrue(finalQueryInfo.isFinalQueryInfo()); } }
Source:
public void testConcurrentNormalJobsWithFastOnes() { final ValidationThreadPool pool = new ValidationThreadPool(VALIDATION_THREAD_COUNT); final IJobManager manager = Job.getJobManager(); final List<Promise<Object>> validationPromises = Lists.newArrayList(); for (int i = 0; i < 10; i++) { validationPromises.add(pool.submit(CheckType.NORMAL, createValidatableRunnable(CheckType.FAST, manager))); if (i % 2 == 0) { validationPromises.add(pool.submit(CheckType.FAST, createValidatableRunnable(CheckType.FAST, manager))); } } Promise.all(validationPromises).getSync(); }

Target:
public void testConcurrentNormalJobsWithFastOnes() { final IJobManager manager = Job.getJobManager(); final List<Promise<Object>> validationPromises = Lists.newArrayList(); for (int i = 0; i < 10; i++) { validationPromises.add(pool.submit(CheckType.NORMAL, createValidatableRunnable(CheckType.NORMAL, manager))); if (i % 2 == 0) { validationPromises.add(pool.submit(CheckType.FAST, createValidatableRunnable(CheckType.FAST, manager))); } } Promise.all(validationPromises).getSync(); }
Source:
public boolean process() { checkState(!finished); finished = prerequisite.process(); if (!finished) { return false; } finished = true; result = transform.apply(prerequisite.getResult()); return true; }

Target:
public boolean process() { checkState(!finished); finished = prerequisite.process(); if (!finished) { return false; } result = transform.apply(prerequisite.getResult()); return true; }
Source:
public void clear() { File[] files = new File(getMapStorePath()).listFiles(getFilenameFilter()); if (files != null) { for (File file : files) { try { Files.delete(file.toPath()); } catch (IOException e) { LOGGER.debug("File was unable to be deleted: {}", file.getAbsolutePath()); } } } }

Target:
public void clear() { File[] files = new File(getMapStorePath()).listFiles(getFilenameFilter()); if (files != null) { for (File file : files) { try { Files.delete(file.toPath()); } catch (IOException e) { LOGGER.debug("File was unable to be deleted: {}", file.getAbsolutePath(), e); LOGGER.warn( "Unable to delete file [{}]. Turn logging to debug for more info.", file.getAbsolutePath()); } } } }