auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean restore_state(InputObjectState os, int ot) { if (!super.restore_state(os, ot) || !restore_list(os, ot, pendingList) || !restore_list(os, ot, preparedList)) { return false; } uid = get_uid().fileStringForm(); try { String s = os.unpackString(); id = s == null ? null : new URI(s); s = os.unpackString(); parentId = s == null ? null : new URI(s); clientId = os.unpackString(); startTime = os.unpackBoolean() ? LocalDateTime.ofInstant(Instant.ofEpochMilli(os.unpackLong()), ZoneOffset.UTC) : null; finishTime = os.unpackBoolean() ? LocalDateTime.ofInstant(Instant.ofEpochMilli(os.unpackLong()), ZoneOffset.UTC) : null; status = os.unpackBoolean() ? LRAStatus.valueOf(os.unpackString()) : null; int cnt = os.unpackInt(); if (cnt == 0) { afterLRAListeners = null; } else { afterLRAListeners = new ArrayList<>(); for (int i = 0; i < cnt; i++) { afterLRAListeners.add(new AfterLRAListener(new URI(os.unpackString()), new URI(os.unpackString()))); } } if (finishTime != null) { long ttl = ChronoUnit.MILLIS.between(LocalDateTime.now(ZoneOffset.UTC), finishTime); if (ttl <= 0) { System.out.printf("TIMER has expired since last reload%n"); status = LRAStatus.Cancelling; } else { System.out.printf("RESTARTING TIMER%n"); } setTimeLimit(ttl); } return true; } catch (IOException | URISyntaxException e) { if (LRALogger.logger.isDebugEnabled()) { LRALogger.logger.debugf(e, "Cannot restore state of objec type '%s'", ot); } return false; } }

Target:
public boolean restore_state(InputObjectState os, int ot) { if (!super.restore_state(os, ot) || !restore_list(os, ot, pendingList) || !restore_list(os, ot, preparedList)) { return false; } uid = get_uid().fileStringForm(); try { String s = os.unpackString(); id = s == null ? null : new URI(s); s = os.unpackString(); parentId = s == null ? null : new URI(s); clientId = os.unpackString(); startTime = os.unpackBoolean() ? LocalDateTime.ofInstant(Instant.ofEpochMilli(os.unpackLong()), ZoneOffset.UTC) : null; finishTime = os.unpackBoolean() ? LocalDateTime.ofInstant(Instant.ofEpochMilli(os.unpackLong()), ZoneOffset.UTC) : null; status = os.unpackBoolean() ? LRAStatus.valueOf(os.unpackString()) : null; int cnt = os.unpackInt(); if (cnt == 0) { afterLRAListeners = null; } else { afterLRAListeners = new ArrayList<>(); for (int i = 0; i < cnt; i++) { afterLRAListeners.add(new AfterLRAListener(new URI(os.unpackString()), new URI(os.unpackString()))); } } if (finishTime != null) { long ttl = ChronoUnit.MILLIS.between(LocalDateTime.now(ZoneOffset.UTC), finishTime); if (ttl <= 0) { if (LRALogger.logger.isDebugEnabled()) { LRALogger.logger.debugf("Timer for LRA '%s' has expired since last reload", id); } status = LRAStatus.Cancelling; } else { if (LRALogger.logger.isDebugEnabled()) { LRALogger.logger.debugf("Restarting time for LRA '%s'", id); } } setTimeLimit(ttl); } return true; } catch (IOException | URISyntaxException e) { if (LRALogger.logger.isDebugEnabled()) { LRALogger.logger.debugf(e, "Cannot restore state of objec type '%s'", ot); } return false; } }
Source:
public void clear(String sceneName) { if (!broadcastSequenceMap.containsKey(sceneName)) { return; } broadcastSequenceMap.get(sceneName).clear(); }

Target:
public void clear(String sceneName) { if (broadcastSequenceMap.containsKey(sceneName)) { broadcastSequenceMap.get(sceneName).clear(); } }
Source:
public ResourceVerifier verifyListAttributeDoesNotContainValue(String attributeName, ModelNode value, String errorMessageSuffix) throws Exception { waitFor(() -> { ModelNodeResult actualResult = ops.readAttribute(resourceAddress, attributeName); return actualResult.isSuccess() && actualResult.hasDefined(Constants.RESULT); }); final ModelNodeResult modelNodeResult = ops.readAttribute(resourceAddress, attributeName); modelNodeResult.assertSuccess(); Assert.assertFalse("Given value '" + value.toString() + "' should not be present in list attribute '" + attributeName + "'!" + (errorMessageSuffix == null || errorMessageSuffix.isEmpty() ? "" : " " + errorMessageSuffix), isModelNodePresentInListAttributeValue(attributeName, value)); return this; }

Target:
public ResourceVerifier verifyListAttributeDoesNotContainValue(String attributeName, ModelNode value, String errorMessageSuffix) throws Exception { waitFor(() -> { ModelNodeResult actualResult = ops.readAttribute(resourceAddress, attributeName); return actualResult.isSuccess() && actualResult.hasDefined(Constants.RESULT) && !isModelNodePresentInListAttributeValue(attributeName, value); }); final ModelNodeResult modelNodeResult = ops.readAttribute(resourceAddress, attributeName); modelNodeResult.assertSuccess(); Assert.assertFalse("Given value '" + value.toString() + "' should not be present in list attribute '" + attributeName + "'!" + (errorMessageSuffix == null || errorMessageSuffix.isEmpty() ? "" : " " + errorMessageSuffix), isModelNodePresentInListAttributeValue(attributeName, value)); return this; }
Source:
public void setDurability(float durability) { if (durability <= 0) { logger.error("Invalid value for the durability. It can't be less than or equal to zero."); this.durability = 1; } this.durability = durability; }

Target:
public void setDurability(float durability) { if (durability <= 0) { logger.error("Invalid value for the durability. It can't be less than or equal to zero."); this.durability = 1; } else { this.durability = durability; } }
Source:
private void requestActivityRecognition() { ActivityRecognitionClient client = ActivityRecognition.getClient(mContext); Intent intent = new Intent(mContext, RecognitionBroadcastReceiver.class); intent.putExtra(TravelBehaviorConstants.RECORD_ID, mRecordId); PendingIntent pi = PendingIntent.getBroadcast(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT); client.requestActivityUpdates(10000l, pi); }

