auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void beforeClass() throws Exception { super.beforeClass(); for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); } _participantsNew = new MockParticipantManager[_numNodes]; for (int i = 0; i < _numNodes; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_NEW_" + (_startPort + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } for (int i = 0; i < _numNodes; i++) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(DelayedStopTask.TASK_COMMAND, DelayedStopTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _participantsNew[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); StateMachineEngine stateMachine = _participantsNew[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participantsNew[i], taskFactoryReg)); _participantsNew[i].syncStart(); } _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); _admin = _gSetupTool.getClusterManagementTool(); }

Target:
public void beforeClass() throws Exception { super.beforeClass(); for (int i = 0; i < _numNodes; i++) { super.stopParticipant(i); } for (int i = 0; i < _numNodes; i++) { Assert.assertFalse(_participants[i].isConnected()); } _participants = new MockParticipantManager[_numNodes]; for (int i = 0; i < _numNodes; i++) { Map<String, TaskFactory> taskFactoryReg = new HashMap<>(); taskFactoryReg.put(DelayedStopTask.TASK_COMMAND, DelayedStopTask::new); String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); StateMachineEngine stateMachine = _participants[i].getStateMachineEngine(); stateMachine.registerStateModelFactory("Task", new TaskStateModelFactory(_participants[i], taskFactoryReg)); _participants[i].syncStart(); } _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _driver = new TaskDriver(_manager); _admin = _gSetupTool.getClusterManagementTool(); }
Source:
public void testSyncCreateWithCustomSerializer() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkSerializer listSerializer = new ZkSerializer() { @Override public byte[] serialize(Object o) throws ZkMarshallingError { List<Integer> list = (List<Integer>) o; return list.stream().map(String::valueOf).collect(Collectors.joining(",")) .getBytes(); } @Override public Object deserialize(byte[] bytes) throws ZkMarshallingError { String string = new String(bytes); return Arrays.stream(string.split(",")).map(Integer::valueOf) .collect(Collectors.toList()); } }; ZkBaseDataAccessor<List<Integer>> accessor = new ZkBaseDataAccessor<>(ZK_ADDR, listSerializer); List<Integer> l0 = ImmutableList.of(1, 2, 3); List<Integer> l1 = ImmutableList.of(4, 5, 6); boolean createResult = accessor.create(path, l0, AccessOption.PERSISTENT); Assert.assertTrue(createResult); List<Integer> data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l0); boolean setResult = accessor.set(path, l1, 0, AccessOption.PERSISTENT); Assert.assertTrue(setResult); data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l1); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }

Target:
public void testSyncCreateWithCustomSerializer() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkBaseDataAccessor<List<Integer>> accessor = new ZkBaseDataAccessor<>(ZK_ADDR, LIST_SERIALIZER); List<Integer> l0 = ImmutableList.of(1, 2, 3); List<Integer> l1 = ImmutableList.of(4, 5, 6); boolean createResult = accessor.create(path, l0, AccessOption.PERSISTENT); Assert.assertTrue(createResult); List<Integer> data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l0); boolean setResult = accessor.set(path, l1, 0, AccessOption.PERSISTENT); Assert.assertTrue(setResult); data = (List<Integer>) accessor.get(path, null, AccessOption.PERSISTENT); Assert.assertEquals(data, l1); accessor.close(); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }
Source:
public String allActiveAlertDefinitions(String query) throws URISyntaxException, IOException { final Executor executor = Executor.newInstance(getHttpClient(100, 5000, 1)); URI uri = new URIBuilder().setPath(config.getProxyControllerUrl() + "/checks/all-active-alert-definitions") .setParameter("query", query).build(); return executor.execute(Request.Get(uri)).returnContent().asString(); }

Target:
public String allActiveAlertDefinitions(String query) throws URISyntaxException, IOException { URI uri = new URIBuilder().setPath(config.getProxyControllerUrl() + "/checks/all-active-alert-definitions") .setParameter("query", query).build(); return getExecutor().execute(Request.Get(uri)).returnContent().asString(); }
Source:
public Optional<String> switchBoard() { List<String> boardNames = getAllBoardNames(); if (getLastOpenBoard().isPresent() && getAllBoardNames().size() > 1) { int lastBoard = boardNames.indexOf(getLastOpenBoard().get()); int index = (lastBoard + 1) % boardNames.size(); setLastOpenBoard(boardNames.get(index)); } else if (!getLastOpenBoard().isPresent() && getAllBoardNames().size() > 1) { setLastOpenBoard(boardNames.get(0)); } return getLastOpenBoard(); }

Target:
public Optional<String> switchBoard() { setBoardToSwitch(); return getLastOpenBoard(); }
Source:
public synchronized void finishInsertIntoExistingTable( ConnectorSession session, String databaseName, String tableName, Path currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate) { setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null || oldTableAction.getData().getTable().isTemporary()) { Table table = getTable(databaseName, tableName) .orElseThrow(() -> new TableNotFoundException(schemaTableName)); PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); HdfsContext context = new HdfsContext(session, databaseName, tableName); tableActions.put( schemaTableName, new Action<>( ActionType.INSERT_EXISTING, new TableAndMore( table, Optional.empty(), Optional.of(currentLocation), Optional.of(fileNames), false, merge(currentStatistics, statisticsUpdate), statisticsUpdate), context)); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into an unpartitioned table that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } }

Target:
public synchronized void finishInsertIntoExistingTable( ConnectorSession session, String databaseName, String tableName, Path currentLocation, List<String> fileNames, PartitionStatistics statisticsUpdate) { setShared(); SchemaTableName schemaTableName = new SchemaTableName(databaseName, tableName); Action<TableAndMore> oldTableAction = tableActions.get(schemaTableName); if (oldTableAction == null || oldTableAction.getData().getTable().getTableType().equals(TEMPORARY_TABLE)) { Table table = getTable(databaseName, tableName) .orElseThrow(() -> new TableNotFoundException(schemaTableName)); PartitionStatistics currentStatistics = getTableStatistics(databaseName, tableName); HdfsContext context = new HdfsContext(session, databaseName, tableName); tableActions.put( schemaTableName, new Action<>( ActionType.INSERT_EXISTING, new TableAndMore( table, Optional.empty(), Optional.of(currentLocation), Optional.of(fileNames), false, merge(currentStatistics, statisticsUpdate), statisticsUpdate), context)); return; } switch (oldTableAction.getType()) { case DROP: throw new TableNotFoundException(schemaTableName); case ADD: case ALTER: case INSERT_EXISTING: throw new UnsupportedOperationException("Inserting into an unpartitioned table that were added, altered, or inserted into in the same transaction is not supported"); default: throw new IllegalStateException("Unknown action type"); } }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); ServletUtils.sendFile(request, response, file, type, cache, file == base && required); }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); ServletUtils.sendFile(request, response, file, type, cache, required); }
Source:
private void setupView(final ProcessConfig processConfig) { String runtimeStrategy = ClientRuntimeStrategy.SINGLETON.getValue(view.getTranslationService()); if (processConfig.getRuntimeStrategy() != null && !"".equals(processConfig.getRuntimeStrategy())) { runtimeStrategy = runtimeStrategyMapping.get(processConfig.getRuntimeStrategy()).getValue(view.getTranslationService()); } String mergeMode = ClientMergeMode.MERGE_COLLECTIONS.getValue(view.getTranslationService()); if (processConfig.getMergeMode() != null && !"".equals(processConfig.getMergeMode())) { mergeMode = ClientMergeMode.valueOf(processConfig.getMergeMode()).getValue(view.getTranslationService()); } this.view.setContent(runtimeStrategy, processConfig.getKBase(), processConfig.getKSession(), mergeMode); }

Target:
private void setupView(final ProcessConfig processConfig) { final String runtimeStrategy = ClientRuntimeStrategy.valueOf(processConfig.getRuntimeStrategy()).getValue(view.getTranslationService()); final String mergeMode = ClientMergeMode.valueOf(processConfig.getMergeMode()).getValue(view.getTranslationService()); this.view.setContent(runtimeStrategy, processConfig.getKBase(), processConfig.getKSession(), mergeMode); }
Source:
private Interval getInterval(LocalDate earliestPossibleDate, LocalDate currentUnitDate, Pageable pageable, ChronoUnit timeUnit) { LocalDate requestedStartDate = currentUnitDate.minus(pageable.getOffset() + pageable.getPageSize() - 1L, timeUnit); LocalDate startDate = TimeUtil.max(requestedStartDate, earliestPossibleDate); if (timeUnit == ChronoUnit.WEEKS) { startDate = TimeUtil.getStartOfWeek(startDate); } LocalDate endDate = currentUnitDate.minus(pageable.getOffset() - 1L, timeUnit); Require.that(!endDate.isBefore(startDate), () -> InvalidDataException.dateTooEarly(requestedStartDate, earliestPossibleDate)); return Interval.createInterval(startDate, endDate); }

Target:
private Interval getInterval(LocalDate earliestPossibleDate, LocalDate currentUnitDate, Pageable pageable, ChronoUnit timeUnit) { LocalDate requestedStartDate = currentUnitDate.minus(pageable.getOffset() + pageable.getPageSize() - 1L, timeUnit); LocalDate startDate = TimeUtil.max(requestedStartDate, earliestPossibleDate); if (timeUnit == ChronoUnit.WEEKS) { startDate = TimeUtil.getStartOfWeek(startDate); } LocalDate endDate = currentUnitDate.minus(pageable.getOffset() - 1L, timeUnit); Require.that(!endDate.isBefore(earliestPossibleDate), () -> InvalidDataException.dateTooEarly(endDate, earliestPossibleDate)); return Interval.createInterval(startDate, endDate); }
Source:
private Optional<Type> getCommonSuperTypeForRow(RowType firstType, RowType secondType) { ImmutableList.Builder<Type> commonParameterTypes = ImmutableList.builder(); ImmutableList.Builder<String> commonParameterNames = ImmutableList.builder(); List<RowField> firstFields = firstType.getFields(); List<RowField> secondFields = secondType.getFields(); if (firstFields.size() != secondFields.size()) { return Optional.empty(); } for (int i = 0; i < firstFields.size(); i++) { Optional<Type> commonParameterType = getCommonSuperType(firstFields.get(i).getType(), secondFields.get(i).getType()); if (!commonParameterType.isPresent()) { return Optional.empty(); } commonParameterTypes.add(commonParameterType.get()); Optional<String> firstParameterName = firstFields.get(i).getName(); Optional<String> secondParameterName = secondFields.get(i).getName(); if (commonParameterNames != null && firstParameterName.isPresent() && secondParameterName.isPresent() && firstParameterName.get().equals(secondParameterName.get())) { commonParameterNames.add(firstParameterName.get()); } else { commonParameterNames = null; } } return Optional.of(new RowType(commonParameterTypes.build(), commonParameterNames == null ? Optional.empty() : Optional.of(commonParameterNames.build()))); }

