auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDeploymentArtifacts() { String templateUrl = getClasspathUrlForResource(TEMPLATES_FOLDER + "deployment-artifact.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<TomcatServer> tomcatServer = (EntitySpec<TomcatServer>) ToscaPlanToSpecTransformer .findChildEntitySpecByPlanId(app, "tomcat_server"); assertEquals(tomcatServer.getConfig().get(TomcatServer.ROOT_WAR), "<LINK_0>" + "brooklyn-example-hello-world-sql-webapp/0.6.0/" + "brooklyn-example-hello-world-sql-webapp-0.6.0.war"); }

Target:
public void testDeploymentArtifacts() { String templateUrl = getClasspathUrlForResource(TEMPLATES_FOLDER + "deployment-artifact.tosca.yaml"); EntitySpec<? extends Application> app = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(app); assertEquals(app.getChildren().size(), 1); EntitySpec<?> tomcatServer = ToscaPlanToSpecTransformer .findChildEntitySpecByPlanId(app, "tomcat_server"); assertEquals(tomcatServer.getConfig().get(TomcatServer.ROOT_WAR), "<LINK_0>" + "brooklyn-example-hello-world-sql-webapp/0.6.0/" + "brooklyn-example-hello-world-sql-webapp-0.6.0.war"); }
Source:
private void setAuthorAndCommitter(CommitCommand commitCommand) throws TeamException { final Date commitDate = new Date(); final TimeZone timeZone = TimeZone.getDefault(); final PersonIdent enteredAuthor = RawParseUtils.parsePersonIdent(author); final PersonIdent enteredCommitter = RawParseUtils.parsePersonIdent(committer); if (enteredAuthor == null) throw new TeamException(NLS.bind( CoreText.CommitOperation_errorParsingPersonIdent, author)); if (enteredCommitter == null) throw new TeamException( NLS.bind(CoreText.CommitOperation_errorParsingPersonIdent, committer)); PersonIdent authorIdent; if (repo.getRepositoryState().equals( RepositoryState.CHERRY_PICKING_RESOLVED)) { try { ObjectId cherryPickHead = repo.readCherryPickHead(); authorIdent = new RevWalk(repo).parseCommit(cherryPickHead) .getAuthorIdent(); } catch (IOException e) { Activator .error(CoreText.CommitOperation_ParseCherryPickCommitFailed, e); throw new IllegalStateException(e); } } else { authorIdent = new PersonIdent(enteredAuthor, commitDate, timeZone); } final PersonIdent committerIdent = new PersonIdent(enteredCommitter, commitDate, timeZone); if (amending) { RepositoryUtil repoUtil = Activator.getDefault().getRepositoryUtil(); RevCommit headCommit = repoUtil.parseHeadCommit(repo); if (headCommit != null) { final PersonIdent headAuthor = headCommit.getAuthorIdent(); authorIdent = new PersonIdent(enteredAuthor, headAuthor.getWhen(), headAuthor.getTimeZone()); } } commitCommand.setAuthor(authorIdent); commitCommand.setCommitter(committerIdent); }

Target:
private void setAuthorAndCommitter(CommitCommand commitCommand) throws TeamException { final Date commitDate = new Date(); final TimeZone timeZone = TimeZone.getDefault(); final PersonIdent enteredAuthor = RawParseUtils.parsePersonIdent(author); final PersonIdent enteredCommitter = RawParseUtils.parsePersonIdent(committer); if (enteredAuthor == null) throw new TeamException(NLS.bind( CoreText.CommitOperation_errorParsingPersonIdent, author)); if (enteredCommitter == null) throw new TeamException( NLS.bind(CoreText.CommitOperation_errorParsingPersonIdent, committer)); PersonIdent authorIdent; if (repo.getRepositoryState().equals( RepositoryState.CHERRY_PICKING_RESOLVED)) { RevWalk rw = new RevWalk(repo); try { ObjectId cherryPickHead = repo.readCherryPickHead(); authorIdent = rw.parseCommit(cherryPickHead) .getAuthorIdent(); } catch (IOException e) { Activator .error(CoreText.CommitOperation_ParseCherryPickCommitFailed, e); throw new IllegalStateException(e); } finally { rw.release(); } } else { authorIdent = new PersonIdent(enteredAuthor, commitDate, timeZone); } final PersonIdent committerIdent = new PersonIdent(enteredCommitter, commitDate, timeZone); if (amending) { RepositoryUtil repoUtil = Activator.getDefault().getRepositoryUtil(); RevCommit headCommit = repoUtil.parseHeadCommit(repo); if (headCommit != null) { final PersonIdent headAuthor = headCommit.getAuthorIdent(); authorIdent = new PersonIdent(enteredAuthor, headAuthor.getWhen(), headAuthor.getTimeZone()); } } commitCommand.setAuthor(authorIdent); commitCommand.setCommitter(committerIdent); }
Source:
public void onAuditedFieldChange( String newValue ) { if ( getDataObject() != null ) { Boolean doAdd = Boolean.TRUE.toString().equals( newValue ); DataModelCommand command; if ( doAdd ) { List<ValuePair> defaultValues = new ArrayList<>( ); defaultValues.add( new ValuePair( "targetAuditMode", "NOT_AUDITED" ) ); command = commandBuilder.buildDataObjectAddAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED, defaultValues ); } else { command = commandBuilder.buildDataObjectRemoveAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED ); } command.execute(); } }

