auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void markCanBeCompleted(Long id) { completedOperationIds.offer(id); if (outstandingOperationsCount.decrementAndGet() == 0) { synchronized (this) { notify(); } } }

Target:
public void markCanBeCompleted(Long id) { completedOperationIds.offer(id); if (this.isFlushing.get() && completedOperationIds.size() == pendingOperationsWithSize.size()) { synchronized (this) { notify(); } } }
Source:
public void onNext(final DataOperation<Long> op) { final LongKeyOperation operation = (LongKeyOperation) op; final String dataType = operation.getDataType(); final List<LongRange> dataKeyRanges = operation.getDataKeyRanges(); final Map<Integer, LongRange> blockToSubKeyRangeMap; final Iterator<LongRange> rangeIterator = dataKeyRanges.iterator(); if (rangeIterator.hasNext()) { final LongRange keyRange = rangeIterator.next(); blockToSubKeyRangeMap = router.resolveBlocks(keyRange); } else { LOG.log(Level.SEVERE, "Invalid operation"); return; } while (rangeIterator.hasNext()) { final LongRange keyRange = rangeIterator.next(); blockToSubKeyRangeMap.putAll(router.resolveBlocks(keyRange)); } final int numSubOps = blockToSubKeyRangeMap.size(); resultAggregator.registerOp(operation, numSubOps); if (!blockToSubKeyRangeMap.isEmpty()) { if (typeToBlocks.containsKey(dataType)) { enqueueOperation(operation, blockToSubKeyRangeMap); } else { if (operation.getOperationType() == DataOpType.PUT) { initBlocks(dataType); enqueueOperation(operation, blockToSubKeyRangeMap); } } } }

Target:
public void onNext(final DataOperation<Long> op) { final LongKeyOperation operation = (LongKeyOperation) op; final String dataType = operation.getDataType(); final List<LongRange> dataKeyRanges = operation.getDataKeyRanges(); final Map<Integer, Pair<Long, Long>> blockToSubKeyRangeMap; final Iterator<LongRange> rangeIterator = dataKeyRanges.iterator(); if (rangeIterator.hasNext()) { final LongRange keyRange = rangeIterator.next(); blockToSubKeyRangeMap = router.resolveBlocks(keyRange.getMinimumLong(), keyRange.getMaximumLong()); } else { LOG.log(Level.SEVERE, "Invalid operation"); resultAggregator.submitLocalResult(operation, Collections.EMPTY_MAP, Collections.EMPTY_LIST); return; } while (rangeIterator.hasNext()) { final LongRange keyRange = rangeIterator.next(); blockToSubKeyRangeMap.putAll(router.resolveBlocks(keyRange.getMinimumLong(), keyRange.getMaximumLong())); } final int numSubOps = blockToSubKeyRangeMap.size(); resultAggregator.registerOp(operation, numSubOps); if (!blockToSubKeyRangeMap.isEmpty()) { if (typeToBlocks.containsKey(dataType)) { enqueueOperation(operation, blockToSubKeyRangeMap); } else { if (operation.getOperationType() == DataOpType.PUT) { initBlocks(dataType); enqueueOperation(operation, blockToSubKeyRangeMap); } } } }
Source:
public boolean hasEmptyAnnotationProcessors(Project project, String configurationString) { Optional<Configuration> configuration = getConfiguration(project, configurationString); return configuration.map(files -> hasEmptyAnnotationProcessors(project, files)).orElse(true); }

Target:
public boolean hasEmptyAnnotationProcessors(Project project, String configurationString) { Optional<Configuration> configuration = getConfiguration(project, configurationString); return configuration.map(config -> hasEmptyAnnotationProcessors(project, config)).orElse(false); }
Source:
public void init() { super.init(); setStorageDomainId(getDiskImage().getStorageIds().get(0)); setStoragePoolId(getDiskImage().getStoragePoolId()); setImageGroupId(getDiskImage().getId()); setVm(vmDao .getVmsWithPlugInfo(getDiskImage().getId()) .stream() .filter(p -> p.getFirst().getStatus().isRunning()) .filter(p -> p.getSecond().isPlugged()) .map(Pair::getFirst) .findFirst() .orElse(null)); if (getVm() != null) { setVdsId(getVm().getRunOnVds()); } }

Target:
public void init() { super.init(); if (getDiskImage() == null) { return; } setStorageDomainId(getDiskImage().getStorageIds().get(0)); setStoragePoolId(getDiskImage().getStoragePoolId()); setImageGroupId(getDiskImage().getId()); setVm(vmDao .getVmsWithPlugInfo(getDiskImage().getId()) .stream() .filter(p -> p.getFirst().getStatus().isRunning()) .filter(p -> p.getSecond().isPlugged()) .map(Pair::getFirst) .findFirst() .orElse(null)); if (getVm() != null) { setVdsId(getVm().getRunOnVds()); } }
Source:
public void requestActivityInfo(ResultReceiver result) { Bundle bundle = new Bundle(); mLog.trace("requestedActivityInfo uid=%").c(Binder.getCallingUid()).flush(); bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, reportActivityInfo()); result.send(0, bundle); }

Target:
public void requestActivityInfo(ResultReceiver result) { Bundle bundle = new Bundle(); mLog.trace("requestActivityInfo uid=%").c(Binder.getCallingUid()).flush(); bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, reportActivityInfo()); result.send(0, bundle); }
Source:
private static Optional<KeychainAccessStrategy> constructKeychainAccess() { if (!SystemUtils.IS_OS_LINUX) return Optional.empty(); try { Class<?> clazz = Class.forName("org.cryptomator.keychain.LinuxSecretServiceKeychainAccessImpl"); KeychainAccessStrategy instance = (KeychainAccessStrategy) clazz.getDeclaredConstructor().newInstance(); if (instance.isSupported()) return Optional.of(instance); clazz = Class.forName("org.cryptomator.keychain.LinuxKDEWalletKeychainAccessImpl"); instance = (KeychainAccessStrategy) clazz.getDeclaredConstructor().newInstance(); return Optional.of(instance); } catch (Exception e) { return Optional.empty(); } }

