auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String generateConnectionId(SocketChannel channel) { Socket socket = channel.socket(); String localHost = socket.getLocalAddress().getHostAddress(); int localPort = socket.getLocalPort(); String remoteHost = socket.getInetAddress().getHostAddress(); int remotePort = socket.getPort(); long postFix = IdGenerator.getAndIncrement(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(localHost).append(":").append(localPort).append("-").append(remoteHost).append(":") .append(remotePort).append("_").append(postFix); return stringBuilder.toString(); }

Target:
private String generateConnectionId(SocketChannel channel) { Socket socket = channel.socket(); String localHost = socket.getLocalAddress().getHostAddress(); int localPort = socket.getLocalPort(); String remoteHost = socket.getInetAddress().getHostAddress(); int remotePort = socket.getPort(); long connectionIdSuffix = IdGenerator.getAndIncrement(); StringBuilder connectionIdBuilder = new StringBuilder(); connectionIdBuilder.append(localHost).append(":").append(localPort).append("-").append(remoteHost).append(":") .append(remotePort).append("_").append(connectionIdSuffix); return connectionIdBuilder.toString(); }
Source:
public List<RichFacility> getRichFacilities(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.authorizedInternal(sess, "getRichFacilities_policy")) { throw new PrivilegeException(sess, "getRichFacilities"); } List<Facility> facilities = getFacilitiesManagerBl().getFacilities(sess); facilities.removeIf(facility -> AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); return getFacilitiesManagerBl().getRichFacilities(sess, facilities); }

Target:
public List<RichFacility> getRichFacilities(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.authorizedInternal(sess, "getRichFacilities_policy")) { throw new PrivilegeException(sess, "getRichFacilities"); } List<Facility> facilities = getFacilitiesManagerBl().getFacilities(sess); facilities.removeIf(facility -> !AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); return getFacilitiesManagerBl().getRichFacilities(sess, facilities); }
Source:
Map<GroupKey, List<Result>> get(String userName, List<AbstractFilter> filters, DiscoveryAttributes.AttributeType groupAttributeType, Group.GroupSortingAlgorithm groupSortingType, ResultsSorter.SortingMethod domainSortingMethod, SleuthkitCase caseDb, CentralRepository centralRepoDb) throws DiscoveryException { try { final SearchKey searchKey = new SearchKey(userName, filters, groupAttributeType, groupSortingType, domainSortingMethod, caseDb, centralRepoDb); return cache.get(searchKey); } catch (Throwable ex) { throw new DiscoveryException("Error fetching results from cache", ex.getCause()); } }

Target:
Map<GroupKey, List<Result>> get(String userName, List<AbstractFilter> filters, DiscoveryAttributes.AttributeType groupAttributeType, Group.GroupSortingAlgorithm groupSortingType, ResultsSorter.SortingMethod domainSortingMethod, SleuthkitCase caseDb, CentralRepository centralRepoDb) throws DiscoveryException { try { final SearchKey searchKey = new SearchKey(userName, filters, groupAttributeType, groupSortingType, domainSortingMethod, caseDb, centralRepoDb); return cache.get(searchKey); } catch (ExecutionException ex) { throw new DiscoveryException("Error fetching results from cache", ex.getCause()); } }
Source:
public void received(Object message, String remote, Channel channel) throws InterruptedException { List<TaskMessage> msgs; try { msgs = (List<TaskMessage>) message; } catch (ClassCastException e) { LOG.error("Worker netty server receive message other than the expected class List<TaskMessage>", e); return; } enqueue(msgs, remote); }

Target:
public void received(Object message, String remote, Channel channel) throws InterruptedException { List<TaskMessage> msgs; try { msgs = (List<TaskMessage>) message; } catch (ClassCastException e) { LOG.error("Worker netty server received message other than the expected class List<TaskMessage> from remote: {}. Ignored.", remote, e); return; } enqueue(msgs, remote); }
Source:
CheckpointBarrierUnaligner( int[] numberOfInputChannelsPerGate, ChannelStateWriter channelStateWriter, String taskName, AbstractInvokable toNotifyOnCheckpoint) { super(toNotifyOnCheckpoint); this.taskName = taskName; this.channelStateWriter = checkNotNull(channelStateWriter); final int numGates = numberOfInputChannelsPerGate.length; gateChannelOffsets = new int[numGates]; for (int index = 1; index < numGates; index++) { gateChannelOffsets[index] = gateChannelOffsets[index - 1] + numberOfInputChannelsPerGate[index - 1]; } final int totalNumChannels = gateChannelOffsets[numGates - 1] + numberOfInputChannelsPerGate[numGates - 1]; barrierConsumedChannels = new boolean[totalNumChannels]; Arrays.fill(barrierConsumedChannels, true); barrierReceivedChannels = new boolean[totalNumChannels]; Arrays.fill(barrierReceivedChannels, true); numOpenChannels = totalNumChannels; }

Target:
CheckpointBarrierUnaligner( int[] numberOfInputChannelsPerGate, ChannelStateWriter channelStateWriter, String taskName, AbstractInvokable toNotifyOnCheckpoint) { super(toNotifyOnCheckpoint); this.taskName = taskName; final int numGates = numberOfInputChannelsPerGate.length; gateChannelOffsets = new int[numGates]; for (int index = 1; index < numGates; index++) { gateChannelOffsets[index] = gateChannelOffsets[index - 1] + numberOfInputChannelsPerGate[index - 1]; } final int totalNumChannels = gateChannelOffsets[numGates - 1] + numberOfInputChannelsPerGate[numGates - 1]; hasInflightBuffers = new boolean[totalNumChannels]; channelInfos = IntStream.range(0, numGates) .mapToObj(gateIndex -> IntStream.range(0, numberOfInputChannelsPerGate[gateIndex]) .mapToObj(channelIndex -> new InputChannelInfo(gateIndex, channelIndex))) .flatMap(Function.identity()) .toArray(InputChannelInfo[]::new); threadSafeUnaligner = new ThreadSafeUnaligner(totalNumChannels, checkNotNull(channelStateWriter), this); }
Source:
public void testEarlyReadableStreamChannelClose() throws Exception { final AtomicReference<Exception> callbackException = new AtomicReference<>(); Callback<GetBlobResult> callback = new Callback<GetBlobResult>() { @Override public void onCompletion(GetBlobResult result, Exception exception) { if (exception != null) { callbackException.set(exception); } else { try { result.getBlobDataChannel().close(); } catch (IOException e) { callbackException.set(e); } } } }; doPut(); GetBlobOperation op = createOperationAndComplete(callback); if (callbackException.get() != null) { throw callbackException.get(); } Exception operationException = op.getOperationException(); Assert.assertTrue("Unexpected operation exception type", operationException instanceof RouterException); Assert.assertEquals("Unexpected RouterErrorCode", RouterErrorCode.ChannelClosed, ((RouterException) operationException).getErrorCode()); }

