auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testGetOutOfBandManagementOptionsInvalid() { try { oobmService.getOptions(null); Assert.fail("CloudRuntimeException was expected for finding options of host with out-of-band management configuration"); } catch (CloudRuntimeException e) { } }

Target:
public void testGetOutOfBandManagementOptionsInvalid() { oobmService.getOptions(null); Assert.fail("CloudRuntimeException was expected for finding options of host with out-of-band management configuration"); }
Source:
public Set<OperatingSystem> getVirtualGuestOperatingSystems() { return Sets.newHashSet(FluentIterable.from(operatingSystems) .transform(new Function<ContainerVirtualGuestConfigurationOption, OperatingSystem>() { @Override public OperatingSystem apply(ContainerVirtualGuestConfigurationOption input) { if (input.getTemplate().getOperatingSystemReferenceCode() != null) { return OperatingSystem.builder() .id(input.getTemplate().getOperatingSystemReferenceCode()) .operatingSystemReferenceCode(input.getTemplate().getOperatingSystemReferenceCode()) .build(); } else { logger.warn("Skipping entry because of missing operatingSystemReferenceCode for %s", input); return null; } } }).filter(Predicates.notNull())); }

Target:
public Set<OperatingSystem> getVirtualGuestOperatingSystems() { return Sets.newHashSet(FluentIterable.from(operatingSystems) .transform(new Function<ContainerVirtualGuestConfigurationOption, OperatingSystem>() { @Override public OperatingSystem apply(ContainerVirtualGuestConfigurationOption input) { String operatingSystemReferenceCode = input.getTemplate().getOperatingSystemReferenceCode(); if (operatingSystemReferenceCode == null) { return null; } else { return OperatingSystem.builder() .id(operatingSystemReferenceCode) .operatingSystemReferenceCode(operatingSystemReferenceCode) .build(); } } }).filter(Predicates.notNull())); }
Source:
private void fetchGitHubSearch(@NonNull final String searchString) { checkNotNull(searchString); Log.d(TAG, "fetchGitHubSearch(" + searchString + ")"); if (isOngoingRequest(searchString.hashCode())) { Log.d(TAG, "Found an ongoing request for repository " + searchString); return; } final String uri = getUniqueId(searchString); Subscription subscription = createNetworkObservable(searchString) .subscribeOn(Schedulers.computation()) .map((repositories) -> { final List<Integer> repositoryIds = new ArrayList<>(); for (GitHubRepository repository : repositories) { gitHubRepositoryStore.put(repository); repositoryIds.add(repository.getId()); } return new GitHubRepositorySearch(searchString, repositoryIds); }) .doOnSubscribe(() -> startRequest(uri)) .doOnCompleted(() -> completeRequest(uri)) .doOnError(doOnError(uri)) .subscribe(gitHubRepositorySearchStore::put, e -> Log.e(TAG, "Error fetching GitHub repository search for '" + searchString + "'", e)); addRequest(searchString.hashCode(), subscription); }

Target:
private void fetchGitHubSearch(@NonNull final String searchString) { checkNotNull(searchString); Log.d(TAG, "fetchGitHubSearch(" + searchString + ")"); if (isOngoingRequest(searchString.hashCode())) { Log.d(TAG, "Found an ongoing request for repository " + searchString); return; } final String uri = getUniqueId(searchString); Subscription subscription = createNetworkObservable(searchString) .subscribeOn(Schedulers.computation()) .map((repositories) -> { final List<Integer> repositoryIds = new ArrayList<>(repositories.size()); for (GitHubRepository repository : repositories) { gitHubRepositoryStore.put(repository); repositoryIds.add(repository.getId()); } return new GitHubRepositorySearch(searchString, repositoryIds); }) .doOnSubscribe(() -> startRequest(uri)) .doOnCompleted(() -> completeRequest(uri)) .doOnError(doOnError(uri)) .subscribe(gitHubRepositorySearchStore::put, e -> Log.e(TAG, "Error fetching GitHub repository search for '" + searchString + "'", e)); addRequest(searchString.hashCode(), subscription); }
Source:
public Object execute() throws Exception { if (!force) { String answer = session .readLine( "Are you sure you want to remove all gazetteer entries inside of the offline solr gazetteer core?(y/n)", ' ') .toLowerCase(); if (!("y".equals(answer) || "yes".equals(answer))) { session.getConsole().println("Aborting."); return null; } } try { SolrClient solrClient = clientFactory.newClient(OfflineGazetteerPlugin.STANDALONE_GAZETTEER_CORE_NAME); Failsafe.with(retryPolicy).get(() -> solrClient.deleteByQuery("*:*")); } catch (Exception e) { LOGGER.info("Error while executing", e); session.getConsole().println("Error while submitting remove all, exiting."); throw e; } session.getConsole().println("Removeall submitted successfully."); return null; }

Target:
public Object execute() throws Exception { if (!force) { String answer = session .readLine( "Are you sure you want to remove all gazetteer entries inside of the solr gazetteer collection?(y/n)", ' ') .toLowerCase(); if (!("y".equals(answer) || "yes".equals(answer))) { session.getConsole().println("Aborting."); return null; } } SolrClient solrClient = clientFactory.newClient(COLLECTION_NAME); Boolean response = Failsafe.with( new RetryPolicy() .retryWhen(false) .withMaxDuration(5, TimeUnit.SECONDS) .withBackoff(25, 1_000, TimeUnit.MILLISECONDS)) .get(() -> solrClient.isAvailable()); if (response == null || !response) { LOGGER.error("Could not contact solr to remove all"); session.getConsole().println("Could not contact solr to remove all, exiting."); return null; } try { solrClient.deleteByQuery("*:*"); } catch (Exception e) { LOGGER.info("Error while executing", e); session.getConsole().println("Error while submitting remove all, exiting."); throw e; } session.getConsole().println("Removeall submitted successfully."); return null; }
Source:
public void onNext(Object request) { exchange = endpoint.createExchange(); exchange.getIn().setBody(request); exchange.getIn().setHeaders(headers); consumer.process(exchange, doneSync -> { }); if (exchange.hasOut()) { responseObserver.onNext(exchange.getOut().getBody()); } else { responseObserver.onNext(exchange.getIn().getBody()); } responseObserver.onCompleted(); }