Target:
private static Optional<KeychainAccessStrategy> constructKeychainAccess() { try { Class<?> clazz = Class.forName("org.cryptomator.keychain.LinuxSecretServiceKeychainAccessImpl"); KeychainAccessStrategy instance = (KeychainAccessStrategy) clazz.getDeclaredConstructor().newInstance(); if (instance.isSupported()) return Optional.of(instance); clazz = Class.forName("org.cryptomator.keychain.LinuxKDEWalletKeychainAccessImpl"); instance = (KeychainAccessStrategy) clazz.getDeclaredConstructor().newInstance(); return Optional.of(instance); } catch (Exception e) { return Optional.empty(); } }
Source:
private void selectFirstDiffOrDisplayLabelViewer(final Comparison comparison) { if (comparison != null) { List<Diff> differences = comparison.getDifferences(); if (differences.size() == 0) { navigatable.fireOpen(new NoDifferencesCompareInput()); } else if (JFaceUtil.filterVisibleElement(getViewer(), IS_DIFF).size() == 0) { navigatable.fireOpen(new NoVisibleDifferencesCompareInput()); } else { navigatable.selectChange(INavigatable.FIRST_CHANGE); } } }

Target:
private void selectFirstDiffOrDisplayLabelViewer(final Comparison comparison) { if (comparison != null) { List<Diff> differences = comparison.getDifferences(); if (differences.isEmpty()) { navigatable.fireOpen(new NoDifferencesCompareInput()); } else if (JFaceUtil.filterVisibleElement(getViewer(), IS_DIFF).isEmpty()) { navigatable.fireOpen(new NoVisibleItemCompareInput()); } else { navigatable.selectChange(INavigatable.FIRST_CHANGE); } } }
Source:
public void shutDownTask(TaskDefinition task) throws SchedulerException { if (Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { Context.getSchedulerService().shutdownTask(task); } }

Target:
public void shutDownTask(TaskDefinition task) throws SchedulerException { Context.getSchedulerService().shutdownTask(task); }
Source:
public static Description mergeDescriptions(Description testSuiteDescription, Description testCaseDescription) { Description description = new Description(); if (!StringUtils.isEmpty(testSuiteDescription.getValue())) { description.setValue(testSuiteDescription.getValue() + "\n" + testCaseDescription.getValue()); description.setType(testSuiteDescription.getType().equals(DescriptionType.MARKDOWN) ? DescriptionType.MARKDOWN : testCaseDescription.getType()); } return description; }

Target:
public static Description mergeDescriptions(Description testSuiteDescription, Description testCaseDescription) { if (testSuiteDescription == null && testCaseDescription == null) { return null; } if (testSuiteDescription == null) { return testCaseDescription; } if (testCaseDescription == null) { return testSuiteDescription; } Description description = new Description(); if (!StringUtils.isEmpty(testSuiteDescription.getValue())) { DescriptionType descriptionType = testSuiteDescription.getType().equals(DescriptionType.MARKDOWN) ? DescriptionType.MARKDOWN : testCaseDescription.getType(); String descriptionValue = descriptionType.equals(DescriptionType.MARKDOWN) ? String.format("%s\n\n%s", testSuiteDescription.getValue(), testCaseDescription.getValue()) : String.format("%s\n%s", testSuiteDescription.getValue(), testCaseDescription.getValue()); description.setValue(descriptionValue); description.setType(descriptionType); } return description; }
Source:
public CommandCallback getCallback() { if (isDataOperationsByHSM()){ return new ConcurrentChildCommandsExecutionCallback(); } return null; }

Target:
public CommandCallback getCallback() { return isDataOperationsByHSM() ? new ConcurrentChildCommandsExecutionCallback() : null; }
Source:
public void startViewTransition(@NonNull View view) { if (view.getParent() == this) { if (mTransitioningFragmentViews == null) { mTransitioningFragmentViews = new ArrayList<>(); } } mTransitioningFragmentViews.add(view); super.startViewTransition(view); }

Target:
public void startViewTransition(@NonNull View view) { if (view.getParent() == this) { if (mTransitioningFragmentViews == null) { mTransitioningFragmentViews = new ArrayList<>(); } mTransitioningFragmentViews.add(view); } super.startViewTransition(view); }
Source:
public void getValue_asEmptyListAfterClassRemoved() { final String CLASS_NAME = "KingsAndQueens"; DynamicRealm realm = initializeDynamicRealm(CLASS_NAME); RealmResults<DynamicRealmObject> results = realm.where(CLASS_NAME).findAll(); assertEquals(results.get(0).getString("name"), "John"); assertEquals(results.first().getString("name"), "John"); assertEquals(results.last().getString("name"), "John"); removeClassFromDynamicRealm(realm, CLASS_NAME); assertNull(results.get(0)); try { results.first(); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("No results were found.", expected.getMessage()); } try { results.last(); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("No results were found.", expected.getMessage()); } realm.close(); }

Target:
public void getValue_asEmptyListAfterClassRemoved() { final String CLASS_NAME = "KingsAndQueens"; DynamicRealm realm = initializeDynamicRealm(CLASS_NAME); RealmResults<DynamicRealmObject> results = realm.where(CLASS_NAME).findAll(); assertEquals(results.get(0).getString("name"), "John"); assertEquals(results.first().getString("name"), "John"); assertEquals(results.last().getString("name"), "John"); removeClassFromDynamicRealm(realm, CLASS_NAME); try { results.get(0); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("No results were found.", expected.getMessage()); } try { results.first(); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("No results were found.", expected.getMessage()); } try { results.last(); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("No results were found.", expected.getMessage()); } realm.close(); }
Source:
public String toString() { return "BaseActivityObject{" + "Id='" + Id + '\'' + ", HRef='" + HRef + '\'' + ", Context='" + Context + '\'' + ", Type='" + Type + '\'' + ", Name='" + Name + '\'' + ", Location=" + Location + ", StartTime='" + StartTime + '\'' + ", EndTime='" + EndTime + '\'' + ", Duration='" + Duration + '\'' + ", Origin=" + Origin + ", AttributedTo=" + AttributedTo + ", SummaryMap=" + SummaryMap + ", NameMap=" + NameMap + ", tirePressureObject=" + tirePressureObject + '}'; }

Target:
public String toString() { return "BaseActivityObject{" + "Id='" + Id + '\'' + ", HRef='" + HRef + '\'' + ", Context='" + Context + '\'' + ", Type='" + Type + '\'' + ", Name='" + Name + '\'' + ", Location=" + Location + ", StartTime='" + StartTime + '\'' + ", EndTime='" + EndTime + '\'' + ", Duration='" + Duration + '\'' + ", Origin=" + Origin + ", AttributedTo=" + AttributedTo + ", SummaryMap=" + SummaryMap + ", NameMap=" + NameMap + '}'; }
Source:
public MavenExecutionRequest setPom( File pom ) { this.pom = pom; if ( this.pom != null && this.pom.getParentFile() != null ) { this.setBaseDirectory( this.pom.getParentFile() ); } return this; }

Target:
public MavenExecutionRequest setPom( File pom ) { this.pom = pom; return this; }
Source:
public void write(byte[] b) throws IOException { int overflow = buffer(b, 0, b.length); if (overflow > 0) write(b, b.length - overflow, overflow); }

Target:
public void write(byte[] b) throws IOException { int overflow = buffer(b, 0, b.length); if (overflow > 0) { write(b, b.length - overflow, overflow); } }
Source:
public String toString() { return String.format("float@0x%x=%s", Pointer.nativeValue(getPointer()), Float.toString(getValue())); }

Target:
public String toString() { return String.format("float@0x%x=%s", Pointer.nativeValue(getPointer()), getValue()); }
Source:
public void restoreBinding(ContextModel contextModel) { BindingElement element = (BindingElement) getSelectedElement(); if (element == null) { return; } restoreBinding(element); refresh(contextModel); Object obj = element.getModelObject(); ParameterizedCommand cmd = null; if (obj instanceof ParameterizedCommand) { cmd = (ParameterizedCommand) obj; } else if (obj instanceof KeyBinding) { cmd = ((KeyBinding) obj).getParameterizedCommand(); } else { return; } boolean done = false; Iterator i = bindingElements.iterator(); while (i.hasNext() && !done) { BindingElement be = (BindingElement) i.next(); obj = be.getModelObject(); ParameterizedCommand pcmd = null; if (obj instanceof ParameterizedCommand) { pcmd = (ParameterizedCommand) obj; } else if (obj instanceof KeyBinding) { pcmd = ((KeyBinding) obj).getParameterizedCommand(); } if (cmd.equals(pcmd)) { done = true; setSelectedElement(be); } } }

Target:
public void restoreBinding(ContextModel contextModel) { BindingElement element = (BindingElement) getSelectedElement(); if (element == null) { return; } restoreBinding(element); refresh(contextModel); Object obj = element.getModelObject(); ParameterizedCommand cmd = null; if (obj instanceof ParameterizedCommand) { cmd = (ParameterizedCommand) obj; } else if (obj instanceof KeyBinding) { cmd = ((KeyBinding) obj).getParameterizedCommand(); } Assert.isNotNull(cmd); boolean done = false; Iterator i = bindingElements.iterator(); while (i.hasNext() && !done) { BindingElement be = (BindingElement) i.next(); obj = be.getModelObject(); ParameterizedCommand pcmd = null; if (obj instanceof ParameterizedCommand) { pcmd = (ParameterizedCommand) obj; } else if (obj instanceof KeyBinding) { pcmd = ((KeyBinding) obj).getParameterizedCommand(); } if (cmd.equals(pcmd)) { done = true; setSelectedElement(be); } } }
Source:
public static Text getSleepDeprivationMessage(final int idealDuration, final int avgSleepDebtDuration) { final float avgSleepDebtHour = ((float) Math.round(avgSleepDebtDuration / 30) ) / 2; if (avgSleepDebtHour == 1) { return new Text("The importance of sleep", String.format("For the last four nights, you got less than your ideal %d hours of sleep. ", idealDuration) + String.format("During those nights, you slept %.1f hour less than your nightly average.", avgSleepDebtHour)); } return new Text("The importance of sleep", String.format("For the last four nights, you got less than your ideal %d hours of sleep. ", idealDuration) + String.format("During those nights, you slept %.1f hours less than your nightly average.", avgSleepDebtHour)); }

Target:
public static Text getSleepDeprivationMessage(final int idealDuration, final int avgSleepDebtDuration) { final float avgSleepDebtHour = ((float) (avgSleepDebtDuration / 30) ) / 2.0f; final DecimalFormat df = new DecimalFormat("0.###"); String plural = "s"; if (avgSleepDebtHour == 1.0f) { plural = ""; } return new Text("The importance of sleep", String.format("For the last four nights, you got less than your ideal %d hours of sleep. ", idealDuration) + String.format("During those nights, you slept %s hour%s less than your nightly average.", df.format(avgSleepDebtHour), plural)); }
Source:
public List<FeedbackSessionAttributes> getAllOpenFeedbackSessions(Instant rangeStart, Instant rangeEnd) { List<FeedbackSessionAttributes> list = new LinkedList<>(); Calendar startCal = Calendar.getInstance(); startCal.setTime(TimeHelper.convertInstantToDate(rangeStart)); Calendar endCal = Calendar.getInstance(); endCal.setTime(TimeHelper.convertInstantToDate(rangeEnd)); Date curStart = TimeHelper.convertToUserTimeZone(startCal, -25).getTime(); Date curEnd = TimeHelper.convertToUserTimeZone(endCal, 25).getTime(); List<FeedbackSession> endEntities = load() .filter("endTime >", curStart) .filter("endTime <=", curEnd) .list(); List<FeedbackSession> startEntities = load() .filter("startTime >=", curStart) .filter("startTime <", curEnd) .list(); List<FeedbackSession> endTimeEntities = new ArrayList<>(endEntities); List<FeedbackSession> startTimeEntities = new ArrayList<>(startEntities); endTimeEntities.removeAll(startTimeEntities); startTimeEntities.removeAll(endTimeEntities); endTimeEntities.addAll(startTimeEntities); for (FeedbackSession feedbackSession : endTimeEntities) { FeedbackSessionAttributes fs = makeAttributes(feedbackSession); Instant fsStart = fs.getStartTime(); Instant fsEnd = fs.getEndTime(); boolean isStartTimeWithinRange = (fsStart.isAfter(rangeStart) || fsStart.equals(rangeStart)) && fsStart.isBefore(rangeEnd); boolean isEndTimeWithinRange = fsEnd.isAfter(rangeStart) && (fsEnd.isBefore(rangeEnd) || fsEnd.equals(rangeEnd)); if (isStartTimeWithinRange || isEndTimeWithinRange) { list.add(fs); } } return list; }

Target:
public List<FeedbackSessionAttributes> getAllOpenFeedbackSessions(Instant rangeStart, Instant rangeEnd) { List<FeedbackSessionAttributes> list = new LinkedList<>(); Instant start = rangeStart.minus(Duration.ofHours(25)); Instant end = rangeEnd.plus(Duration.ofHours(25)); List<FeedbackSession> endEntities = load() .filter("endTime >", TimeHelper.convertInstantToDate(start)) .filter("endTime <=", TimeHelper.convertInstantToDate(end)) .list(); List<FeedbackSession> startEntities = load() .filter("startTime >=", TimeHelper.convertInstantToDate(start)) .filter("startTime <", TimeHelper.convertInstantToDate(end)) .list(); List<FeedbackSession> endTimeEntities = new ArrayList<>(endEntities); List<FeedbackSession> startTimeEntities = new ArrayList<>(startEntities); endTimeEntities.removeAll(startTimeEntities); startTimeEntities.removeAll(endTimeEntities); endTimeEntities.addAll(startTimeEntities); for (FeedbackSession feedbackSession : endTimeEntities) { FeedbackSessionAttributes fs = makeAttributes(feedbackSession); Instant fsStart = fs.getStartTime(); Instant fsEnd = fs.getEndTime(); boolean isStartTimeWithinRange = (fsStart.isAfter(rangeStart) || fsStart.equals(rangeStart)) && fsStart.isBefore(rangeEnd); boolean isEndTimeWithinRange = fsEnd.isAfter(rangeStart) && (fsEnd.isBefore(rangeEnd) || fsEnd.equals(rangeEnd)); if (isStartTimeWithinRange || isEndTimeWithinRange) { list.add(fs); } } return list; }
Source:
public static Map<String, String> getKiePMMLTreeModelSourcesMap(final DataDictionary dataDictionary, final TreeModel model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, final String packageName) { logger.trace("getKiePMMLTreeModelSourcesMap {}", dataDictionary, model, packageName); CompilationUnit cloneCU = getKiePMMLModelCompilationUnit(dataDictionary, model, fieldTypeMap, packageName, KIE_PMML_TREE_MODEL_TEMPLATE_JAVA, KIE_PMML_TREE_MODEL_TEMPLATE); String className = getSanitizedClassName(model.getModelName()); ClassOrInterfaceDeclaration modelTemplate = cloneCU.getClassByName(className) .orElseThrow(() -> new KiePMMLException(MAIN_CLASS_NOT_FOUND)); final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format("Missing default constructor in ClassOrInterfaceDeclaration %s ", modelTemplate.getName()))); setSuperInvocation(model, constructorDeclaration, modelTemplate.getName()); Map<String, String> toReturn = new HashMap<>(); String fullClassName = packageName + "." + className; toReturn.put(fullClassName, cloneCU.toString()); return toReturn; }

