auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void fillImageParameters(final PDDocument doc, final SignatureImageParameters signatureImageParameters, SignatureOptions options) throws IOException { if(signatureImageParameters != null) { ImageAndResolution ires = ImageUtils.create(signatureImageParameters); InputStream is = ires.getInputStream(); try { PDVisibleSignDesigner visibleSig = new PDVisibleSignDesigner(doc, is, signatureImageParameters.getPage()); visibleSig.xAxis(signatureImageParameters.getxAxis()); visibleSig.yAxis(signatureImageParameters.getyAxis()); if(signatureImageParameters.getWidth()== 0 && signatureImageParameters.getHeight()== 0){ visibleSig.width(signatureImageParameters.getWidth()); visibleSig.height(signatureImageParameters.getHeight()); } else { visibleSig.width(ires.toXPoint(visibleSig.getWidth())); visibleSig.height(ires.toYPoint(visibleSig.getHeight())); } LOG.info("Width: " + visibleSig.getWidth() + " Height: "+ visibleSig.getHeight()); visibleSig.zoom(signatureImageParameters.getZoom() - 100); PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties(); signatureProperties.visualSignEnabled(true).setPdVisibleSignature(visibleSig).buildSignature(); options.setVisualSignature(signatureProperties); options.setPage(signatureImageParameters.getPage() - 1); } finally { Utils.closeQuietly(is); } } }

Target:
protected void fillImageParameters(final PDDocument doc, final SignatureImageParameters signatureImageParameters, SignatureOptions options) throws IOException { if(signatureImageParameters != null) { ImageAndResolution ires = ImageUtils.create(signatureImageParameters); InputStream is = ires.getInputStream(); try { PDVisibleSignDesigner visibleSig = new PDVisibleSignDesigner(doc, is, signatureImageParameters.getPage()); visibleSig.xAxis(signatureImageParameters.getxAxis()); visibleSig.yAxis(signatureImageParameters.getyAxis()); if(signatureImageParameters.getWidth()!= 0 && signatureImageParameters.getHeight()!= 0){ visibleSig.width(signatureImageParameters.getWidth()); visibleSig.height(signatureImageParameters.getHeight()); } else { visibleSig.width(ires.toXPoint(visibleSig.getWidth())); visibleSig.height(ires.toYPoint(visibleSig.getHeight())); } LOG.info("Width: " + visibleSig.getWidth() + " Height: "+ visibleSig.getHeight()); visibleSig.zoom(signatureImageParameters.getZoom() - 100); PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties(); signatureProperties.visualSignEnabled(true).setPdVisibleSignature(visibleSig).buildSignature(); options.setVisualSignature(signatureProperties); options.setPage(signatureImageParameters.getPage() - 1); } finally { Utils.closeQuietly(is); } } }
Source:
public void testThreadNameWithoutNumberNoDemon() { Assert.assertEquals(ThreadUtils.createThreadFactory(THREAD_NAME, false). newThread(EMPTY_RUNNABLE).getName(), THREAD_NAME); }

Target:
public void testThreadNameWithoutNumberNoDemon() { assertEquals(THREAD_NAME, ThreadUtils.createThreadFactory(THREAD_NAME, false). newThread(EMPTY_RUNNABLE).getName()); }
Source:
public void clear() { cleared = true; }

Target:
public void clear() { cleared = true; currentState.clear(); }
Source:
public Map<String, Object> getReturnValues() { Result result = new Result(); return result.toMap(); }

Target:
public Map<String, Object> getReturnValues() { Result result = new Result(); result.totalCount = recordCount; return result.toMap(); }
Source:
public Set<Usermetadata> getUserMetadataByUser(String username, UserMetadataTypeEnum userMetadataTypeEnum) throws UserNotFoundException { User user = userSrv.findUserByLogin(username); assert user != null; Set<Usermetadata> umSet = new HashSet<>(); for (Group group : user.getGroups()) { List<GroupUsermetadata> guList = groupUsermetadataRepo.findByGroup(group); for (GroupUsermetadata gu : guList) { Usermetadata u = gu.getUsermetadata(); if (u.getUsermetadataType().getId().equals(userMetadataTypeEnum.getUserMetadataTypeId()) && u.getIsValid()) { umSet.add(u); } } } return umSet; }

Target:
public Set<Usermetadata> getUserMetadataByUser(String username, UserMetadataTypeEnum userMetadataTypeEnum) throws UserNotFoundException { User user = userSrv.findUserByLogin(username); Set<Usermetadata> umSet = new HashSet<>(); for (Group group : user.getGroups()) { List<GroupUsermetadata> guList = groupUsermetadataRepo.findByGroup(group); for (GroupUsermetadata gu : guList) { Usermetadata u = gu.getUsermetadata(); if (u.getUsermetadataType().getId().equals(userMetadataTypeEnum.getUserMetadataTypeId()) && u.getIsValid()) { umSet.add(u); } } } return umSet; }
Source:
public Set<Encoding> extract(Iterable<Availability> availabilities) { ImmutableSet.Builder<Encoding> encodings = ImmutableSet.builder(); for (Availability availability : availabilities) { Set<Location> locations = getLocationsFor(availability); if (!locations.isEmpty()) { Encoding encoding = new Encoding(); encoding.setAvailableAt(locations); setHorizontalAndVerticalSize(encoding, IS_HD.apply(availability)); encoding.setVideoBitRate(IS_HD.apply(availability) ? HD_BITRATE: SD_BITRATE); encodings.add(encoding); } } return encodings.build(); }