Target:
public void onAuditedFieldChange( String newValue ) { if ( getDataObject() != null ) { Boolean doAdd = Boolean.parseBoolean( newValue ); DataModelCommand command; if ( doAdd ) { List<ValuePair> defaultValues = new ArrayList<>( ); defaultValues.add( new ValuePair( "targetAuditMode", "NOT_AUDITED" ) ); command = commandBuilder.buildDataObjectAddAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED, defaultValues ); } else { command = commandBuilder.buildDataObjectRemoveAnnotationCommand( getContext(), getName(), getDataObject(), JPADomainAnnotations.HIBERNATE_ENVERS_AUDITED ); } command.execute(); } }
Source:
private boolean performLiveSnapshot(final Snapshot snapshot) { if(FeatureSupported.isAsyncLiveSnapshotSupported(getVm().getClusterCompatibilityVersion())) { ActionReturnValue actionReturnValue = runInternalAction(ActionType.CreateLiveSnapshotForVm, createLiveSnapshotParameters(snapshot), ExecutionHandler.createDefaultContextForTasks(getContext())); if (actionReturnValue.getSucceeded()) { setSucceeded(true); return true; } else { log.error("Failed to start live snapshot on VDS"); return false; } } else { return performLiveSnapshotDeprecated(snapshot); } }

Target:
private boolean performLiveSnapshot(final Snapshot snapshot) { if (!FeatureSupported.isAsyncLiveSnapshotSupported(getVm().getClusterCompatibilityVersion())) { return performLiveSnapshotDeprecated(snapshot); } else { ActionReturnValue actionReturnValue = runInternalAction(ActionType.CreateLiveSnapshotForVm, createLiveSnapshotParameters(snapshot), ExecutionHandler.createDefaultContextForTasks(getContext())); if (actionReturnValue.getSucceeded()) { setSucceeded(true); return true; } else { log.error("Failed to start live snapshot on VDS"); return false; } } }
Source:
void verifyForLoopOpenBraceStyle(ForStatementContext ctx) { int numChildren = ctx.getChildCount(); Location loopEndLocation; Object constructBeforeOpenBrace = ctx.getChild(numChildren - 2); if (constructBeforeOpenBrace instanceof TerminalNodeImpl) { Token semicolon = ((TerminalNodeImpl) constructBeforeOpenBrace).getSymbol(); loopEndLocation = getTokenLocation(semicolon); } else { ExpressionContext expressionContext = (ExpressionContext) constructBeforeOpenBrace; loopEndLocation = getContextStopLocation(expressionContext); } verifyCodeBlockOpenBraceStyle(Messages.FOR_LOOP, loopEndLocation, ctx.codeBlock()); }

Target:
void verifyForLoopOpenBraceStyle(ForStatementContext ctx) { int numChildren = ctx.getChildCount(); Location loopEndLocation; ParseTree constructBeforeOpenBrace = ctx.getChild(numChildren - 2); if (constructBeforeOpenBrace instanceof TerminalNodeImpl) { Token semicolon = ((TerminalNodeImpl) constructBeforeOpenBrace).getSymbol(); loopEndLocation = getTokenLocation(semicolon); } else { ExpressionContext expressionContext = (ExpressionContext) constructBeforeOpenBrace; loopEndLocation = getContextStopLocation(expressionContext); } verifyCodeBlockOpenBraceStyle(Messages.FOR_LOOP, loopEndLocation, ctx.codeBlock()); }
Source:
protected void beforeTest() { final String queueName = "hemant-test2"; Assertions.assertNotNull(queueName, "'queueName' cannot be null."); sender = createBuilder().sender().queueName(queueName).buildAsyncClient(); receiver = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(true) .buildAsyncClient(); receiverManualComplete = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(false) .buildAsyncClient(); receiveDeleteModeReceiver = createBuilder() .receiver() .queueName(queueName) .isAutoComplete(false) .receiveMode(ReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }

Target:
protected void beforeTest() { final String queueName = getQueueName(); Assertions.assertNotNull(queueName, "'queueName' cannot be null."); sender = createBuilder().sender().queueName(queueName).buildAsyncClient(); receiver = createBuilder() .receiver() .queueName(queueName) .buildAsyncClient(); receiverManualComplete = createBuilder() .receiver() .queueName(queueName) .buildAsyncClient(); receiveDeleteModeReceiver = createBuilder() .receiver() .queueName(queueName) .receiveMode(ReceiveMode.RECEIVE_AND_DELETE) .buildAsyncClient(); }
Source:
public void setBucketLifeCycle(String bucketName, String lifeCycle) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { if (lifeCycle == null || "".equals(lifeCycle)) { deleteBucketLifeCycle(bucketName); } else { Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Length", Integer.toString(lifeCycle.length())); Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("lifecycle", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, lifeCycle, 0); response.body().close(); } }

Target:
public void setBucketLifeCycle(String bucketName, String lifeCycle) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException,InvalidArgumentException { if ((lifeCycle == null) || "".equals(lifeCycle)) { throw new InvalidArgumentException("life cycle cannot be empty"); } Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Length", Integer.toString(lifeCycle.length())); Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("lifecycle", ""); HttpResponse response = executePut(bucketName, null, headerMap, queryParamMap, lifeCycle, 0); response.body().close(); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(25); sb.append(year).append('-').append(month).append('-').append(day) .append(' ').append(hour).append(':').append(minute) .append(':').append(second).append('.').append(millisecond); return sb.toString(); }

Target:
public String toString() { return new StringBuilder(25).append(year).append('-').append(month) .append('-').append(day).append(' ').append(hour).append(':') .append(minute).append(':').append(second).append('.') .append(millisecond).toString(); }
Source:
public AffinityLabelListModel(VdcQueryType queryType) { this.queryType = queryType; setTitle(ConstantsManager.getInstance().getConstants().affinityLabelsTitle()); setHelpTag(HelpTag.affinity_groups); setHashName("affinity_labels"); setNewCommand(new UICommand("New", this)); setEditCommand(new UICommand("Edit", this)); setRemoveCommand(new UICommand("Remove", this)); entitiesNameMap = new EntityModel<>(); entitiesNameMap.setEntity(new HashMap<>()); updateActionAvailability(); startProgress(); loadEntitiesNameMap(); getItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getSelectedItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getEntityChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); }

Target:
public AffinityLabelListModel(VdcQueryType queryType) { this.queryType = queryType; setTitle(ConstantsManager.getInstance().getConstants().affinityLabelsTitle()); setHelpTag(HelpTag.affinity_groups); setHashName("affinity_labels"); setNewCommand(new UICommand("New", this)); setEditCommand(new UICommand("Edit", this)); setRemoveCommand(new UICommand("Remove", this)); entitiesNameMap = new EntityModel<>(); entitiesNameMap.setEntity(new HashMap<>()); updateActionAvailability(); loadEntitiesNameMap(); getItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getSelectedItemsChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); getEntityChangedEvent().addListener((ev, sender, args) -> loadEntitiesNameMap()); }
Source:
private <T> FeedResponse<T> prepareFeedResponse(FeedResponse<Document> response, Class<T> classType) { QueryInfo queryInfo = ModelBridgeInternal.getQueryInfoFromFeedResponse(response); if (queryInfo != null && queryInfo.hasSelectValue()) { List<T> transformedResults = response.getResults() .stream() .map(d -> { if (d.has(Constants.Properties.VALUE)) { return d.get(Constants.Properties.VALUE); } else { return d; } }) .map(object -> transform(object, classType)) .collect(Collectors.toList()); return BridgeInternal.createFeedResponseWithQueryMetrics(transformedResults, response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); } return BridgeInternal.createFeedResponseWithQueryMetrics( (response.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document , classType)) .collect(Collectors.toList())), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); }