Target:
public static Map<String, String> getKiePMMLTreeModelSourcesMap(final DataDictionary dataDictionary, final TreeModel model, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap, final String packageName) { logger.trace("getKiePMMLTreeModelSourcesMap {}", dataDictionary, model, packageName); CompilationUnit cloneCU = getKiePMMLModelCompilationUnit(dataDictionary, model, fieldTypeMap, packageName, KIE_PMML_TREE_MODEL_TEMPLATE_JAVA, KIE_PMML_TREE_MODEL_TEMPLATE); String className = getSanitizedClassName(model.getModelName()); ClassOrInterfaceDeclaration modelTemplate = cloneCU.getClassByName(className) .orElseThrow(() -> new KiePMMLException(MAIN_CLASS_NOT_FOUND + ": " + className)); final ConstructorDeclaration constructorDeclaration = modelTemplate.getDefaultConstructor().orElseThrow(() -> new KiePMMLInternalException(String.format("Missing default constructor in ClassOrInterfaceDeclaration %s ", modelTemplate.getName()))); setSuperInvocation(model, constructorDeclaration, modelTemplate.getName()); Map<String, String> toReturn = new HashMap<>(); String fullClassName = packageName + "." + className; toReturn.put(fullClassName, cloneCU.toString()); return toReturn; }
Source:
public void runByTrigger() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.assertItemNames(0); s.addTrigger(new PeriodicFolderTrigger("1m")); Thread.sleep(65000); s.assertItemNames(1); }