Target:
public void testEarlyReadableStreamChannelClose() throws Exception { for (int numChunksInBlob = 0; numChunksInBlob <= 4; numChunksInBlob++) { for (int numChunksToRead = 0; numChunksToRead < numChunksInBlob; numChunksToRead++) { testEarlyReadableStreamChannelClose(numChunksInBlob, numChunksToRead); } } }
Source:
public void testGetInt_invalid2() throws CTFReaderException { BitBuffer small_fixture = new BitBuffer(ByteBuffer.allocateDirect(128)); small_fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(small_fixture, 2); small_fixture.position(1); int length = 64; boolean signed = true; small_fixture.get(length, signed); }

Target:
public void testGetInt_invalid2() throws CTFReaderException { final BitBuffer small_fixture = new BitBuffer( java.nio.ByteBuffer.allocateDirect(128)); small_fixture.setByteOrder(ByteOrder.BIG_ENDIAN); createBuffer(small_fixture, 2); small_fixture.position(1); final int length = 64; final boolean signed = true; small_fixture.get(length, signed); }
Source:
private String createSamlRequestRedirectUrl(HttpServletRequest request, RelyingPartyRegistration relyingParty) { Saml2AuthenticationRequest authnRequest = createAuthenticationRequest(relyingParty, request, true); MultiValueMap<String, String> qp = this.authenticationRequestFactory .createAuthenticationRequestParameters(authnRequest) .getQueryParameters(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(relyingParty.getIdpWebSsoUrl()); for (Map.Entry<String, List<String>> e : qp.entrySet()) { for (String value : e.getValue()) { uriBuilder.queryParam( UriUtils.encode(e.getKey(), ISO_8859_1), UriUtils.encode(value, ISO_8859_1) ); } } return uriBuilder .build(true) .toUriString(); }

Target:
private String createSamlRequestRedirectUrl(HttpServletRequest request, RelyingPartyRegistration relyingParty) { Saml2AuthenticationRequestContext authnRequest = createRedirectAuthenticationRequestContext(relyingParty, request); Saml2RedirectAuthenticationRequest authNData = this.authenticationRequestFactory.createRedirectAuthenticationRequest(authnRequest); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authNData.getAuthenticationRequestUri()); addParameter("SAMLRequest", authNData.getSamlRequest(), uriBuilder); addParameter("RelayState", authNData.getRelayState(), uriBuilder); addParameter("SigAlg", authNData.getSigAlg(), uriBuilder); addParameter("Signature", authNData.getSignature(), uriBuilder); return uriBuilder .build(true) .toUriString(); }
Source:
public static NetworkType fromValue(String value) { if (value == null) return null; return NetworkType.valueOf(value.toUpperCase()); }

Target:
public static NetworkType fromValue(String value) { return NetworkType.valueOf(value.toUpperCase()); }
Source:
public boolean isAttached() { return reportedConfigurations != null; }

Target:
public boolean isAttached() { return attachedToNic != null; }
Source:
public void processEvent(final Map<String, String> dispatchMap) { if (mEventName != EventStrings.TOKEN_CACHE_LOOKUP) { return; } final List eventList = getEventList(); final int size = eventList.size(); final Object countObject = dispatchMap.get(EventStrings.CACHE_EVENT_COUNT); if (countObject == null) { dispatchMap.put(EventStrings.CACHE_EVENT_COUNT, "1"); } else { dispatchMap.put(EventStrings.CACHE_EVENT_COUNT, Integer.toString(Integer.parseInt((String) countObject) + 1)); } dispatchMap.put(EventStrings.TOKEN_TYPE_IS_FRT, ""); dispatchMap.put(EventStrings.TOKEN_TYPE_IS_MRRT, ""); dispatchMap.put(EventStrings.TOKEN_TYPE_IS_RT, ""); for (int i = 0; i < size; i++) { final Pair eventPair = (Pair<String, String>) eventList.get(i); final String name = (String) eventPair.first; if (name.equals(EventStrings.TOKEN_TYPE_IS_FRT) || name.equals(EventStrings.TOKEN_TYPE_IS_RT) || name.equals(EventStrings.TOKEN_TYPE_IS_MRRT)) { dispatchMap.put(name, (String) eventPair.second); } } }

Target:
public void processEvent(final Map<String, String> dispatchMap) { if (mEventName != EventStrings.TOKEN_CACHE_LOOKUP) { return; } final List<Pair<String, String>> eventList = getEventList(); final String count = dispatchMap.get(EventStrings.CACHE_EVENT_COUNT); if (count == null) { dispatchMap.put(EventStrings.CACHE_EVENT_COUNT, "1"); } else { dispatchMap.put(EventStrings.CACHE_EVENT_COUNT, Integer.toString(Integer.parseInt(count) + 1)); } dispatchMap.put(EventStrings.TOKEN_TYPE_IS_FRT, ""); dispatchMap.put(EventStrings.TOKEN_TYPE_IS_MRRT, ""); dispatchMap.put(EventStrings.TOKEN_TYPE_IS_RT, ""); for (Pair<String, String> eventPair : eventList) { final String name = eventPair.first; if (name.equals(EventStrings.TOKEN_TYPE_IS_FRT) || name.equals(EventStrings.TOKEN_TYPE_IS_RT) || name.equals(EventStrings.TOKEN_TYPE_IS_MRRT)) { dispatchMap.put(name, eventPair.second); } } }
Source:
public void testNotificationIsNotShownOnRequiredFieldEmpty() { HashMap<String, String> data = new HashMap<>(); data.put(CloudMessage.TITLE, ""); data.put(CloudMessage.MESSAGE, "Message"); data.put(CloudMessage.WEB_PAGE_URL, "<LINK_0>"); checkNotificationNotShownForInvalidData(data); }