Target:
private <T> FeedResponse<T> prepareFeedResponse(FeedResponse<Document> response, Class<T> classType) { QueryInfo queryInfo = ModelBridgeInternal.getQueryInfoFromFeedResponse(response); if (queryInfo != null && queryInfo.hasSelectValue()) { List<T> transformedResults = response.getResults() .stream() .map(d -> d.has(Constants.Properties.VALUE) ? transform(d.get(Constants.Properties.VALUE), classType) : ModelBridgeInternal.toObjectFromJsonSerializable(d, classType)) .collect(Collectors.toList()); return BridgeInternal.createFeedResponseWithQueryMetrics(transformedResults, response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); } return BridgeInternal.createFeedResponseWithQueryMetrics( (response.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document , classType)) .collect(Collectors.toList())), response.getResponseHeaders(), ModelBridgeInternal.queryMetrics(response)); }
Source:
protected TransportConfiguration addAcceptorConfiguration(ActiveMQServer server, int port) { HashMap<String, Object> params = new HashMap<>(); params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(port)); params.put(TransportConstants.PROTOCOLS_PROP_NAME, getConfiguredProtocols()); params.put(TransportConstants.NETTY_READ_TIMEOUT, readTimeout); HashMap<String, Object> amqpParams = new HashMap<>(); configureAMQPAcceptorParameters(amqpParams); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-acceptor", amqpParams); }

Target:
protected TransportConfiguration addAcceptorConfiguration(ActiveMQServer server, int port) { HashMap<String, Object> params = new HashMap<>(); params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(port)); params.put(TransportConstants.PROTOCOLS_PROP_NAME, getConfiguredProtocols()); HashMap<String, Object> amqpParams = new HashMap<>(); configureAMQPAcceptorParameters(amqpParams); return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-acceptor", amqpParams); }
Source:
public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) { Function scale = args.getQuick(1); if (scale.isConstant()) { int scaleValue = scale.getInt(null); if (scaleValue != Numbers.INT_NaN) { if (scaleValue > -1 && scaleValue < Numbers.pow10max + 2) { return new FuncPosConst(position, args.getQuick(0), scaleValue); } if (scaleValue < 0 && scaleValue > -Numbers.pow10max) { return new FuncNegConst(position, args.getQuick(0), -scaleValue); } } return new DoubleConstant(position, Double.NaN); } return new Func(position, args.getQuick(0), args.getQuick(1)); }

Target:
public Function newInstance(ObjList<Function> args, int position, CairoConfiguration configuration) { Function scale = args.getQuick(1); if (scale.isConstant()) { int scaleValue = scale.getInt(null); if (scaleValue != Numbers.INT_NaN) { if (scaleValue > -1 && scaleValue + 2 < Numbers.pow10max) { return new FuncPosConst(position, args.getQuick(0), scaleValue); } if (scaleValue < 0 && scaleValue > -Numbers.pow10max) { return new FuncNegConst(position, args.getQuick(0), -scaleValue); } } return new DoubleConstant(position, Double.NaN); } return new Func(position, args.getQuick(0), args.getQuick(1)); }
Source:
public PlanNodeCostEstimate visitExchange(ExchangeNode node, Void context) { return calculateExchangeCost(numberOfNodes, getStats(node), node.getType(), node.getScope()); }