Target:
public void runByTrigger() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.assertItemNames(0); PeriodicFolderTrigger t = new PeriodicFolderTrigger("1m"); s.addTrigger(t); t.run(); r.waitUntilNoActivity(); s.assertItemNames(1); }
Source:
public static boolean isAuthenticated(HttpServletRequest request) { HttpSession session = request.getSession(false); return session != null && session.getAttribute(Constants.AUTHENTICATED_KEY) != null && (boolean) session.getAttribute(Constants.AUTHENTICATED_KEY); }

Target:
public static boolean isAuthenticated(HttpServletRequest request) { HttpSession session = request.getSession(false); return session != null && Boolean.valueOf((Boolean) session.getAttribute(Constants.AUTHENTICATED_KEY)); }
Source:
Journal(String dataDir, int maxEntriesToJournal, int maxEntriesToReturn) { journal = new ConcurrentSkipListMap<>(); recentCrcs = new HashMap<>(); this.maxEntriesToJournal = maxEntriesToJournal; this.maxEntriesToReturn = maxEntriesToReturn; this.currentNumberOfEntries = new AtomicInteger(0); this.dataDir = dataDir; }

Target:
Journal(String dataDir, int maxEntriesToJournal, int maxEntriesToReturn) { journal = new ConcurrentSkipListMap<>(); recentCrcs = new ConcurrentHashMap<>(); this.maxEntriesToJournal = maxEntriesToJournal; this.maxEntriesToReturn = maxEntriesToReturn; this.currentNumberOfEntries = new AtomicInteger(0); this.dataDir = dataDir; }
Source:
public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { if (masterBuffer.isEmpty()) { clientBuffer.setNoMorePages(); } else { clientBuffer.loadPagesIfNecessary(masterBuffer); } } checkFlushComplete(); }