Target:
public void testNotificationIsNotShownOnRequiredFieldEmpty() { HashMap<String, String> data = new HashMap<>(); data.put(CloudMessage.TITLE, ""); data.put(CloudMessage.MESSAGE, "Message"); data.put(CloudMessage.WEB_PAGE_URL, "<LINK_2>"); checkNotificationNotShownForInvalidData(data); }
Source:
private Map<String, Object> getMongoConfigDetails(MongoConfiguration config) { Map<String, Object> configDetails = new LinkedHashMap<>(); try { configDetails.put("connectionsPerHost", config.getConnectionsPerHost()); configDetails.put("credentials", config.getCredentials()); configDetails.put("database", config.getDatabase()); configDetails.put("maxResultSetSize", config.getMaxResultSetSize()); configDetails.put("maxQueryTimeMS", config.getMaxQueryTimeMS()); configDetails.put("mongoClient", config.getMongoClient()); configDetails.put("mongoClientOptions", config.getMongoClientOptions()); configDetails.put("readPreference", config.getReadPreference()); configDetails.put("server", config.getServer()); List<ServerAddress> serverAddresses = new ArrayList<>(); config.getServerAddresses().forEachRemaining(serverAddresses::add); configDetails.put("serverAddresses", serverAddresses); configDetails.put("writeConcern", config.getWriteConcern()); } catch (Exception e) { LOGGER.error("Error reading Mongo config details"); } return configDetails; }

Target:
private Map<String, Object> getMongoConfigDetails(MongoConfiguration config) { Map<String, Object> configDetails = new LinkedHashMap<>(); try { configDetails.put("connectionsPerHost", config.getConnectionsPerHost()); configDetails.put("credentials", config.getCredentials()); configDetails.put("database", config.getDatabase()); configDetails.put("maxResultSetSize", config.getMaxResultSetSize()); configDetails.put("maxQueryTimeMS", config.getMaxQueryTimeMS()); configDetails.put("mongoClientOptions", config.getMongoClientOptions()); configDetails.put("readPreference", config.getReadPreference()); configDetails.put("server", config.getServer()); List<ServerAddress> serverAddresses = new ArrayList<>(); config.getServerAddresses().forEachRemaining(serverAddresses::add); configDetails.put("serverAddresses", serverAddresses); configDetails.put("writeConcern", config.getWriteConcern()); } catch (Exception e) { LOGGER.error("Error reading Mongo config details"); } return configDetails; }
Source:
private void assignRegions(MasterProcedureEnv env, List<RegionInfo> regions) throws IOException { LOG.info("=============assign " + regions); AssignmentManager am = env.getMasterServices().getAssignmentManager(); for (RegionInfo region : regions) { RegionStateNode regionNode = am.getRegionStates().getOrCreateRegionStateNode(region); regionNode.lock(); try { if (!isMatchingRegionLocation(regionNode)) { if (!am.isRunning()) { throw new DoNotRetryIOException( "AssignmentManager has been stopped, can not process assignment any more"); } LOG.info("{} found whose regionLocation no longer matches {}, skipping assign...", this, regionNode, serverName); continue; } if (regionNode.getProcedure() != null) { LOG.info("{} found RIT {}; {}", this, regionNode.getProcedure(), regionNode); regionNode.getProcedure().serverCrashed(env, regionNode, getServerName()); continue; } if (env.getMasterServices().getTableStateManager() .isTableState(regionNode.getTable(), TableState.State.DISABLING)) { env.getAssignmentManager().regionClosedAbnormally(regionNode); LOG.info("{} found table disabling for region {}, set it state to ABNORMALLY_CLOSED.", this, regionNode); continue; } if (env.getMasterServices().getTableStateManager() .isTableState(regionNode.getTable(), TableState.State.DISABLED)) { LOG.warn("Found table disabled for region {}, procDetails: {}", regionNode, this); continue; } TransitRegionStateProcedure proc = TransitRegionStateProcedure.assign(env, region, true, null); regionNode.setProcedure(proc); addChildProcedure(proc); } finally { regionNode.unlock(); } } }

Target:
private void assignRegions(MasterProcedureEnv env, List<RegionInfo> regions) throws IOException { AssignmentManager am = env.getMasterServices().getAssignmentManager(); for (RegionInfo region : regions) { RegionStateNode regionNode = am.getRegionStates().getOrCreateRegionStateNode(region); regionNode.lock(); try { if (!isMatchingRegionLocation(regionNode)) { if (!am.isRunning()) { throw new DoNotRetryIOException( "AssignmentManager has been stopped, can not process assignment any more"); } LOG.info("{} found whose regionLocation no longer matches {}, skipping assign...", this, regionNode, serverName); continue; } if (regionNode.getProcedure() != null) { LOG.info("{} found RIT {}; {}", this, regionNode.getProcedure(), regionNode); regionNode.getProcedure().serverCrashed(env, regionNode, getServerName()); continue; } if (env.getMasterServices().getTableStateManager() .isTableState(regionNode.getTable(), TableState.State.DISABLING)) { env.getAssignmentManager().regionClosedAbnormally(regionNode); LOG.info("{} found table disabling for region {}, set it state to ABNORMALLY_CLOSED.", this, regionNode); continue; } if (env.getMasterServices().getTableStateManager() .isTableState(regionNode.getTable(), TableState.State.DISABLED)) { LOG.warn("Found table disabled for region {}, procDetails: {}", regionNode, this); continue; } TransitRegionStateProcedure proc = TransitRegionStateProcedure.assign(env, region, true, null); regionNode.setProcedure(proc); addChildProcedure(proc); } finally { regionNode.unlock(); } } }
Source:
public double getGrowthSpeed() { return settings.getInteger("GROWTH_SPEED"); }

Target:
public int getGrowthSpeed() { return settings.getInteger("GROWTH_SPEED"); }
Source:
public Noop() { super("Noop"); }