Target:
public PlanNodeCostEstimate visitExchange(ExchangeNode node, Void context) { return calculateExchangeCost(numberOfNodes, getStats(node), node.getOutputSymbols(), node.getType(), node.getScope()); }
Source:
private boolean _isWaterSafe() { boolean isWaterSafe = config.getBoolean("is-water-safe", false); LocationUtil.setIsWaterSafe(isWaterSafe); return isWaterSafe; }

Target:
private boolean _isWaterSafe() { boolean _isWaterSafe = config.getBoolean("is-water-safe", false); LocationUtil.setIsWaterSafe(_isWaterSafe); return _isWaterSafe; }
Source:
PropertiesHolder(final File file) { this.m_file = file; this.m_properties = null; }

Target:
PropertiesHolder(final File file) { m_file = file; m_properties = null; }
Source:
public Map<String,String> loadAll() { try (DbSession dbSession = dbClient.openSession(false)) { Map<String,String> result = new HashMap<>(); dbClient.propertiesDao().selectGlobalProperties(dbSession) .forEach(p -> result.put(p.getKey(), defaultString(p.getValue()))); return Collections.unmodifiableMap(result); } }

Target:
public Map<String, String> loadAll() { try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.propertiesDao().selectGlobalProperties(dbSession) .stream() .collect(MoreCollectors.uniqueIndex(PropertyDto::getKey, p -> defaultString(p.getValue()))); } }
Source:
public boolean ping() { return (subscription != null) && (subscription.getDeliveryMethod() instanceof Pingable) && ((Pingable) subscription.getDeliveryMethod()).ping(); }

Target:
public boolean ping() { return (subscription == null) || !(subscription.getDeliveryMethod() instanceof Pingable) || ((Pingable) subscription.getDeliveryMethod()).ping(); }
Source:
protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().equals(HttpResponseStatus.SERVICE_UNAVAILABLE)) { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } return Observable.just(t1); } }); } }; }

Target:
protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { final AtomicInteger count = new AtomicInteger(0); @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().code()/100 == 4 || t1.getStatus().code()/100 == 5) return responseToErrorPolicy.call(t1, backoffStrategy.call(count.getAndIncrement())); else return Observable.just(t1); } }); } }; }
Source:
private Boolean checkDomainVersionSupport() { StorageFormatType numericDomainFormat = getStorageDomain().getStorageFormat(); List<VDS> haveNotSupportedVDSes = vdsDao.getAllForStoragePool(getStorageDomain().getStoragePoolId()) .stream() .filter(vds -> !vds.getSupportedDomainVersions().contains(numericDomainFormat)) .collect(Collectors.toList()); if (!haveNotSupportedVDSes.isEmpty()) { List<String> replacements = new ArrayList<>(2); List<String> vdsNames = haveNotSupportedVDSes.stream().map(VDS::getName).collect(Collectors.toList()); replacements.add(ReplacementUtils.createSetVariableString("hosts", vdsNames)); replacements.add(ReplacementUtils.createSetVariableString("formatversion", numericDomainFormat)); return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_VERSION_UNSUPPORTED, replacements); } return true; }

Target:
private Boolean checkDomainVersionSupport() { StorageFormatType numericDomainFormat = getStorageDomain().getStorageFormat(); List<String> haveNotSupportedVDSes = vdsDao.getAllForStoragePool(getStorageDomain().getStoragePoolId()) .stream() .filter(vds -> !vds.getSupportedDomainVersions().contains(numericDomainFormat)) .map(VDS::getName) .collect(Collectors.toList()); if (!haveNotSupportedVDSes.isEmpty()) { List<String> replacements = new ArrayList<>(2); replacements.add(ReplacementUtils.createSetVariableString("hosts", haveNotSupportedVDSes)); replacements.add(ReplacementUtils.createSetVariableString("formatversion", numericDomainFormat)); return failValidation(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_VERSION_UNSUPPORTED, replacements); } return true; }
Source:
public TextArgs with(String name, Object arg) { if (positionedArgsBuilder == null) { throw new IllegalArgumentException("Named arguments were already accessed, to add" + "more arguments use TextArgs.copy()"); } namedArgsBuilder.put(name, arg); return this; }