Target:
public void onNext(Object request) { CountDownLatch latch = new CountDownLatch(1); Object responseBody = null; exchange = endpoint.createExchange(); exchange.getIn().setBody(request); exchange.getIn().setHeaders(headers); consumer.process(exchange, doneSync -> { latch.countDown(); }); try { latch.await(); if (exchange.hasOut()) { responseBody = exchange.getOut().getBody(); } else { responseBody = exchange.getIn().getBody(); } if (responseBody instanceof List) { List<?> responseList = (List<?>)responseBody; responseList.forEach((responseItem) -> { responseObserver.onNext(responseItem); }); } else { responseObserver.onNext(responseBody); } responseObserver.onCompleted(); } catch (InterruptedException e) { responseObserver.onError(e); } }
Source:
public void testDclassWrapper() { String userAgentSample = "Mozilla/5.0 (Linux; U; Android 2.2; en; HTC Aria A6380 Build/ERE27) AppleWebKit/540.13+ (KHTML, like Gecko) Version/3.1 Mobile Safari/524.15.0"; dClass dw = new dClass(dtree_path); dw.init(); HashMap c = (HashMap) dw.classify(userAgentSample); assertEquals("Vendor as expected", "HTC" , c.get("vendor")); assertEquals("Model as expected" , "A6366", c.get("model")); assertEquals("device_os as expected","Android",c.get("device_os")); assertEquals("is_tablet as expected","false",c.get("is_tablet")); }

Target:
public void testDclassWrapper() { String userAgentSample = "Mozilla/5.0 (Linux; U; Android 2.2; en; HTC Aria A6380 Build/ERE27) AppleWebKit/540.13+ (KHTML, like Gecko) Version/3.1 Mobile Safari/524.15.0"; dClass dw = new dClass(dtree_path); dw.init(); Map<String, String> c = dw.classify(userAgentSample); assertEquals("Vendor as expected", "HTC" , c.get("vendor")); assertEquals("Model as expected" , "A6366", c.get("model")); assertEquals("device_os as expected","Android",c.get("device_os")); assertEquals("is_tablet as expected","false",c.get("is_tablet")); }
Source:
public void close() { shutdownExecutorService(); for (String executorKey : executors.keySet()) { DefaultExecutor executor = executors.remove(executorKey); if (executor != null) { executor.getWatchdog().destroyProcess(); } } }

Target:
public void close() { shutdownExecutorService(); for (String executorKey : executors.keySet()) { DefaultExecutor executor = executors.remove(executorKey); if (executor != null) { try { executor.getWatchdog().destroyProcess(); } catch (Exception e){ LOGGER.error("error destroying executor for paragraphId: " + executorKey, e); } } } }
Source:
public static IntervalList concatenate(final Collection<IntervalList> lists) { return lists.stream() .reduce(IntervalList::concatenate) .orElseThrow(() -> new SAMException("Cannot concatenate an empty list of IntervalLists.")); }

Target:
public static IntervalList concatenate(final Collection<IntervalList> lists) { final SAMFileHeader header = lists.stream() .findFirst() .map(IntervalList::getHeader) .orElseThrow( () -> new IllegalArgumentException("Cannot combine empty collection of IntervalLists")); return lists.stream() .reduce(new IntervalList(header), IntervalList::addOther, IntervalList::concatenate); }
Source:
private boolean slaveAttributesMatch(Offer offer) { boolean slaveTypeMatch = true; JSONObject cloudAttributes = getMesosCloud().getCloudAttributes(); if (cloudAttributes != null && cloudAttributes.size() > 0) { Iterator<Attribute> iter = offer.getAttributesList().iterator(); while (iter.hasNext()) { Attribute attribute = iter.next(); if (!(cloudAttributes.containsKey(attribute.getName()) && attribute.getText().getValue().equals(cloudAttributes.getString(attribute.getName())))) { slaveTypeMatch = false; break; } } } return slaveTypeMatch; }

Target:
private boolean slaveAttributesMatch(Offer offer) { boolean slaveTypeMatch = true; JSONObject slaveAttributes = getMesosCloud().getSlaveAttributes(); Map<String, String> attributesMap = new HashMap<String, String>(); for (Attribute attribute : offer.getAttributesList()) { attributesMap.put(attribute.getName(), attribute.getText().getValue()); } if (slaveAttributes != null && slaveAttributes.size() > 0) { Iterator iterator = slaveAttributes.keys(); while (iterator.hasNext()) { String key = (String) iterator.next(); if (!(attributesMap.containsKey(key) && attributesMap.get(key).toString().equals(slaveAttributes.getString(key)))) { slaveTypeMatch = false; break; } } } return slaveTypeMatch; }
Source:
public final void putChar(char value) { checkLimits(2); Unsafe.getUnsafe().putChar(appendAddress, value); appendAddress += 2; }

Target:
public final void putChar(char value) { checkLimits(Character.BYTES); Unsafe.getUnsafe().putChar(appendAddress, value); appendAddress += Character.BYTES; }
Source:
public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; StreamConfig config = (StreamConfig) obj; if (!(config instanceof StreamConfig)) { return false; } if (config.getStreamType() == null) { if (this.getStreamType() != null) return false; } else { if (!config.getStreamType().equals(this.getStreamType())) return false; } if (config.getLocation() == null) { if (this.getLocation() != null) return false; } else { if (!config.getLocation().equals(this.getLocation())) return false; } if (config.getURL() == null) { if (this.getURL() != null) return false; } else { if (!config.getURL().equals(this.getURL())) return false; } return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StreamConfig other = (StreamConfig) obj; if (location == null) { if (other.location != null) return false; } else if (!location.equals(other.location)) return false; if (streamType != other.streamType) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; }
Source:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { MqttFixedHeader pingreqFixedHeader = new MqttFixedHeader(MqttMessageType.PINGREQ, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttMessage pingreqMessage = new MqttMessage(pingreqFixedHeader); ctx.channel().writeAndFlush(pingreqMessage); System.out.println("Sent PINGREQ"); } else { super.userEventTriggered(ctx, evt); } }