Target:
public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { clientBuffer.loadPagesIfNecessary(masterBuffer); } checkFlushComplete(); }
Source:
public static int getPreferredBrowser() { return isMacOS ? SWT.WEBKIT : SWT.WEBKIT; }

Target:
public static int getPreferredBrowser() { return isMacOS ? SWT.WEBKIT : SWT.MOZILLA; }
Source:
public void testPutAllMapNull() throws Exception { final Map<String, String> originalStoreContent = getEntryMap(KEY_SET_A, KEY_SET_B); final FakeStore fakeStore = new FakeStore(originalStoreContent); this.store = spy(fakeStore); final Ehcache<String, String> ehcache = getEhcache(); try { ehcache.putAll(null); fail(); } catch (NullPointerException e) { } verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any()); }

Target:
public void testPutAllMapNull() throws Exception { buildStore(getEntryMap(KEY_SET_A, KEY_SET_B)); final Ehcache<String, String> ehcache = getEhcache(); try { ehcache.putAll(null); fail(); } catch (NullPointerException e) { } verify(cacheEventListener, never()).onEvent(Matchers.<CacheEvent<String, String>>any()); }
Source:
public OAuth2InitialClientMessage getInitialResponse() throws AuthenticationMechanismException { final CredentialCallback credentialCallback = new CredentialCallback(BearerTokenCredential.class); try { MechanismUtil.handleCallbacks(this.mechanismName, this.callbackHandler, credentialCallback); } catch (UnsupportedCallbackException e) { throw ElytronMessages.log.mechCallbackHandlerDoesNotSupportUserName(this.mechanismName, e); } assertTrue(credentialCallback.isCredentialTypeSupported(BearerTokenCredential.class)); BearerTokenCredential credential = credentialCallback.getCredential(BearerTokenCredential.class); if (credential == null || credential.getToken() == null) { throw ElytronMessages.log.mechNoTokenGiven(this.mechanismName); } final String token = credential.getToken(); final ByteStringBuilder encoded = new ByteStringBuilder(); encoded.append("n").append(","); if (this.authorizationId != null) { encoded.append('a').append('='); StringPrep.encode(this.authorizationId, encoded, StringPrep.PROFILE_SASL_STORED | StringPrep.MAP_SCRAM_LOGIN_CHARS); } encoded.append(",").append(KV_DELIMITER).append("auth").append("=").append("Bearer").append(" ").append(token).append(KV_DELIMITER); return new OAuth2InitialClientMessage(null, null, encoded.toArray()); }

Target:
public OAuth2InitialClientMessage getInitialResponse() throws AuthenticationMechanismException { final CredentialCallback credentialCallback = new CredentialCallback(BearerTokenCredential.class); try { MechanismUtil.handleCallbacks(this.mechanismName, this.callbackHandler, credentialCallback); } catch (UnsupportedCallbackException e) { throw ElytronMessages.log.mechCallbackHandlerDoesNotSupportUserName(this.mechanismName, e); } assertTrue(credentialCallback.isCredentialTypeSupported(BearerTokenCredential.class)); final String token = credentialCallback.applyToCredential(BearerTokenCredential.class, BearerTokenCredential::getToken); if (token == null) { throw ElytronMessages.log.mechNoTokenGiven(this.mechanismName); } final ByteStringBuilder encoded = new ByteStringBuilder(); encoded.append("n").append(","); if (this.authorizationId != null) { encoded.append('a').append('='); StringPrep.encode(this.authorizationId, encoded, StringPrep.PROFILE_SASL_STORED | StringPrep.MAP_SCRAM_LOGIN_CHARS); } encoded.append(",").append(KV_DELIMITER).append("auth").append("=").append("Bearer").append(" ").append(token).append(KV_DELIMITER); return new OAuth2InitialClientMessage(null, null, encoded.toArray()); }
Source:
protected List<CandidateCellForSweeping> computeNext() { if (end) { return endOfData(); } else { List<CandidateCellForSweeping> candidates = Lists.newArrayList(); while (candidates.isEmpty() && rawIter.hasNext()) { List<CassandraRawCellValue> cols = rawIter.next(); for (CassandraRawCellValue col : cols) { processColumn(col, candidates); } } if (candidates.isEmpty()) { end = true; if (!currentTimestamps.isEmpty()) { return ImmutableList.of(createCandidate()); } else { return endOfData(); } } else { return candidates; } } }

Target:
protected List<CandidateCellForSweeping> computeNext() { if (reachedEnd) { return endOfData(); } else { List<CandidateCellForSweeping> candidates = Lists.newArrayList(); while (candidates.isEmpty() && rawIter.hasNext()) { List<CassandraRawCellValue> cols = rawIter.next(); for (CassandraRawCellValue col : cols) { processColumn(col).ifPresent(candidates::add); } } if (candidates.isEmpty()) { reachedEnd = true; if (!currentTimestamps.isEmpty()) { return ImmutableList.of(createCandidate()); } else { return endOfData(); } } else { return candidates; } } }
Source:
protected @C.Accessibility int parseAccessibility(List<Descriptor> accessibilityDescriptors) { for (int i = 0; i < accessibilityDescriptors.size(); i++) { Descriptor descriptor = accessibilityDescriptors.get(i); if ("urn:mpeg:dash:role:2011".equalsIgnoreCase(descriptor.schemeIdUri) && descriptor.value != null) { switch (descriptor.value){ case "description": return C.ACCESSIBILITY_DESCRIPTION; case "enhanced-audio-intelligibility": return C.ACCESSIBILITY_ENHANCED_AUDIO_INTELLIGIBILITY; case "caption": return C.ACCESSIBILITY_CAPTION; case "sign": return C.ACCESSIBILITY_SIGN; default: return C.ACCESSIBILITY_UNSET; } } if ("urn:tva:metadata:cs:AudioPurposeCS:2007".equalsIgnoreCase(descriptor.schemeIdUri) && descriptor.value != null) { switch (descriptor.value){ case "1": return C.ACCESSIBILITY_ENHANCED_AUDIO_INTELLIGIBILITY; case "2": return C.ACCESSIBILITY_CAPTION; default: return C.ACCESSIBILITY_UNSET; } } } return C.ACCESSIBILITY_UNSET; }