Target:
private void requestActivityRecognition() { ActivityRecognitionClient client = ActivityRecognition.getClient(mContext); Intent intent = new Intent(mContext, RecognitionBroadcastReceiver.class); intent.putExtra(TravelBehaviorConstants.RECORD_ID, mRecordId); int reqCode = PreferenceUtils.getInt(TravelBehaviorConstants.RECOGNITION_REQUEST_CODE, 0); PendingIntent pi = PendingIntent.getBroadcast(mContext, reqCode++, intent, PendingIntent.FLAG_ONE_SHOT); PreferenceUtils.saveInt(TravelBehaviorConstants.RECOGNITION_REQUEST_CODE, reqCode); client.requestActivityUpdates(TimeUnit.SECONDS.toMillis(10), pi); }
Source:
public List<AttestationValue> parsePostedResp(String str) throws JsonParseException, IOException { JsonFactory jfactory = new JsonFactory(); List<AttestationValue> values = new ArrayList<AttestationValue>(); JsonParser jParser = jfactory.createJsonParser(str); try { jParser.nextToken(); while (jParser.nextToken() != JsonToken.END_OBJECT) { if (jParser.getCurrentName().equalsIgnoreCase(HEADER_HOSTS)) { jParser.nextToken(); jParser.nextToken(); jParser.nextToken(); AttestationValue value = new AttestationValue(); while (jParser.getCurrentToken() != JsonToken.END_ARRAY) { String fieldname = jParser.getCurrentName(); if (fieldname.equalsIgnoreCase(HEADER_HOST_NAME)) { jParser.nextToken(); value.setHostName(jParser.getText()); } else if (fieldname.equalsIgnoreCase(HEADER_RESULT)) { jParser.nextToken(); value.setTrustLevel(AttestationResultEnum .valueOf(jParser.getText().toUpperCase())); } else if (fieldname.equalsIgnoreCase(HEADER_VTIME)) { jParser.nextToken(); } else if (!jParser.nextToken().isScalarValue()) { jParser.skipChildren(); } if (jParser.nextToken() == JsonToken.END_OBJECT) { log.debug("host_name:" + value.getHostName() + ", trustLevel:" + value.getTrustLevel()); values.add(value); value = new AttestationValue(); if (jParser.nextToken() == JsonToken.START_OBJECT) { jParser.nextToken(); } } } break; } else if (!jParser.nextToken().isScalarValue()) { jParser.skipChildren(); } } } finally { jParser.close(); } return values; }

Target:
public List<AttestationValue> parsePostedResp(String str) throws JsonProcessingException, IOException { List<AttestationValue> values = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.readTree(str); JsonNode hosts = tree.get(HEADER_HOSTS); if (hosts != null) { for (JsonNode host : hosts) { String name = host.get(HEADER_HOST_NAME).asText(); String level = host.get(HEADER_RESULT).asText(); AttestationValue value = new AttestationValue(); value.setHostName(name); value.setTrustLevel(AttestationResultEnum.valueOf(level.toUpperCase())); values.add(value); } } return values; }
Source:
public void deallocateIfExternal() { if (getNetwork() != null && getNetwork().isExternal()) { Provider<?> provider = DbFacade.getInstance().getProviderDao().get(getNetwork().getProvidedBy().getProviderId()); NetworkProviderProxy providerProxy = ProviderProxyFactory.getInstance().create(provider); try { providerProxy.deallocate(nic); } catch (VdcBLLException e) { AuditLogableBase removePortFailureEvent = new AuditLogableBase(); removePortFailureEvent.addCustomValue("PortName", nic.getName()); removePortFailureEvent.addCustomValue("PortId", nic.getId().toString()); removePortFailureEvent.addCustomValue("ProviderName", provider.getName()); AuditLogDirector.log(removePortFailureEvent, AuditLogType.REMOVE_PORT_FROM_EXTERNAL_PROVIDER_FAILED); } } }

Target:
public void deallocateIfExternal() { if (getNetwork() != null && getNetwork().isExternal()) { Provider<?> provider = DbFacade.getInstance().getProviderDao().get(getNetwork().getProvidedBy().getProviderId()); NetworkProviderProxy providerProxy = ProviderProxyFactory.getInstance().create(provider); try { providerProxy.deallocate(nic); } catch (VdcBLLException e) { AuditLogableBase removePortFailureEvent = new AuditLogableBase(); removePortFailureEvent.addCustomValue("NicName", nic.getName()); removePortFailureEvent.addCustomValue("NicId", nic.getId().toString()); removePortFailureEvent.addCustomValue("ProviderName", provider.getName()); AuditLogDirector.log(removePortFailureEvent, AuditLogType.REMOVE_PORT_FROM_EXTERNAL_PROVIDER_FAILED); } } }
Source:
public void clickOnVideoCloseButon() { wait.forElementVisible(closeVideoButton).click(); }

Target:
public void clickOnVideoCloseButon() { wait.forElementVisible(closeVideoButtonSelector).click(); }
Source:
public EvaluatedVisitData evaluate(VisitDataDefinition definition, EvaluationContext context) throws EvaluationException { OrderForVisitDataDefinition visitDef = (OrderForVisitDataDefinition) definition; EvaluatedVisitData evaluatedData = new EvaluatedVisitData(visitDef, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return evaluatedData; } HqlQueryBuilder q = new HqlQueryBuilder(); q.select("v.visitId", "o"); q.from(Order.class, "o"); q.whereIn("o.orderType", visitDef.getTypes()); q.innerJoin("o.encounter", "e"); q.innerJoin("e.visit", "v"); q.whereVisitIn("v.visitId", context); List<Object[]> queryResult = evaluationService.evaluateToList(q, context); ListMap<Integer, Order> ordersForVisits = new ListMap<Integer, Order>(); for (Object[] row : queryResult) { ordersForVisits.putInList((Integer)row[0], (Order)row[1]); } for (Integer vid : ordersForVisits.keySet()) { List<Order> l = ordersForVisits.get(vid); evaluatedData.addData(vid, l); } return evaluatedData; }