Target:
private Optional<Type> getCommonSuperTypeForRow(RowType firstType, RowType secondType) { List<RowField> firstFields = firstType.getFields(); List<RowField> secondFields = secondType.getFields(); if (firstFields.size() != secondFields.size()) { return Optional.empty(); } ImmutableList.Builder<Type> commonParameterTypes = ImmutableList.builder(); List<Optional<String>> commonParameterNames = new ArrayList<>(); for (int i = 0; i < firstFields.size(); i++) { Optional<Type> commonParameterType = getCommonSuperType(firstFields.get(i).getType(), secondFields.get(i).getType()); if (!commonParameterType.isPresent()) { return Optional.empty(); } commonParameterTypes.add(commonParameterType.get()); Optional<String> firstParameterName = firstFields.get(i).getName(); Optional<String> secondParameterName = secondFields.get(i).getName(); if (firstParameterName.equals(secondParameterName)) { commonParameterNames.add(firstParameterName); } else { commonParameterNames.add(Optional.empty()); } } List<String> names = null; if (commonParameterNames.stream().allMatch(Optional::isPresent)) { names = commonParameterNames.stream() .map(Optional::get) .collect(toImmutableList()); } return Optional.of(new RowType(commonParameterTypes.build(), Optional.ofNullable(names))); }
Source:
public List<UserDto> getUsersByProjectUUId(final String projectUUID) { final List<UserDto> users = new ArrayList<>(); try { if (projectUUID != null) { final SQLQuery query = this.getSession().createSQLQuery(User.GET_USERS_BY_PROJECT_UUID); query.setParameter("project_uuid", projectUUID); final List<Object> results = query.list(); for (final Object o : results) { final Object[] user = (Object[]) o; final Integer userId = (Integer) user[0]; final String username = (String) user[1]; final String firstName = (String) user[2]; final String lastName = (String) user[3]; final String role = (String) user[4]; final Integer status = (Integer) user[5]; final String email = (String) user[6]; final UserDto u = new UserDto(userId, username, firstName, lastName, role, status, email); users.add(u); } } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error in getUsersByProjectUUId(project_uuid=" + projectUUID + ")" + e.getMessage(), e); } return users; }

Target:
public List<UserDto> getUsersByProjectUUId(final String projectUUID) { final List<UserDto> users = new ArrayList<>(); try { if (projectUUID != null) { final SQLQuery query = this.getSession().createSQLQuery(User.GET_USERS_BY_PROJECT_UUID); query.setParameter("project_uuid", projectUUID); final List<Object> results = query.list(); for (final Object o : results) { final Object[] user = (Object[]) o; final Integer userId = (Integer) user[0]; final String username = (String) user[1]; final String firstName = (String) user[2]; final String lastName = (String) user[3]; final String role = (String) user[4]; final Integer status = (Integer) user[5]; final String email = (String) user[6]; final UserDto u = new UserDto(userId, username, firstName, lastName, role, status, email); users.add(u); } } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error in getUsersByProjectUUId(project_uuid=" + projectUUID + ")", e); } return users; }
Source:
protected int getMaxFieldWidth() { return convertWidthInCharsToPixels(40); }

Target:
private int getMaxFieldWidth() { return convertWidthInCharsToPixels(25); }
Source:
protected void cleanupExecutionBlock(List<TajoIdProtos.ExecutionBlockIdProto> executionBlockIds) { String cleanupMessage = ""; String prefix = ""; for (TajoIdProtos.ExecutionBlockIdProto eachEbId: executionBlockIds) { cleanupMessage += prefix + (new ExecutionBlockId(eachEbId)).toString(); prefix = ","; } LOG.info("cleanup executionBlocks: " + cleanupMessage); NettyClientBase rpc = null; List<TajoMasterProtocol.WorkerResourceProto> workers = getAllWorker(); TajoWorkerProtocol.ExecutionBlockListProto.Builder builder = TajoWorkerProtocol.ExecutionBlockListProto.newBuilder(); builder.addAllExecutionBlockId(Lists.newArrayList(executionBlockIds)); TajoWorkerProtocol.ExecutionBlockListProto executionBlockListProto = builder.build(); for (TajoMasterProtocol.WorkerResourceProto worker : workers) { try { if (worker.getPeerRpcPort() == 0) continue; rpc = connPool.getConnection(NetUtils.createSocketAddr(worker.getHost(), worker.getPeerRpcPort()), TajoWorkerProtocol.class, true); TajoWorkerProtocol.TajoWorkerProtocolService tajoWorkerProtocolService = rpc.getStub(); tajoWorkerProtocolService.cleanupExecutionBlocks(null, executionBlockListProto, NullCallback.get()); } catch (Exception e) { continue; } finally { connPool.releaseConnection(rpc); } } }

Target:
protected void cleanupExecutionBlock(List<TajoIdProtos.ExecutionBlockIdProto> executionBlockIds) { StringBuilder cleanupMessage = new StringBuilder(); String prefix = ""; for (TajoIdProtos.ExecutionBlockIdProto eachEbId: executionBlockIds) { cleanupMessage.append(prefix).append(new ExecutionBlockId(eachEbId).toString()); prefix = ","; } LOG.info("cleanup executionBlocks: " + cleanupMessage); NettyClientBase rpc = null; List<TajoMasterProtocol.WorkerResourceProto> workers = getAllWorker(); TajoWorkerProtocol.ExecutionBlockListProto.Builder builder = TajoWorkerProtocol.ExecutionBlockListProto.newBuilder(); builder.addAllExecutionBlockId(Lists.newArrayList(executionBlockIds)); TajoWorkerProtocol.ExecutionBlockListProto executionBlockListProto = builder.build(); for (TajoMasterProtocol.WorkerResourceProto worker : workers) { try { if (worker.getPeerRpcPort() == 0) continue; rpc = connPool.getConnection(NetUtils.createSocketAddr(worker.getHost(), worker.getPeerRpcPort()), TajoWorkerProtocol.class, true); TajoWorkerProtocol.TajoWorkerProtocolService tajoWorkerProtocolService = rpc.getStub(); tajoWorkerProtocolService.cleanupExecutionBlocks(null, executionBlockListProto, NullCallback.get()); } catch (Exception e) { continue; } finally { connPool.releaseConnection(rpc); } } }
Source:
public void shouldTryReturnNotNull() { Try<Object> _try = Try(() -> 1); assertThat(_try).isNotNull(); assertThat(_try.isSuccess()).isTrue(); }

Target:
public void shouldTryReturnNotNull() { final Try<?> t = Try(() -> 1); assertThat(t).isNotNull(); assertThat(t.isSuccess()).isTrue(); }
Source:
public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); if (nativePath.toFile().isDirectory()) { return null; } try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } }

Target:
public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } }
Source:
public void addListener(Listener listener) { Assert.notNull(listener, "Listener cannot be null"); if (this.listeners.size() == 0) { this.delegate.addConfirmListener(this); this.delegate.addReturnListener(this); } if (!this.listeners.values().contains(listener)){ this.listeners.put(listener.getUUID(), listener); this.pendingConfirms.put(listener, Collections.synchronizedSortedMap(new TreeMap<Long, PendingConfirm>())); if (logger.isDebugEnabled()) { logger.debug("Added listener " + listener); } } }