Target:
protected @C.RoleFlags int parseAccessibility(List<Descriptor> accessibilityDescriptors) { @C.RoleFlags int result = 0; for (int i = 0; i < accessibilityDescriptors.size(); i++) { Descriptor descriptor = accessibilityDescriptors.get(i); if ("urn:mpeg:dash:role:2011".equalsIgnoreCase(descriptor.schemeIdUri)) { result |= parseRoleSchemeValue(descriptor.value); } else if ("urn:tva:metadata:cs:AudioPurposeCS:2007".equalsIgnoreCase(descriptor.schemeIdUri)) { result |= parseAudioPurposeValue(descriptor.value); } } return result; }
Source:
private void updateRngDevice() { if (getParameters().isUpdateRngDevice()) { VdcQueryReturnValue query = getBackend().runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); @SuppressWarnings("unchecked") List<VmRngDevice> rngDevs = query.getReturnValue(); if (getParameters().getRngDevice() != null) { getParameters().getRngDevice().setVmId(getParameters().getVmId()); } VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = getBackend().runInternalAction(VdcActionType.AddRngDevice, params); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = getBackend().runInternalAction(VdcActionType.RemoveRngDevice, params); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = getBackend().runInternalAction(VdcActionType.UpdateRngDevice, params); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { getReturnValue().setSucceeded(false); } } }

Target:
private void updateRngDevice() { if (getParameters().isUpdateRngDevice()) { VdcQueryReturnValue query = getBackend().runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); @SuppressWarnings("unchecked") List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = getBackend().runInternalAction(VdcActionType.AddRngDevice, params); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = getBackend().runInternalAction(VdcActionType.RemoveRngDevice, params); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = getBackend().runInternalAction(VdcActionType.UpdateRngDevice, params); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { getReturnValue().setSucceeded(false); } } }
Source:
private void updateHostList(String searchFilter) { Provider provider = (Provider) getProviders().getSelectedItem(); if (provider != null ) { AsyncQuery getHostsQuery = new AsyncQuery(); getHostsQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object result) { ArrayList<VDS> hosts = (ArrayList<VDS>) result; ListModel hostNameListModel = getExternalHostName(); hosts.add(0, null); hostNameListModel.setItems(hosts); hostNameListModel.setIsChangable(true); getProviderSearchFilter().setIsChangable(true); getProviderSearchFilterLabel().setIsChangable(true); getUpdateHostsCommand().setIsExecutionAllowed(true); } }; AsyncDataProvider.GetExternalProviderHostList(getHostsQuery, provider.getId(), true, searchFilter); } else { getExternalHostName().setItems(null); getExternalHostName().setIsChangable(false); getProviderSearchFilter().setIsChangable(false); getProviderSearchFilterLabel().setIsChangable(false); getUpdateHostsCommand().setIsExecutionAllowed(false); } }

Target:
private void updateHostList(String searchFilter) { Provider provider = (Provider) getProviders().getSelectedItem(); if (provider != null ) { AsyncQuery getHostsQuery = new AsyncQuery(); getHostsQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object result) { ArrayList<VDS> hosts = (ArrayList<VDS>) result; ListModel hostNameListModel = getExternalHostName(); hosts.add(0, null); hostNameListModel.setItems(hosts); hostNameListModel.setIsChangable(true); setEnableSearchHost(true); } }; AsyncDataProvider.GetExternalProviderHostList(getHostsQuery, provider.getId(), true, searchFilter); } else { getExternalHostName().setItems(null); getExternalHostName().setIsChangable(false); setEnableSearchHost(false); } }
Source:
boolean run() throws IOException, InterruptedException { log("Docker Build"); String imageId = buildImage(); if (imageId == null) { return false; } log("Docker Build Response : " + imageId); run.addAction(new DockerBuildImageAction(dockerApi.getDockerHost().getUri(), imageId, tagsToUse, cleanupWithJenkinsJobDelete, pushOnSuccess, noCache, pull)); run.save(); if (pushOnSuccess) { log("Pushing " + tagsToUse); pushImages(); } if (cleanImages) { log("Cleaning local images [" + imageId + "]"); try { cleanImages(imageId); } catch (Exception ex) { log("Error attempting to clean images"); } } log("Docker Build Done"); return true; }

Target:
boolean run() throws IOException, InterruptedException { log("Docker Build"); String imageId = buildImage(); if (imageId == null) { return false; } log("Docker Build Response : " + imageId); Action action = new DockerBuildImageAction(dockerApi.getDockerHost().getUri(), imageId, tagsToUse, cleanupWithJenkinsJobDelete, pushOnSuccess, noCache, pull); run.addAction(action); run.save(); if (pushOnSuccess) { log("Pushing " + tagsToUse); pushImages(); } if (cleanImages) { log("Cleaning local images [" + imageId + "]"); try { cleanImages(imageId); } catch (Exception ex) { log("Error attempting to clean images"); } } log("Docker Build Done"); return true; }
Source:
public void close() throws Exception { try { database.close(); } catch (LiquibaseException e){ LOGGER.warn("Failed to close liquibase", e); } dataSource.stop(); }