Target:
public EvaluatedVisitData evaluate(VisitDataDefinition definition, EvaluationContext context) throws EvaluationException { OrderForVisitDataDefinition visitDef = (OrderForVisitDataDefinition) definition; EvaluatedVisitData evaluatedData = new EvaluatedVisitData(visitDef, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return evaluatedData; } HqlQueryBuilder q = new HqlQueryBuilder(); q.select("v.visitId", "o"); q.from(Order.class, "o"); q.whereIn("o.orderType", visitDef.getTypes()); q.innerJoin("o.encounter", "e"); q.innerJoin("e.visit", "v"); q.whereVisitIn("v.visitId", context); q.orderAsc("o.startDate"); List<Object[]> queryResult = evaluationService.evaluateToList(q, context); ListMap<Integer, Order> ordersForVisits = new ListMap<Integer, Order>(); for (Object[] row : queryResult) { ordersForVisits.putInList((Integer)row[0], (Order)row[1]); } for (Integer vid : ordersForVisits.keySet()) { List<Order> l = ordersForVisits.get(vid); evaluatedData.addData(vid, l); } return evaluatedData; }
Source:
private FutureTask<EventResult> submitTaskInternal(Event event, Callable<EventResult> callable) { FutureTask<EventResult> task = null; Guid storagePoolId = event.getStoragePoolId(); ReentrantLock lock = getPoolLock(storagePoolId); lock.lock(); try { Event currentEvent = poolCurrentEventMap.get(storagePoolId); if (currentEvent != null) { switch (currentEvent.getEventType()) { case RECOVERY: if (event.getEventType() == EventType.VDSCONNECTTOPOOL || event.getEventType() == EventType.DOMAINFAILOVER) { task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); } else { log.debugFormat("Current event was skiped because of recovery is running now for pool {0}, event {1}", storagePoolId, event); } break; case RECONSTRUCT: if (event.getEventType() == EventType.VDSCONNECTTOPOOL || event.getEventType() == EventType.RECOVERY || event.getEventType() == EventType.DOMAINFAILOVER) { task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); } else { log.debugFormat("Current event was skiped because of reconstruct is running now for pool {0}, event {1}", storagePoolId, event); } break; default: task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); break; } } else { task = addTaskToQueue(event, callable, storagePoolId, false); poolCurrentEventMap.put(storagePoolId, event); ThreadPoolUtil.execute(new InternalEventQueueThread(storagePoolId, lock, poolsEventsMap, poolCurrentEventMap)); } } finally { lock.unlock(); } return task; }

Target:
private FutureTask<EventResult> submitTaskInternal(Event event, Callable<EventResult> callable) { FutureTask<EventResult> task = null; Guid storagePoolId = event.getStoragePoolId(); ReentrantLock lock = getPoolLock(storagePoolId); lock.lock(); try { Event currentEvent = poolCurrentEventMap.get(storagePoolId); if (currentEvent != null) { switch (currentEvent.getEventType()) { case RECOVERY: if (event.getEventType() == EventType.VDSCONNECTTOPOOL) { task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); } else { log.debugFormat("Current event was skiped because of recovery is running now for pool {0}, event {1}", storagePoolId, event); } break; case RECONSTRUCT: if (event.getEventType() == EventType.VDSCONNECTTOPOOL || event.getEventType() == EventType.RECOVERY || event.getEventType() == EventType.DOMAINFAILOVER) { task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); } else { log.debugFormat("Current event was skiped because of reconstruct is running now for pool {0}, event {1}", storagePoolId, event); } break; default: task = addTaskToQueue(event, callable, storagePoolId, isEventShouldBeFirst(event)); break; } } else { task = addTaskToQueue(event, callable, storagePoolId, false); poolCurrentEventMap.put(storagePoolId, event); ThreadPoolUtil.execute(new InternalEventQueueThread(storagePoolId, lock, poolsEventsMap, poolCurrentEventMap)); } } finally { lock.unlock(); } return task; }
Source:
public void run() throws Exception { IConfigurationElement[] configElements = extension.getConfigurationElements(); if (configElements.length == 0) { handleException(null); } for (IConfigurationElement element : configElements) { if (element != null&& element.getName().equals(IWorkbenchConstants.TAG_STARTUP)) { runEarlyStartup(getExecutableExtension(element)); } } }

Target:
public void run() throws Exception { IConfigurationElement[] configElements = extension.getConfigurationElements(); if (configElements.length == 0) { missingStartupElementMessage("The org.eclipse.ui.IStartup extension from '" + extension.getNamespaceIdentifier() + "' does not provide a valid '" + IWorkbenchConstants.TAG_STARTUP + "' element."); } for (IConfigurationElement element : configElements) { if (element != null&& element.getName().equals(IWorkbenchConstants.TAG_STARTUP)) { runEarlyStartup(getExecutableExtension(element)); } } }
Source:
private void deleteRecursive(File fileOrFolder) throws IOException { if (fileOrFolder.isDirectory()) { for (File child : fileOrFolder.listFiles()) { deleteRecursive(child); } } if (!fileOrFolder.delete()) throw new IOException("Could not delete " + fileOrFolder.getPath()); }