Target:
public Set<Encoding> extract(Iterable<Availability> availabilities) { ImmutableSet.Builder<Encoding> encodings = ImmutableSet.builder(); for (Availability availability : availabilities) { Set<Location> locations = getLocationsFor(availability); if (!locations.isEmpty()) { Encoding encoding = new Encoding(); encoding.setAvailableAt(locations); if (IS_IPTV.apply(availability)) { setHorizontalAndVerticalSize(encoding, IS_HD.apply(availability)); encoding.setVideoBitRate(IS_HD.apply(availability) ? HD_BITRATE : SD_BITRATE); } encodings.add(encoding); } } return encodings.build(); }
Source:
public static Resources getResourcesForSubId(Context context, int subId, boolean useRootLocale) { Pair<Context, Integer> cacheKey = null; if (isValidSubscriptionId(subId) && !useRootLocale) { cacheKey = Pair.create(context, subId); if (sResourcesCache.containsKey(cacheKey)) { return sResourcesCache.get(cacheKey); } } final SubscriptionInfo subInfo = SubscriptionManager.from(context).getActiveSubscriptionInfo(subId); Configuration config = context.getResources().getConfiguration(); Configuration newConfig = new Configuration(); newConfig.setTo(config); if (subInfo != null) { newConfig.mcc = subInfo.getMcc(); newConfig.mnc = subInfo.getMnc(); if (newConfig.mnc == 0) newConfig.mnc = Configuration.MNC_ZERO; } if (useRootLocale) { newConfig.setLocale(Locale.ROOT); } Context newContext = context.createConfigurationContext(newConfig); Resources res = newContext.getResources(); if (cacheKey != null) { sResourcesCache.put(cacheKey, res); } return res; }

Target:
public static Resources getResourcesForSubId(Context context, int subId, boolean useRootLocale) { Pair<Context, Integer> cacheKey = null; if (isValidSubscriptionId(subId) && !useRootLocale) { cacheKey = Pair.create(context, subId); if (sResourcesCache.containsKey(cacheKey)) { return sResourcesCache.get(cacheKey); } } final SubscriptionInfo subInfo = SubscriptionManager.from(context).getActiveSubscriptionInfo(subId); Configuration overrideConfig = new Configuration(); if (subInfo != null) { overrideConfig.mcc = subInfo.getMcc(); overrideConfig.mnc = subInfo.getMnc(); if (overrideConfig.mnc == 0) overrideConfig.mnc = Configuration.MNC_ZERO; } if (useRootLocale) { overrideConfig.setLocale(Locale.ROOT); } Context newContext = context.createConfigurationContext(overrideConfig); Resources res = newContext.getResources(); if (cacheKey != null) { sResourcesCache.put(cacheKey, res); } return res; }
Source:
public void doTable(Parse table) { initialiseDataTables(); Parse lastRow = table.parts.more; if (lastRow == null) { throw new Error("Query structure missing from second row"); } loadRowStructure(lastRow); lastRow = processDataTable(dt1, dt2, lastRow, symbol2); List<DataRow> unproc = dt2.getUnprocessedRows(); for (DataRow dr : unproc) { Parse errorRow = parseDataRowAsError(dr, " missing from " + symbol1); lastRow.more = errorRow; } }

Target:
public void doTable(Parse table) { initialiseDataTables(); Parse lastRow = table.parts.more; if (lastRow == null) { throw new Error("Query structure missing from second row"); } loadRowStructure(lastRow); lastRow = processDataTable(dt1, dt2, lastRow, symbol2); List<DataRow> unproc = dt2.getUnprocessedRows(); for (DataRow dr : unproc) { Parse errorRow = parseDataRowAsError(dr, " missing from " + symbol1); lastRow.more = errorRow; lastRow = errorRow; } }
Source:
public static PmProxyType fromValue(String v) { try { if (v==null) { return null; } if (v.equals("cluster")) { return CLUSTER; } else if (v.equals("dc")) { return DC; } else { return valueOf(v.toUpperCase()); } } catch (IllegalArgumentException e) { return null; } }

Target:
public static PmProxyType fromValue(String v) { try { if (v==null) { return null; } if (v.equals("cluster")) { return CLUSTER; } else if (v.equals("dc")) { return DC; } else { return null; } } catch (IllegalArgumentException e) { return null; } }
Source:
public void setup() { this.context = new MockContext(); this.jobContextMetadata = new JobContextMetadata(null, null); when(this.context.getTaskContext().getTaskMetricsRegistry()).thenReturn(new MetricsRegistryMap()); when(this.context.getTaskContext().getTaskModel()).thenReturn(mock(TaskModel.class)); when(this.context.getContainerContext().getContainerMetricsRegistry()).thenReturn(new MetricsRegistryMap()); }

Target:
public void setup() { this.context = new MockContext(); this.internalTaskContext = mock(InternalTaskContext.class); when(this.internalTaskContext.getContext()).thenReturn(this.context); when(this.internalTaskContext.fetchObject(EndOfStreamStates.class.getName())).thenReturn(mock(EndOfStreamStates.class)); when(this.internalTaskContext.fetchObject(WatermarkStates.class.getName())).thenReturn(mock(WatermarkStates.class)); when(this.context.getTaskContext().getTaskMetricsRegistry()).thenReturn(new MetricsRegistryMap()); when(this.context.getTaskContext().getTaskModel()).thenReturn(mock(TaskModel.class)); when(this.context.getContainerContext().getContainerMetricsRegistry()).thenReturn(new MetricsRegistryMap()); }
Source:
public ChromeDriver(ChromeDriverService service, Capabilities capabilities) { super(new ChromeDriverCommandExecutor(service), capabilities); if (capabilities.getCapability("enableDownloading")!=null){ sendCommandForDownloadChromeHeadLess( (String) capabilities.getCapability("enableDownloading")); } locationContext = new RemoteLocationContext(getExecuteMethod()); webStorage = new RemoteWebStorage(getExecuteMethod()); touchScreen = new RemoteTouchScreen(getExecuteMethod()); networkConnection = new RemoteNetworkConnection(getExecuteMethod()); }