Target:
public Noop() { super(); setName("NOOP"); }
Source:
@OnClick(R.id.wikitext_button_preview_link) void onClickButtonPreviewLink(View v) { if (editText.getInputConnection() == null) { return; } @Nullable String title = null; CharSequence selection = editText.getInputConnection().getSelectedText(0); String before; String after; if (selection != null && selection.length() > 0 && !selection.toString().contains("[[")) { title = trimPunctuation(selection.toString()); } else { if (selection != null && selection.length() > 1) { String selectionStr = selection.toString(); before = selectionStr.substring(0, selectionStr.length() / 2); after = selectionStr.substring(selectionStr.length() / 2); } else { final int peekLength = 64; before = editText.getInputConnection().getTextBeforeCursor(peekLength, 0).toString(); after = editText.getInputConnection().getTextAfterCursor(peekLength, 0).toString(); } if (TextUtils.isEmpty(before) || TextUtils.isEmpty(after)) { return; } String str = before + after; int i1 = lastIndexOf(before, "[["); int i2 = after.indexOf("]]") + before.length(); if (i1 >= 0 && i2 > 0 && i2 > i1) { str = str.substring(i1 + 2, i2).trim(); if (!TextUtils.isEmpty(str)) { if (str.contains("|")) { str = str.split("\\|")[0]; } title = str; } } } if (title != null && callback != null) { callback.onPreviewLink(title); } }

Target:
@OnClick(R.id.wikitext_button_preview_link) void onClickButtonPreviewLink(View v) { if (editText.getInputConnection() == null) { return; } @Nullable String title = null; CharSequence selection = editText.getInputConnection().getSelectedText(0); if (selection != null && selection.length() > 0 && !selection.toString().contains("[[")) { title = trimPunctuation(selection.toString()); } else { String before; String after; if (selection != null && selection.length() > 1) { String selectionStr = selection.toString(); before = selectionStr.substring(0, selectionStr.length() / 2); after = selectionStr.substring(selectionStr.length() / 2); } else { final int peekLength = 64; before = editText.getInputConnection().getTextBeforeCursor(peekLength, 0).toString(); after = editText.getInputConnection().getTextAfterCursor(peekLength, 0).toString(); } if (TextUtils.isEmpty(before) || TextUtils.isEmpty(after)) { return; } String str = before + after; int i1 = lastIndexOf(before, "[["); int i2 = after.indexOf("]]") + before.length(); if (i1 >= 0 && i2 > 0 && i2 > i1) { str = str.substring(i1 + 2, i2).trim(); if (!TextUtils.isEmpty(str)) { if (str.contains("|")) { str = str.split("\\|")[0]; } title = str; } } } if (title != null && callback != null) { callback.onPreviewLink(title); } }
Source:
private void layOutDefinitionsByUsage() { LayoutInflater inflater = LayoutInflater.from(getContext()); LinearLayout fullDefinitionsList = (LinearLayout) rootView.findViewById(R.id.wiktionary_definitions_by_part_of_speech); RbDefinition.Usage[] usageList = currentDefinition.getUsages(); for (int i = 0; i < usageList.length; i++) { View usageView = inflater.inflate(R.layout.item_wiktionary_definitions_list, (ViewGroup) rootView, false); layOutUsage(usageList[i], usageView, inflater); fullDefinitionsList.addView(usageView); } }

Target:
private void layOutDefinitionsByUsage() { LayoutInflater inflater = LayoutInflater.from(getContext()); LinearLayout fullDefinitionsList = (LinearLayout) rootView.findViewById(R.id.wiktionary_definitions_by_part_of_speech); RbDefinition.Usage[] usageList = currentDefinition.getUsages(); if (usageList.length == 0) { displayNoDefinitionsFound(); } for (int i = 0; i < usageList.length; i++) { View usageView = inflater.inflate(R.layout.item_wiktionary_definitions_list, (ViewGroup) rootView, false); layOutUsage(usageList[i], usageView, inflater); fullDefinitionsList.addView(usageView); } }
Source:
public List<ConstrainedTerm> proveRule( ConstrainedTerm initialTerm, ConstrainedTerm targetTerm, List<Rule> rules) { List<ConstrainedTerm> proofResults = new ArrayList<ConstrainedTerm>(); Set<ConstrainedTerm> visited = new HashSet<ConstrainedTerm>(); List<ConstrainedTerm> queue = new ArrayList<ConstrainedTerm>(); List<ConstrainedTerm> nextQueue = new ArrayList<ConstrainedTerm>(); visited.add(initialTerm); queue.add(initialTerm); boolean guarded = false; while (!queue.isEmpty()) { if (queue.size() == 1) { System.out.print(""); } for (ConstrainedTerm term : queue) { if (term.implies(targetTerm)) { continue; } if (guarded) { ConstrainedTerm result = applyRule(term, rules); if (result != null) { if (visited.add(result)) nextQueue.add(result); continue; } } computeRewriteStep(term); if (results.isEmpty()) { proofResults.add(term); } else { HashSet<Variable> ruleVariables = new HashSet<Variable>(initialTerm.variableSet()); ruleVariables.addAll(targetTerm.variableSet()); Map<Variable, Variable> freshSubstitution = Variable.getFreshSubstitution( ruleVariables); } for (int i = 0; getTransition(i) != null; ++i) { if (visited.add(getTransition(i))) { nextQueue.add(getTransition(i)); } } } List<ConstrainedTerm> temp; temp = queue; queue = nextQueue; nextQueue = temp; nextQueue.clear(); guarded = true; } return proofResults; }