Target:
public void addListener(Listener listener) { Assert.notNull(listener, "Listener cannot be null"); if (this.listeners.size() == 0) { this.delegate.addConfirmListener(this); this.delegate.addReturnListener(this); } if (this.listeners.putIfAbsent(listener.getUUID(), listener) == null) { this.pendingConfirms.put(listener, new ConcurrentSkipListMap<Long, PendingConfirm>()); if (logger.isDebugEnabled()) { logger.debug("Added listener " + listener); } } }
Source:
private boolean isClockwiseWay(TLongList c){ int csize = c.size(); if(csize == 0){ return true; } int mask = 0xffffffff; long middleY = 0; for(int i=0; i< csize; i++) { middleY += (c.get(i) & mask); } middleY /= (long) csize; double clockwiseSum = 0; boolean firstDirectionUp = false; int previousX = Integer.MIN_VALUE; int firstX = Integer.MIN_VALUE; int prevX = (int) (c.get(0) >> 32); int prevY = (int) (c.get(0) & mask); for (int i = 1; i < csize; i++) { int x = (int) (c.get(i) >> 32); int y = (int) (c.get(i) & mask); int rX = ray_intersect_x(prevX, prevY, x, y, (int) middleY); if (rX != Integer.MIN_VALUE) { boolean skipSameSide = (y <= middleY) == (prevY <= middleY); if (skipSameSide) { continue; } boolean directionUp = prevY >= middleY; if (firstX == -Integer.MIN_VALUE) { firstDirectionUp = directionUp; firstX = rX; } else { boolean clockwise = (!directionUp) == (previousX < rX); if (clockwise) { clockwiseSum += Math.abs(previousX - rX); } else { clockwiseSum -= Math.abs(previousX - rX); } } previousX = rX; prevX = x; prevY = y; } } if(firstX != -360){ boolean clockwise = (!firstDirectionUp) == (previousX < firstX); if(clockwise){ clockwiseSum += Math.abs(previousX - firstX); } else { clockwiseSum -= Math.abs(previousX - firstX); } } return clockwiseSum >= 0; }

Target:
private boolean isClockwiseWay(TLongList c){ int csize = c.size(); if(csize == 0){ return true; } int mask = 0xffffffff; long middleY = 0; for(int i=0; i< csize; i++) { middleY += (c.get(i) & mask); } middleY /= (long) csize; double clockwiseSum = 0; boolean firstDirectionUp = false; int previousX = Integer.MIN_VALUE; int firstX = Integer.MIN_VALUE; int prevX = (int) (c.get(0) >> 32); int prevY = (int) (c.get(0) & mask); for (int i = 1; i < csize; i++) { long ci = c.get(i); int x = (int) (ci >> 32); int y = (int) (ci & mask); int rX = ray_intersect_x(prevX, prevY, x, y, (int) middleY); if (rX != Integer.MIN_VALUE) { boolean skipSameSide = (y <= middleY) == (prevY <= middleY); if (skipSameSide) { continue; } boolean directionUp = prevY >= middleY; if (firstX == -Integer.MIN_VALUE) { firstDirectionUp = directionUp; firstX = rX; } else { boolean clockwise = (!directionUp) == (previousX < rX); if (clockwise) { clockwiseSum += Math.abs(previousX - rX); } else { clockwiseSum -= Math.abs(previousX - rX); } } previousX = rX; prevX = x; prevY = y; } } if(firstX != -360){ boolean clockwise = (!firstDirectionUp) == (previousX < firstX); if(clockwise){ clockwiseSum += Math.abs(previousX - firstX); } else { clockwiseSum -= Math.abs(previousX - firstX); } } return clockwiseSum >= 0; }
Source:
public void evaluate_shouldReturnAllPatientsCurrentlyNotActiveOnDrugs() throws Exception { cohortDefinition.setOnlyCurrentlyActive(false); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); System.out.println("Currently Not on Drugs " + cohort.getMemberIds() + " " + cohortDefinition + "==="); }