Target:
public ChromeDriver(ChromeDriverService service, Capabilities capabilities) { super(new ChromeDriverCommandExecutor(service), capabilities); if (capabilities.getCapability("chromium:enableDownloadTo") instanceof String) { sendCommandForDownloadChromeHeadless( (String) capabilities.getCapability("chromium:enableDownloadTo")); } locationContext = new RemoteLocationContext(getExecuteMethod()); webStorage = new RemoteWebStorage(getExecuteMethod()); touchScreen = new RemoteTouchScreen(getExecuteMethod()); networkConnection = new RemoteNetworkConnection(getExecuteMethod()); }
Source:
public TokenFactory tokenFactoryFor(String partitioner) { if (partitioner.endsWith("Murmur3Partitioner")) { LOG.debug("[{}] Detected Murmur3 partitioner ({})", logPrefix, partitioner); return new Murmur3TokenFactory(partitioner); } else if (partitioner.endsWith("RandomPartitioner")) { LOG.debug("[{}] Detected random partitioner ({})", logPrefix, partitioner); return new RandomTokenFactory(partitioner); } else if (partitioner.endsWith("OrderedPartitioner")) { LOG.debug("[{}] Detected byte ordered partitioner ({})", logPrefix, partitioner); return new ByteOrderedTokenFactory(partitioner); } else { LOG.warn( "[{}] Unsupported partitioner '{}', token map will be empty.", logPrefix, partitioner); return null; } }

Target:
public TokenFactory tokenFactoryFor(String partitioner) { if (Murmur3TokenFactory.PARTITIONER_NAME.equals(partitioner)) { LOG.debug("[{}] Detected Murmur3 partitioner ({})", logPrefix, partitioner); return new Murmur3TokenFactory(); } else if (RandomTokenFactory.PARTITIONER_NAME.equals(partitioner)) { LOG.debug("[{}] Detected random partitioner ({})", logPrefix, partitioner); return new RandomTokenFactory(); } else if (ByteOrderedTokenFactory.PARTITIONER_NAME.equals(partitioner)) { LOG.debug("[{}] Detected byte ordered partitioner ({})", logPrefix, partitioner); return new ByteOrderedTokenFactory(); } else { LOG.warn( "[{}] Unsupported partitioner '{}', token map will be empty.", logPrefix, partitioner); return null; } }
Source:
public URIish(String s) throws URISyntaxException { if (StringUtils.isEmptyOrNull(s)) { throw new URISyntaxException("The uri was empty or null", JGitText.get().cannotParseGitURIish); } Matcher matcher = SINGLE_SLASH_FILE_URI.matcher(s); if (matcher.matches()) { scheme = matcher.group(1); path = cleanLeadingSlashes(unescape(matcher.group(2)), scheme); return; } matcher = FULL_URI.matcher(s); if (matcher.matches()) { scheme = matcher.group(1); user = unescape(matcher.group(2)); pass = unescape(matcher.group(3)); host = unescape(matcher.group(4)); if (matcher.group(5) != null) port = Integer.parseInt(matcher.group(5)); path = cleanLeadingSlashes(unescape(n2e(matcher.group(6)) + n2e(matcher.group(7))), scheme); return; } matcher = RELATIVE_SCP_URI.matcher(s); if (matcher.matches()) { user = unescape(matcher.group(1)); pass = unescape(matcher.group(2)); host = unescape(matcher.group(3)); path = unescape(matcher.group(4)); return; } matcher = ABSOLUTE_SCP_URI.matcher(s); if (matcher.matches()) { user = matcher.group(1); pass = matcher.group(2); host = matcher.group(3); path = matcher.group(4); return; } matcher = LOCAL_FILE.matcher(s); if (matcher.matches()) { path = matcher.group(1); return; } throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); }

Target:
public URIish(String s) throws URISyntaxException { if (StringUtils.isEmptyOrNull(s)) { throw new URISyntaxException("The uri was empty or null", JGitText.get().cannotParseGitURIish); } Matcher matcher = SINGLE_SLASH_FILE_URI.matcher(s); if (matcher.matches()) { scheme = matcher.group(1); path = cleanLeadingSlashes(unescape(matcher.group(2)), scheme); return; } matcher = FULL_URI.matcher(s); if (matcher.matches()) { scheme = matcher.group(1); user = unescape(matcher.group(2)); pass = unescape(matcher.group(3)); host = unescape(matcher.group(4)); if (matcher.group(5) != null) port = Integer.parseInt(matcher.group(5)); path = cleanLeadingSlashes(unescape(n2e(matcher.group(6)) + n2e(matcher.group(7))), scheme); return; } matcher = RELATIVE_SCP_URI.matcher(s); if (matcher.matches()) { user = matcher.group(1); pass = matcher.group(2); host = matcher.group(3); path = matcher.group(4); return; } matcher = ABSOLUTE_SCP_URI.matcher(s); if (matcher.matches()) { user = matcher.group(1); pass = matcher.group(2); host = matcher.group(3); path = matcher.group(4); return; } matcher = LOCAL_FILE.matcher(s); if (matcher.matches()) { path = matcher.group(1); return; } throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); }
Source:
private Cursor makeCardsTypesCursor() { String query = "select " + "sum(case when queue=2 and ivl >= 21 then 1 else 0 end), -- mtr\n" + "sum(case when queue in (1,3) or (queue=2 and ivl < 21) then 1 else 0 end), -- yng/lrn\n" + "sum(case when queue=0 then 1 else 0 end), -- new\n" + "sum(case when queue<0 then 1 else 0 end) -- susp\n" + "from cards"; return mCollection.getDb() .getDatabase() .rawQuery(query, null); }