Target:
public TextArgs with(String name, Object arg) { return new TextArgs( positionedArgs, ImmutableMap.<String, Object>builder().putAll(namedArgs).put(name, arg).build() ); }
Source:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { String jsonPatch = null; Service service = (Service) postParams.get("service"); Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class); String targetService = json.toJson(postParams.get("updateService")); String sourceService = json.toJson(service.toUpdatableService().build()); ObjectMapper mapper = new ObjectMapper(); try { jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not create a JSONPatch"); } return bindToRequest(request, (Object) jsonPatch); }

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { String jsonPatch = null; Service service = (Service) postParams.get("service"); String targetService = json.toJson(postParams.get("updateService")); String sourceService = json.toJson(service.toUpdatableService().build()); ObjectMapper mapper = new ObjectMapper(); try { jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString(); } catch (IOException e) { throw new RuntimeException("Could not create a JSONPatch", e); } return bindToRequest(request, (Object) jsonPatch); }
Source:
public void handleEvent(JsonObject json) { int zone = 0; JsonObject param = json.get("params").getAsJsonArray().get(0).getAsJsonObject(); if (param.has("output")) { String output_str = param.get("output").getAsString(); Pattern pattern = Pattern.compile(".*zone=(\\d+)"); Matcher m = pattern.matcher(output_str); if (m.matches()) { zone = Integer.parseInt(m.group(1)); } } if (json.get("method").getAsString().equalsIgnoreCase("notifyPlayingContentInfo")) { String uri = param.get("uri").getAsString(); if (param.has("broadcastFreq")) { int freq = param.get("broadcastFreq").getAsInt(); listener.updateBroadcastFreq(freq); checkRadioPreset(uri); } listener.updateInputSource(zone, uri); listener.updateSeekStation(""); } if (json.get("method").getAsString().equalsIgnoreCase("notifyVolumeInformation")) { int volume = param.get("volume").getAsInt(); volume = Math.round(100 * (volume - min_volume) / (max_volume - min_volume)); listener.updateVolume(zone, volume); String mute = param.get("mute").getAsString(); listener.updateMute(zone, mute.equalsIgnoreCase("on")); } if (json.get("method").getAsString().equalsIgnoreCase("notifyPowerStatus")) { String power = param.get("status").getAsString(); listener.updatePowerStatus(zone, power.equalsIgnoreCase("active")); } listener.updateConnectionState(true); }

Target:
public void handleEvent(JsonObject json) { int zone = 0; JsonObject param; try { param = json.getAsJsonArray("params").get(0).getAsJsonObject(); } catch (NullPointerException e) { logger.debug("Invalid json in handleEvent"); return; } catch (IndexOutOfBoundsException e) { logger.debug("Invalid json in handleEvent"); return; } if (param == null) { logger.debug("Unable to get params form json in handleEvent"); return; } if (param.has("output")) { String outputStr = param.get("output").getAsString(); Pattern pattern = Pattern.compile(".*zone=(\\d+)"); Matcher m = pattern.matcher(outputStr); if (m.matches()) { try { zone = Integer.parseInt(m.group(1)); } catch (NumberFormatException e) { logger.error("This should never happen, pattern should only match integers"); return; } } } if (json.get("method").getAsString().equalsIgnoreCase("notifyPlayingContentInfo")) { SonyAudioInput input = new SonyAudioInput(); ; input.input = param.get("uri").getAsString(); if (param.has("broadcastFreq")) { int freq = param.get("broadcastFreq").getAsInt(); input.radio_freq = Optional.of(freq); checkRadioPreset(input.input); } listener.updateInput(zone, input); listener.updateSeekStation(""); } if (json.get("method").getAsString().equalsIgnoreCase("notifyVolumeInformation")) { SonyAudioVolume volume = new SonyAudioVolume(); int rawVolume = param.get("volume").getAsInt(); volume.volume = Math.round(100 * (rawVolume - min_volume) / (max_volume - min_volume)); volume.mute = param.get("mute").getAsString().equalsIgnoreCase("on"); listener.updateVolume(zone, volume); } if (json.get("method").getAsString().equalsIgnoreCase("notifyPowerStatus")) { String power = param.get("status").getAsString(); listener.updatePowerStatus(zone, power.equalsIgnoreCase("active")); } listener.updateConnectionState(true); }
Source:
public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); final Cursor c = cursor; final CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.checkmark); final Activity curActivity = (Activity) context; ctv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckedTextView cview = (CheckedTextView) v.findViewById(R.id.checkmark); cview.toggle(); curActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) curActivity.invalidateOptionsMenu(); } }); } }); }

Target:
public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); final CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.checkmark); final Activity curActivity = (Activity) context; ctv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckedTextView cview = (CheckedTextView) v.findViewById(R.id.checkmark); cview.toggle(); curActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { curActivity.invalidateOptionsMenu(); } } }); } }); }
Source:
public Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }

Target:
Key(byte row[], int rOff, int rLen, byte cf[], int cfOff, int cfLen, byte cq[], int cqOff, int cqLen, byte cv[], int cvOff, int cvLen, long ts, boolean deleted, boolean copy) { init(row, rOff, rLen, cf, cfOff, cfLen, cq, cqOff, cqLen, cv, cvOff, cvLen, ts, deleted, copy); }
Source:
private <T> T readSinglePositionFromArray(PortablePosition position) throws IOException { assert position.getType() != null : "Unsupported type read: null"; switch (position.getType()) { case BYTE: case BYTE_ARRAY: return (T) Byte.valueOf(in.readByte(position.getStreamPosition())); case SHORT: case SHORT_ARRAY: return (T) Short.valueOf(in.readShort(position.getStreamPosition())); case INT: case INT_ARRAY: return (T) Integer.valueOf(in.readInt(position.getStreamPosition())); case LONG: case LONG_ARRAY: return (T) Long.valueOf(in.readLong(position.getStreamPosition())); case FLOAT: case FLOAT_ARRAY: return (T) Float.valueOf(in.readFloat(position.getStreamPosition())); case DOUBLE: case DOUBLE_ARRAY: return (T) Double.valueOf(in.readDouble(position.getStreamPosition())); case BOOLEAN: case BOOLEAN_ARRAY: return (T) Boolean.valueOf(in.readBoolean(position.getStreamPosition())); case CHAR: case CHAR_ARRAY: return (T) Character.valueOf(in.readChar(position.getStreamPosition())); case UTF: case UTF_ARRAY: in.position(position.getStreamPosition()); return (T) in.readUTF(); case PORTABLE: case PORTABLE_ARRAY: in.position(position.getStreamPosition()); return (T) serializer.readAndInitialize(in, position.getFactoryId(), position.getClassId()); default: throw new IllegalArgumentException("Unsupported type: " + position.getType()); } }