Target:
public void evaluate_shouldReturnAllPatientsCurrentlyNotActiveOnDrugs() throws Exception { cohortDefinition.setOnlyCurrentlyActive(false); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(8)); Assert.assertEquals(1, cohort.size()); }
Source:
Court GetCourt(@PathVariable("id") Long id) { if (id == null) { LogSystem.LogEvent("non id passed to controller"); throw new IncorrectResultSizeDataAccessException("non courtId passed",1); } Court court = courtManager.GetCourtById(id); return court; }

Target:
Court GetCourt(@PathVariable("id") Long id) throws NotFoundException { Court court = courtManager.GetCourtById(id); if (court == null) { throw new NotFoundException("Court Not Found"); } return court; }
Source:
public Condition createCondition(Condition condition) { List<String> errors = new ArrayList<>(); if (condition.isEmpty()) { errors.add("Condition resource is null"); throw new NullPointerException("Condition resource cannot be null"); } if (condition.getSubject().isEmpty()) { errors.add("No subject"); throw new NullPointerException("condition Subject cannot be null"); } Obs obs = Context.getObsService() .saveObs(FHIRConditionUtil.generateOpenMrsObsFromFHIRCondition(condition), ""); FHIRUtils.checkGeneratorErrorList(errors); return FHIRConditionUtil.generateFHIRConditionFromOpenMRSObs(obs); }

Target:
public Condition createCondition(Condition condition) { if (condition.isEmpty()) { throw new UnprocessableEntityException("condition resource cannot be null"); } if (condition.getSubject().isEmpty()) { throw new UnprocessableEntityException("condition resource cannot be null"); } Obs obs = Context.getObsService() .saveObs(FHIRConditionUtil.generateOpenMrsObsFromFHIRCondition(condition), ""); return FHIRConditionUtil.generateFHIRConditionFromOpenMRSObs(obs); }
Source:
public void createControl(Composite parent, IEEFFormContainer formContainer) { super.createControl(parent, formContainer); EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); Composite composite = parent; boolean isInGroup = this.getWidgetDescription().eContainer() instanceof EEFGroupDescription; boolean isCheckbox = this.getWidgetDescription() instanceof EEFCheckboxDescription; boolean needsLabel = isInGroup || (!Util.isBlank(this.getWidgetDescription().getLabelExpression()) && !isCheckbox); if (needsLabel) { this.label = widgetFactory.createStyledText(composite, SWT.NONE); this.label.setEditable(false); } boolean needsHelp = isInGroup || !Util.isBlank(this.getWidgetDescription().getHelpExpression()); if (needsHelp) { this.help = widgetFactory.createCLabel(composite, ""); if (!Util.isBlank(this.getWidgetDescription().getHelpExpression())) { this.help.setImage(EEFIdeUiPlugin.getPlugin().getImageRegistry().get(Icons.HELP)); this.help.setToolTipText(""); } } this.createMainControl(composite, formContainer); }

Target:
public void createControl(Composite parent, IEEFFormContainer formContainer) { super.createControl(parent, formContainer); EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); Composite composite = parent; boolean isInGroup = this.getWidgetDescription().eContainer() instanceof EEFGroupDescription; boolean needsSeparatedLabel = this.needSeparatedLabel(); boolean isBlankLabel = Util.isBlank(this.getWidgetDescription().getLabelExpression()); boolean needsLabel = isInGroup || (!isBlankLabel && needsSeparatedLabel); boolean needsHelp = isInGroup || !Util.isBlank(this.getWidgetDescription().getHelpExpression()); if (!isInGroup && (needsLabel || needsHelp)) { composite = widgetFactory.createComposite(parent); int numColumn = 1; if (needsLabel) { numColumn = numColumn + 1; } if (needsHelp) { numColumn = numColumn + 1; } GridLayout layout = new GridLayout(numColumn, false); composite.setLayout(layout); GridData layoutData = new GridData(GridData.FILL_HORIZONTAL); layoutData.horizontalSpan = 1; composite.setLayoutData(layoutData); } if (needsLabel) { this.label = widgetFactory.createStyledText(composite, SWT.NONE); this.label.setEditable(false); this.label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); } if (needsHelp) { this.help = widgetFactory.createCLabel(composite, ""); if (!Util.isBlank(this.getWidgetDescription().getHelpExpression())) { this.help.setImage(EEFIdeUiPlugin.getPlugin().getImageRegistry().get(Icons.HELP)); this.help.setToolTipText(""); } } this.createMainControl(composite, formContainer); }
Source:
private void initializeFavoriteCheck() { if (ConnectorFactory.getConnector(cache).supportsAddToFavorite(cache, typeSelected)) { if (premFavPoints > 0) { favCheck.setVisibility(View.VISIBLE); favCheck.setText(getString(R.string.fav_points_remaining, String.valueOf(premFavPoints))); } } else { favCheck.setVisibility(View.GONE); } }

Target:
private void initializeFavoriteCheck() { if (ConnectorFactory.getConnector(cache).supportsAddToFavorite(cache, typeSelected)) { if (premFavPoints > 0) { favCheck.setVisibility(View.VISIBLE); favCheck.setText(getString(R.string.fav_points_remaining, premFavPoints)); } } else { favCheck.setVisibility(View.GONE); } }
Source:
public void testParseEncoding_badEncoding() { try { RawParseUtils.parseEncoding("encoding xyz\n".getBytes()); fail("should throw an UnsupportedCharsetException: xyz"); } catch (UnsupportedCharsetException e) { assertNotNull(e); assertEquals("xyz", e.getMessage()); } }