Target:
private Cursor makeCardsTypesCursor() { SQLiteDatabase db = getDbOrNull(); if (db == null) { initCollection(); db = getDbOrNull(); } if (db == null) { return null; } return Stats.getCardTypesStats(db); }
Source:
private void handleInvalidRefreshToken(TokenResponse tokenResponse) { final TokenErrorResponseType errorType = tokenResponse.getErrorType(); final ErrorResponseCode errorCode; if (errorType == INVALID_GRANT) { errorCode = INVALID_REFRESH_TOKEN; } else { errorCode = INTERNAL_ERROR_NO_PARAMS; } throw new HttpException(errorCode); }

Target:
private void handleInvalidRefreshToken(TokenResponse tokenResponse) { final TokenErrorResponseType errorType = tokenResponse.getErrorType(); final ErrorResponseCode errorCode; if (errorType == INVALID_GRANT) { errorCode = INVALID_REFRESH_TOKEN; } else { errorCode = INTERNAL_ERROR_NO_PARAMS; } LOG.error(errorCode.getDescription()); throw new HttpException(errorCode); }
Source:
public boolean select(Viewer viewer, Object parent, Object element) { IBreakpoint breakpoint = (IBreakpoint) element; IInteractionElement interactionElement = ContextCore.getContextManager().getElement( structureBridge.getHandleIdentifier(breakpoint)); if (interactionElement == null) { return true; } return !interactionElement.getInterest().isInteresting(); }

Target:
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IBreakpoint) { IBreakpoint breakpoint = (IBreakpoint) element; IInteractionElement interactionElement = ContextCore.getContextManager().getElement( structureBridge.getHandleIdentifier(breakpoint)); if (interactionElement == null) { return true; } return !interactionElement.getInterest().isInteresting(); } return true; }
Source:
public void validate_shouldFailForAConceptIfThereIsNotAtLeastOneNonBlankDescription() throws Exception { Concept concept = new Concept(); concept.addDescription(new ConceptDescription(null)); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); Assert.assertEquals(true, errors.hasErrors()); }

Target:
public void validate_shouldFailForAConceptIfThereIsNotAtLeastOneNonBlankDescription() throws Exception { Concept concept = new Concept(); concept.addDescription(new ConceptDescription(null)); concept.addDescription(new ConceptDescription("", Context.getLocale())); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); boolean found = false; for (ObjectError error : errors.getAllErrors()) { if (error.getCode().equals("Concept.error.notAtLeastOneNonBlankDescription")) { found = true; break; } } Assert.assertTrue(found); }
Source:
private CompositeBlobInfo deserializeMetadataContentV3(ByteBuffer metadataContent, StoreKeyFactory storeKeyFactory) throws MessageFormatException, IOException { ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(metadataContent); DataInputStream inputStream = new DataInputStream(byteBufferInputStream); short metadataContentVersion = inputStream.readShort(); Assert.assertEquals("Metadata Content Version mismatch ", MessageFormatRecord.Metadata_Content_Version_V3, metadataContentVersion); return MessageFormatRecord.Metadata_Content_Format_V3.deserializeMetadataContentRecord(inputStream, storeKeyFactory); }