Target:
private <T> T readSinglePositionFromArray(PortablePosition position) throws IOException { assert position.getType() != null : "Unsupported type read: null"; in.position(position.getStreamPosition()); switch (position.getType()) { case BYTE: case BYTE_ARRAY: return (T) Byte.valueOf(in.readByte()); case SHORT: case SHORT_ARRAY: return (T) Short.valueOf(in.readShort()); case INT: case INT_ARRAY: return (T) Integer.valueOf(in.readInt()); case LONG: case LONG_ARRAY: return (T) Long.valueOf(in.readLong()); case FLOAT: case FLOAT_ARRAY: return (T) Float.valueOf(in.readFloat()); case DOUBLE: case DOUBLE_ARRAY: return (T) Double.valueOf(in.readDouble()); case BOOLEAN: case BOOLEAN_ARRAY: return (T) Boolean.valueOf(in.readBoolean()); case CHAR: case CHAR_ARRAY: return (T) Character.valueOf(in.readChar()); case UTF: case UTF_ARRAY: return (T) in.readUTF(); case PORTABLE: case PORTABLE_ARRAY: return (T) serializer.readAndInitialize(in, position.getFactoryId(), position.getClassId()); default: throw new IllegalArgumentException("Unsupported type: " + position.getType()); } }
Source:
public Defaults getDefaults() { return new Defaults() .withSemanticZoomLevel(0) .withPreferredLayout("Hierarchy Layout") .withCriteria(() -> { List<VertexHopGraphProvider.VertexHopCriteria> focusCriteria = new ArrayList<>(); for (Vertex vertex : this.getVertices()) { Status status = statusProvider.getStatusForSingleVertex(this, vertex); if (!status.computeStatus().equalsIgnoreCase(OnmsSeverity.NORMAL.getLabel())) { focusCriteria.addAll(FocusStrategy.SPECIFIC.getFocusCriteria(PathOutageProvider.this, vertex.getId())); } } return Lists.newArrayList(focusCriteria); }); }

Target:
public Defaults getDefaults() { return new Defaults() .withSemanticZoomLevel(0) .withPreferredLayout("Hierarchy Layout") .withCriteria(() -> { Map<VertexRef, Status> resultMap = statusProvider.getStatusForVertices(this, Lists.newArrayList(this.getVertices()), new Criteria[0]); Optional<Map.Entry<VertexRef, Status>> max = resultMap.entrySet().stream().max(Comparator.comparing(e -> OnmsSeverity.get(e.getValue().computeStatus()))); if (max.isPresent()) { return Lists.newArrayList(new VertexHopGraphProvider.DefaultVertexHopCriteria(max.get().getKey())); } else if (this.getVertexTotalCount() > 0) { return Lists.newArrayList(new VertexHopGraphProvider.DefaultVertexHopCriteria(this.getVertices().get(0))); } else { return Lists.newArrayList(); } }); }
Source:
private void readFirstLocalFileHeader(final byte[] lfh) throws IOException { readFully(lfh); final ZipLong sig = new ZipLong(lfh); if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER) || sig.equals(ZipLong.DD_SIG)) { final byte[] missedLfhBytes = new byte[4]; readFully(missedLfhBytes); System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4); System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4); } }

Target:
private void readFirstLocalFileHeader(final byte[] lfh) throws IOException { readFully(lfh); final ZipLong sig = new ZipLong(lfh); if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER) || (skipSplitSig && sig.equals(ZipLong.DD_SIG))) { final byte[] missedLfhBytes = new byte[4]; readFully(missedLfhBytes); System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4); System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4); } }
Source:
private ArrayList<ILaunchConfiguration> collectAssociatedLaunches(IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(); IResource[] resources = null; for (ILaunchConfiguration config : configs) { if(config.isLocal()) { resources = config.getMappedResources(); if(resources != null) { for (IResource resource2 : resources) { if(resource.equals(resource2) || resource.getFullPath().isPrefixOf(resource2.getFullPath())) { list.add(config); break; } } } } } } catch (CoreException e) { DebugPlugin.log(e); } return list; }

Target:
private ArrayList<ILaunchConfiguration> collectAssociatedLaunches(IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(); IResource[] resources = null; for (ILaunchConfiguration config : configs) { if(config.isLocal()) { resources = config.getMappedResources(); if(resources != null) { for (IResource res : resources) { if(resource.equals(res) || resource.getFullPath().isPrefixOf(res.getFullPath())) { list.add(config); break; } } } } } } catch (CoreException e) { DebugPlugin.log(e); } return list; }
Source:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; if (model.optBoolean("latexsvg", false)) ext = "svg"; String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }

Target:
private static String _imgLink(Collection col, String latex, JSONObject model) { String txt = _latexFromHtml(col, latex); String ext = "png"; if (model.optBoolean("latexsvg", false)) { ext = "svg"; } String fname = "latex-" + Utils.checksum(txt) + "." + ext; return "<img class=latex src=\"" + fname + "\">"; }
Source:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { this.executor = config.auditlog_enabled() ? executor : null; this.auditLogService = auditLogService; }