Target:
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { MqttFixedHeader pingreqFixedHeader = new MqttFixedHeader(MqttMessageType.PINGREQ, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttMessage pingreqMessage = new MqttMessage(pingreqFixedHeader); ctx.writeAndFlush(pingreqMessage); System.out.println("Sent PINGREQ"); } else { super.userEventTriggered(ctx, evt); } }
Source:
protected void deleteAsyncQuery() { String cleanupDateFormatted = evaluateFormattedFilterDate(Calendar.DATE, queryCleanupDays); String filterExpression = "createdOn=le='" + cleanupDateFormatted + "'"; Collection<AsyncQuery> asyncQueryList = asyncQueryDao.deleteAsyncQueryAndResultCollection(filterExpression); Iterator itr = asyncQueryList.iterator(); while (itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); resultStorageEngine.deleteResultsByID(query.getId()); } }

Target:
protected void deleteAsyncQuery() { try { Date cleanupDate = DateUtil.calculateFilterDate(Calendar.DATE, queryCleanupDays); PathElement createdOnPathElement = new PathElement(AsyncQuery.class, Long.class, "createdOn"); FilterExpression fltDeleteExp = new LEPredicate(createdOnPathElement, cleanupDate); Collection<AsyncQuery> asyncQueryList = asyncQueryDao.deleteAsyncQueryAndResultCollection(fltDeleteExp); resultStorageEngine.deleteResultsCollection(asyncQueryList); } catch (Exception e) { log.error("Exception in scheduled cleanup: {}", e); } }
Source:
private static ZoneInfo lookupZoneInfo(String timezoneId) { try { ZoneInfo zoneInfo = ZoneInfoDB.getInstance().makeTimeZone(timezoneId); if (zoneInfo == null) { zoneInfo = ZoneInfoDB.getInstance().makeTimeZone("GMT"); } if (zoneInfo == null) { throw new IllegalStateException("GMT not found: \"" + timezoneId + "\""); } return zoneInfo; } catch (IOException e) { throw new IllegalStateException( "Error loading timezone: \"" + timezoneId + "\"", e); } }

Target:
private static ZoneInfo lookupZoneInfo(String timezoneId) { try { ZoneInfo zoneInfo = ZoneInfoDB.getInstance().makeTimeZone(timezoneId); if (zoneInfo == null) { zoneInfo = ZoneInfoDB.getInstance().makeTimeZone("GMT"); } if (zoneInfo == null) { throw new AssertionError("GMT not found: \"" + timezoneId + "\""); } return zoneInfo; } catch (IOException e) { throw new AssertionError("Error loading timezone: \"" + timezoneId + "\"", e); } }
Source:
public void notify(EclipseContext context, EventType type, Object data) { if (!Policy.DEBUG_CONTEXTS) { return; } String msg = context.toString(); if (msg.startsWith("Anonymous Context")) { return; } msg = type + " : " + describe(context); WorkbenchSWTActivator.trace(Policy.DEBUG_CONTEXTS_FLAG, msg, null); }

Target:
public void notify(EclipseContext context, EventType type, Object data) { if (!Policy.DEBUG_CONTEXTS) { return; } String msg = context.toString(); if (EclipseContext.ANONYMOUS_CONTEXT_NAME.equals(msg)) { return; } msg = type + " : " + describe(context); WorkbenchSWTActivator.trace(Policy.DEBUG_CONTEXTS_FLAG, msg, null); }
Source:
public void setSelectedTestArtifactName(@NotNull String selectedTestArtifactName) { ImmutableSet<String> knownArtifacts = ImmutableSet.of(AndroidProject.ARTIFACT_ANDROID_TEST, AndroidProject.ARTIFACT_UNIT_TEST); checkArgument(knownArtifacts.contains(selectedTestArtifactName), "Unknown test artifact %s.", selectedTestArtifactName); mySelectedTestArtifactName = selectedTestArtifactName; }

Target:
public void setSelectedTestArtifactName(@NotNull String selectedTestArtifactName) { checkArgument(selectedTestArtifactName == AndroidProject.ARTIFACT_ANDROID_TEST || selectedTestArtifactName == AndroidProject.ARTIFACT_UNIT_TEST); mySelectedTestArtifactName = selectedTestArtifactName; }
Source:
public Person[] getRecipients(ZulipApp app) { Person[] recipientsCache; String[] ids = TextUtils.split(this.getDisplayRecipent(), ","); recipientsCache = new Person[ids.length]; for (int i = 0; i < ids.length; i++) { recipientsCache[i] = Person.getById(app, Integer.parseInt(ids[i])); } return recipientsCache; }

Target:
public Person[] getRecipients(ZulipApp app) { Person[] recipientsCache; String[] ids = TextUtils.split(this.getDisplayRecipent(), ","); recipientsCache = new Person[ids.length]; for (int i = 0; i < ids.length; i++) { try { recipientsCache[i] = Person.getById(app, Integer.parseInt(ids[i])); } catch (NumberFormatException e) { ZLog.logException(e); } } return recipientsCache; }
Source:
private boolean fetchUsersList(String dotComBlogId, final int localTableBlogId, final int offset) { if (mUsersEndOfListReached || mUsersFetchRequestInProgress || !NetworkUtils.checkConnection(this)) { return false; } mUsersFetchRequestInProgress = true; PeopleUtils.fetchUsers(dotComBlogId, localTableBlogId, offset, new PeopleUtils.FetchUsersCallback() { @Override public void onSuccess(List<Person> peopleList, boolean isEndOfList) { boolean isFreshList = (offset == 0); mCanRefreshUsers = false; mUsersEndOfListReached = isEndOfList; PeopleTable.saveUsers(peopleList, localTableBlogId, isFreshList); PeopleListFragment peopleListFragment = getListFragment(); if (peopleListFragment != null) { peopleListFragment.fetchingRequestFinished(PeopleListFilter.TEAM, isFreshList, true); } refreshOnScreenFragmentDetails(); mUsersFetchRequestInProgress = false; } @Override public void onError() { PeopleListFragment peopleListFragment = getListFragment(); if (peopleListFragment != null) { boolean isFirstPage = offset == 0; peopleListFragment.fetchingRequestFinished(PeopleListFilter.TEAM, isFirstPage, false); } mUsersFetchRequestInProgress = false; ToastUtils.showToast(PeopleManagementActivity.this, R.string.error_fetch_users_list, ToastUtils.Duration.SHORT); } }); return true; }