Target:
private CompositeBlobInfo deserializeMetadataContentV3(ByteBuffer metadataContent, StoreKeyFactory storeKeyFactory) throws IOException { ByteBufferInputStream byteBufferInputStream = new ByteBufferInputStream(metadataContent); DataInputStream inputStream = new DataInputStream(byteBufferInputStream); short metadataContentVersion = inputStream.readShort(); Assert.assertEquals("Metadata Content Version mismatch ", MessageFormatRecord.Metadata_Content_Version_V3, metadataContentVersion); return MessageFormatRecord.Metadata_Content_Format_V3.deserializeMetadataContentRecord(inputStream, storeKeyFactory); }
Source:
public void setCheckAllLedgersCTime(long checkAllLedgersCTime) throws UnavailableException { LOG.debug("setCheckAllLedgersCTime"); try { if (zkc.exists(checkAllLedgersCtimeZnode, false) != null) { zkc.setData(checkAllLedgersCtimeZnode, Long.toString(checkAllLedgersCTime).getBytes(UTF_8), -1); } else { zkc.create(checkAllLedgersCtimeZnode, Long.toString(checkAllLedgersCTime).getBytes(UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (KeeperException ke) { throw new ReplicationException.UnavailableException("Error contacting zookeeper", ke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new ReplicationException.UnavailableException("Interrupted while contacting zookeeper", ie); } }

Target:
public void setCheckAllLedgersCTime(long checkAllLedgersCTime) throws UnavailableException { if (LOG.isDebugEnabled()) { LOG.debug("setCheckAllLedgersCTime"); } try { List<ACL> zkAcls = ZkUtils.getACLs(conf); CheckAllLedgersFormat.Builder builder = CheckAllLedgersFormat.newBuilder(); builder.setCheckAllLedgersCTime(checkAllLedgersCTime); byte[] checkAllLedgersFormatByteArray = builder.build().toByteArray(); if (zkc.exists(checkAllLedgersCtimeZnode, false) != null) { zkc.setData(checkAllLedgersCtimeZnode, checkAllLedgersFormatByteArray, -1); } else { zkc.create(checkAllLedgersCtimeZnode, checkAllLedgersFormatByteArray, zkAcls, CreateMode.PERSISTENT); } } catch (KeeperException ke) { throw new ReplicationException.UnavailableException("Error contacting zookeeper", ke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new ReplicationException.UnavailableException("Interrupted while contacting zookeeper", ie); } }
Source:
private byte[] internalWrite(final int major) throws IOException { try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ITF8.writeUnsignedITF8(sequenceId, outputStream); ITF8.writeUnsignedITF8(alignmentStart, outputStream); ITF8.writeUnsignedITF8(alignmentSpan, outputStream); ITF8.writeUnsignedITF8(recordCount, outputStream); LTF8.writeUnsignedLTF8(globalRecordCounter, outputStream); ITF8.writeUnsignedITF8(dataBlockCount, outputStream); CramIntArray.write(contentIDs, outputStream); ITF8.writeUnsignedITF8(embeddedRefBlockContentID, outputStream); outputStream.write(refMD5 == null ? NO_MD5 : refMD5); if (major >= CramVersions.CRAM_v3.major && tags != null) { final BinaryCodec binaryCoded = new BinaryCodec(outputStream); final BinaryTagCodec binaryTagCodec = new BinaryTagCodec(binaryCoded); SAMBinaryTagAndValue samBinaryTagAndValue = tags; do { log.debug("Writing slice tag: " + SAMTag.makeStringTag(samBinaryTagAndValue.tag)); binaryTagCodec.writeTag(samBinaryTagAndValue.tag, samBinaryTagAndValue.value, samBinaryTagAndValue.isUnsignedArray()); } while ((samBinaryTagAndValue = samBinaryTagAndValue.getNext()) != null); } return outputStream.toByteArray(); } }

Target:
private byte[] internalWrite(final int major) throws IOException { try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ITF8.writeUnsignedITF8(sequenceId, outputStream); ITF8.writeUnsignedITF8(sliceAlignment.getStart(), outputStream); ITF8.writeUnsignedITF8(sliceAlignment.getSpan(), outputStream); ITF8.writeUnsignedITF8(sliceAlignment.getCount(), outputStream); LTF8.writeUnsignedLTF8(globalRecordCounter, outputStream); ITF8.writeUnsignedITF8(dataBlockCount, outputStream); CramIntArray.write(contentIDs, outputStream); ITF8.writeUnsignedITF8(embeddedRefBlockContentID, outputStream); outputStream.write(refMD5 == null ? NO_MD5 : refMD5); if (major >= CramVersions.CRAM_v3.major && sliceHeaderTags != null) { try (final BinaryCodec codec = new BinaryCodec(outputStream)) { final BinaryTagCodec binaryTagCodec = new BinaryTagCodec(codec); SAMBinaryTagAndValue samBinaryTagAndValue = sliceHeaderTags; do { log.debug("Writing slice tag: " + SAMTag.makeStringTag(samBinaryTagAndValue.tag)); binaryTagCodec.writeTag(samBinaryTagAndValue.tag, samBinaryTagAndValue.value, samBinaryTagAndValue.isUnsignedArray()); } while ((samBinaryTagAndValue = samBinaryTagAndValue.getNext()) != null); } } return outputStream.toByteArray(); } }
Source:
public void should_skip_invalid_peers_row_v2(String columnToCheck) { topologyMonitor.isSchemaV2 = true; node2.broadcastAddress = ADDRESS2; AdminRow peer2 = mockPeersV2Row(2, node2.getHostId()); switch (columnToCheck) { case "native_address": when(peer2.getInetAddress(columnToCheck)).thenReturn(null); break; case "native_port": when(peer2.getInteger(columnToCheck)).thenReturn(null); break; case "host_id": when(peer2.getUuid(columnToCheck)).thenReturn(null); break; case "data_center": when(peer2.getUuid(columnToCheck)).thenReturn(null); break; } topologyMonitor.stubQueries( new StubbedQuery( "SELECT * FROM system.peers_v2 WHERE peer = :address and peer_port = :port", ImmutableMap.of("address", ADDRESS2.getAddress(), "port", 9042), mockResult(peer2))); CompletionStage<Optional<NodeInfo>> futureInfo = topologyMonitor.refreshNode(node2); assertThatStage(futureInfo).isSuccess(maybeInfo -> assertThat(maybeInfo).isEmpty()); assertThat(node2.broadcastAddress).isNotNull().isEqualTo(ADDRESS2); assertLog( Level.WARN, "[null] Found invalid row in system.peers_v2 for peer: /127.0.0.2. " + "This is likely a gossip or snitch issue, this node will be ignored."); }

Target:
public void should_skip_invalid_peers_row_v2(String columnToCheck) { topologyMonitor.isSchemaV2 = true; node2.broadcastAddress = ADDRESS2; AdminRow peer2 = mockPeersV2Row(2, node2.getHostId()); when(peer2.isNull(columnToCheck)).thenReturn(true); topologyMonitor.stubQueries( new StubbedQuery( "SELECT * FROM system.peers_v2 WHERE peer = :address and peer_port = :port", ImmutableMap.of("address", ADDRESS2.getAddress(), "port", 9042), mockResult(peer2))); CompletionStage<Optional<NodeInfo>> futureInfo = topologyMonitor.refreshNode(node2); assertThatStage(futureInfo).isSuccess(maybeInfo -> assertThat(maybeInfo).isEmpty()); assertThat(node2.broadcastAddress).isNotNull().isEqualTo(ADDRESS2); assertLog( Level.WARN, "[null] Found invalid row in system.peers_v2 for peer: /127.0.0.2. " + "This is likely a gossip or snitch issue, this node will be ignored."); }
Source:
public void stepExecutionWithCredentials() throws Exception { assumeNotWindows(); IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials); WorkflowJob p = r.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " mockDockerLoginWithEcho {\n" + " withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" + " echo 'config would be set up to connect to https://my-reg:1234'\n" + " }\n" + " }\n" + "}", true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.assertLogContains("docker login -u me -p pass https://my-reg:1234", r.assertBuildStatusSuccess(r.waitForCompletion(b))); r.assertLogContains("config would be set up to connect to https://my-reg:1234", b); }

Target:
public void stepExecutionWithCredentials() throws Exception { assumeNotWindows(); IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials); WorkflowJob p = r.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " mockDockerLoginWithEcho {\n" + " withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" + " }\n" + " }\n" + "}", true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.assertLogContains("docker login -u me -p pass https://my-reg:1234", r.assertBuildStatusSuccess(r.waitForCompletion(b))); }
Source:
public List<RebaseTodoLine> readRebaseTodo(String path, boolean includeComments) throws IOException { byte[] buf = IO.readFully(new File(repo.getDirectory(), path)); int ptr = 0; int tokenBegin = 0; List<RebaseTodoLine> r = new LinkedList<RebaseTodoLine>(); while (ptr < buf.length) { tokenBegin = ptr; ptr = RawParseUtils.nextLF(buf, ptr); int lineStart = tokenBegin; int lineEnd = ptr - 2; if (lineEnd >= 0 && buf[lineEnd] == '\r') lineEnd--; if (buf[tokenBegin] == '#') { if (includeComments) { RebaseTodoLine line = null; String commentString = RawParseUtils.decode(buf, tokenBegin, lineEnd + 1); try { int skip = tokenBegin + 1; skip = nextParsableToken(buf, skip, lineEnd); if (skip != -1) { line = parseLine(buf, skip, lineEnd); line.setAction(Action.COMMENT); line.setComment(commentString); } } catch (Exception e) { line = null; } finally { if (line == null) line = new RebaseTodoLine(commentString); r.add(line); } } continue; } tokenBegin = nextParsableToken(buf, tokenBegin, lineEnd); if (tokenBegin == -1) { if (includeComments) r.add(new RebaseTodoLine(RawParseUtils.decode(buf, lineStart, 1 + lineEnd))); continue; } RebaseTodoLine line = parseLine(buf, tokenBegin, lineEnd); if (line == null) continue; r.add(line); } return r; }

Target:
public List<RebaseTodoLine> readRebaseTodo(String path, boolean includeComments) throws IOException { byte[] buf = IO.readFully(new File(repo.getDirectory(), path)); int ptr = 0; int tokenBegin = 0; List<RebaseTodoLine> r = new LinkedList<RebaseTodoLine>(); while (ptr < buf.length) { tokenBegin = ptr; ptr = RawParseUtils.nextLF(buf, ptr); int lineStart = tokenBegin; int lineEnd = ptr - 2; if (lineEnd >= 0 && buf[lineEnd] == '\r') lineEnd--; if (buf[tokenBegin] == '#') { if (includeComments) { parseComments(buf, tokenBegin, r, lineEnd); } } else { tokenBegin = nextParsableToken(buf, tokenBegin, lineEnd); if (tokenBegin == -1) { if (includeComments) r.add(new RebaseTodoLine(RawParseUtils.decode(buf, lineStart, 1 + lineEnd))); continue; } RebaseTodoLine line = parseLine(buf, tokenBegin, lineEnd); if (line == null) continue; r.add(line); } } return r; }
Source:
public void remove() throws AlreadyInitializedException { if (applicationRunning()) { throw new AlreadyInitializedException( "Error - The Fluo '" + config.getApplicationName() + "' application" + " is already running and must be stopped before removing. " + " Aborted remove."); } if (!config.hasRequiredAdminProps()) { throw new IllegalArgumentException("Admin configuration is missing required properties"); } Preconditions.checkArgument( !ZookeeperUtil.parseRoot(config.getInstanceZookeepers()).equals("/"), "The Zookeeper connection string (set by 'fluo.connection.zookeepers') " + " must have a chroot suffix."); if (OracleServerUtils.oracleExists(getAppCurator())) { throw new FluoException("Must stop the oracle server to remove an application"); } Connector conn = AccumuloUtil.getConnector(config); boolean tableExists = conn.tableOperations().exists(config.getAccumuloTable()); if (tableExists) { logger.info("The Accumulo table '{}' will be dropped", config.getAccumuloTable()); try { conn.tableOperations().delete(config.getAccumuloTable()); } catch (Exception e) { throw new RuntimeException(e); } } try { if (rootCurator.checkExists().forPath(appRootDir) != null) { logger.info("Clearing Fluo '{}' application in Zookeeper at {}", config.getApplicationName(), config.getAppZookeepers()); rootCurator.delete().deletingChildrenIfNeeded().forPath(appRootDir); } } catch (KeeperException.NoNodeException nne) { } catch (Exception e) { logger.error("An error occurred deleting Zookeeper root of [" + config.getAppZookeepers() + "], error=[" + e.getMessage() + "]"); throw new RuntimeException(e); } }

Target:
public void remove() { if (applicationRunning()) { throw new FluoException("Error - The Fluo '" + config.getApplicationName() + "' application" + " is already running and must be stopped before removing. Aborted remove."); } if (!config.hasRequiredAdminProps()) { throw new IllegalArgumentException("Admin configuration is missing required properties"); } Preconditions.checkArgument( !ZookeeperUtil.parseRoot(config.getInstanceZookeepers()).equals("/"), "The Zookeeper connection string (set by 'fluo.connection.zookeepers') " + " must have a chroot suffix."); if (OracleServerUtils.oracleExists(getAppCurator())) { throw new FluoException("Must stop the oracle server to remove an application"); } Connector conn = AccumuloUtil.getConnector(config); boolean tableExists = conn.tableOperations().exists(config.getAccumuloTable()); if (tableExists) { logger.info("The Accumulo table '{}' will be dropped", config.getAccumuloTable()); try { conn.tableOperations().delete(config.getAccumuloTable()); } catch (Exception e) { throw new RuntimeException(e); } } try { if (rootCurator.checkExists().forPath(appRootDir) != null) { logger.info("Clearing Fluo '{}' application in Zookeeper at {}", config.getApplicationName(), config.getAppZookeepers()); rootCurator.delete().deletingChildrenIfNeeded().forPath(appRootDir); } } catch (KeeperException.NoNodeException nne) { } catch (Exception e) { logger.error("An error occurred deleting Zookeeper root of [" + config.getAppZookeepers() + "], error=[" + e.getMessage() + "]"); throw new RuntimeException(e); } }
Source:
private boolean calculateMaxOffset(int size) { if (size + Bytes.SIZEOF_INT + 2 <= Short.MAX_VALUE) { return true; } return false; }

Target:
private boolean calculateMaxOffset(int size) { if ((size + Bytes.SIZEOF_INT + MAX_POSSIBLE_VINT_LENGTH) <= (2 * Short.MAX_VALUE)) { return true; } return false; }
Source:
public SearchMapping getSearchMapping() { SearchMapping mapping = new SearchMapping(); mapping .analyzerDef(LuceneAnalyzers.PHRASE_ANALYZER, KeywordTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class); mapping.analyzerDef(LuceneAnalyzers.EXACT_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class); mapping.analyzerDef(LuceneAnalyzers.START_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class) .filter(EdgeNGramFilterFactory.class) .param("minGramSize", "2") .param("maxGramSize", "20"); mapping.analyzerDef(LuceneAnalyzers.ANYWHERE_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class) .filter(NGramFilterFactory.class) .param("minGramSize", "2") .param("maxGramSize", "20"); mapping.analyzerDef(LuceneAnalyzers.SOUNDEX_ANALYZER, StandardTokenizerFactory.class) .filter(PhoneticFilterFactory.class) .param("encoder", "Soundex") .param("inject", "true"); return mapping; }

Target:
public SearchMapping getSearchMapping() { SearchMapping mapping = new SearchMapping(); mapping .analyzerDef(LuceneAnalyzers.PHRASE_ANALYZER, KeywordTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class); mapping.analyzerDef(LuceneAnalyzers.EXACT_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class); mapping.analyzerDef(LuceneAnalyzers.START_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class) .filter(EdgeNGramFilterFactory.class) .param("minGramSize", "2") .param("maxGramSize", "20"); mapping.analyzerDef(LuceneAnalyzers.ANYWHERE_ANALYZER, WhitespaceTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(ASCIIFoldingFilterFactory.class) .filter(NGramFilterFactory.class) .param("minGramSize", "2") .param("maxGramSize", "20"); mapping.analyzerDef(LuceneAnalyzers.SOUNDEX_ANALYZER, StandardTokenizerFactory.class) .filter(ClassicFilterFactory.class) .filter(LowerCaseFilterFactory.class) .filter(PhoneticFilterFactory.class) .param("encoder", "Soundex"); return mapping; }
Source:
public void createSiteRequest(String type, Site site){ HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); if (type.equals(CREATE)) { CreateSiteRequest createSiteRequest = new CreateSiteRequest(mMainActivity, site, params, new Response.Listener<Site>() { @Override public void onResponse(Site site) { Log.e("successful site", "creation"); } }); mNetworkManager.getRequestQueue().add(createSiteRequest); SiteListFragment returnFragment = SiteListFragment.newInstance(); mMainActivity.replaceFragment(returnFragment); } else { EditSiteRequest editSiteRequest = new EditSiteRequest(mMainActivity, site, params, new Response.Listener<Site>() { @Override public void onResponse(Site site) { Log.e("successful site", "edit"); } }); mNetworkManager.getRequestQueue().add(editSiteRequest); mMainActivity.getSupportFragmentManager().popBackStack(); } }

Target:
public void createSiteRequest(String type, Site site){ HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); if (type.equals(CREATE)) { CreateSiteRequest createSiteRequest = new CreateSiteRequest(mMainActivity, site, params, new Response.Listener<Site>() { @Override public void onResponse(Site site) { Log.e("successful site", "creation"); } }); mNetworkManager.getRequestQueue().add(createSiteRequest); } else { EditSiteRequest editSiteRequest = new EditSiteRequest(mMainActivity, site, params, new Response.Listener<Site>() { @Override public void onResponse(Site site) { Log.e("successful site", "edit"); } }); mNetworkManager.getRequestQueue().add(editSiteRequest); } mMainActivity.getSupportFragmentManager().popBackStack(); }
Source:
protected boolean canDoAction() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RECONSTRUCT_MASTER); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__STORAGE__DOMAIN); List<storage_pool_iso_map> poolDomains = DbFacade.getInstance() .getStoragePoolIsoMapDAO().getAllForStoragePool(getStoragePool().getId()); for (storage_pool_iso_map poolDomain : poolDomains) { if (poolDomain.getstatus() == StorageDomainStatus.Locked) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); addCanDoActionMessage(String.format("$status %1$s", getStorageDomain().getstatus())); return false; } } return InitializeVds(); }