Target:
public ContentAuditLogSupportImpl( final ContentConfig config, @Reference(service = ContentAuditLogExecutor.class) final Executor executor, @Reference AuditLogService auditLogService ) { this.executor = config.auditlog_enabled() ? executor : c -> { }; this.auditLogService = auditLogService; }
Source:
public void run() { T instance = null; final AtomicBoolean taskCanceled = new AtomicBoolean(false); try { instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { if (taskCanceled.get()) { return; } T instanceToReturn = null; try { instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); }catch (RuntimeException e) { callback.onError(e); } finally { fgRealmCreatedLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } } }); if (!results) { fgRealmCreatedLatch.countDown(); } if (!fgRealmCreatedLatch.await(5, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { taskCanceled.set(true); RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final RuntimeException e) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } finally { if (instance != null) { instance.close(); } } }

Target:
public void run() { T instance = null; try { instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } finally { if (instance != null) { instance.close(); } } }
Source:
public QualityGateDto selectBuiltIn(DbSession dbSession) { QualityGateDto qualityGateDto = mapper(dbSession).selectBuiltIn(); checkState(qualityGateDto != null, "Builtin quality gate is missing."); return qualityGateDto; }

Target:
public QualityGateDto selectBuiltIn(DbSession dbSession) { return mapper(dbSession).selectBuiltIn(); }
Source:
private boolean imageValidation() { if (disk.getDiskStorageType() != DiskStorageType.IMAGE) { return true; } StorageDomain storageDomain = getStorageDomainDAO().getForStoragePool( ((DiskImage) disk).getStorageIds().get(0), ((DiskImage) disk).getStoragePoolId()); StorageDomainValidator storageDomainValidator = new StorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()); }

Target:
private boolean imageValidation() { if (disk.getDiskStorageType() != DiskStorageType.IMAGE || (getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.Paused)) { return true; } StorageDomain storageDomain = getStorageDomainDAO().getForStoragePool( ((DiskImage) disk).getStorageIds().get(0), ((DiskImage) disk).getStoragePoolId()); StorageDomainValidator storageDomainValidator = new StorageDomainValidator(storageDomain); return validate(storageDomainValidator.isDomainExistAndActive()); }
Source:
final void assertionError(String message) { StringBuilder b = new StringBuilder(); if (onCompletedEvents.isEmpty()) { b.append("(active) "); } b.append(message); if (!onErrorEvents.isEmpty()) { b.append(" (+ ") .append(onErrorEvents.size()) .append(" errors)"); } AssertionError ae = new AssertionError(b.toString()); if (!onErrorEvents.isEmpty()) { if (onErrorEvents.size() == 1) { ae.initCause(onErrorEvents.get(0)); } else { ae.initCause(new CompositeException(onErrorEvents)); } } throw ae; }

Target:
final void assertionError(String message) { StringBuilder b = new StringBuilder(message.length() + 32); b.append(message); b.append(" ("); int c = onCompletedEvents.size(); b.append(c); b.append(" completion"); if (c != 1) { b.append("s"); } b.append(")"); if (!onErrorEvents.isEmpty()) { int size = onErrorEvents.size(); b.append(" (+") .append(size) .append(" error"); if (size != 1) { b.append("s"); } b.append(")"); } AssertionError ae = new AssertionError(b.toString()); if (!onErrorEvents.isEmpty()) { if (onErrorEvents.size() == 1) { ae.initCause(onErrorEvents.get(0)); } else { ae.initCause(new CompositeException(onErrorEvents)); } } throw ae; }
Source:
public void setUp() throws Exception { receiver = new Receiver(reporter) { @Override public Object fromJSON(final String json) { return returnObject; } }; receiver.setUp(worker); verify(worker).setOnMessage(messageHandlerArgumentCaptor.capture()); }

Target:
public void setUp() { receiver = new Receiver(reporter) { @Override public Object fromJSON(final String json) { return returnObject; } }; receiver.setUp(worker); verify(worker).setOnMessage(messageHandlerArgumentCaptor.capture()); }
Source:
public static ResAllocs addAll(List<ResAllocs> resToAdd) { if (resToAdd.isEmpty()) { throw new IllegalArgumentException("Empty list provided"); } if (resToAdd.size() == 1) { return resToAdd.get(0); } double cores = 0; double memory = 0; double network = 0; double disk = 0; for (ResAllocs r : resToAdd) { cores += r.getCores(); memory += r.getMemory(); network += r.getNetworkMbps(); disk += r.getDisk(); } return new ResAllocsBuilder(resToAdd.get(0).getTaskGroupName()) .withCores(cores) .withMemory(memory) .withNetworkMbps(network) .withDisk(disk) .build(); }