Target:
private void deleteRecursive(File fileOrFolder) throws IOException { File[] children = fileOrFolder.listFiles(); if (children != null) { for (File child : children) deleteRecursive(child); } if (!fileOrFolder.delete()) throw new IOException("Could not delete " + fileOrFolder.getPath()); }
Source:
public void initialise() { setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation()); UILabel versionLabel = find("version", UILabel.class); versionLabel.setText(TerasologyVersion.getInstance().getHumanVersion()); SelectGameScreen selectScreen = getManager().createScreen(SelectGameScreen.ASSET_URI, SelectGameScreen.class); WidgetUtil.trySubscribe(this, "singleplayer", button -> { selectScreen.setLoadingAsServer(false); triggerForwardAnimation(selectScreen); }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { selectScreen.setLoadingAsServer(true); triggerForwardAnimation(selectScreen); }); WidgetUtil.trySubscribe(this, "join", button -> triggerForwardAnimation(JoinGameScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "settings", button -> triggerForwardAnimation(SettingsMenuScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "credits", button -> triggerForwardAnimation(CreditsScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); WidgetUtil.trySubscribe(this, "crashReporter", widget -> CrashReporter.report(new Throwable("Report a error."), LoggingContext.getLoggingPath(), false)); }

Target:
public void initialise() { setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation()); UILabel versionLabel = find("version", UILabel.class); versionLabel.setText(TerasologyVersion.getInstance().getHumanVersion()); SelectGameScreen selectScreen = getManager().createScreen(SelectGameScreen.ASSET_URI, SelectGameScreen.class); WidgetUtil.trySubscribe(this, "singleplayer", button -> { selectScreen.setLoadingAsServer(false); triggerForwardAnimation(selectScreen); }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { selectScreen.setLoadingAsServer(true); triggerForwardAnimation(selectScreen); }); WidgetUtil.trySubscribe(this, "join", button -> triggerForwardAnimation(JoinGameScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "settings", button -> triggerForwardAnimation(SettingsMenuScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "credits", button -> triggerForwardAnimation(CreditsScreen.ASSET_URI)); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); WidgetUtil.trySubscribe(this, "crashReporter", widget -> CrashReporter.report(new Throwable("There is no error."), LoggingContext.getLoggingPath(), CrashReporter.MODE.ISSUE_REPORTER)); }
Source:
public StorageEngine<ByteArray, byte[], byte[]> getStore(StoreDefinition storeDef, RoutingStrategy strategy) { String storeName = storeDef.getName(); if(!stores.containsKey(storeName)) { String dataDir = this.voldemortconfig.getRdbDataDirectory() + "/" + storeName; new File(dataDir).mkdirs(); try { Options rdbOptions = new Options().setCreateIfMissing(true) .createStatistics() .setWriteBufferSize(8 * SizeUnit.KB) .setMaxWriteBufferNumber(3) .setMaxBackgroundCompactions(10) .setCompressionType(org.rocksdb.CompressionType.SNAPPY_COMPRESSION); RocksDB rdbStore = null; RocksDbStorageEngine rdbStorageEngine; if(this.voldemortconfig.getRocksdbPrefixKeysWithPartitionId()) { rdbOptions.useFixedLengthPrefixExtractor(StoreBinaryFormat.PARTITIONID_PREFIX_SIZE); rdbStore = RocksDB.open(rdbOptions, dataDir); rdbStorageEngine = new PartitionPrefixedRocksDbStorageEngine(storeName, rdbStore, lockStripes, strategy); } else { rdbStore = RocksDB.open(rdbOptions, dataDir); rdbStorageEngine = new RocksDbStorageEngine(storeName, rdbStore, lockStripes); } stores.put(storeName, rdbStorageEngine); } catch(Exception e) { throw new StorageInitializationException(e); } } return stores.get(storeName); }

Target:
public StorageEngine<ByteArray, byte[], byte[]> getStore(StoreDefinition storeDef, RoutingStrategy strategy) { String storeName = storeDef.getName(); if(!stores.containsKey(storeName)) { String dataDir = this.voldemortconfig.getRdbDataDirectory() + "/" + storeName; new File(dataDir).mkdirs(); try { Options rdbOptions = new Options().setCreateIfMissing(true) .createStatistics() .setWriteBufferSize(8 * SizeUnit.KB) .setMaxWriteBufferNumber(3) .setMaxBackgroundCompactions(10) .setCompressionType(org.rocksdb.CompressionType.SNAPPY_COMPRESSION); RocksDB rdbStore = null; RocksDbStorageEngine rdbStorageEngine; if(this.voldemortconfig.getRocksdbPrefixKeysWithPartitionId()) { rdbOptions.useFixedLengthPrefixExtractor(StoreBinaryFormat.PARTITIONID_PREFIX_SIZE); rdbStore = RocksDB.open(rdbOptions, dataDir); rdbStorageEngine = new PartitionPrefixedRocksDbStorageEngine(storeName, rdbStore, lockStripes, strategy, voldemortconfig.isRocksdbEnableReadLocks()); } else { rdbStore = RocksDB.open(rdbOptions, dataDir); rdbStorageEngine = new RocksDbStorageEngine(storeName, rdbStore, lockStripes, voldemortconfig.isRocksdbEnableReadLocks()); } stores.put(storeName, rdbStorageEngine); } catch(Exception e) { throw new StorageInitializationException(e); } } return stores.get(storeName); }
Source:
private boolean isEditable(Entity entity) { return clientgui.getBots().containsKey(entity.getOwner().getName()) || entity.getOwnerId() == clientgui.getClient().getLocalPlayer().getId(); }

Target:
private boolean isEditable(Entity entity) { return clientgui.getBots().containsKey(entity.getOwner().getName()) || (entity.getOwnerId() == clientgui.getClient().getLocalPlayer().getId()); }
Source:
private List<ContentType> dbSearch(String search, int baseType, String orderBy, int limit, int offset) throws DotDataException { int bottom = (baseType == 0) ? 0 : baseType; int top = (baseType == 0) ? 100000 : baseType; if (limit == 0) throw new DotDataException("limit param must be more than 0"); limit = (limit < 0) ? 10000 : limit; SearchCondition searchCondition = new SearchCondition(search); if(SQLUtil.sanitizeSortBy(orderBy).isEmpty()){ orderBy = "mod_date"; } DotConnect dc = new DotConnect(); dc.setSQL( String.format( this.contentTypeSql.SELECT_QUERY_CONDITION, SQLUtil.sanitizeCondition( searchCondition.condition ), orderBy ) ); dc.setMaxRows(limit); dc.setStartRow(offset); dc.addParam( SQLUtil.sanitizeParameter( searchCondition.search ) ); dc.addParam( SQLUtil.sanitizeParameter( searchCondition.search ) ); dc.addParam( SQLUtil.sanitizeParameter( searchCondition.search ) ); dc.addParam(bottom); dc.addParam(top); Logger.debug(this, "QUERY " + dc.getSQL()); return new DbContentTypeTransformer(dc.loadObjectResults()).asList(); }

Target:
private List<ContentType> dbSearch(String search, int baseType, String orderBy, int limit, int offset) throws DotDataException { int bottom = (baseType == 0) ? 0 : baseType; int top = (baseType == 0) ? 100000 : baseType; if (limit == 0) throw new DotDataException("limit param must be more than 0"); limit = (limit < 0) ? 10000 : limit; SearchCondition searchCondition = new SearchCondition(search); if(SQLUtil.sanitizeSortBy(orderBy).isEmpty()){ orderBy = "mod_date"; } DotConnect dc = new DotConnect(); dc.setSQL( String.format( this.contentTypeSql.SELECT_QUERY_CONDITION, SQLUtil.sanitizeCondition( searchCondition.condition ), orderBy ) ); dc.setMaxRows(limit); dc.setStartRow(offset); dc.addParam( searchCondition.search ); dc.addParam( searchCondition.search ); dc.addParam( searchCondition.search ); dc.addParam(bottom); dc.addParam(top); Logger.debug(this, "QUERY " + dc.getSQL()); return new DbContentTypeTransformer(dc.loadObjectResults()).asList(); }
Source:
public synchronized T removeItem(int index) { if (selectedIndex > -1 && !items.isEmpty()) { items.remove(index); if (selectedIndex >= items.size()) { selectedIndex--; } invalidate(); } return self(); }

Target:
public synchronized T removeItem(int index) { if (index >= 0 && index < items.size()) { items.remove(index); if (selectedIndex >= items.size()) { selectedIndex--; } invalidate(); } return self(); }
Source:
public void applyStatus(Consumer c, SystemPurposeComplianceStatus status, boolean updateConsumer) { String newHash = getComplianceStatusHash(status, c); boolean complianceChanged = !newHash.equals(c.getComplianceStatusHash()); if (complianceChanged) { log.debug("Compliance has changed, sending Compliance event."); c.setComplianceStatusHash(newHash); eventSink.emitCompliance(c, status); } boolean statusChanged = !status.getStatus().equals(c.getSystemPurposeStatus()); if (statusChanged) { c.setSystemPurposeStatus(status.getStatus()); } if (updateConsumer && (complianceChanged || statusChanged)) { consumerCurator.update(c, false); } }

Target:
public void applyStatus(Consumer c, SystemPurposeComplianceStatus status, boolean updateConsumer) { String newHash = getComplianceStatusHash(status, c); boolean complianceChanged = !newHash.equals(c.getComplianceStatusHash()); if (complianceChanged) { log.debug("System purpose compliance has changed, sending Compliance event."); c.setComplianceStatusHash(newHash); eventSink.emitCompliance(c, status); } boolean statusChanged = !status.getStatus().equals(c.getSystemPurposeStatus()); if (statusChanged) { c.setSystemPurposeStatus(status.getStatus()); } if (updateConsumer && (complianceChanged || statusChanged)) { consumerCurator.update(c, false); } }
Source:
public ProbeStatus run() { if (Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } return ProbeStatus.newFailure("Runtime not started"); }

Target:
public ProbeStatus run() { if (Framework.getRuntime() != null && Framework.getRuntime().isStarted()) { return ProbeStatus.newSuccess("Runtime started"); } else { return ProbeStatus.newFailure("Runtime not started"); } }
Source:
final protected List<AccountProjectWatch> getProjectWatches() throws OrmException { final List<AccountProjectWatch> projectWatches = new LinkedList<AccountProjectWatch>(); final List<Account.Id> projectWatchers = new LinkedList<Account.Id>(); final ProjectState ps = getProjectState(); if (ps != null) { for (final AccountProjectWatch w : db.accountProjectWatches().byProject(ps.getProject().getNameKey())) { projectWatches.add(w); projectWatchers.add(w.getAccountId()); } } for (final AccountProjectWatch w : db.accountProjectWatches().byProject(wildProject)) { if (!projectWatchers.contains(w.getAccountId())) { projectWatches.add(w); } } return Collections.unmodifiableList(projectWatches); }

Target:
final protected Set<AccountProjectWatch> getProjectWatches() throws OrmException { final Set<AccountProjectWatch> projectWatches = new HashSet<AccountProjectWatch>(); final Set<Account.Id> projectWatchers = new HashSet<Account.Id>(); final ProjectState ps = getProjectState(); if (ps != null) { for (final AccountProjectWatch w : db.accountProjectWatches().byProject(ps.getProject().getNameKey())) { projectWatches.add(w); projectWatchers.add(w.getAccountId()); } } for (final AccountProjectWatch w : db.accountProjectWatches().byProject(wildProject)) { if (!projectWatchers.contains(w.getAccountId())) { projectWatches.add(w); } } return Collections.unmodifiableSet(projectWatches); }
Source:
public String getStatusMessage(HttpServletRequest request, String status) { Set<String> validStatus = new LinkedHashSet<>(); validStatus.add("unverified"); validStatus.add("verified"); validStatus.add("created"); validStatus.add("forgot"); validStatus.add("reset"); if (validStatus.contains(status)) { return messageSource.getMessage("stormpath.web.login.form.status." + status, request.getLocale(), verifyEmailUri); } else { throw new IllegalArgumentException("Status '" + status + "' is not valid."); } }

Target:
public String getStatusMessage(HttpServletRequest request, String status) { EnumSet<LoginStatus> validStatus = EnumSet.allOf(LoginStatus.class); if (validStatus.contains(LoginStatus.valueOf(status.toUpperCase()))) { return messageSource.getMessage("stormpath.web.login.form.status." + status, request.getLocale(), verifyEmailUri); } else { return ""; } }
Source:
public Set<Integer> getUsedPorts(SupervisorDetails supervisor) { return nodeToUsedPortsCache.computeIfAbsent(supervisor.getId(), (x) -> new HashSet<>()).stream().map(WorkerSlot::getPort).collect(Collectors.toSet()); }

Target:
public Set<Integer> getUsedPorts(SupervisorDetails supervisor) { return nodeToUsedSlotsCache.computeIfAbsent(supervisor.getId(), (x) -> new HashSet<>()).stream().map(WorkerSlot::getPort).collect(Collectors.toSet()); }
Source:
public void runWithFlags(boolean force, boolean suspendMajor, boolean suspendMinor) { if (force) { LOG.info("Garbage collector thread forced to perform GC before expiry of wait time."); } changeMajorCompactionThreshold(); compactor.cleanUpAndRecover(); entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); doGcLedgers(); doGcEntryLogs(); if (suspendMajor) { LOG.info("Disk almost full, suspend major compaction to slow down filling disk."); } if (suspendMinor) { LOG.info("Disk full, suspend minor compaction to slow down filling disk."); } long curTime = MathUtils.now(); if (enableMajorCompaction && (!suspendMajor) && (force || curTime - lastMajorCompactionTime > majorCompactionInterval)) { LOG.info("Enter major compaction, suspendMajor {}", suspendMajor); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = MathUtils.now(); lastMinorCompactionTime = lastMajorCompactionTime; return; } if (enableMinorCompaction && (!suspendMinor) && (force || curTime - lastMinorCompactionTime > minorCompactionInterval)) { LOG.info("Enter minor compaction, suspendMinor {}", suspendMinor); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = MathUtils.now(); } restoreThreshold(); }

Target:
public void runWithFlags(boolean force, boolean suspendMajor, boolean suspendMinor) { long threadStart = MathUtils.nowInNano(); if (force) { LOG.info("Garbage collector thread forced to perform GC before expiry of wait time."); } compactor.cleanUpAndRecover(); entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); doGcLedgers(); doGcEntryLogs(); if (suspendMajor) { LOG.info("Disk almost full, suspend major compaction to slow down filling disk."); } if (suspendMinor) { LOG.info("Disk full, suspend minor compaction to slow down filling disk."); } long curTime = MathUtils.now(); if (enableMajorCompaction && (!suspendMajor) && (force || curTime - lastMajorCompactionTime > majorCompactionInterval)) { LOG.info("Enter major compaction, suspendMajor {}", suspendMajor); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = MathUtils.now(); lastMinorCompactionTime = lastMajorCompactionTime; majorCompactionCounter.inc(); } else if (enableMinorCompaction && (!suspendMinor) && (force || curTime - lastMinorCompactionTime > minorCompactionInterval)) { LOG.info("Enter minor compaction, suspendMinor {}", suspendMinor); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = MathUtils.now(); minorCompactionCounter.inc(); } this.gcThreadRuntime.registerSuccessfulEvent( MathUtils.nowInNano() - threadStart, TimeUnit.NANOSECONDS); }
Source:
private IDeviceCertificate getWPJAPIInstance(Class<IDeviceCertificate> certClazz) throws AuthenticationException { IDeviceCertificate deviceCertProxy; Constructor<?> constructor; try { constructor = certClazz.getDeclaredConstructor(); deviceCertProxy = (IDeviceCertificate)constructor.newInstance((Object[])null); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_API_EXCEPTION, "WPJ Api constructor is not defined", e); } return deviceCertProxy; }