Target:
protected boolean canDoAction() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RECONSTRUCT_MASTER); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__STORAGE__DOMAIN); List<storage_pool_iso_map> poolDomains = DbFacade.getInstance() .getStoragePoolIsoMapDAO().getAllForStoragePool(getStoragePool().getId()); for (storage_pool_iso_map poolDomain : poolDomains) { if (poolDomain.getstatus() == StorageDomainStatus.Locked) { addStorageDomainStateIllegalMessage(poolDomain.getstatus()); return false; } } return InitializeVds(); }
Source:
public void connectStoragePool() { Map<String, String> storageDomains = null; storageDomains = StoragePoolDomainHelper.buildStoragePoolDomainsMap(getParameters().getStorageDomains()); log.info("executing with domain map: {}", storageDomains); status = getBroker().connectStoragePool( getParameters().getStoragePoolId().toString(), getParameters().getVds().getVdsSpmId(), getParameters().getStoragePoolId().toString(), getParameters().getMasterDomainId().toString(), getParameters().getStoragePool().getMasterDomainVersion(), storageDomains); }

Target:
public void connectStoragePool() { Map<String, String> storageDomains = null; storageDomains = StoragePoolDomainHelper.buildStoragePoolDomainsMap(getParameters().getStorageDomains()); log.info("Executing with domain map: {}", storageDomains); status = getBroker().connectStoragePool( getParameters().getStoragePoolId().toString(), getParameters().getVds().getVdsSpmId(), getParameters().getStoragePoolId().toString(), getParameters().getMasterDomainId().toString(), getParameters().getStoragePool().getMasterDomainVersion(), storageDomains); }
Source:
public synchronized void reloginFromKeytab(boolean ignoreTimeElapsed) throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKeytab) { return; } long now = Time.now(); if (!shouldRenewImmediatelyForTests && !ignoreTimeElapsed && !hasSufficientTimeElapsed(now)) { return; } KerberosTicket tgt = getTGT(); if (tgt != null && !shouldRenewImmediatelyForTests && now < getRefreshTime(tgt)) { return; } LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } long start = 0; user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } synchronized (UserGroupInformation.class) { login.logout(); login = newLoginContext( HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(), new HadoopConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + keytabPrincipal); } start = Time.now(); login.login(); fixKerberosTicketOrder(); metrics.loginSuccess.add(Time.now() - start); setLogin(login); } } catch (LoginException le) { if (start > 0) { metrics.loginFailure.add(Time.now() - start); } KerberosAuthException kae = new KerberosAuthException(LOGIN_FAILURE, le); kae.setPrincipal(keytabPrincipal); kae.setKeytabFile(keytabFile); throw kae; } }