Target:
public void testParseEncoding_badEncoding() { try { RawParseUtils.parseEncoding(Constants .encodeASCII("encoding xyz\n")); fail("should throw an UnsupportedCharsetException: xyz"); } catch (UnsupportedCharsetException e) { assertEquals("xyz", e.getMessage()); } }
Source:
protected void setPropertyOnUserModel(Property<Object> userModelProperty, UserModel user, String ldapAttrValue) { if (ldapAttrValue == null) { if (Boolean.class.equals(userModelProperty.getJavaClass()) || boolean.class.equals(userModelProperty.getJavaClass())) { userModelProperty.setValue(user, false); } else { userModelProperty.setValue(user, null); } userModelProperty.setValue(user, null); } else { Class<Object> clazz = userModelProperty.getJavaClass(); if (String.class.equals(clazz)) { userModelProperty.setValue(user, ldapAttrValue); } else if (Boolean.class.equals(clazz) || boolean.class.equals(clazz)) { Boolean boolVal = false; if (ldapAttrValue.equals("TRUE")) { boolVal = true; } userModelProperty.setValue(user, boolVal); } else { logger.warnf("Don't know how to set the property '%s' on user '%s' . Value of LDAP attribute is '%s' ", userModelProperty.getName(), user.getUsername(), ldapAttrValue.toString()); } } }

Target:
protected void setPropertyOnUserModel(Property<Object> userModelProperty, UserModel user, String ldapAttrValue) { if (ldapAttrValue == null) { if (Boolean.class.equals(userModelProperty.getJavaClass()) || boolean.class.equals(userModelProperty.getJavaClass())) { userModelProperty.setValue(user, false); } else { userModelProperty.setValue(user, null); } userModelProperty.setValue(user, null); } else { Class<Object> clazz = userModelProperty.getJavaClass(); if (String.class.equals(clazz)) { userModelProperty.setValue(user, ldapAttrValue); } else if (Boolean.class.equals(clazz) || boolean.class.equals(clazz)) { Boolean boolVal = Boolean.valueOf(ldapAttrValue); userModelProperty.setValue(user, boolVal); } else { logger.warnf("Don't know how to set the property '%s' on user '%s' . Value of LDAP attribute is '%s' ", userModelProperty.getName(), user.getUsername(), ldapAttrValue.toString()); } } }
Source:
private String getWebSocketURL(HttpRequest req) { String protocol = "ws"; if (isConnectionSecured) { protocol = "wss"; } String url = protocol + "://" + req.headers().get("Host") + req.getUri(); return url; }

Target:
private String getWebSocketURL(HttpRequest req) { String protocol = Constants.WEBSOCKET_PROTOCOL; if (isConnectionSecured) { protocol = Constants.WEBSOCKET_PROTOCOL_SECURED; } String url = protocol + "://" + req.headers().get("Host") + req.getUri(); return url; }
Source:
private boolean isInEnrollList(StudentAttributes student, List<StudentAttributes> studentInfoList) { for (StudentAttributes studentInfo : studentInfoList) { if (studentInfo.email.equals(student.email)) { return true; } } return false; }

Target:
private boolean isInEnrollList(StudentAttributes student, List<StudentAttributes> studentInfoList) { for (StudentAttributes studentInfo : studentInfoList) { if (studentInfo.email.equalsIgnoreCase(student.email)) { return true; } } return false; }
Source:
public static void loadUrlBasedOnOsVersion(@NonNull final Context context, @NonNull final WebView webView, @NonNull final String url, @NonNull final WebViewStatusListener viewInterface, @NonNull final FullScreenErrorNotification errorNotification, @NonNull OkHttpClientProvider okHttpClientProvider) { if (!NetworkUtil.isConnected(context)) { errorNotification.showError(context, new IOException()); } else { errorNotification.hideError(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { viewInterface.showLoadingProgress(); okHttpClientProvider.get().newCall(new Request.Builder() .url(url) .get() .build()) .enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { HANDLER.post((new Runnable() { @Override public void run() { errorNotification.showError(context, e); viewInterface.hideLoadingProgress(); viewInterface.clearWebView(); } })); } @Override public void onResponse(Call call, final okhttp3.Response response) throws IOException { HANDLER.post(new Runnable() { @Override public void run() { final int responseCode = response.code(); if (responseCode >= HttpStatus.BAD_REQUEST) { errorNotification.showError(context, new HttpStatusException(Response.error(responseCode, ResponseBody.create(MediaType.parse("text/plain"), response.message())))); viewInterface.hideLoadingProgress(); viewInterface.clearWebView(); } else { webView.loadUrl(url); } } }); } }); } else { webView.loadUrl(url); } } }

Target:
public static void loadUrlBasedOnOsVersion(@NonNull final Context context, @NonNull final WebView webView, @NonNull final String url, @NonNull final WebViewStatusListener viewInterface, @NonNull final FullScreenErrorNotification errorNotification, @NonNull OkHttpClientProvider okHttpClientProvider) { if (!NetworkUtil.isConnected(context)) { errorNotification.showError(context, new IOException()); } else { errorNotification.hideError(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { viewInterface.showLoadingProgress(); okHttpClientProvider.get().newCall(new Request.Builder() .url(url) .get() .build()) .enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { webView.post((new Runnable() { @Override public void run() { errorNotification.showError(context, e); viewInterface.hideLoadingProgress(); viewInterface.clearWebView(); } })); } @Override public void onResponse(Call call, final okhttp3.Response response) throws IOException { webView.post(new Runnable() { @Override public void run() { final int responseCode = response.code(); if (responseCode >= HttpStatus.BAD_REQUEST) { errorNotification.showError(context, new HttpStatusException(Response.error(responseCode, ResponseBody.create(MediaType.parse("text/plain"), response.message())))); viewInterface.hideLoadingProgress(); viewInterface.clearWebView(); } else { webView.loadUrl(url); } } }); } }); } else { webView.loadUrl(url); } } }
Source:
public boolean visit(MethodDeclaration node) { Block body= node.getBody(); if (body == null) return false; Selection selection= getSelection(); int nodeStart= body.getStartPosition(); int nodeExclusiveEnd= nodeStart + body.getLength(); if (((nodeStart >= selection.getOffset()) || (selection.getExclusiveEnd() >= nodeExclusiveEnd))) return false; return super.visit(node); }