Target:
private boolean fetchUsersList(String dotComBlogId, final int localTableBlogId, final int offset) { if (mUsersEndOfListReached || mUsersFetchRequestInProgress || !NetworkUtils.checkConnection(this)) { return false; } mUsersFetchRequestInProgress = true; PeopleUtils.fetchUsers(dotComBlogId, localTableBlogId, offset, new PeopleUtils.FetchUsersCallback() { @Override public void onSuccess(List<Person> peopleList, boolean isEndOfList) { boolean isFreshList = (offset == 0); mHasRefreshedUsers = true; mUsersEndOfListReached = isEndOfList; PeopleTable.saveUsers(peopleList, localTableBlogId, isFreshList); PeopleListFragment peopleListFragment = getListFragment(); if (peopleListFragment != null) { peopleListFragment.fetchingRequestFinished(PeopleListFilter.TEAM, isFreshList, true); } refreshOnScreenFragmentDetails(); mUsersFetchRequestInProgress = false; } @Override public void onError() { PeopleListFragment peopleListFragment = getListFragment(); if (peopleListFragment != null) { boolean isFirstPage = offset == 0; peopleListFragment.fetchingRequestFinished(PeopleListFilter.TEAM, isFirstPage, false); } mUsersFetchRequestInProgress = false; ToastUtils.showToast(PeopleManagementActivity.this, R.string.error_fetch_users_list, ToastUtils.Duration.SHORT); } }); return true; }
Source:
private String insanelyHugeCommitMessage() { StringBuilder b = new StringBuilder(HUGE_SIZE); b.append("An insanely huge commit message\n\n"); String oneLine = "012345678901234567890123456789012345678901234567890123456789\n"; while (b.length() < HUGE_SIZE) { b.append(oneLine); } return b.toString(); }

Target:
private String insanelyHugeCommitMessage() { final String oneLine = "012345678901234567890123456789012345678901234567890123456789\n"; StringBuilder b = new StringBuilder(HUGE_SIZE + oneLine.length()); b.append("An insanely huge commit message\n\n"); while (b.length() < HUGE_SIZE) { b.append(oneLine); } return b.toString(); }
Source:
public boolean checkHaReservationStatusForCluster(VDSGroup cluster, List<VDS> failedHosts) { List<VDS> hosts = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(cluster.getId()); if (hosts == null) { return true; } if (hosts.size() < 2) { return false; } List<Pair<Guid, Pair<Integer, Integer>>> hostsUnutilizedResources = getUnutilizedResources(hosts); List<VM> vmInCluster = DbFacade.getInstance().getVmDao().getAllForVdsGroup(cluster.getId()); if (vmInCluster == null) { return true; } vmInCluster = LinqUtils.filter(vmInCluster, new Predicate<VM>() { @Override public boolean eval(VM v) { return v.isAutoStartup(); } }); Map<Guid, List<VM>> hostToHaVmsMapping = mapVmToHost(vmInCluster); for (VDS host : hosts) { boolean isHaSafe = findReplacementForHost(cluster, host, hostToHaVmsMapping.get(host.getId()), hostsUnutilizedResources); if (!isHaSafe) { failedHosts.add(host); } } if (failedHosts.size() == 0) { return true; } else { return false; } }

Target:
public boolean checkHaReservationStatusForCluster(VDSGroup cluster, List<VDS> failedHosts) { List<VDS> hosts = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(cluster.getId()); if (hosts == null || hosts.isEmpty()) { return true; } if (hosts.size() < 2) { failedHosts.addAll(hosts); return false; } List<Pair<Guid, Pair<Integer, Integer>>> hostsUnutilizedResources = getUnutilizedResources(hosts); Map<Guid, List<VM>> hostToHaVmsMapping = mapHaVmToHostByCluster(cluster.getId()); for (VDS host : hosts) { if (hostToHaVmsMapping.get(host.getId()) != null) { boolean isHaSafe = findReplacementForHost(cluster, host, hostToHaVmsMapping.get(host.getId()), hostsUnutilizedResources); if (!isHaSafe) { failedHosts.add(host); } } } return failedHosts.isEmpty(); }
Source:
public void addItemToNonListPropertyTest() throws IOException, OperationException { String fieldsDataAsJSon = readPropertiesFromFile("newFields.json"); OperationContext ctx = new OperationContext(coreSession); ctx.setInput(doc); OperationChain chain = new OperationChain("testChain"); chain.add(AddItemToListProperty.ID).set("xpath", "dc:title").set("ComplexJsonProperties", fieldsDataAsJSon); DocumentModel resultDoc = (DocumentModel) service.run(ctx, chain); }

Target:
public void addItemToNonListPropertyTest() throws IOException, OperationException { String fieldsDataAsJson = readPropertiesFromFile("newFields.json"); OperationContext ctx = new OperationContext(coreSession); ctx.setInput(doc); OperationChain chain = new OperationChain("testChain"); chain.add(AddItemToListProperty.ID).set("xpath", "dc:title").set("complexJsonProperties", fieldsDataAsJson); DocumentModel resultDoc = (DocumentModel) service.run(ctx, chain); }
Source:
public static void signout(Context context) { try { signOut(); } catch (IllegalStateException e) { initialize(context); signOut(); } }

Target:
public static void signout(Context context) { try { Twitter.getInstance(); } catch (IllegalStateException e) { initialize(context); } signOut(); }
Source:
public CompletionTime processOneToOne(String tenantId, Span item) throws RetryAttemptException { if (item.topLevelSpan()) { CompletionTime ct = new CompletionTime(); ct.setId(item.getId()); URL url = item.url(); if (url != null) { if (item.clientSpan()) { ct.setUri(Constants.URI_CLIENT_PREFIX + url.getPath()); } else { ct.setUri(url.getPath()); } ct.setEndpointType(url.getProtocol() == null ? null : url.getProtocol().toUpperCase()); } else { ct.setEndpointType("Unknown"); } ct.setDuration(TimeUnit.MILLISECONDS.convert(item.getDuration(), TimeUnit.NANOSECONDS)); ct.setTimestamp(item.getTimestamp()/1000); ct.setOperation(SpanDeriverUtil.deriveOperation(item)); ct.setFault(SpanDeriverUtil.deriveFault(item)); List<Property> spanProperties = item.properties(); ct.getProperties().addAll(spanProperties); ct.setHostAddress(Span.ipv4Address(spanProperties)); if (log.isLoggable(Level.FINEST)) { log.finest("TraceCompletionTimeDeriver span=" + item + " ret=" + ct); } return ct; } return null; }