Target:
private synchronized void reloginFromKeytab(boolean ignoreTimeElapsed) throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKeytab) { return; } long now = Time.now(); if (!shouldRenewImmediatelyForTests && !ignoreTimeElapsed && !hasSufficientTimeElapsed(now)) { return; } KerberosTicket tgt = getTGT(); if (tgt != null && !shouldRenewImmediatelyForTests && now < getRefreshTime(tgt)) { return; } LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new KerberosAuthException(MUST_FIRST_LOGIN_FROM_KEYTAB); } long start = 0; user.setLastLogin(now); try { if (LOG.isDebugEnabled()) { LOG.debug("Initiating logout for " + getUserName()); } synchronized (UserGroupInformation.class) { login.logout(); login = newLoginContext( HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject(), new HadoopConfiguration()); if (LOG.isDebugEnabled()) { LOG.debug("Initiating re-login for " + keytabPrincipal); } start = Time.now(); login.login(); fixKerberosTicketOrder(); metrics.loginSuccess.add(Time.now() - start); setLogin(login); } } catch (LoginException le) { if (start > 0) { metrics.loginFailure.add(Time.now() - start); } KerberosAuthException kae = new KerberosAuthException(LOGIN_FAILURE, le); kae.setPrincipal(keytabPrincipal); kae.setKeytabFile(keytabFile); throw kae; } }
Source:
public ConfigurationBuilder addServers(String servers) { IpStackType stackType = InternetProtocols.getIpStackType(); for (String server : servers.split(";")) { switch (stackType) { case IPv4: parseIPv4Server(server); break; case IPv6: parseIpV6Server(server); break; } } return this; }