Target:
public static Optional<ResAllocs> addAll(List<ResAllocs> resToAdd) { if (resToAdd.isEmpty()) { return Optional.empty(); } if (resToAdd.size() == 1) { return Optional.of(resToAdd.get(0)); } double cores = 0; double memory = 0; double network = 0; double disk = 0; for (ResAllocs r : resToAdd) { cores += r.getCores(); memory += r.getMemory(); network += r.getNetworkMbps(); disk += r.getDisk(); } ResAllocs total = new ResAllocsBuilder(resToAdd.get(0).getTaskGroupName()) .withCores(cores) .withMemory(memory) .withNetworkMbps(network) .withDisk(disk) .build(); return Optional.of(total); }
Source:
private Void monitorAndGetSplits() throws Exception { stateLock.writeLock().lock(); try { List<Tuple2<Partition, T>> partitions = fetcher.fetchPartitions(fetcherContext, currentReadOffset); if (partitions.isEmpty()) { return null; } partitions.sort(Comparator.comparing(o -> o.f1)); List<HiveSourceSplit> newSplits = new ArrayList<>(); T maxOffset = currentReadOffset; Set<List<String>> nextSeen = new HashSet<>(); for (Tuple2<Partition, T> tuple2 : partitions) { Partition partition = tuple2.f0; List<String> partSpec = partition.getValues(); if (seenPartitions.add(partSpec)) { T offset = tuple2.f1; if (offset.compareTo(currentReadOffset) > 0) { nextSeen.add(partSpec); } if (offset.compareTo(maxOffset) > 0) { maxOffset = offset; } LOG.info("Found new partition of table {}, generating splits for it", partSpec, tablePath.getFullName()); newSplits.addAll(HiveSourceFileEnumerator.createInputSplits( 0, Collections.singletonList(fetcherContext.toHiveTablePartition(partition)), jobConf)); } } currentReadOffset = maxOffset; splitAssigner.addSplits(new ArrayList<>(newSplits)); if (!nextSeen.isEmpty()) { seenPartitions.clear(); seenPartitions.addAll(nextSeen); } return null; } finally { stateLock.writeLock().unlock(); } }

Target:
private Void monitorAndGetSplits() throws Exception { stateLock.writeLock().lock(); try { List<Tuple2<Partition, T>> partitions = fetcher.fetchPartitions(fetcherContext, currentReadOffset); if (partitions.isEmpty()) { return null; } partitions.sort(Comparator.comparing(o -> o.f1)); List<HiveSourceSplit> newSplits = new ArrayList<>(); T maxOffset = currentReadOffset; Set<List<String>> nextSeen = new HashSet<>(); for (Tuple2<Partition, T> tuple2 : partitions) { Partition partition = tuple2.f0; List<String> partSpec = partition.getValues(); if (seenPartitionsSinceOffset.add(partSpec)) { T offset = tuple2.f1; if (offset.compareTo(currentReadOffset) > 0) { nextSeen.add(partSpec); } if (offset.compareTo(maxOffset) > 0) { maxOffset = offset; } LOG.info("Found new partition of table {}, generating splits for it", partSpec, tablePath.getFullName()); newSplits.addAll(HiveSourceFileEnumerator.createInputSplits( 0, Collections.singletonList(fetcherContext.toHiveTablePartition(partition)), jobConf)); } } currentReadOffset = maxOffset; splitAssigner.addSplits(new ArrayList<>(newSplits)); if (!nextSeen.isEmpty()) { seenPartitionsSinceOffset.clear(); seenPartitionsSinceOffset.addAll(nextSeen); } return null; } finally { stateLock.writeLock().unlock(); } }
Source:
private void rename() throws IOException { if(mFile != null && Files.exists(mFile)) { String renamed = mFile.getFileName().toString(); renamed = renamed.replace(".tmp", ".wav"); Path renamedPath = mFile.resolveSibling(renamed); int suffix = 1; while(Files.exists(renamedPath) && suffix < 4) { String renamedWithSuffix = mFile.getFileName().toString(); renamedWithSuffix = renamedWithSuffix.replace(".tmp", "_" + suffix + ".wav"); String cleaned = StringUtils.replaceIllegalCharacters(renamedWithSuffix); Path renamedWithSuffixPath = mFile.resolveSibling(cleaned); renamedPath = mFile.resolveSibling(renamedWithSuffixPath); suffix++; } Files.move(mFile, renamedPath); } }

Target:
private void rename() throws IOException { if(mFile != null && Files.exists(mFile)) { String renamed = mFile.getFileName().toString(); renamed = renamed.replace(".tmp", ".wav"); Path renamedPath = mFile.resolveSibling(renamed); int suffix = 1; while(Files.exists(renamedPath) && suffix < 4) { String renamedWithSuffix = mFile.getFileName().toString(); renamedWithSuffix = renamedWithSuffix.replace(".tmp", "_" + suffix + ".wav"); Path renamedWithSuffixPath = mFile.resolveSibling(renamedWithSuffix); renamedPath = mFile.resolveSibling(renamedWithSuffixPath); suffix++; } Files.move(mFile, renamedPath); } }
Source:
protected ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName) { ConnectorFactory cachedFactory = connectorFactory; if (cachedFactory != null && cachedFactory.getClass().getName().equals(connectorFactoryClassName)) { return cachedFactory; } return AccessController.doPrivileged(new PrivilegedAction<ConnectorFactory>() { @Override public ConnectorFactory run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(ClientSessionFactoryImpl.class.getClassLoader()); return (ConnectorFactory) ClassloadingUtil.newInstanceFromClassLoader(connectorFactoryClassName); } finally { Thread.currentThread().setContextClassLoader(cl); } } }); }

Target:
protected ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName) { ConnectorFactory cachedFactory = connectorFactory; if (cachedFactory != null && cachedFactory.getClass().getName().equals(connectorFactoryClassName)) { return cachedFactory; } return AccessController.doPrivileged(new PrivilegedAction<ConnectorFactory>() { @Override public ConnectorFactory run() { return (ConnectorFactory) ClassloadingUtil.newInstanceFromClassLoader(ClientSessionFactoryImpl.class, connectorFactoryClassName); } }); }