Target:
public CompletionTime processOneToOne(String tenantId, Span item) throws RetryAttemptException { if (item.topLevelSpan()) { CompletionTime ct = new CompletionTime(); ct.setId(item.getId()); URL url = item.url(); if (url != null) { if (item.clientSpan()) { ct.setUri(Constants.URI_CLIENT_PREFIX + url.getPath()); } else { ct.setUri(url.getPath()); } ct.setEndpointType(url.getProtocol() == null ? null : url.getProtocol().toUpperCase()); } else { ct.setEndpointType("Unknown"); } ct.setDuration(TimeUnit.MILLISECONDS.convert(item.getDuration(), TimeUnit.NANOSECONDS)); ct.setTimestamp(item.getTimestamp()/1000); ct.setOperation(SpanDeriverUtil.deriveOperation(item)); ct.setFault(SpanDeriverUtil.deriveFault(item)); List<Property> spanProperties = item.properties(); ct.getProperties().addAll(spanProperties); ct.setHostAddress(Span.ipv4Address(spanProperties)); if (log.isLoggable(Level.FINEST)) { log.finest("TraceCompletionTimeDeriver span=" + item + " completion time=" + ct); } return ct; } return null; }
Source:
public void testHeaderRowCountDoesNotMatch() { ConcurRequestExtractFile testFile = buildConcurRequestExtractFile(); testFile.setRecordCount(new Integer(3)); if (concurRequestExtractFileValidationService.fileRowCountMatchesHeaderRowCount(testFile)) { assertTrue("Invalid: Header row count matched file row count. They should NOT have matched.", false); } else { assertTrue("Valid: Header row count did NOT match file row count.", true); } }

Target:
public void testHeaderRowCountDoesNotMatch() { List<ConcurRequestExtractFile> testFiles = ConcurRequestExtractFileFixture.BAD_FILE_COUNT_FILE.createConcurRequestExtractFiles(); assertFalse("Expected Result: Header row count should NOT match file row count.", concurRequestExtractFileValidationService.requestExtractHeaderRowValidatesToFileContents(testFiles)); }
Source:
@Test public void implicitError() throws Exception { Controller c = new PowershellScript("$ErrorActionPreference = 'Stop'; Write-Error \"Bogus error\"").launch(new EnvVars(), ws, launcher, listener); while (c.exitStatus(ws, launcher, listener) == null) { Thread.sleep(100); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws, baos); assertTrue(c.exitStatus(ws, launcher).intValue() != 0); assertTrue(baos.toString().contains("Bogus error")); c.cleanup(ws); }

Target:
@Test public void implicitError() throws Exception { Controller c = new PowershellScript("$ErrorActionPreference = 'Stop'; Write-Error \"Bogus error\"").launch(new EnvVars(), ws, launcher, listener); while (c.exitStatus(ws, launcher, listener) == null) { Thread.sleep(100); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); c.writeLog(ws, baos); assertTrue(c.exitStatus(ws, launcher).intValue() != 0); assertThat(baos.toString(), containsString("Bogus error")); c.cleanup(ws); }
Source:
private static void format(List<FileResource<?>> fileResourceList, Properties formatProfile) { for (FileResource<?> fileResource : fileResourceList) { if (fileResource.isDirectory()) { List<FileResource<?>> newFileResourceList = new ArrayList<>(); List<Resource<?>> resourceList = fileResource.listResources(); for (Resource<?> resource : resourceList) { newFileResourceList.add(resource.reify(FileResource.class)); } format(newFileResourceList, formatProfile); } else if (fileResource.getName().endsWith(".java")) { fileResource.setContents(Roaster.format(formatProfile, fileResource.getContents())); } } }

Target:
private static void format(List<FileResource<?>> fileResourceList, Properties formatProfile) { for (FileResource<?> fileResource : fileResourceList) { if (fileResource.isDirectory()) { List<FileResource<?>> newFileResourceList = new ArrayList<>(); List<Resource<?>> resourceList = fileResource.listResources(); for (Resource<?> resource : resourceList) newFileResourceList.add(resource.reify(FileResource.class)); format(newFileResourceList, formatProfile); } else if (fileResource instanceof JavaResource) { if (formatProfile == null) fileResource.setContents(Roaster.format(fileResource.getContents())); else fileResource.setContents(Roaster.format(formatProfile, fileResource.getContents())); } } }
Source:
public void createSavepoint() { String savepointName = "eee" + this.hashCode(); if (savepointName.length() > 10) savepointName = savepointName.substring(1, 9); savepoint = null; try { savepoint = statement.getConnection().setSavepoint(savepointName); } catch (SQLException e) { e.printStackTrace(); } }

Target:
public void createSavepoint() { String savepointName = "eee" + this.hashCode(); if (savepointName.length() > 10) savepointName = savepointName.substring(1, 9); savepoint = null; try { savepoint = statement.getConnection().setSavepoint(savepointName); } catch (SQLException e) { throw new RuntimeException("Exception while setting savepoint", e); } }
Source:
public void launch(List<ModuleLaunchRequest> moduleLaunchRequests, boolean aggregate, String parentArgs[]) { List<ModuleLaunchRequest> reversed = new ArrayList<>(moduleLaunchRequests); Collections.reverse(reversed); if (moduleLaunchRequests.size() == 1 || !aggregate) { launchModulesIndividually(moduleLaunchRequests); } else { aggregateAndLaunchModules(moduleLaunchRequests, parentArgs); } }

Target:
public void launch(List<ModuleLaunchRequest> moduleLaunchRequests, boolean aggregate, String parentArgs[]) { List<ModuleLaunchRequest> reversed = new ArrayList<>(moduleLaunchRequests); Collections.reverse(reversed); if (moduleLaunchRequests.size() == 1 || !aggregate) { launchIndividualModules(moduleLaunchRequests); } else { launchAggregatedModules(moduleLaunchRequests, parentArgs); } }
Source:
private int newOrderIndex(SAMRecord read, int oldIndex, Map<Integer, Integer> newOrder) { if (oldIndex == NO_ALIGNMENT_REFERENCE_INDEX) return NO_ALIGNMENT_REFERENCE_INDEX; else { final Integer n = newOrder.get(oldIndex); if (n == null) throw new PicardException("BUG: no mapping found for read " + read.getSAMString()); else return n; } }