Target:
public boolean visit(MethodDeclaration node) { Block body= node.getBody(); if (body == null) return false; Selection selection= getSelection(); int nodeStart= body.getStartPosition(); int nodeExclusiveEnd= nodeStart + body.getLength(); if ((nodeStart >= selection.getOffset()) || (selection.getExclusiveEnd() >= nodeExclusiveEnd)) return false; return super.visit(node); }
Source:
public Task<List<OpResult>> multi(List<Op> ops, Executor executor) { return Task.blocking(() -> _zkClient.multi(ops), executor) .recoverWith(e -> { if (e instanceof KeeperException) { e = getCause((KeeperException) e, ops); } return Task.failure(e); }); }

Target:
public Task<List<OpResult>> multi(List<Op> ops, Executor executor) { return Task.blocking(() -> _zkClient.multi(ops), executor); }
Source:
public ObjectId get(AnyObjectId id) throws IOException { return root.get(id, reader); }

Target:
public ObjectId get(AnyObjectId id) throws IOException { Note n = root.getNote(id, reader); return n == null ? null : n.getData(); }
Source:
public static GuestNicConfiguration map(VmInitNetwork entity, GuestNicConfiguration template) { GuestNicConfiguration model = template != null ? template : new GuestNicConfiguration(); model.setName(entity.getName()); model.setOnBoot(entity.getStartOnBoot()); model.setBootProtocol(entity.getBootProtocol() == NetworkBootProtocol.STATIC_IP ? BootProtocol.STATIC.name() : entity.getBootProtocol().name()); IP ip = new IP(); model.setIp(ip); ip.setAddress(entity.getIp()); ip.setNetmask(entity.getNetmask()); ip.setGateway(entity.getGateway()); return model; }

Target:
public static GuestNicConfiguration map(VmInitNetwork entity, GuestNicConfiguration template) { GuestNicConfiguration model = template != null ? template : new GuestNicConfiguration(); model.setName(entity.getName()); model.setOnBoot(entity.getStartOnBoot()); if (entity.getBootProtocol() != null) { model.setBootProtocol(BootProtocolMapper.map(entity.getBootProtocol(), null).value()); } IP ip = new IP(); model.setIp(ip); ip.setAddress(entity.getIp()); ip.setNetmask(entity.getNetmask()); ip.setGateway(entity.getGateway()); return model; }
Source:
public static void waitTillInstancesAreCreated(ColoHelper coloHelper, String entity, int bundleSeqNo, int totalMinutesToWait ) throws JAXBException, OozieClientException { int sleep = totalMinutesToWait * 60 / 20; String entityName = Util.readEntityName(entity); ENTITY_TYPE type = Util.getEntityType(entity); String bundleID = getSequenceBundleID(coloHelper,entityName,type, bundleSeqNo); String coordID = getDefaultCoordIDFromBundle(coloHelper, bundleID); for (int sleepCount = 0; sleepCount < sleep; sleepCount++) { CoordinatorJob coordInfo = coloHelper.getProcessHelper().getOozieClient() .getCoordJobInfo(coordID); if(coordInfo.getActions().size() > 0) break; logger.info("Coord "+ coordInfo.getId() + " still dosent have " + "instance created on oozie: " + coloHelper.getProcessHelper() .getOozieClient().getOozieUrl()); try { Thread.sleep(20000); } catch (InterruptedException e) { logger.error(e.getMessage()); } } }

Target:
public static void waitTillInstancesAreCreated(ColoHelper coloHelper, String entity, int bundleSeqNo, int totalMinutesToWait ) throws JAXBException, OozieClientException { int sleep = totalMinutesToWait * 60 / 5; String entityName = Util.readEntityName(entity); ENTITY_TYPE type = Util.getEntityType(entity); String bundleID = getSequenceBundleID(coloHelper,entityName,type, bundleSeqNo); String coordID = getDefaultCoordIDFromBundle(coloHelper, bundleID); for (int sleepCount = 0; sleepCount < sleep; sleepCount++) { CoordinatorJob coordInfo = coloHelper.getProcessHelper().getOozieClient() .getCoordJobInfo(coordID); if(coordInfo.getActions().size() > 0) break; logger.info("Coord "+ coordInfo.getId() + " still dosent have " + "instance created on oozie: " + coloHelper.getProcessHelper() .getOozieClient().getOozieUrl()); try { Thread.sleep(5000); } catch (InterruptedException e) { logger.error(e.getMessage()); } } }
Source:
protected VersionedOperationResponse executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, REPLACE_IF_UNMODIFIED_REQUEST); transport.writeArray(key); transport.writeVInt(lifespan); transport.writeVInt(maxIdle); codec.writeExpirationNanoTimes(transport, lifespanNanos, maxIdleNanos, internalFlags); transport.writeLong(version); transport.writeArray(value); transport.flush(); return returnVersionedOperationResponse(transport, params); }