Target:
public void close() throws Exception { try { database.close(); } finally { dataSource.stop(); } }
Source:
private void internalInitialize(String machineName) { final WorkspaceImpl workspace = appContext.getWorkspace(); final RuntimeImpl runtime = workspace.getRuntime(); if (runtime == null) { return; } runtime .getMachineByName(machineName) .ifPresent( machine -> { Optional<ServerImpl> execAgentServer = machine.getServerByName(SERVER_EXEC_AGENT_WEBSOCKET_REFERENCE); execAgentServer.ifPresent( server -> initializer.initialize( machine.getName(), singletonMap("url", wsAgentURLModifier.modify(server.getUrl())))); }); }

Target:
private void internalInitialize(String machineName) { final WorkspaceImpl workspace = appContext.getWorkspace(); final RuntimeImpl runtime = workspace.getRuntime(); if (runtime == null) { return; } runtime .getMachineByName(machineName) .ifPresent( machine -> { Optional<ServerImpl> execAgentServer = machine.getServerByName(SERVER_EXEC_AGENT_WEBSOCKET_REFERENCE); execAgentServer.ifPresent( server -> initializer.initialize( machine.getName(), singletonMap("url", agentURLModifier.modify(server.getUrl())))); }); }
Source:
public static long hash(long seed, Slice data, int offset, int length) { checkPositionIndexes(0, offset + length, data.length()); Object base = data.getBase(); long address = data.getAddress() + offset; long hash; if (length >= 32) { hash = updateBody(seed, base, address, length - 32); } else { hash = seed + PRIME64_5; } hash += length; int index = length & -32; while (index <= length - 8) { hash = updateTail(hash, unsafe.getLong(base, address + index)); index += 8; } if (index <= length - 4) { hash = updateTail(hash, unsafe.getInt(base, address + index)); index += 4; } while (index < length) { hash = updateTail(hash, unsafe.getByte(base, address + index)); index++; } hash = finalShuffle(hash); return hash; }

Target:
public static long hash(long seed, Slice data, int offset, int length) { checkPositionIndexes(0, offset + length, data.length()); Object base = data.getBase(); final long address = data.getAddress() + offset; long hash; if (length >= 32) { hash = updateBody(seed, base, address, length - 32); } else { hash = seed + PRIME64_5; } hash += length; int index = length & 0xFFFFFFE0; return updateTail(hash, base, address, index, length); }
Source:
public RawPacket reverseTransform(RawPacket pkt) { boolean dropPkt = false; if ((ssrcAudioLevelExtID > 0) && ssrcAudioLevelDirection.allowsReceiving() && !pkt.isInvalid() && RTPHeader.VERSION == pkt.getVersion()) { byte level = pkt.extractSsrcAudioLevel(ssrcAudioLevelExtID); if (level == 127 ) { if (dropMutedAudioSourceInReverseTransform) { dropPkt = droppedMutedAudioSourceInReverseTransform < MAX_DROPPED_MUTED_AUDIO_SOURCE_IN_REVERSE_TRANSFORM; } else { pkt.setFlags(Buffer.FLAG_SILENCE | pkt.getFlags()); } } if (!dropPkt && (csrcAudioLevelDispatcher != null) && (level >= 0)) { long[] levels = new long[2]; levels[0] = pkt.getSSRCAsLong(); levels[1] = 127 - level; csrcAudioLevelDispatcher.addLevels(levels, pkt.getTimestamp()); } } SequenceNumberRewriter rewriter = ssrcToRewriter.get(pkt.getSSRCAsLong()); if (rewriter == null) { rewriter = new SequenceNumberRewriter(); ssrcToRewriter.put(pkt.getSSRCAsLong(), rewriter); } rewriter.rewrite( !dropPkt, pkt.getBuffer(), pkt.getOffset(), pkt.getLength()); if (dropPkt) { droppedMutedAudioSourceInReverseTransform++; return null; } else { droppedMutedAudioSourceInReverseTransform = 0; return pkt; } }

Target:
public RawPacket reverseTransform(RawPacket pkt) { boolean dropPkt = false; if ((ssrcAudioLevelExtID > 0) && ssrcAudioLevelDirection.allowsReceiving() && !pkt.isInvalid() && RTPHeader.VERSION == pkt.getVersion()) { byte level = pkt.extractSsrcAudioLevel(ssrcAudioLevelExtID); if (level == 127 ) { if (dropMutedAudioSourceInReverseTransform) { dropPkt = droppedMutedAudioSourceInReverseTransform < MAX_DROPPED_MUTED_AUDIO_SOURCE_IN_REVERSE_TRANSFORM; } else { pkt.setFlags(Buffer.FLAG_SILENCE | pkt.getFlags()); } } if (!dropPkt && (csrcAudioLevelDispatcher != null) && (level >= 0)) { long[] levels = new long[2]; levels[0] = pkt.getSSRCAsLong(); levels[1] = 127 - level; csrcAudioLevelDispatcher.addLevels(levels, pkt.getTimestamp()); } } if (dropPkt) { droppedMutedAudioSourceInReverseTransform++; pkt.setFlags(Buffer.FLAG_DISCARD | pkt.getFlags()); } else { droppedMutedAudioSourceInReverseTransform = 0; } return pkt; }
Source:
public long check(EC2Computer c) { if (!checkLock.tryLock()) { return 1; } else { try { if (this.clock == null){ this.clock = Clock.systemUTC(); } long currentTime = this.clock.millis(); if (currentTime > nextCheckAfter) { long intervalMins = internalCheck(c); nextCheckAfter = currentTime + TimeUnit.MINUTES.toMillis(intervalMins); return intervalMins; } else { return 1; } } finally { checkLock.unlock(); } } }

Target:
public long check(EC2Computer c) { if (!checkLock.tryLock()) { return 1; } else { try { long currentTime = this.clock.millis(); if (currentTime > nextCheckAfter) { long intervalMins = internalCheck(c); nextCheckAfter = currentTime + TimeUnit.MINUTES.toMillis(intervalMins); return intervalMins; } else { return 1; } } finally { checkLock.unlock(); } } }
Source:
public ZooKeeperHolder zooKeeperHolder(final Environment environment) throws Exception { return new ZooKeeperHolder( environment.getProperty("nakadi.zookeeper.brokers"), environment.getProperty("nakadi.zookeeper.kafkaNamespace", ""), environment.getProperty("nakadi.zookeeper.exhibitor.brokers", ""), Integer.parseInt(environment.getProperty("nakadi.zookeeper.exhibitor.port", "0")) ); }