Target:
private int newOrderIndex(SAMRecord read, int oldIndex, Map<Integer, Integer> newOrder) { if (oldIndex == NO_ALIGNMENT_REFERENCE_INDEX) { return NO_ALIGNMENT_REFERENCE_INDEX; } else { final Integer n = newOrder.get(oldIndex); if (n == null) { throw new PicardException("BUG: no mapping found for read " + read.getSAMString()); } else { return n; } } }
Source:
public APIMethodCaller<T> fetch(String id) { return this.fetch().addPathComponent("id", id); }

Target:
public APIMethodCaller<T> fetch(String id) { return this.fetch().addParam("id", id); }
Source:
public void init() throws Exception { try { final DefaultConfigurationBuilder objectConfiguration = new DefaultConfigurationBuilder(); objectConfiguration.addProperty("[@destinationURL]", destination); objectRepository = new FilePersistentObjectRepository(); objectRepository.setFileSystem(fileSystem); objectRepository.configure(objectConfiguration); objectRepository.init(); LOGGER.debug("{} created in {}", getClass().getName(), destination); } catch (Exception e) { LOGGER.error("Failed to initialize repository: {}", e.getMessage(), e); throw e; } }

Target:
public void init() throws Exception { try { final DefaultConfigurationBuilder objectConfiguration = new DefaultConfigurationBuilder(); objectConfiguration.addProperty("[@destinationURL]", destination); objectRepository = new FilePersistentObjectRepository(); objectRepository.setFileSystem(fileSystem); objectRepository.configure(objectConfiguration); objectRepository.init(); LOGGER.debug("{} created in {}", getClass().getName(), destination); } catch (Exception e) { LOGGER.error("Failed to initialize repository", e); throw e; } }
Source:
public void visitFunctionInvocation(FunctionInvocation functionInvocation) { String name = functionInvocation.getName().replaceAll("\\.", "#"); String typeDef = goloFunctionSignature(functionInvocation.getArity()); Handle handle = FUNCTION_INVOCATION_HANDLE; List<Object> bootstrapArgs = new ArrayList<>(); bootstrapArgs.add(functionInvocation.isConstant() ? 1 : 0); if (functionInvocation.isOnReference()) { ReferenceTable table = context.referenceTableStack.peek(); methodVisitor.visitVarInsn(ALOAD, table.get(functionInvocation.getName()).getIndex()); } if (functionInvocation.isOnModuleState()) { visitReferenceLookup(new ReferenceLookup(functionInvocation.getName())); } if (functionInvocation.isAnonymous() || functionInvocation.isOnReference() || functionInvocation.isOnModuleState()) { methodVisitor.visitTypeInsn(CHECKCAST, "java/lang/invoke/MethodHandle"); MethodType type = genericMethodType(functionInvocation.getArity() + 1).changeParameterType(0, MethodHandle.class); typeDef = type.toMethodDescriptorString(); handle = CLOSURE_INVOCATION_HANDLE; } List<String> argumentNames = visitInvocationArguments(functionInvocation); bootstrapArgs.addAll(argumentNames); methodVisitor.visitInvokeDynamicInsn(name, typeDef, handle, bootstrapArgs.toArray()); for (FunctionInvocation invocation : functionInvocation.getAnonymousFunctionInvocations()) { invocation.accept(this); } }

Target:
public void visitFunctionInvocation(FunctionInvocation functionInvocation) { String name = functionInvocation.getName().replaceAll("\\.", "#"); String typeDef = goloFunctionSignature(functionInvocation.getArity()); Handle handle = FUNCTION_INVOCATION_HANDLE; List<Object> bootstrapArgs = new ArrayList<>(); bootstrapArgs.add(functionInvocation.isConstant() ? 1 : 0); if (functionInvocation.isOnReference()) { ReferenceTable table = context.referenceTableStack.peek(); methodVisitor.visitVarInsn(ALOAD, table.get(functionInvocation.getName()).getIndex()); } if (functionInvocation.isOnModuleState()) { visitReferenceLookup(new ReferenceLookup(functionInvocation.getName())); } if (functionInvocation.isAnonymous() || functionInvocation.isOnReference() || functionInvocation.isOnModuleState()) { methodVisitor.visitTypeInsn(CHECKCAST, "gololang/FunctionReference"); MethodType type = genericMethodType(functionInvocation.getArity() + 1).changeParameterType(0, FunctionReference.class); typeDef = type.toMethodDescriptorString(); handle = CLOSURE_INVOCATION_HANDLE; } List<String> argumentNames = visitInvocationArguments(functionInvocation); bootstrapArgs.addAll(argumentNames); methodVisitor.visitInvokeDynamicInsn(name, typeDef, handle, bootstrapArgs.toArray()); for (FunctionInvocation invocation : functionInvocation.getAnonymousFunctionInvocations()) { invocation.accept(this); } }
Source:
protected ResultIterator newIterator(ParallelScanGrouper scanGrouper) throws SQLException { ResultIterator scanner = new ResultIterator() { private final Iterator<Tuple> tupleIterator = tuples.iterator(); private boolean closed = false; private int count = 0; @Override public void close() throws SQLException { this.closed = true;; } @Override public Tuple next() throws SQLException { while (!this.closed && (offset != null && count < offset) && tupleIterator.hasNext()) { count++; tupleIterator.next(); } if (!this.closed && (limit == null || count++ < limit) && tupleIterator.hasNext()) { return tupleIterator.next(); } return null; } @Override public void explain(List<String> planSteps) { } }; if (context.getSequenceManager().getSequenceCount() > 0) { scanner = new SequenceResultIterator(scanner, context.getSequenceManager()); } return scanner; }