Target:
protected VersionedOperationResponse executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, REPLACE_IF_UNMODIFIED_REQUEST); transport.writeArray(key); codec.writeExpirationParams(transport, lifespan, maxIdle, internalFlags); transport.writeLong(version); transport.writeArray(value); transport.flush(); return returnVersionedOperationResponse(transport, params); }
Source:
public static String getFileExtension(File file) { String extension; try { extension = FilenameUtils.getExtension(file.getAbsolutePath()); } catch (Exception e) { extension = null; } return extension.toLowerCase(); }

Target:
public static String getFileExtension(File file) { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); }
Source:
public void init(String configFilePath) throws ManageDomainsResult { try { utilityConfiguration = new ManageDomainsConfiguration(configFilePath); } catch (ConfigurationException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.FAILED_READING_CONFIGURATION, "Verify that postgresql service is up and check DB configurations", e.getMessage()); } try { daoImpl = new ManageDomainsDAOImpl(); } catch (SQLException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.DB_EXCEPTION, "Verify that postgresql service is up and check DB configurations", e.getMessage()); } }

Target:
public void init(String configFilePath) throws ManageDomainsResult { try { utilityConfiguration = new ManageDomainsConfiguration(configFilePath); } catch (ConfigurationException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.FAILED_READING_CONFIGURATION, e.getMessage()); } try { daoImpl = new ManageDomainsDAOImpl(); } catch (SQLException e) { throw new ManageDomainsResult("Please verify the following:\n1. Your database credentials are valid.\n2. The database machine is accessible.\n3. The database service is running", ManageDomainsResultEnum.DB_EXCEPTION, e.getMessage()); } }
Source:
@Override public TResult current() { final List<Object> list = Arrays.asList(elements.clone()); @SuppressWarnings("unchecked") final TOuter outer = (TOuter) list.get(0); @SuppressWarnings("unchecked") final TInner inner = (TInner) list.get(1); return this.resultSelector.apply(outer, inner); }

Target:
@Override public TResult current() { final TOuter outer = (TOuter) elements[0]; final TInner inner = (TInner) elements[1]; return this.resultSelector.apply(outer, inner); }
Source:
public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; }

Target:
public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; String extension = getExtension(originalImage.getAbsolutePath()); ImageWidget.ImageType type = ImageWidget.ImageType.fromExtension(extension); if (type == null) { Log.i(t, "Could not scale image " + originalImage.getAbsolutePath() + " due to incompatible extension"); return false; } Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); bitmap.compress(type.getCompressFormat(), 100, out); scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; }
Source:
public synchronized void load(PackageLoader packageLoader, boolean resolve) { if (state == State.PROXY) { EPackage[] ePackages = null; ePackages = loadPackagesFromGlobalRegistry(); if (ePackages == null) { ePackages = packageLoader.loadPackages(this); } for (EPackage ePackage : ePackages) { String packageURI = ePackage.getNsURI(); InternalCDOPackageInfo packageInfo = getPackageInfo(packageURI); if (resolve) { packageRegistry.registerPackageInfo(ePackage, packageInfo); synchronized (ePackage) { EcoreUtil.resolveAll(ePackage); } } } setState(State.LOADED); } }

Target:
public synchronized void load(PackageLoader packageLoader, boolean resolve) { if (state == State.PROXY) { EPackage[] ePackages = null; ePackages = loadPackagesFromGlobalRegistry(); if (ePackages == null) { ePackages = packageLoader.loadPackages(this); } for (EPackage ePackage : ePackages) { String packageURI = ePackage.getNsURI(); InternalCDOPackageInfo packageInfo = getPackageInfo(packageURI); packageRegistry.registerPackageInfo(ePackage, packageInfo); if (resolve) { synchronized (ePackage) { EcoreUtil.resolveAll(ePackage); } } } setState(State.LOADED); } }
Source:
public void setUrlResourceReaderRootDirs(String... rootResourceDirs) throws IOException { Set<String> newRootResourceDirs = ImmutableSet.<String>builder().add(rootResourceDirs).build(); Configuration configuration = configAdmin.getConfiguration(PID, null); if (configuration == null) { LOGGER.warn( "{} configuration was null, cannot update {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } if (configuration.getProperties() != null) { Set<String> currentRootResourceDirs = ImmutableSet.copyOf( (Collection<String>) configuration.getProperties().get(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY)); LOGGER.debug( "{} {}, current value: {}, new value: {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, currentRootResourceDirs, newRootResourceDirs); if (rootResourceDirsEqual(currentRootResourceDirs, newRootResourceDirs)) { LOGGER.debug( "{} unchanged, skipping update", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } } Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, newRootResourceDirs); configuration.update(properties); for (int i = 0; i < 5; i++) { Configuration updatedConfig = configAdmin.getConfiguration(PID, null); if (updatedConfig .getProperties() .get(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY) .equals(newRootResourceDirs)) { break; } boolean interrupted = false; try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } LOGGER.debug("{} properties after update: {}", PID, configuration.getProperties()); }

Target:
public void setUrlResourceReaderRootDirs(String... rootResourceDirs) throws IOException { Collection<String> newRootResourceDirs = ImmutableSet.<String>builder().add(rootResourceDirs).build(); Configuration configuration = configAdmin.getConfiguration(PID, null); Collection<String> currentRootResourceDirs = getCurrentRootResourceDirs(configuration); if (currentRootResourceDirs != null) { LOGGER.debug( "{} {}, current value: {}, new value: {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, currentRootResourceDirs, newRootResourceDirs); if (rootResourceDirsEqual(currentRootResourceDirs, newRootResourceDirs)) { LOGGER.debug( "{} unchanged, skipping update", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } } updateUrlResourceReaderRootDirs(configuration, newRootResourceDirs); }