Target:
public List<ConstrainedTerm> proveRule( ConstrainedTerm initialTerm, ConstrainedTerm targetTerm, List<Rule> rules) { List<ConstrainedTerm> proofResults = new ArrayList<ConstrainedTerm>(); Set<ConstrainedTerm> visited = new HashSet<ConstrainedTerm>(); List<ConstrainedTerm> queue = new ArrayList<ConstrainedTerm>(); List<ConstrainedTerm> nextQueue = new ArrayList<ConstrainedTerm>(); visited.add(initialTerm); queue.add(initialTerm); boolean guarded = false; while (!queue.isEmpty()) { for (ConstrainedTerm term : queue) { if (term.implies(targetTerm)) { continue; } if (guarded) { ConstrainedTerm result = applyRule(term, rules); if (result != null) { if (visited.add(result)) nextQueue.add(result); continue; } } computeRewriteStep(term); if (results.isEmpty()) { proofResults.add(term); } else { HashSet<Variable> ruleVariables = new HashSet<Variable>(initialTerm.variableSet()); ruleVariables.addAll(targetTerm.variableSet()); Map<Variable, Variable> freshSubstitution = Variable.getFreshSubstitution( ruleVariables); } for (int i = 0; getTransition(i) != null; ++i) { if (visited.add(getTransition(i))) { nextQueue.add(getTransition(i)); } } } List<ConstrainedTerm> temp; temp = queue; queue = nextQueue; nextQueue = temp; nextQueue.clear(); guarded = true; } return proofResults; }
Source:
public String zRead(String path) throws KeeperException, InterruptedException { logger.debug("Trying to read data at {]", path); byte[] b; String data; this.st = new Stat(); b = this.client.readData(path,st,false); data = new String(b, StandardCharsets.UTF_8); logger.debug("Requested path contains {}", path, data); return data; }

Target:
public String zRead(String path) throws KeeperException, InterruptedException { logger.debug("Trying to read data at {}", path); byte[] b; String data; this.st = new Stat(); b = this.client.readData(path,st,false); data = new String(b, StandardCharsets.UTF_8); logger.debug("Requested path contains {}", path, data); return data; }
Source:
@Override protected final IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.CACHE_STORE); IgniteConfiguration c = super.getConfiguration(igniteInstanceName); if (getTestIgniteInstanceIndex(igniteInstanceName) != GRID_CNT - 1) { CacheConfiguration cc = defaultCacheConfiguration(); cc.setCacheMode(PARTITIONED); cc.setWriteSynchronizationMode(FULL_SYNC); cc.setAtomicityMode(TRANSACTIONAL); cc.setBackups(1); cc.setCacheStoreFactory(new TestStoreFactory()); cc.setReadThrough(true); cc.setWriteThrough(true); cc.setLoadPreviousValue(true); c.setCacheConfiguration(cc); } return c; }

Target:
@Override protected final IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.CACHE_STORE); IgniteConfiguration c = super.getConfiguration(igniteInstanceName); if (!c.isClientMode()) { CacheConfiguration cc = defaultCacheConfiguration(); cc.setCacheMode(PARTITIONED); cc.setWriteSynchronizationMode(FULL_SYNC); cc.setAtomicityMode(TRANSACTIONAL); cc.setBackups(1); cc.setCacheStoreFactory(new TestStoreFactory()); cc.setReadThrough(true); cc.setWriteThrough(true); cc.setLoadPreviousValue(true); c.setCacheConfiguration(cc); } return c; }
Source:
protected void connectSensors() { Map<String, Object> flags = MutableMap.<String, Object>builder() .put("name", "Controller targets tracker") .build(); AbstractMembershipTrackingPolicy serverPoolMemberTrackerPolicy = new AbstractMembershipTrackingPolicy(flags) { protected void onEntityChange(Entity member) { onServerPoolMemberChanged(member); } protected void onEntityAdded(Entity member) { onServerPoolMemberChanged(member); } protected void onEntityRemoved(Entity member) { onServerPoolMemberChanged(member); } }; addPolicy(serverPoolMemberTrackerPolicy); serverPoolMemberTrackerPolicy.setGroup(this); }

Target:
protected void connectSensors() { Map<String, ?> flags = ImmutableMap.of("name", "Controller targets tracker"); AbstractMembershipTrackingPolicy serverPoolMemberTrackerPolicy = new AbstractMembershipTrackingPolicy(flags) { protected void onEntityChange(Entity member) { onServerPoolMemberChanged(member); } protected void onEntityAdded(Entity member) { onServerPoolMemberChanged(member); } protected void onEntityRemoved(Entity member) { onServerPoolMemberChanged(member); } }; addPolicy(serverPoolMemberTrackerPolicy); serverPoolMemberTrackerPolicy.setGroup(this); }
Source:
List<Scoreboard> getScoreboards() { return m_scoreboardContainers.values().stream().map(s-> {return s.siteScoreboard;}) .collect(Collectors.toList()); }

Target:
List<Scoreboard> getScoreboards() { return m_scoreBoards; }
Source:
public UserInRoleDescriptor inRole(@Required @Description("role inside a scope") @QueryParam("role") String role, @DefaultValue("system") @Description("scope of the role (like system, workspace)") @QueryParam("scope") String scope, @DefaultValue("") @Description("id used by the scope, like workspaceId for workspace scope") @QueryParam("scopeId") String scopeId, @Context SecurityContext context) throws NotFoundException, ServerException, ForbiddenException { boolean isInRole = false; if ("system".equals(scope)) { isInRole = context.isUserInRole(scope + "/" + role); } else { throw new ForbiddenException(String.format("Only system scope is handled for now. Provided scope is %s", scope)); } return DtoFactory.getInstance().createDto(UserInRoleDescriptor.class).withIsInRole(isInRole).withRoleName(role).withScope(scope).withScopeId(scopeId); }

Target:
public UserInRoleDescriptor inRole(@Required @Description("role inside a scope") @QueryParam("role") String role, @DefaultValue("system") @Description("scope of the role (like system, workspace)") @QueryParam("scope") String scope, @DefaultValue("") @Description("id used by the scope, like workspaceId for workspace scope") @QueryParam("scopeId") String scopeId, @Context SecurityContext context) throws NotFoundException, ServerException, ForbiddenException { boolean isInRole; if ("system".equals(scope)) { String roleToCheck; if ("user".equals(role) || "temp_user".equals(role)) { roleToCheck = role; } else { roleToCheck = "system/" + role; } isInRole = context.isUserInRole(roleToCheck); } else { throw new ForbiddenException(String.format("Only system scope is handled for now. Provided scope is %s", scope)); } return DtoFactory.getInstance().createDto(UserInRoleDescriptor.class).withIsInRole(isInRole).withRoleName(role).withScope(scope).withScopeId(scopeId); }
Source:
public RandomTeleport(final IEssentials essentials) { this.essentials = essentials; File file = new File(essentials.getDataFolder(), "random.yml"); config = new EssentialsConf(file); config.setTemplateName("/random.yml"); reloadConfig(); }