Target:
public ConfigurationBuilder addServers(String servers) { for (String server : servers.split(";")) { Matcher matcher = ADDRESS_PATTERN.matcher(server); if (matcher.matches()) { String v6host = matcher.group(2); String v4host = matcher.group(3); String host = v6host != null ? v6host : v4host; String portString = matcher.group(4); int port = portString == null ? ConfigurationProperties.DEFAULT_HOTROD_PORT : Integer.parseInt(portString); this.addServer().host(host).port(port); } else { throw log.parseErrorServerAddress(server); } } return this; }
Source:
public final TreCollection parse(final NitfReader reader, final int treLength, final TreSource sourceSegment) throws NitfFormatException { TreCollection treCollection = new TreCollectionImpl(); int bytesRead = 0; while (bytesRead < treLength) { String tag = reader.readBytes(TreConstants.TAG_LENGTH); bytesRead += TreConstants.TAG_LENGTH; int fieldLength = reader.readBytesAsInteger(TreConstants.TAGLEN_LENGTH); bytesRead += TreConstants.TAGLEN_LENGTH; Tre tre = treParser.parseOneTre(reader, tag, fieldLength, sourceSegment); if (tre != null) { treCollection.add(tre); } bytesRead += fieldLength; } return treCollection; }

Target:
public final TreCollection parse(final NitfReader reader, final int treLength, final TreSource sourceSegment) throws NitfFormatException { TreCollection treCollection = new TreCollectionImpl(); int bytesRead = 0; while (bytesRead < treLength) { String tag = reader.readBytes(TAG_LENGTH); bytesRead += TAG_LENGTH; int fieldLength = reader.readBytesAsInteger(TAGLEN_LENGTH); bytesRead += TAGLEN_LENGTH; Tre tre = treParser.parseOneTre(reader, tag, fieldLength, sourceSegment); if (tre != null) { treCollection.add(tre); } bytesRead += fieldLength; } return treCollection; }
Source:
public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof AmmoStorage) { continue; } if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart) part).findReplacement(true); } if (null != replacement) { if (replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement); } } else { newShoppingList.add(part); } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }

Target:
public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof AmmoStorage) { continue; } if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart) part).findReplacement(true); } if (null != replacement) { if (replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement); } } else { newShoppingList.add(part); } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && ((null == newArmorSupplies) || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }
Source:
public void testInvalidCharacterOption() { thrown.expect(ValidationException.class); thrown.expect(containsCause(new ValidationException("Option [csv.quote-character] must be a Character."))); final Map<String, String> options = getModifiedOptions(opts -> opts.put("csv.quote-character", "abc")); createTableSink(options); }

Target:
public void testInvalidCharacterOption() { thrown.expect(ValidationException.class); thrown.expect(containsCause(new ValidationException("Option 'csv.quote-character' must be " + "a string with single character, but was: abc"))); final Map<String, String> options = getModifiedOptions(opts -> opts.put("csv.quote-character", "abc")); createTableSink(options); }