Target:
public ZooKeeperHolder zooKeeperHolder(final Environment environment) throws Exception { return new ZooKeeperHolder( environment.getProperty("nakadi.zookeeper.brokers"), environment.getProperty("nakadi.zookeeper.kafkaNamespace", ""), environment.getProperty("nakadi.zookeeper.exhibitor.brokers"), Integer.parseInt(environment.getProperty("nakadi.zookeeper.exhibitor.port", "0")) ); }
Source:
synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); realm.doClose(); if (geTotalLiveRealmGlobalRefCount() == 0) { configuration = null; for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); if (cachedRealm != null) { cachedRealm.close(); } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()) .realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } }

Target:
synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); realm.doClose(); if (getTotalLiveRealmGlobalRefCount() == 0) { configuration = null; for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); if (cachedRealm != null) { while (!cachedRealm.isClosed()) { cachedRealm.close(); } } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()).realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } }
Source:
private Pattern turnOperandIntoRegExp(Object operand) { String operandAsString = operand.toString(); StringBuilder operandAsRegExp = new StringBuilder(replaceWildCardLikeChars(operandAsString)); if (!operandAsString.startsWith("%") && operandAsString.contains("%")) { operandAsRegExp = operandAsRegExp.insert(0, "^"); } return Pattern.compile(operandAsRegExp.toString(), Pattern.CASE_INSENSITIVE); }

Target:
private Pattern turnOperandIntoRegExp(Object operand) { StringBuilder operandAsRegExp = new StringBuilder(replaceWildCardLikeChars(operand.toString())); operandAsRegExp.insert(0, "^").append("$"); return Pattern.compile(operandAsRegExp.toString(), Pattern.CASE_INSENSITIVE); }
Source:
public void initializeTest() { ActivityController<? extends CourseBaseActivity> controller = Robolectric.buildActivity(getActivityClass()).withIntent(getIntent()); CourseBaseActivity activity = controller.get(); controller.create(); assertNotNull(activity.findViewById(R.id.last_accessed_bar)); controller.postCreate(null).resume().postResume().visible(); }

Target:
public void initializeTest() { ActivityController<? extends CourseBaseActivity> controller = Robolectric.buildActivity(getActivityClass()).withIntent(getIntent()); CourseBaseActivity activity = controller.get(); controller.create(); controller.postCreate(null).resume().postResume().visible(); }
Source:
public <T> boolean parse(T param, HttpServletRequest req, HttpServletResponse res) throws IOException { return parse(param, req, res, new ArrayList<String>()); }

Target:
public <T> boolean parse(T param, HttpServletRequest req, HttpServletResponse res) throws IOException { return parse(param, req, res, Collections.<String>emptySet()); }
Source:
public void publishWorkflowAndTestDiscourseTopicCreation() { final ApiClient curatorApiClient = getWebClient(CURATOR_USERNAME); EntriesApi curatorEntriesApi = new EntriesApi(curatorApiClient); final ApiClient userApiClient = getWebClient(USER_2_USERNAME); WorkflowsApi userWorkflowsApi = new WorkflowsApi(userApiClient); String workflowName = Long.toString(Instant.now().toEpochMilli()); userWorkflowsApi.manualRegister("github", "DockstoreTestUser2/gdc-dnaseq-cwl", "/workflows/dnaseq/transform.cwl", workflowName, "cwl", "/workflows/dnaseq/transform.cwl.json"); final Workflow workflowByPathGithub = userWorkflowsApi.getWorkflowByPath(DOCKSTORE_TEST_USER2_GDC_DNASEQ_CWL_WORKFLOW + "/" + workflowName, null); final Workflow workflow = userWorkflowsApi.refresh(workflowByPathGithub.getId()); userWorkflowsApi.publish(workflow.getId(), new PublishRequest(){ public Boolean isPublish() { return true;} }); boolean thrownException = false; Integer wrongCategoryId = 3; try { curatorEntriesApi.setDiscourseTopic(workflow.getId(), wrongCategoryId, ""); } catch (ApiException ex) { thrownException = true; } assertTrue("Should fail creating a topic in category 3.", thrownException); Integer correctCategoryId = 9; thrownException = false; try { curatorEntriesApi.setDiscourseTopic(workflow.getId(), correctCategoryId, ""); } catch (ApiException ex) { thrownException = true; } assertTrue("Should fail creating another topic for a workflow that has one.", thrownException); }

Target:
public void publishWorkflowAndTestDiscourseTopicCreation() { final ApiClient curatorApiClient = getWebClient(CURATOR_USERNAME); EntriesApi curatorEntriesApi = new EntriesApi(curatorApiClient); final ApiClient userApiClient = getWebClient(USER_2_USERNAME); WorkflowsApi userWorkflowsApi = new WorkflowsApi(userApiClient); String workflowName = Long.toString(Instant.now().toEpochMilli()); userWorkflowsApi.manualRegister("github", "DockstoreTestUser2/gdc-dnaseq-cwl", "/workflows/dnaseq/transform.cwl", workflowName, "cwl", "/workflows/dnaseq/transform.cwl.json"); final Workflow workflowByPathGithub = userWorkflowsApi.getWorkflowByPath(DOCKSTORE_TEST_USER2_GDC_DNASEQ_CWL_WORKFLOW + "/" + workflowName, null); final Workflow workflow = userWorkflowsApi.refresh(workflowByPathGithub.getId()); userWorkflowsApi.publish(workflow.getId(), new PublishRequest(){ public Boolean isPublish() { return true;} }); Integer wrongCategoryId = 3; try { curatorEntriesApi.setDiscourseTopic(workflow.getId(), wrongCategoryId); fail("Should not be able to set discourse topic."); } catch (ApiException ex) { } Integer correctCategoryId = 9; try { curatorEntriesApi.setDiscourseTopic(workflow.getId(), correctCategoryId); fail("Should still not be able to set discourse topic."); } catch (ApiException ex) { } }