Target:
public RandomTeleport(final IEssentials essentials) { this.essentials = essentials; File file = new File(essentials.getDataFolder(), "tpr.yml"); config = new EssentialsConf(file); config.setTemplateName("/tpr.yml"); config.options().copyHeader(true); reloadConfig(); }
Source:
public void prepareRun(StageSubmitterContext context) { init(context.getInputSchema(), context.getFailureCollector()); List<FieldOperation> output = new ArrayList<>(); Collection<String> fieldsToKeep = this.fieldsToKeep; if (fieldsToKeep.isEmpty()) { fieldsToKeep = TransformLineageRecorderUtils.getFields(context.getInputSchema()); } output.addAll(TransformLineageRecorderUtils.generateOneToOnes(new ArrayList<>(fieldsToKeep), "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); output.addAll(TransformLineageRecorderUtils.generateDrops(new ArrayList<>(fieldsToDrop))); output.addAll(fieldsToRename.keySet().stream().map(field -> new FieldTransformOperation("renameField" + field, "Renamed fields as specified.", Collections.singletonList(field), fieldsToRename.get(field))).collect(Collectors.toList())); context.record(output); }

Target:
public void prepareRun(StageSubmitterContext context) { init(context.getInputSchema(), context.getFailureCollector()); List<FieldOperation> output = new ArrayList<>(); List<String> fieldsToKeep = new ArrayList<>(this.fieldsToKeep); List<String> fieldsToDrop = new ArrayList<>(this.fieldsToDrop); if (fieldsToKeep.isEmpty()) { fieldsToKeep = TransformLineageRecorderUtils.getFields(context.getInputSchema()); } else { fieldsToDrop = new ArrayList<>(TransformLineageRecorderUtils.getFields(context.getInputSchema())); fieldsToDrop.removeAll(fieldsToKeep); } output.addAll(TransformLineageRecorderUtils.generateOneToOnes(fieldsToKeep, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); output.addAll(TransformLineageRecorderUtils.generateDrops(fieldsToDrop)); output.addAll(fieldsToRename.keySet().stream().map(field -> new FieldTransformOperation("renameField" + field, "Renamed fields as specified.", Collections.singletonList(field), fieldsToRename.get(field))).collect(Collectors.toList())); context.record(output); }
Source:
public void verifyBucketOwnership(UserInfo userInfo, BucketOwnerStorageLocationSetting storageLocation) { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocation, "The storage location"); ValidateArgument.required(storageLocation.getBucket(), "The bucket"); BucketObjectReader reader = getObjectReader(storageLocation); String bucketName = storageLocation.getBucket(); String baseKey = storageLocation.getBaseKey(); String ownerKey = baseKey == null ? OWNER_MARKER : baseKey + "/" + OWNER_MARKER; List<PrincipalAlias> ownerAliases = getBucketOwnerAliases(userInfo.getId()); InputStream stream; try { stream = reader.openStream(bucketName, ownerKey); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage() + ". " + getExplanation(ownerAliases, bucketName, ownerKey), e); } BufferedReader content = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); inspectUsername(content, ownerAliases, bucketName, ownerKey); }

Target:
public void verifyBucketOwnership(UserInfo userInfo, BucketOwnerStorageLocationSetting storageLocation) { ValidateArgument.required(userInfo, "The user"); ValidateArgument.required(storageLocation, "The storage location"); ValidateArgument.required(storageLocation.getBucket(), "The bucket"); BucketObjectReader reader = getObjectReader(storageLocation); String bucketName = storageLocation.getBucket(); String baseKey = storageLocation.getBaseKey(); String ownerKey = baseKey == null ? OWNER_MARKER : baseKey + "/" + OWNER_MARKER; List<PrincipalAlias> ownerAliases = getBucketOwnerAliases(userInfo.getId()); String ownerContent; try (InputStream stream = reader.openStream(bucketName, ownerKey)) { BufferedReader content = newStreamReader(stream); ownerContent = content.readLine(); } catch (IOException e) { throw new IllegalArgumentException("Could not read username from key " + ownerKey + " from bucket " + bucketName + ". " + getExplanation(ownerAliases, bucketName, ownerKey)); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage() + ". " + getExplanation(ownerAliases, bucketName, ownerKey), e); } validateOwnerContent(ownerContent, ownerAliases, bucketName, ownerKey); }
Source:
protected boolean checkFileSize(File file){ if (FileUtil.isFileToLargeToUpload(file)) { String fileSize = FileUtil.getFileSize(file) / 1024 + ""; showOversizedMediaWarning(fileSize); return true; } else if (FileUtil.isFileOversized(file)) { notifyWarning(StringUtils.getStringRobust(getContext(), R.string.attachment_oversized, FileUtil.getFileSize(file) + "")); } return false; }

Target:
protected boolean checkFileSize(File file){ if (FileUtil.isFileToLargeToUpload(file)) { String fileSize = FileUtil.getFileSizeInMegs(file) + ""; showOversizedMediaWarning(fileSize); return true; } else if (FileUtil.isFileOversized(file)) { notifyWarning(StringUtils.getStringRobust(getContext(), R.string.attachment_oversized, FileUtil.getFileSize(file) + "")); } return false; }
Source:
public SkEcdsaPublicKey decodePublicKey( SessionContext session, String keyType, InputStream keyData, Map<String, String> headers) throws IOException, GeneralSecurityException { if (!KEY_TYPE.equals(keyType)) { throw new InvalidKeySpecException("Invalid keyType: " + keyType); } boolean noTouchRequired = false; if (headers.containsKey(NO_TOUCH_REQUIRED_HEADER)) { noTouchRequired = Boolean.parseBoolean(headers.get(NO_TOUCH_REQUIRED_HEADER)); } ECPublicKey ecPublicKey = ECDSAPublicKeyEntryDecoder.INSTANCE.decodePublicKey(ECCurves.nistp256, keyData); String appName = KeyEntryResolver.decodeString(keyData, MAX_APP_NAME_LENGTH); return new SkEcdsaPublicKey(appName, noTouchRequired, ecPublicKey); }