Target:
protected ResultIterator newIterator(ParallelScanGrouper scanGrouper) throws SQLException { ResultIterator scanner = new ResultIterator() { private final Iterator<Tuple> tupleIterator = tuples.iterator(); private boolean closed = false; private int count = 0; private int offsetCount = 0; @Override public void close() throws SQLException { this.closed = true;; } @Override public Tuple next() throws SQLException { while (!this.closed && (offset != null && offsetCount < offset) && tupleIterator.hasNext()) { offsetCount++; tupleIterator.next(); } if (!this.closed && (limit == null || count++ < limit) && tupleIterator.hasNext()) { return tupleIterator.next(); } return null; } @Override public void explain(List<String> planSteps) { } }; if (context.getSequenceManager().getSequenceCount() > 0) { scanner = new SequenceResultIterator(scanner, context.getSequenceManager()); } return scanner; }
Source:
public boolean apply(Game game, Ability source) { Map<UUID, Integer> destroyedArtifactPerPlayer = new HashMap<>(); for (UUID targetID : this.targetPointer.getTargets(game, source)) { Permanent permanent = game.getPermanent(targetID); if (permanent != null) { if (permanent.destroy(source.getSourceId(), game, false)) { if (game.getState().getZone(permanent.getId()) == Zone.GRAVEYARD) { destroyedArtifactPerPlayer.merge(permanent.getControllerId(), 1, Integer::sum); } } } } for (Map.Entry<UUID, Integer> entry : destroyedArtifactPerPlayer.entrySet()) { Player player = game.getState().getPlayer(entry.getKey()); player.damage(entry.getValue(), source.getSourceId(), game, false, true); } return true; }

Target:
public boolean apply(Game game, Ability source) { Map<UUID, Integer> destroyedArtifactPerPlayer = new HashMap<>(); for (UUID targetID : this.targetPointer.getTargets(game, source)) { Permanent permanent = game.getPermanent(targetID); if (permanent != null) { if (permanent.destroy(source.getSourceId(), game, false)) { if (game.getState().getZone(permanent.getId()) == Zone.GRAVEYARD) { destroyedArtifactPerPlayer.merge(permanent.getControllerId(), 1, Integer::sum); } } } } for (Map.Entry<UUID, Integer> entry : destroyedArtifactPerPlayer.entrySet()) { Player player = game.getPlayer(entry.getKey()); if(player != null) { player.damage(entry.getValue(), source.getSourceId(), game, false, true); } } return true; }
Source:
public void mucRoleTestForReceivingModerator() throws Exception { EntityBareJid mucAddress = getRandomRoom("smack-inttest-"); MultiUserChat mucAsSeenByOne = mucManagerOne.getMultiUserChat(mucAddress); MultiUserChat mucAsSeenByTwo = mucManagerTwo.getMultiUserChat(mucAddress); final ResultSyncPoint<String, Exception> resultSyncPoint = new ResultSyncPoint<>(); mucAsSeenByTwo.addUserStatusListener(new UserStatusListener() { @Override public void moderatorGranted() { resultSyncPoint.signal("done"); } }); MucCreateConfigFormHandle handle = mucAsSeenByOne.createOrJoin(Resourcepart.from("one-" + randomString)); try { if (handle != null) { handle.makeInstant(); } final Resourcepart nicknameTwo = Resourcepart.from("two-" + randomString); mucAsSeenByTwo.join(nicknameTwo); mucAsSeenByOne.grantModerator(nicknameTwo); resultSyncPoint.waitForResult(timeout); } finally { tryDestroy(mucAsSeenByOne); } }

Target:
public void mucRoleTestForReceivingModerator() throws Exception { EntityBareJid mucAddress = getRandomRoom("smack-inttest"); MultiUserChat mucAsSeenByOne = mucManagerOne.getMultiUserChat(mucAddress); MultiUserChat mucAsSeenByTwo = mucManagerTwo.getMultiUserChat(mucAddress); final ResultSyncPoint<String, Exception> resultSyncPoint = new ResultSyncPoint<>(); mucAsSeenByTwo.addUserStatusListener(new UserStatusListener() { @Override public void moderatorGranted() { resultSyncPoint.signal("done"); } }); createMUC(mucAsSeenByOne, "one-" + randomString); final Resourcepart nicknameTwo = Resourcepart.from("two-" + randomString); mucAsSeenByTwo.join(nicknameTwo); mucAsSeenByOne.grantModerator(nicknameTwo); try { resultSyncPoint.waitForResult(timeout); } catch (TimeoutException e) { throw new AssertionError("Failed to receive presence"); } finally { tryDestroy(mucAsSeenByOne); } }
Source:
public void testCreateIDoc() throws Exception { File file = new File("data/testRegistry.ecore"); IDocUtil.loadRegistry(file); EPackage ePackage = EPackage.Registry.INSTANCE.getEPackage("<LINK_0>"); assertNotNull("Failded to load base IDoc package", ePackage); ePackage = EPackage.Registry.INSTANCE.getEPackage("<LINK_0>/NPL/HRMD_B01 assertNotNull("Failed to load derived IDoc package", ePackage); Document document = IDocUtil.createDocument("NPL", "HRMD_B01", null, "31G", null); assertNotNull("Failed to create IDoc document", document); assertEquals("New IDoc document has incorrect IDoc type", "HRMD_B01", document.getIDocType()); assertEquals("New IDoc document has incorrect IDoc type extension", "", document.getIDocTypeExtension()); Segment rootSegment = document.getRootSegment(); assertEquals("New IDoc document has incorrect root segment type", "ROOT", rootSegment.getType()); assertEquals("Root segment of new IDoc document has incorrect hierarchy level", 1, rootSegment.getHierarchyLevel()); assertNotNull("Document reference not assinged to root segment", rootSegment.getDocument()); }

Target:
public void testCreateIDoc() throws Exception { File file = new File("data/testRegistry.ecore"); IDocUtil.loadRegistry(file); EPackage ePackage = EPackage.Registry.INSTANCE.getEPackage("<LINK_0>"); assertNotNull("Failded to load base IDoc package", ePackage); ePackage = EPackage.Registry.INSTANCE.getEPackage("<LINK_0>/NPL/HRMD_B01 assertNotNull("Failed to load derived IDoc package", ePackage); Document document = IDocUtil.createDocument("NPL", "HRMD_B01", null, "31G", null); assertNotNull("Failed to create IDoc document", document); assertEquals("New IDoc document has incorrect IDoc type", "HRMD_B01", document.getIDocType()); assertEquals("New IDoc document has incorrect IDoc type extension", "", document.getIDocTypeExtension()); Segment rootSegment = document.getRootSegment(); assertEquals("New IDoc document has incorrect root segment type", "ROOT", rootSegment.getType()); assertEquals("Root segment of new IDoc document has incorrect hierarchy level", 1, rootSegment.getHierarchyLevel()); assertNotNull("Document reference not assigned to root segment", rootSegment.getDocument()); }
Source:
public void engineIsRunningNotification() { try { log.debug("DWH Heart Beat - Start"); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, () -> { heartBeatVar.setDateTime(new Date()); dwhHistoryTimekeepingDao.save(heartBeatVar); log.debug("DWH Heart Beat - End"); return null; }); } catch (Exception ex) { log.error("Error updating DWH Heart Beat: {}", ex.getMessage()); log.debug("Exception", ex); } }

Target:
public void engineIsRunningNotification() { try { log.debug("DWH Heart Beat - Start"); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, () -> { heartBeatVar.setDateTime(new Date()); dwhHistoryTimekeepingDao.save(heartBeatVar); return null; }); log.debug("DWH Heart Beat - End"); } catch (Exception ex) { log.error("Error updating DWH Heart Beat: {}", ex.getMessage()); log.debug("Exception", ex); } }
Source:
public synchronized boolean deregister(String method) { oneToOneHandlers.remove(method); oneToManyHandlers.remove(method); oneToNoneHandlers.remove(method); manyToOneHandlers.remove(method); manyToManyHandlers.remove(method); manyToNoneHandlers.remove(method); noneToOneHandlers.remove(method); noneToManyHandlers.remove(method); noneToNoneHandlers.remove(method); return methodToCategory.remove(method) != null; }

Target:
public synchronized boolean deregister(String method) { Category category = methodToCategory.remove(method); if (category == null) { return false; } switch (category) { case ONE_TO_ONE: oneToOneHandlers.remove(method); break; case ONE_TO_MANY: oneToManyHandlers.remove(method); break; case ONE_TO_NONE: oneToNoneHandlers.remove(method); break; case MANY_TO_ONE: manyToOneHandlers.remove(method); break; case MANY_TO_MANY: manyToManyHandlers.remove(method); break; case MANY_TO_NONE: manyToNoneHandlers.remove(method); break; case NONE_TO_ONE: noneToOneHandlers.remove(method); break; case NONE_TO_MANY: noneToManyHandlers.remove(method); break; case NONE_TO_NONE: noneToNoneHandlers.remove(method); } return true; }
Source:
public void executeCommand(Command command, ExecutionHandlerContext context) { if (command.getProcessedCommand().size() < 2) { command .setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.GETEXECUTOR)); return; } ByteArrayWrapper key = command.getKey(); checkDataType(key, RedisDataType.REDIS_STRING, context); Region<ByteArrayWrapper, ByteArrayWrapper> r = context.getRegionProvider().getStringsRegion(); ByteArrayWrapper wrapper = r.get(key); respondBulkStrings(command, context, wrapper); }