Target:
private IDeviceCertificate getWPJAPIInstance(Class<IDeviceCertificate> certClazz) throws AuthenticationException { final IDeviceCertificate deviceCertProxy; final Constructor<?> constructor; try { constructor = certClazz.getDeclaredConstructor(); deviceCertProxy = (IDeviceCertificate)constructor.newInstance((Object[])null); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_API_EXCEPTION, "WPJ Api constructor is not defined", e); } return deviceCertProxy; }
Source:
protected TreeNode buildTree(ArrayList<Record> records) throws InvalidRecordsException { HashMap<Integer, Integer> parentMap = new HashMap<>(); HashMap<Integer, TreeNode> nodesMap = new HashMap<>(); records.sort(Comparator.comparing(Record::getRecordId)); ArrayList<Integer> orderedRecordIds = new ArrayList<>(); for (Record record : records) { orderedRecordIds.add(record.getRecordId()); } for (Record record : records) { validateRecord(record); parentMap.put(record.getRecordId(), record.getParentId()); nodesMap.put(record.getRecordId(), new TreeNode(record.getRecordId())); } int rootId = 0; for (int i = 0; i < records.size(); i++) { if (i != orderedRecordIds.get(i)) { throw new InvalidRecordsException("Invalid Records"); } if (orderedRecordIds.get(i) != rootId) { int parentId = parentMap.get(i); nodesMap.get(parentId).children.add(nodesMap.get(i)); } } return nodesMap.get(rootId); }