Target:
public SkEcdsaPublicKey decodePublicKey( SessionContext session, String keyType, InputStream keyData, Map<String, String> headers) throws IOException, GeneralSecurityException { if (!KEY_TYPE.equals(keyType)) { throw new InvalidKeySpecException("Invalid keyType: " + keyType); } boolean noTouchRequired = parseBooleanHeader(headers, NO_TOUCH_REQUIRED_HEADER, false); ECPublicKey ecPublicKey = ECDSAPublicKeyEntryDecoder.INSTANCE.decodePublicKey(ECCurves.nistp256, keyData); String appName = KeyEntryResolver.decodeString(keyData, MAX_APP_NAME_LENGTH); return new SkEcdsaPublicKey(appName, noTouchRequired, ecPublicKey); }
Source:
private boolean updateWorkspaceSelection() { final String selectedFolder = txtFolder.getText(); boolean result = false; if (null != selectedFolder && selectedFolder.trim().length() > 0) { File chosenDirectory = new File(txtFolder.getText()); if (chosenDirectory.exists()) { final Workspace bndWorkspace; try { bndWorkspace = Workspace.getWorkspace(chosenDirectory); setErrorMessage(null); txtFolderErrorDecorator.hide(); tableViewer.setInput(bndWorkspace.getAllProjects()); result = true; } catch (Exception e) { setErrorMessage(e.getMessage()); txtFolderErrorDecorator.show(); } } else { setErrorMessage("No Workspace found from: " + selectedFolder); txtFolderErrorDecorator.show(); } } if (!result) { tableViewer.setInput(Collections.emptyList()); } for (TableColumn col : tableViewer.getTable().getColumns()) { col.pack(); } tableViewer.refresh(); return result; }

Target:
private boolean updateWorkspaceSelection() { final String selectedFolder = txtFolder.getText(); boolean result = false; if (null != selectedFolder && selectedFolder.trim().length() > 0) { File chosenDirectory = new File(txtFolder.getText()); if (chosenDirectory.exists()) { final Workspace bndWorkspace; try { bndWorkspace = Workspace.getWorkspace(chosenDirectory); setErrorMessage(null); txtFolderErrorDecorator.hide(); List<Object> tableEntries = new ArrayList<Object>(bndWorkspace.getAllProjects()); tableEntries.add(bndWorkspace.getBuildDir()); tableViewer.setInput(tableEntries); result = true; } catch (Exception e) { setErrorMessage(e.getMessage()); txtFolderErrorDecorator.show(); } } else { setErrorMessage("No Workspace found from: " + selectedFolder); txtFolderErrorDecorator.show(); } } if (!result) { tableViewer.setInput(Collections.emptyList()); } for (TableColumn col : tableViewer.getTable().getColumns()) { col.pack(); } tableViewer.refresh(); return result; }
Source:
public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } for (Patch p : patches) { AccountPatchReview.Key key = new AccountPatchReview.Key(p.getKey(), me); AccountPatchReview apr = db.accountPatchReviews().get(key); if (apr != null) p.setReviewed(true); } } }

Target:
public void load(final ReviewDb db, final PatchSet ps) throws OrmException { patchSet = ps; info = db.patchSetInfo().get(patchSet.getId()); patches = db.patches().byPatchSet(patchSet.getId()).toList(); final Account.Id me = Common.getAccountId(); if (me != null) { final List<PatchLineComment> comments = db.patchComments().draft(ps.getId(), me).toList(); if (!comments.isEmpty()) { final Map<Patch.Key, Patch> byKey = db.patches().toMap(patches); for (final PatchLineComment c : comments) { final Patch p = byKey.get(c.getKey().getParentKey()); if (p != null) { p.setDraftCount(p.getDraftCount() + 1); } } } ResultSet<AccountPatchReview> reviews = db.accountPatchReviews().byReviewer(me); HashSet<Patch.Key> reviewedPatches = new HashSet<Patch.Key>(); for (AccountPatchReview review : reviews) { reviewedPatches.add(review.getKey().getPatchKey()); } for (Patch p : patches) { if (reviewedPatches.contains(p.getKey())) p.setReviewedByCurrentUser(true); } } }
Source:
ContentTooLargeException(long contentLength, int max) { super(format("Content-Length is too large [length:%s, max:%s].", contentLength, max)); }

Target:
ContentTooLargeException(long contentLength, int max) { super(format("Content-Length is larger than max on this topic [length:%s, max:%s].", contentLength, max)); }
Source:
private boolean checkIfProgramEnrollmentWasCreatedProperly() { int programEnrollmentCount = 0; List<ProgramEnrollment> programEnrollmentList = programEnrollmentService.getProgramEnrollmentByPatientUuid(DEFAULT_CONFIG_NAME, createdProgramEnrollment.getPatient().getUuid()); for (ProgramEnrollment programEnrollment : programEnrollmentList) { if (programEnrollment.getPatient().getUuid().equals(createdProgramEnrollment.getPatient().getUuid()) && programEnrollment.getProgram().getUuid().equals(createdProgramEnrollment.getProgram().getUuid())) { programEnrollmentCount++; } } return programEnrollmentCount == 2; }

Target:
private boolean checkIfProgramEnrollmentWasCreatedProperly() { List<ProgramEnrollment> programEnrollmentList = programEnrollmentService.getProgramEnrollmentByPatientUuid(DEFAULT_CONFIG_NAME, createdProgramEnrollment.getPatient().getUuid()); if (programEnrollmentList.size() == 2) { for (ProgramEnrollment programEnrollment : programEnrollmentList) { if (!programEnrollment.getUuid().equals(createdPatient.getUuid()) && programEnrollment.getPatient().getUuid().equals(createdProgramEnrollment.getPatient().getUuid()) && programEnrollment.getProgram().getUuid().equals(createdProgramEnrollment.getProgram().getUuid()) && programEnrollment.getDateCompleted().equals(createdProgramEnrollment.getDateCompleted()) && programEnrollment.getDateEnrolled().equals(createdProgramEnrollment.getDateEnrolled())) { return true; } } } return false; }
Source:
private void logPlugins(List<PluginProperties.PluginConfiguration> pluginConfigurations) { if (pluginConfigurations.size() > 0) { for (PluginProperties.PluginConfiguration pluginConfiguration : pluginConfigurations) { log.info("Loading " + pluginConfiguration.toString()); } } else { log.info("Did not find any plugins to load"); } }