Target:
public void executeCommand(Command command, ExecutionHandlerContext context) { if (command.getProcessedCommand().size() < 2) { command .setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.GETEXECUTOR)); return; } ByteArrayWrapper key = command.getKey(); checkDataType(key, RedisDataType.REDIS_STRING, context); Region<ByteArrayWrapper, ByteArrayWrapper> region = context.getRegionProvider().getStringsRegion(); ByteArrayWrapper wrapper = region.get(key); respondBulkStrings(command, context, wrapper); }
Source:
private void shareEmbroideryFile() { if (stageListener.embroideryList.size() > 1) { String filename = FileMetaDataExtractor.encodeSpecialCharsForFileSystem(ProjectManager.getInstance().getCurrentProject().getName()); DSTFileGenerator dstFileGenerator = new DSTFileGenerator(stageListener.embroideryList); File dstFile = new File(Constants.CACHE_DIR, filename + ".dst"); if (dstFile.exists()) { dstFile.delete(); } try { if (dstFile.createNewFile()) { dstFileGenerator.writeToDSTFile(dstFile); new ExportEmbroideryFileLauncher(stageActivity, dstFile).startActivity(); } } catch (IOException e) { ToastUtil.showError(stageActivity, R.string.error_embroidery_file_export); Log.e(TAG, "Writing to dst file failed"); } } dismiss(); }

Target:
private void shareEmbroideryFile() { if (stageListener.embroideryList.size() > 1) { String filename = FileMetaDataExtractor.encodeSpecialCharsForFileSystem(ProjectManager.getInstance().getCurrentProject().getName()); DSTFileGenerator dstFileGenerator = new DSTFileGenerator(stageListener.embroideryList); File dstFile = new File(Constants.CACHE_DIR, filename + Constants.EMBROIDERY_FILE_EXTENSION); if (dstFile.exists()) { dstFile.delete(); } try { if (dstFile.createNewFile()) { dstFileGenerator.writeToDSTFile(dstFile); new ExportEmbroideryFileLauncher(stageActivity, dstFile).startActivity(); } } catch (IOException e) { ToastUtil.showError(stageActivity, R.string.error_embroidery_file_export); Log.e(TAG, "Writing to dst file failed"); } } dismiss(); }
Source:
public void start() { if (isRunning()) { return; } try { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.defaultPartitionSuffix); config.addAdditionalBindCredentials("uid=admin,ou=system", "secret"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", this.port)); config.setEnforceSingleStructuralObjectClass(false); config.setEnforceAttributeSyntaxCompliance(true); DN dn = new DN(this.defaultPartitionSuffix); Entry entry = new Entry(dn); entry.addAttribute("objectClass", "top", "domain", "extensibleObject"); entry.addAttribute("dc", dn.getRDN().getAttributeValues()[0]); InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config); directoryServer.add(entry); importLdif(directoryServer); directoryServer.startListening(); this.port = directoryServer.getListenPort(); this.directoryServer = directoryServer; this.running = true; } catch (LDAPException ex) { throw new RuntimeException("Server startup failed", ex); } catch (IllegalArgumentException ex){ throw ex; } }

Target:
public void start() { if (isRunning()) { return; } try { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.defaultPartitionSuffix); config.addAdditionalBindCredentials("uid=admin,ou=system", "secret"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", this.port)); config.setEnforceSingleStructuralObjectClass(false); config.setEnforceAttributeSyntaxCompliance(true); DN dn = new DN(this.defaultPartitionSuffix); Entry entry = new Entry(dn); entry.addAttribute("objectClass", "top", "domain", "extensibleObject"); entry.addAttribute("dc", dn.getRDN().getAttributeValues()[0]); InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config); directoryServer.add(entry); importLdif(directoryServer); directoryServer.startListening(); this.port = directoryServer.getListenPort(); this.directoryServer = directoryServer; this.running = true; } catch (LDAPException ex) { throw new RuntimeException("Server startup failed", ex); } }