Target:
TreeNode buildTree(ArrayList<Record> records) throws InvalidRecordsException { HashMap<Integer, Integer> parentMap = new HashMap<>(); HashMap<Integer, TreeNode> nodesMap = new HashMap<>(); records.sort(Comparator.comparing(Record::getRecordId)); ArrayList<Integer> orderedRecordIds = new ArrayList<>(); for (Record record : records) { orderedRecordIds.add(record.getRecordId()); } for (Record record : records) { validateRecord(record); parentMap.put(record.getRecordId(), record.getParentId()); nodesMap.put(record.getRecordId(), new TreeNode(record.getRecordId())); } int rootId = 0; for (int i = 0; i < records.size(); i++) { if (i != orderedRecordIds.get(i)) { throw new InvalidRecordsException("Invalid Records"); } if (orderedRecordIds.get(i) != rootId) { int parentId = parentMap.get(i); nodesMap.get(parentId).getChildren().add(nodesMap.get(i)); } } return nodesMap.get(rootId); }
Source:
boolean disableCompactionForBlobStore(BlobStore store) { if (compactionExecutor == null) { return false; } compactionExecutor.disableCompactionForBlobStore(store); return true; }

Target:
boolean disableCompactionForBlobStore(BlobStore store) { return compactionExecutor == null || compactionExecutor.disableCompactionForBlobStore(store); }
Source:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, UIText.PullResultDialog_closeButtonLabel, true); }

Target:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.CLOSE_LABEL, true); }
Source:
public NeutronSecurityGroupExtensionLiveTest() { provider = "openstack-nova"; Properties overrides = setupProperties(); neutronApiContext = ContextBuilder.newBuilder("openstack-neutron") .endpoint(setIfTestSystemPropertyPresent(overrides, "openstack-neutron.endpoint")) .credentials(setIfTestSystemPropertyPresent(overrides, "openstack-neutron.identity"), setIfTestSystemPropertyPresent(overrides, "openstack-neutron.credential")) .modules(ImmutableSet.<Module>of( new SshjSshClientModule(), new SLF4JLoggingModule(), new BouncyCastleCryptoModule()) ) .build(new TypeToken<ApiContext<NeutronApi>>() {}); }