Target:
private void logPlugins(List<PluginProperties.PluginConfiguration> pluginConfigurations) { if (!pluginConfigurations.isEmpty()) { for (PluginProperties.PluginConfiguration pluginConfiguration : pluginConfigurations) { log.info("Loading {}", pluginConfiguration); } } else { log.info("Did not find any plugins to load"); } }
Source:
private void cleanupFinishedOperations() { if (!completedOperationIds.isEmpty()) { List<Long> toClean = new ArrayList<>(); boolean cleaned = false; if (completedOperationIds.drainTo(toClean) > 0) { cleaned = true; for (Long operationSequenceId : toClean) { markOperationComplete(operationSequenceId); } toClean.clear(); } if (cleaned) { lastOperationChange = System.currentTimeMillis(); } } }

Target:
private void cleanupFinishedOperations() { List<Long> toClean = new ArrayList<>(); completedOperationIds.drainTo(toClean); if (!toClean.isEmpty()) { for (Long operationSequenceId : toClean) { markOperationComplete(operationSequenceId); } lastOperationChange = System.currentTimeMillis(); } }
Source:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); if (!defaultApp.contains(":")) { defaultApp = getDefaultVersion(supportedApps, defaultApp); } return defaultApp; }

Target:
public String getDefaultApp(Set<String> supportedApps) { String defaultApp = getAut(); if (getLaunchActivity() != null) { return defaultApp; } if (!defaultApp.contains(":")) { return getDefaultVersion(supportedApps, defaultApp); } return supportedApps.contains(defaultApp) ? defaultApp : null; }
Source:
public int hashCode() { return ~~(int) (id ^ (id >>> 32)); }

Target:
public int hashCode() { return HashUtil.combineHashCodes(super.hashCode(), Objects.hashCode(id)); }
Source:
public Response addTechnology(TechnologyResponse technology) throws InternalServerErrorException, BadRequestException { String techName = technology.getName(); if (techName == null || techName.equals("")) { throw new BadRequestException("Nome da Tecnologia não pode ser em branco!"); } else { Technology entity = new Technology(); entity.setName(techName); technologyDAO.add(entity); technology.setId(entity.getId()); return technology; } }

Target:
public Response addTechnology(TechnologyResponse technology) throws InternalServerErrorException, BadRequestException { String techName = technology.getName(); if (techName == null || techName.equals("")) { throw new BadRequestException("Technology's name cannot be blank."); } else { Technology entity = new Technology(); entity.setName(techName); technologyDAO.add(entity); technology.setId(entity.getId()); return technology; } }
Source:
public String getLabelFilter() { return labelFilter == null ? "" : labelFilter; }

Target:
public String getLabelFilter() { return labelFilter; }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crop_image); task = new SaveUriToFileTask(this, (Uri) getIntent().getParcelableExtra(EXTRA_IMAGE_URI)) { @Override protected void onSuccess(final Uri imageUri) throws Exception { final CropImageView imageView = (CropImageView) findViewById(R.id.image); imageView.setImage(ImageSource.uri(imageUri)); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (imageView != null) { setResult(Activity.RESULT_OK, new Intent() .putExtra(EXTRA_CROP_RECT, imageView.getCropRect()) .putExtra(EXTRA_IMAGE_URI, imageUri) .putExtra(EXTRA_FROM_CAMERA, getIntent().getBooleanExtra(EXTRA_FROM_CAMERA, false)) ); finish(); } } }); } @Override protected void onException(Exception e) throws RuntimeException { throw new RuntimeException(e); } }; task.execute(); findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crop_image); task = new SaveUriToFileTask(this, (Uri) getIntent().getParcelableExtra(EXTRA_IMAGE_URI)) { @Override protected void onSuccess(final Uri imageUri) throws Exception { final CropImageView imageView = (CropImageView) findViewById(R.id.image); imageView.setImage(ImageSource.uri(imageUri)); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isReady()) { setResult(Activity.RESULT_OK, new Intent() .putExtra(EXTRA_CROP_RECT, imageView.getCropRect()) .putExtra(EXTRA_IMAGE_URI, imageUri) .putExtra(EXTRA_FROM_CAMERA, getIntent().getBooleanExtra(EXTRA_FROM_CAMERA, false)) ); finish(); } } }); } @Override protected void onException(Exception e) throws RuntimeException { throw new RuntimeException(e); } }; task.execute(); findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); }
Source:
private void testUsingZippedInput(final String filepath, final int nVariants, final Function<File,OutputStream> outputStreamProvider) throws IOException { File tmp = new File(filepath); if( tmp.getName().endsWith(IOUtil.VCF_FILE_EXTENSION)) { tmp = File.createTempFile("tmp",IOUtil.COMPRESSED_VCF_FILE_EXTENSION); tmp.deleteOnExit(); try( FileInputStream in = new FileInputStream(filepath); OutputStream out = outputStreamProvider.apply(tmp); ) { IOUtil.copyStream(in, out); out.flush(); } catch(final IOException err) { throw err; } } final VCFIterator r = new VCFIteratorBuilder().open(tmp); assertExpectedNumberOfVariants(r, nVariants); r.close(); }

Target:
private void testUsingZippedInput(final String filepath, final int nVariants, final Function<File,OutputStream> outputStreamProvider) throws IOException { File tmp = new File(filepath); if( tmp.getName().endsWith(IOUtil.VCF_FILE_EXTENSION)) { tmp = File.createTempFile("tmp",IOUtil.COMPRESSED_VCF_FILE_EXTENSION); tmp.deleteOnExit(); try( FileInputStream in = new FileInputStream(filepath); OutputStream out = outputStreamProvider.apply(tmp); ) { IOUtil.copyStream(in, out); out.flush(); } catch(final IOException err) { throw err; } } try (final VCFIterator r = new VCFIteratorBuilder().open(tmp) ) { assertExpectedNumberOfVariants(r, nVariants); } }