Target:
public NeutronSecurityGroupExtensionLiveTest() { provider = "openstack-nova"; Properties overrides = setupProperties(); neutronApiContext = ContextBuilder.newBuilder("openstack-neutron") .endpoint(setIfTestSystemPropertyPresent(overrides, "openstack-nova.endpoint")) .credentials(setIfTestSystemPropertyPresent(overrides, "openstack-nova.identity"), setIfTestSystemPropertyPresent(overrides, "openstack-nova.credential")) .modules(ImmutableSet.<Module>of( new SshjSshClientModule(), new SLF4JLoggingModule()) ) .build(new TypeToken<ApiContext<NeutronApi>>() {}); }
Source:
protected void executeCommand() { VdcActionType actionToExecute = getParameters().getAction(); VdcActionParametersBase actionParameters = getParameters().getActionParameters(); actionParameters.setEndProcedure(VdcActionParametersBase.EndProcedure.COMMAND_MANAGED); actionParameters.setParentCommand(VdcActionType.RunAsyncAction); actionParameters.setParentParameters(getParameters()); CommandCoordinatorUtil.executeAsyncCommand( actionToExecute, actionParameters, cloneContextAndDetachFromParent()); setSucceeded(true); }

Target:
protected void executeCommand() { CommandCoordinatorUtil.executeAsyncCommand( getParameters().getAction(), getParameters().getActionParameters(), cloneContextAndDetachFromParent()); setSucceeded(true); }
Source:
public void removeAllCertsOfAProject(String projectname) { List<UserCerts> items = findUserCertsByProjectId(projectname); removeCerts(items); String[] tokens = projectname.split("__"); if (tokens.length == 2) { removeProjectGenericCertificates(tokens[0] + Settings.PROJECT_GENERIC_USER_SUFFIX); } }

Target:
public void removeAllCertsOfAProject(String projectname) { List<UserCerts> items = findUserCertsByProjectId(projectname); removeCerts(items); removeProjectGenericCertificates(projectname + Settings.PROJECT_GENERIC_USER_SUFFIX); }
Source:
public Map<String, byte[]> get(Set<String> keys) { Objects.requireNonNull(keys); Map<String, byte[]> kvMap = new HashMap<>(keys.size()); Block<Document> block = doc -> { String key = doc.getString(ID_KEY); Object value = doc.get(VALUE_KEY); byte[] bytesValue; if (value instanceof String) { bytesValue = ((String) value).getBytes(UTF_8); } else if (value instanceof Binary) { bytesValue = ((Binary) value).getData(); } else { throw new UnsupportedOperationException(value.getClass().getName()); } kvMap.put(key, bytesValue); }; findByKeys(keys, block); return kvMap; }

Target:
public Map<String, byte[]> get(Set<String> keys) { Objects.requireNonNull(keys); Map<String, byte[]> map = new HashMap<>(keys.size()); Block<Document> block = doc -> { String key = doc.getString(ID_KEY); Object value = doc.get(VALUE_KEY); if (value != null) { byte[] bytesValue = null; if (value instanceof String) { bytesValue = ((String) value).getBytes(UTF_8); } else if (value instanceof Binary) { bytesValue = ((Binary) value).getData(); } else { throw new UnsupportedOperationException(String.format( "Value of class %s is not supported for key: %s", value.getClass().getName(), key)); } map.put(key, bytesValue); } }; findByKeys(keys, block); return map; }
Source:
private void recover(TopicPartition topicPart) throws IOException { if (!recovered.contains(topicPart)) { WAL wal = new WAL(conf, url, topicsDir, topicPart); wal.apply(); wals.put(topicPart, wal); recovered.add(topicPart); readOffsets(topicPart); } }

Target:
public void recover(TopicPartition topicPart) { try { switch (states.get(topicPart)) { case RECOVERY_STARTED: pause(topicPart); nextState(topicPart); case RECOVERY_PARTITION_PAUSED: createWAL(topicPart); nextState(topicPart); case WAL_CREATED: applyWAL(topicPart); nextState(topicPart); case WAL_APPLIED: truncateWAL(topicPart); nextState(topicPart); case WAL_TRUNCATED: resetOffsets(topicPart); nextState(topicPart); case OFFSET_RESET: resume(topicPart); nextState(topicPart); break; default: log.error("{} is not a valid state to perform recovery.", states.get(topicPart)); } } catch (CopycatException e) { log.error("Recovery failed."); recordFailureTime(topicPart); setRetryBackoff(backOffMs); } }
Source:
public RedisFeatureStore(RedisFeatureStoreBuilder builder) { if (builder.poolConfig == null) { this.pool = new JedisPool(getPoolConfig(), builder.uri, builder.connectTimeout, builder.socketTimeout); } else { this.pool = new JedisPool(builder.poolConfig, builder.uri, builder.connectTimeout, builder.socketTimeout); } setPrefix(builder.prefix); createCache(builder.cacheTimeSecs, builder.refreshStaleValues, builder.asyncRefresh); createInitCache(builder.cacheTimeSecs); }

Target:
protected RedisFeatureStore(RedisFeatureStoreBuilder builder) { if (builder.poolConfig == null) { this.pool = new JedisPool(getPoolConfig(), builder.uri, builder.connectTimeout, builder.socketTimeout); } else { this.pool = new JedisPool(builder.poolConfig, builder.uri, builder.connectTimeout, builder.socketTimeout); } setPrefix(builder.prefix); createCache(builder.cacheTimeSecs, builder.refreshStaleValues, builder.asyncRefresh); createInitCache(builder.cacheTimeSecs); }
Source:
private AWSIotMqttManager( final Region region, final String mqttClientId, final String endpoint) { if (TextUtils.isEmpty(mqttClientId)) { throw new IllegalArgumentException("mqttClientId is null or empty"); } if (region == null) { throw new IllegalArgumentException("region is null"); } if (endpoint == null) { throw new IllegalArgumentException("endpoint is null or an invalid domain."); } this.topicListeners = new ConcurrentHashMap<String, AWSIotMqttTopic>(); this.mqttMessageQueue = new ConcurrentLinkedQueue<AWSIotMqttQueueMessage>(); this.endpoint = endpoint; this.mqttClientId = mqttClientId; this.region = region; this.accountEndpointPrefix = null; initDefaults(); }

Target:
private AWSIotMqttManager( final Region region, final String mqttClientId, final String endpoint) { if (TextUtils.isEmpty(mqttClientId)) { throw new IllegalArgumentException("mqttClientId is null or empty"); } if (region == null) { throw new IllegalArgumentException("region is null"); } if (TextUtils.isEmpty(endpoint)) { throw new IllegalArgumentException("endpoint is null or empty."); } this.topicListeners = new ConcurrentHashMap<String, AWSIotMqttTopic>(); this.mqttMessageQueue = new ConcurrentLinkedQueue<AWSIotMqttQueueMessage>(); this.endpoint = endpoint; this.mqttClientId = mqttClientId; this.region = region; this.accountEndpointPrefix = null; initDefaults(); }
Source:
static final HashMap<String, String> getJsonResponse(HttpWebResponse webResponse) throws JSONException{ HashMap<String, String> response = new HashMap<>(); if(webResponse != null && !TextUtils.isEmpty(webResponse.getBody())) { JSONObject jsonObject = new JSONObject(webResponse.getBody()); Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { String key = (String) i.next(); response.put(key, jsonObject.getString(key)); } } return response; }

Target:
static final Map<String, String> getJsonResponse(HttpWebResponse webResponse) throws JSONException{ Map<String, String> response = new HashMap<>(); if(webResponse != null && !TextUtils.isEmpty(webResponse.getBody())) { JSONObject jsonObject = new JSONObject(webResponse.getBody()); Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { String key = (String) i.next(); response.put(key, jsonObject.getString(key)); } } return response; }
Source:
protected CreateContainerCmd dockerCommand() { return dockerClient.createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withNetworkMode("host") .withBinds(Bind.parse("/var/run/docker.sock:/tmp/docker.sock")) .withCmd(String.format("consul://%s:8500", consulContainer.getIpAddress())) .withName(getName()); }

Target:
protected CreateContainerCmd dockerCommand() { return dockerClient.createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withNetworkMode("host") .withBinds(Bind.parse("/var/run/docker.sock:/tmp/docker.sock")) .withCmd("-internal", String.format("consul://%s:%d", consulContainer.getIpAddress(), ConsulConfig.CONSUL_HTTP_PORT)) .withName(getName()); }
Source:
public String toString() { final StringBuilder stringBuilder = new StringBuilder(); for (final SubstitutionBase r : SubstitutionBase.values()) { stringBuilder.append((char) r.getBase()); stringBuilder.append(':'); for (int i = 0; i < CODES_PER_BASE; i++) { stringBuilder.append((char) baseByCode[r.getBase()][i]); } stringBuilder.append('\t'); } for (final SubstitutionBase r : SubstitutionBase.values()) { stringBuilder.append(Character.toLowerCase((char)r.getBase())); stringBuilder.append(':'); for (int i = 0; i < CODES_PER_BASE; i++) { stringBuilder.append((char) baseByCode[Character.toLowerCase((char)r.getBase())][i]); } stringBuilder.append('\t'); } return stringBuilder.toString(); }

Target:
public String toString() { final int DISPLAY_SIZE = BASES_SIZE * (CODES_PER_BASE + 3) * 2; final StringBuilder stringBuilder = new StringBuilder(DISPLAY_SIZE); for (final SubstitutionBase r : BASES) { stringBuilder.append((char) r.getBase()); stringBuilder.append(':'); for (int i = 0; i < CODES_PER_BASE; i++) { stringBuilder.append((char) baseByCode[r.getBase()][i]); } stringBuilder.append('\t'); } for (final SubstitutionBase r : BASES) { char lowerCaseBase = Character.toLowerCase((char)r.getBase()); stringBuilder.append(lowerCaseBase); stringBuilder.append(':'); for (int i = 0; i < CODES_PER_BASE; i++) { stringBuilder.append((char) baseByCode[lowerCaseBase][i]); } stringBuilder.append('\t'); } return stringBuilder.toString(); }
Source:
private List<Revision> getRevisions(String cloudId, String representationName) throws MCSException { Representation representation = sourceRecordServiceClient.getRepresentation(cloudId, representationName); return representation.getRevisions(); }

Target:
private List<Revision> getRevisions(String cloudId, String representationName) throws MCSException { return sourceRecordServiceClient.getRepresentation(cloudId, representationName).getRevisions(); }
Source:
public Path renameWorkaround( final Path path, final String newName, final String newContent, final String comment ) { try { final org.uberfire.java.nio.file.Path _path = Paths.convert( path ); String originalFileName = _path.getFileName().toString(); final String extension = originalFileName.substring( originalFileName.lastIndexOf( "." ) ); final org.uberfire.java.nio.file.Path _target = _path.resolveSibling( newName + extension ); final Path targetPath = Paths.convert( _target ); try { if ( newContent != null ) { ioService.write( _path, newContent, serviceHelper.makeCommentedOption( comment ) ); } ioService.startBatch( new FileSystem[]{ _target.getFileSystem() } ); ioService.move( _path, _target, serviceHelper.makeCommentedOption( "File [" + path.toURI() + "] renamed to [" + targetPath.toURI() + "]." ) ); if ( renameHelperInstance != null ) { for ( DataModelerRenameWorkaroundHelper renameHelper : renameHelperInstance ) { renameHelper.postProcess( Paths.convert( _path ), Paths.convert( _target ) ); } } } catch ( final Exception e ) { throw e; } finally { ioService.endBatch(); } return Paths.convert( _target ); } catch ( Exception e ) { throw ExceptionUtilities.handleException( e ); } }

Target:
public Path renameWorkaround( final Path path, final String newName, final String newContent, final String comment ) { try { final org.uberfire.java.nio.file.Path _path = Paths.convert( path ); String originalFileName = _path.getFileName().toString(); final String extension = originalFileName.substring( originalFileName.lastIndexOf( "." ) ); final org.uberfire.java.nio.file.Path _target = _path.resolveSibling( newName + extension ); final Path targetPath = Paths.convert( _target ); try { if ( newContent != null ) { ioService.write( _path, newContent, serviceHelper.makeCommentedOption( comment ) ); } ioService.startBatch( new FileSystem[]{ _target.getFileSystem() } ); ioService.move( _path, _target, serviceHelper.makeCommentedOption( "File [" + path.toURI() + "] renamed to [" + targetPath.toURI() + "]." ) ); if ( renameHelperInstance != null ) { for ( DataModelerRenameWorkaroundHelper renameHelper : renameHelperInstance ) { renameHelper.postProcess( path, targetPath ); } } } catch ( final Exception e ) { throw e; } finally { ioService.endBatch(); } return Paths.convert( _target ); } catch ( Exception e ) { throw ExceptionUtilities.handleException( e ); } }