auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Observable<Location> findLocationByName(String name) { return createObservableIO(() -> { if(!StringUtils.notNull(name)){ return null; } Location location = new Location(); String where = String.format("%s = ?", LocationTable.Column.DISPLAY); String[] whereArgs = new String[]{name}; DBOpenHelper helper = OpenMRSDBOpenHelper.getInstance().getDBOpenHelper(); final Cursor cursor = helper.getReadableDatabase().query(LocationTable.TABLE_NAME, null, where, whereArgs, null, null, null); if (null != cursor) { try { if (cursor.moveToFirst()) { location = cursorToLocation(cursor); } } finally { cursor.close(); } } return location; }); }

Target:
public Location findLocationByName(String name) { if(!StringUtils.notNull(name)){ return null; } Location location = new Location(); String where = String.format("%s = ?", LocationTable.Column.DISPLAY); String[] whereArgs = new String[]{name}; DBOpenHelper helper = OpenMRSDBOpenHelper.getInstance().getDBOpenHelper(); final Cursor cursor = helper.getReadableDatabase().query(LocationTable.TABLE_NAME, null, where, whereArgs, null, null, null); if (null != cursor) { try { if (cursor.moveToFirst()) { location = cursorToLocation(cursor); } } finally { cursor.close(); } } return location; }
Source:
private void assertBadTableName(String tableName){ boolean failed = false; try { createTable(TableName.valueOf(tableName)); } catch (Exception ex) { failed = true; } Assert.assertTrue("Should fail as table name: '" + tableName + "'", failed); }

Target:
private void assertBadTableName(String tableName){ try { createTable(TableName.valueOf(tableName)); Assert.fail("Should fail as table name: '" + tableName + "'"); } catch (Exception ex) { } }
Source:
private static boolean checkImageConfiguration(StorageDomainStatic storageDomain, VolumeType volumeType, VolumeFormat volumeFormat, DiskBackup diskBackup) { return !((volumeType == VolumeType.Preallocated && volumeFormat == VolumeFormat.COW && diskBackup != DiskBackup.Incremental) || volumeFormat == VolumeFormat.RAW && diskBackup == DiskBackup.Incremental || (storageDomain.getStorageType().isBlockDomain() && volumeType == VolumeType.Sparse && volumeFormat == VolumeFormat.RAW) || volumeFormat == VolumeFormat.Unassigned || volumeType == VolumeType.Unassigned); }

Target:
private static boolean checkImageConfiguration(StorageDomainStatic storageDomain, VolumeType volumeType, VolumeFormat volumeFormat, DiskBackup diskBackup) { return !((volumeType == VolumeType.Preallocated && volumeFormat == VolumeFormat.COW && diskBackup != DiskBackup.Incremental) || (volumeFormat == VolumeFormat.RAW && diskBackup == DiskBackup.Incremental) || (storageDomain.getStorageType().isBlockDomain() && volumeType == VolumeType.Sparse && volumeFormat == VolumeFormat.RAW) || volumeFormat == VolumeFormat.Unassigned || volumeType == VolumeType.Unassigned); }
Source:
public void ksEventReceived(KSEvent ksEvent) { if (!processing) { this.isSTTServerAborting = false; if (ksEvent instanceof KSpottedEvent) { toggleProcessing(true); if (stt != null) { try { this.sttServiceHandle = stt.recognize(this, source.getInputStream(format), this.locale, new HashSet<String>()); } catch (STTException | AudioException e) { logger.error("Error during recognition", e); say("Error during recognition: " + e.getMessage()); } } } else if (ksEvent instanceof KSErrorEvent) { KSErrorEvent kse = (KSErrorEvent) ksEvent; say("Encountered error spotting keywords, " + kse.getMessage()); } } }

Target:
public void ksEventReceived(KSEvent ksEvent) { if (!processing) { this.isSTTServerAborting = false; if (ksEvent instanceof KSpottedEvent) { toggleProcessing(true); if (stt != null) { try { this.sttServiceHandle = stt.recognize(this, source.getInputStream(format), this.locale, new HashSet<String>()); } catch (STTException e) { say("Error during recognition: " + e.getMessage()); } catch (AudioException e) { logger.error("Error creating the audio stream", e); } } } else if (ksEvent instanceof KSErrorEvent) { KSErrorEvent kse = (KSErrorEvent) ksEvent; say("Encountered error spotting keywords, " + kse.getMessage()); } } }
Source:
public void testFatalErrorOnCanceling() throws Exception { final CompletableFuture<Throwable> fatalErrorFuture = new CompletableFuture<>(); final TestingTaskManagerActions taskManagerActions = TestingTaskManagerActions.newBuilder() .setNotifyFatalErrorConsumer((s, throwable) -> fatalErrorFuture.complete(throwable)) .build(); final Configuration config = new Configuration(); config.setLong(TaskManagerOptions.TASK_CANCELLATION_INTERVAL, 5); config.setLong(TaskManagerOptions.TASK_CANCELLATION_TIMEOUT, 50); final Task task = spy(createTaskBuilder() .setInvokable(InvokableBlockingWithTrigger.class) .setTaskManagerConfig(config) .setTaskManagerActions(taskManagerActions) .build()); final Class<OutOfMemoryError> fatalErrorType = OutOfMemoryError.class; doThrow(fatalErrorType).when(task).cancelOrFailAndCancelInvokableInternal(eq(ExecutionState.CANCELING), eq(null)); try { task.startTaskThread(); awaitLatch.await(); task.cancelExecution(); final Throwable fatalError = fatalErrorFuture.join(); assertThat(fatalError, instanceOf(fatalErrorType)); } catch (Throwable t) { fail("No exception is expected to be thrown by fatal error handling"); } finally { triggerLatch.trigger(); } }

Target:
public void testFatalErrorOnCanceling() throws Exception { final CompletableFuture<Throwable> fatalErrorFuture = new CompletableFuture<>(); final TestingTaskManagerActions taskManagerActions = TestingTaskManagerActions.newBuilder() .setNotifyFatalErrorConsumer((s, throwable) -> fatalErrorFuture.complete(throwable)) .build(); final Configuration config = new Configuration(); config.setLong(TaskManagerOptions.TASK_CANCELLATION_INTERVAL, 5); config.setLong(TaskManagerOptions.TASK_CANCELLATION_TIMEOUT, 50); final Task task = spy(createTaskBuilder() .setInvokable(InvokableBlockingWithTrigger.class) .setTaskManagerConfig(config) .setTaskManagerActions(taskManagerActions) .build()); final Class<OutOfMemoryError> fatalErrorType = OutOfMemoryError.class; doThrow(fatalErrorType).when(task).cancelOrFailAndCancelInvokableInternal(eq(ExecutionState.CANCELING), eq(null)); try { task.startTaskThread(); awaitLatch.await(); task.cancelExecution(); final Throwable fatalError = fatalErrorFuture.join(); assertThat(fatalError, instanceOf(fatalErrorType)); } finally { triggerLatch.trigger(); } }
Source:
private Optional<PendingTaskManagerSlot> allocateResource(ResourceProfile requestedSlotResourceProfile) { if (getNumberPendingTaskManagerSlots() + getNumberRegisteredSlots() + numSlotsPerWorker > maxSlotNum) { LOG.warn("Could not allocate more slots since the number of slots already reach maximum {}.", getNumberPendingTaskManagerSlots() + getNumberRegisteredSlots(), maxSlotNum); return Optional.empty(); } if (!defaultSlotResourceProfile.isMatching(requestedSlotResourceProfile)) { return Optional.empty(); } if (!resourceActions.allocateResource(defaultWorkerResourceSpec)) { return Optional.empty(); } PendingTaskManagerSlot pendingTaskManagerSlot = null; for (int i = 0; i < numSlotsPerWorker; ++i) { pendingTaskManagerSlot = new PendingTaskManagerSlot(defaultSlotResourceProfile); pendingSlots.put(pendingTaskManagerSlot.getTaskManagerSlotId(), pendingTaskManagerSlot); } return Optional.of(Preconditions.checkNotNull(pendingTaskManagerSlot, "At least one pending slot should be created.")); }

Target:
private Optional<PendingTaskManagerSlot> allocateResource(ResourceProfile requestedSlotResourceProfile) { final int numRegisteredSlots = getNumberRegisteredSlots(); final int numPendingSlots = getNumberPendingTaskManagerSlots(); if (isMaxSlotNumExceededAfterAdding(numSlotsPerWorker)) { LOG.warn("Could not allocate more slots. The number of registered and pending slots is {}, while the maximum is {}.", numSlotsPerWorker, numPendingSlots + numRegisteredSlots, maxSlotNum); return Optional.empty(); } if (!defaultSlotResourceProfile.isMatching(requestedSlotResourceProfile)) { return Optional.empty(); } if (!resourceActions.allocateResource(defaultWorkerResourceSpec)) { return Optional.empty(); } PendingTaskManagerSlot pendingTaskManagerSlot = null; for (int i = 0; i < numSlotsPerWorker; ++i) { pendingTaskManagerSlot = new PendingTaskManagerSlot(defaultSlotResourceProfile); pendingSlots.put(pendingTaskManagerSlot.getTaskManagerSlotId(), pendingTaskManagerSlot); } return Optional.of(Preconditions.checkNotNull(pendingTaskManagerSlot, "At least one pending slot should be created.")); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.form_entry_patient_list_menu, menu); final SearchView findPatientView; MenuItem mFindPatientMenuItem = menu.findItem(R.id.actionSearchRemoteFormEntry); findPatientView = (SearchView) MenuItemCompat.getActionView(mFindPatientMenuItem); findPatientView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { findPatientView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String query) { mPresenter.setQuery(query); mPresenter.updatePatientsList(); return true; } }); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.form_entry_patient_list_menu, menu); final SearchView findPatientView; MenuItem mFindPatientMenuItem = menu.findItem(R.id.actionSearchRemoteFormEntry); findPatientView = (SearchView) mFindPatientMenuItem.getActionView(); findPatientView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { findPatientView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String query) { mPresenter.setQuery(query); mPresenter.updatePatientsList(); return true; } }); return true; }
Source:
public void setUp() throws Exception { sponsoredMembershipInOrganizationsAttrDef.setId(100); group1.setId(1); group2.setId(2); sess = mock(PerunSessionImpl.class); PerunBl perunBl = mock(PerunBl.class); when(sess.getPerunBl()).thenReturn(perunBl); AttributesManagerBl am = mock(AttributesManagerBl.class); GroupsManagerBl gm = mock(GroupsManagerBl.class); MembersManagerBl mm = mock(MembersManagerBl.class); when(sess.getPerunBl().getAttributesManagerBl()).thenReturn(am); when(sess.getPerunBl().getGroupsManagerBl()).thenReturn(gm); when(sess.getPerunBl().getMembersManagerBl()).thenReturn(mm); when(sess.getPerunBl().getGroupsManagerBl().getGroupsWhereMemberIsActive(sess, member1)).thenReturn(Arrays.asList(group1)); when(sess.getPerunBl().getGroupsManagerBl().getGroupsWhereMemberIsActive(sess, member2)).thenReturn(Arrays.asList(group2)); when(sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group1, organizationIdentifierAttrName)).thenReturn(groupAttr1); when(sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group2, organizationIdentifierAttrName)).thenReturn(groupAttr2); when(sess.getPerunBl().getMembersManagerBl().getMembersByUserWithStatus(sess, user, Status.VALID)).thenReturn(Arrays.asList(member1, member2)); }

Target:
public void setUp() throws Exception { sponsoredMembershipInOrganizationsAttrDef.setId(100); group1.setId(1); group2.setId(2); sess = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); when(sess.getPerunBl().getGroupsManagerBl().getGroupsWhereMemberIsActive(sess, member1)) .thenReturn(Arrays.asList(group1)); when(sess.getPerunBl().getGroupsManagerBl().getGroupsWhereMemberIsActive(sess, member2)) .thenReturn(Arrays.asList(group2)); when(sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group1, organizationIdentifierAttrName)) .thenReturn(groupAttr1); when(sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group2, organizationIdentifierAttrName)) .thenReturn(groupAttr2); when(sess.getPerunBl().getMembersManagerBl().getMembersByUserWithStatus(sess, user, Status.VALID)) .thenReturn(Arrays.asList(member1, member2)); }
Source:
public void addOutputStream(Stream stream) { declaredOutputStreams.add(stream); }

Target:
public void addOutputStream(Stream stream) { outputStreams.add(stream); }
Source:
public void testCorrectMergeOperatorSet() throws Exception { prepareRocksDB(); final ColumnFamilyOptions columnFamilyOptions = userMisuseOptimizeForPointLookup ? spy(optimizePointLookupOption(new ColumnFamilyOptions())) : spy(new ColumnFamilyOptions()); RocksDBKeyedStateBackend<Integer> test = null; try { test = RocksDBTestUtils.builderForTestDB( tempFolder.newFolder(), IntSerializer.INSTANCE, db, defaultCFHandle, columnFamilyOptions) .setEnableIncrementalCheckpointing(enableIncrementalCheckpointing) .build(); ValueStateDescriptor<String> stubState1 = new ValueStateDescriptor<>("StubState-1", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState1); ValueStateDescriptor<String> stubState2 = new ValueStateDescriptor<>("StubState-2", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState2); verify(columnFamilyOptions, Mockito.times(2)) .setMergeOperatorName(RocksDBKeyedStateBackend.MERGE_OPERATOR_NAME); } finally { if (test != null) { IOUtils.closeQuietly(test); test.dispose(); } columnFamilyOptions.close(); } }

Target:
public void testCorrectMergeOperatorSet() throws Exception { prepareRocksDB(); final ColumnFamilyOptions columnFamilyOptions = spy(new ColumnFamilyOptions()); RocksDBKeyedStateBackend<Integer> test = null; try { test = RocksDBTestUtils.builderForTestDB( tempFolder.newFolder(), IntSerializer.INSTANCE, db, defaultCFHandle, columnFamilyOptions) .setEnableIncrementalCheckpointing(enableIncrementalCheckpointing) .build(); ValueStateDescriptor<String> stubState1 = new ValueStateDescriptor<>("StubState-1", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState1); ValueStateDescriptor<String> stubState2 = new ValueStateDescriptor<>("StubState-2", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState2); verify(columnFamilyOptions, Mockito.times(2)) .setMergeOperatorName(RocksDBKeyedStateBackend.MERGE_OPERATOR_NAME); } finally { if (test != null) { IOUtils.closeQuietly(test); test.dispose(); } columnFamilyOptions.close(); } }
Source:
public void testSessionFactoryUnique() throws Exception { deployBundle("org.nuxeo.ecm.platform.mail"); pushInlineDeployments("org.nuxeo.ecm.platform.mail.test:OSGI-INF/mailService-session-factory-test-contrib.xml"); MailService mailService = Framework.getService(MailService.class); Session session1 = mailService.getSession("testFactory"); assertNotNull(session1); Session session1a = mailService.getSession("testFactory"); assertNotNull(session1a); assertTrue("Sessions should be equals", session1 == session1a); Session session2 = mailService.getSession("testFactory2"); assertNotNull(session2); assertFalse("Sessions shouldn't be equals", session1 == session2); }

Target:
public void testSessionFactoryUnique() throws Exception { deployBundle("org.nuxeo.ecm.platform.mail"); pushInlineDeployments("org.nuxeo.ecm.platform.mail.test:OSGI-INF/mailService-session-factory-test-contrib.xml"); MailService mailService = Framework.getService(MailService.class); Session session1 = mailService.getSession("testFactory"); assertNotNull(session1); Session session1a = mailService.getSession("testFactory"); assertNotNull(session1a); assertSame("Sessions should be equals", session1, session1a); Session session2 = mailService.getSession("testFactory2"); assertNotNull(session2); assertNotSame("Sessions shouldn't be equals", session1, session2); }
Source:
public Stream<Pair<MethodYield, ProgramState>> statesAfterInvocation(List<SymbolicValue> invocationArguments, List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) { Set<ProgramState> results = new LinkedHashSet<>(); for (int index = 0; index < invocationArguments.size(); index++) { Constraint constraint = getConstraint(index, invocationTypes); if (constraint == null) { continue; } SymbolicValue invokedArg = invocationArguments.get(index); Set<ProgramState> programStates = programStatesForConstraint(results.isEmpty() ? Lists.newArrayList(programState) : results, invokedArg, constraint); if (programStates.isEmpty()) { return Stream.empty(); } results = programStates; } if(results.isEmpty()) { results.add(programState); } SymbolicValue sv; if (resultIndex < 0) { sv = svSupplier.get(); } else { sv = invocationArguments.get(resultIndex); } Stream<ProgramState> stateStream = results.stream().map(s -> s.stackValue(sv)); if (resultConstraint != null) { stateStream = stateStream.map(s -> s.addConstraint(sv, resultConstraint)); } return stateStream.distinct().map(ps -> new Pair<>(this, ps)); }

Target:
public Stream<ProgramState> statesAfterInvocation(List<SymbolicValue> invocationArguments, List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) { Set<ProgramState> results = new LinkedHashSet<>(); for (int index = 0; index < invocationArguments.size(); index++) { Constraint constraint = getConstraint(index, invocationTypes); if (constraint == null) { continue; } SymbolicValue invokedArg = invocationArguments.get(index); Set<ProgramState> programStates = programStatesForConstraint(results.isEmpty() ? Lists.newArrayList(programState) : results, invokedArg, constraint); if (programStates.isEmpty()) { return Stream.empty(); } results = programStates; } if(results.isEmpty()) { results.add(programState); } SymbolicValue sv; if (resultIndex < 0) { sv = svSupplier.get(); } else { sv = invocationArguments.get(resultIndex); } Stream<ProgramState> stateStream = results.stream().map(s -> s.stackValue(sv)); if (resultConstraint != null) { stateStream = stateStream.map(s -> s.addConstraint(sv, resultConstraint)); } return stateStream.distinct(); }
Source:
private final void fireCommandManagerChanged(final CommandManagerEvent event) { if (event == null) { throw new NullPointerException(); } final Object[] listeners = getListeners(); for (Object listener2 : listeners) { final ICommandManagerListener listener = (ICommandManagerListener) listener2; listener.commandManagerChanged(event); } }

Target:
private final void fireCommandManagerChanged(final CommandManagerEvent event) { if (event == null) { throw new NullPointerException(); } final Object[] listeners = getListeners(); for (Object listener : listeners) { final ICommandManagerListener commandManagerListener = (ICommandManagerListener) listener; commandManagerListener.commandManagerChanged(event); } }
Source:
private void doNamesection(Jar dot, Manifest manifest) { Parameters namesection = parseHeader(getProperties().getProperty(NAMESECTION)); Instructions instructions = new Instructions(namesection); Set<String> resources = new HashSet<>(dot.getResources() .keySet()); dot.getDirectories() .keySet() .stream() .map(d -> d.concat( "/")) .forEach(resources::add); for (Map.Entry<Instruction, Attrs> instr : instructions.entrySet()) { boolean matched = false; for (Iterator<String> i = resources.iterator(); i.hasNext();) { String path = i.next(); if (instr.getKey() .matches(path)) { matched = true; if (!instr.getKey() .isNegated()) { Attributes attrs = manifest.getAttributes(path); if (attrs == null) { attrs = new Attributes(); manifest.getEntries() .put(path, attrs); } for (Map.Entry<String, String> property : instr.getValue() .entrySet()) { setProperty("@", path); try { String processed = getReplacer().process(property.getValue()); attrs.putValue(property.getKey(), processed); } finally { unsetProperty("@"); } } } i.remove(); } } if (!matched && resources.size() > 0) warning("The instruction %s in %s did not match any resources", instr.getKey(), NAMESECTION); } }

Target:
private void doNamesection(Jar dot, Manifest manifest) { Parameters namesection = parseHeader(getProperties().getProperty(NAMESECTION)); Instructions instructions = new Instructions(namesection); Set<String> resources = new HashSet<>(dot.getResources() .keySet()); MapStream.of(dot.getDirectories()) .filterValue(mdir -> Objects.nonNull(mdir) && !mdir.isEmpty()) .keys() .map(d -> d.concat( "/")) .forEach(resources::add); for (Map.Entry<Instruction, Attrs> instr : instructions.entrySet()) { boolean matched = false; for (Iterator<String> i = resources.iterator(); i.hasNext();) { String path = i.next(); Instruction instruction = instr.getKey(); if (path.endsWith("/") && !instruction.toString() .endsWith("/")) { } else if (instruction.matches(path)) { matched = true; if (!instr.getKey() .isNegated()) { Attributes attrs = manifest.getAttributes(path); if (attrs == null) { attrs = new Attributes(); manifest.getEntries() .put(path, attrs); } for (Map.Entry<String, String> property : instr.getValue() .entrySet()) { setProperty("@", path); try { String processed = getReplacer().process(property.getValue()); attrs.putValue(property.getKey(), processed); } finally { unsetProperty("@"); } } } i.remove(); } } if (!matched && resources.size() > 0) warning("The instruction %s in %s did not match any resources", instr.getKey(), NAMESECTION); } }
Source:
public CourseEditInstructorPanel(int instructorToShowIndex, int instructorIndex, InstructorAttributes instructor, List<String> sectionNames, List<String> feedbackNames) { if (instructorToShowIndex == -1) { index = instructorIndex; isAccessControlDisplayed = false; } else { index = instructorToShowIndex; isAccessControlDisplayed = true; } this.instructor = instructor; createSectionRows(instructorIndex, sectionNames, feedbackNames); permissionInputGroup1 = createPermissionInputGroup1ForInstructorPanel(); permissionInputGroup2 = createPermissionInputGroup2ForInstructorPanel(); permissionInputGroup3 = createPermissionInputGroup3ForInstructorPanel(); if (instructor != null) { String style = null; if (instructor.privileges.numberOfSectionsSpecial() >= sectionNames.size()) { style = "display: none;"; } String onClick = "showTuneSectionPermissionsDiv(" + index + ", " + instructor.privileges.numberOfSectionsSpecial() + ")"; String content = "Give different permissions for a specific section"; String id = "addSectionLevelForInstructor" + index; addSectionLevelForInstructorButton = createButton(content, "small", id, "javascript:;", style, onClick); } }

Target:
public CourseEditInstructorPanel(int instructorToShowIndex, int instructorIndex, InstructorAttributes instructor, List<String> sectionNames, List<String> feedbackNames) { if (instructorToShowIndex == -1) { index = instructorIndex; isAccessControlDisplayed = false; } else { index = instructorToShowIndex; isAccessControlDisplayed = true; } this.instructor = instructor; sectionRows = createSectionRows(instructorIndex, sectionNames, feedbackNames); permissionInputGroup1 = createPermissionInputGroup1ForInstructorPanel(); permissionInputGroup2 = createPermissionInputGroup2ForInstructorPanel(); permissionInputGroup3 = createPermissionInputGroup3ForInstructorPanel(); if (instructor != null) { String style = null; if (instructor.privileges.numberOfSectionsSpecial() >= sectionNames.size()) { style = "display: none;"; } String onClick = "showTuneSectionPermissionsDiv(" + index + ", " + instructor.privileges.numberOfSectionsSpecial() + ")"; String content = "Give different permissions for a specific section"; String id = "addSectionLevelForInstructor" + index; addSectionLevelForInstructorButton = createButton(content, "small", id, "javascript:;", style, onClick); } }
Source:
private void dropStored() { final int titleId = (adapter.getCheckedCount() > 0) ? R.string.caches_remove_selected : R.string.caches_remove_all; final int count= adapter.getCheckedOrAllCount(); final String message = (adapter.getCheckedCount() > 0) ? res.getQuantityString(R.plurals.caches_remove_selected_confirm, count, count) : res.getQuantityString(R.plurals.caches_remove_all_confirm,count,count); Dialogs.confirmYesNo(this, titleId, message, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { final List<Geocache> selected = adapter.getCheckedOrAllCaches(); final int lastListPosition = getListView().getFirstVisiblePosition(); new DropDetailsTask(lastListPosition).execute(selected.toArray(new Geocache[selected.size()])); dialog.cancel(); } }); }

Target:
private void dropStored() { final int titleId = (adapter.getCheckedCount() > 0) ? R.string.caches_remove_selected : R.string.caches_remove_all; final int count= adapter.getCheckedOrAllCount(); final String message=res.getQuantityString(adapter.getCheckedCount() > 0 ? R.plurals.caches_remove_selected_confirm:R.plurals.caches_remove_all_confirm,count,count); Dialogs.confirmYesNo(this, titleId, message, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { final List<Geocache> selected = adapter.getCheckedOrAllCaches(); final int lastListPosition = getListView().getFirstVisiblePosition(); new DropDetailsTask(lastListPosition).execute(selected.toArray(new Geocache[selected.size()])); dialog.cancel(); } }); }
Source:
private List<Map.Entry<String, String>> validate( final List<Map.Entry<String, String>> pairs) throws UnsupportedEncodingException { final List<Map.Entry<String, String>> ext = new LinkedList<Map.Entry<String, String>>(); ext.add( new AbstractMap.SimpleEntry<String, String>( "cmd", "_notify-validate" ) ); ext.addAll(pairs); try { new JdkRequest(URI.create("<LINK_0>")) .body() .set(this.join(ext)) .back() .fetch() .as(RestResponse.class) .assertBody(Matchers.equalTo("VERIFIED")); } catch (IOException ex) { throw new IllegalStateException(ex); } return pairs; }

Target:
private List<Map.Entry<String, String>> validate( final List<Map.Entry<String, String>> pairs) throws UnsupportedEncodingException { final List<Map.Entry<String, String>> ext = new LinkedList<Map.Entry<String, String>>(); ext.add( new AbstractMap.SimpleEntry<String, String>( "cmd", "_notify-validate" ) ); ext.addAll(pairs); try { new JdkRequest("<LINK_0>") .body() .set(this.join(ext)) .back() .fetch() .as(RestResponse.class) .assertBody(Matchers.equalTo("VERIFIED")); } catch (IOException ex) { throw new IllegalStateException(ex); } return pairs; }
Source:
private List<JackrabbitAccessControlList> findAcls(ResourceResolver resourceResolver, String principalName, JackrabbitAccessControlManager accessControlManager) throws RepositoryException { final Set<String> paths = new HashSet<String>(); final List<JackrabbitAccessControlList> acls = new ArrayList<JackrabbitAccessControlList>(); final Map<String, String> params = new HashMap<String, String>(); params.put("type", AccessControlConstants.NT_REP_ACE); params.put("property", AccessControlConstants.REP_PRINCIPAL_NAME); params.put("property.value", principalName); params.put("p.limit", "-1"); final Query query = queryBuilder.createQuery(PredicateGroup.create(params), resourceResolver.adaptTo(Session.class)); final Iterator<Resource> resources = query.getResult().getResources(); while (resources.hasNext()) { Resource contentResource = resources.next().getParent().getParent(); if (!paths.contains(contentResource.getPath())) { for (AccessControlPolicy policy : accessControlManager.getPolicies(contentResource.getPath())) { if (policy instanceof JackrabbitAccessControlList) { acls.add((JackrabbitAccessControlList) policy); break; } } } } return acls; }

Target:
private List<JackrabbitAccessControlList> findAcls(ResourceResolver resourceResolver, String principalName, JackrabbitAccessControlManager accessControlManager) throws RepositoryException { final Set<String> paths = new HashSet<String>(); final List<JackrabbitAccessControlList> acls = new ArrayList<JackrabbitAccessControlList>(); final Map<String, String> params = new HashMap<String, String>(); params.put("type", AccessControlConstants.NT_REP_ACE); params.put("property", AccessControlConstants.REP_PRINCIPAL_NAME); params.put("property.value", principalName); params.put("p.limit", "-1"); final Query query = queryBuilder.createQuery(PredicateGroup.create(params), resourceResolver.adaptTo(Session.class)); ResourceResolver leakingResourceResolver = null; for (final Hit hit : query.getResult().getHits()) { try { if (leakingResourceResolver == null) { leakingResourceResolver = hit.getResource().getResourceResolver(); } final Resource aceResource = resourceResolver.getResource(hit.getPath()); final Resource contentResource = aceResource.getParent().getParent(); if (!paths.contains(contentResource.getPath())) { for (AccessControlPolicy policy : accessControlManager.getPolicies(contentResource.getPath())) { if (policy instanceof JackrabbitAccessControlList) { acls.add((JackrabbitAccessControlList) policy); break; } } } } catch (RepositoryException e) { log.error("Failed to get resource for query result.", e); } } if (leakingResourceResolver != null) { leakingResourceResolver.close(); } return acls; }
Source:
public final Flowable<T> toFlowable(BackpressureStrategy strategy) { Flowable<T> o = new FlowableFromObservable<T>(this); switch (strategy) { case DROP: return o.onBackpressureDrop(); case LATEST: return o.onBackpressureLatest(); case NONE: return o; case ERROR: return o.onBackpressureError(); case BUFFER: return o.onBackpressureBuffer(); default: throw new UnsupportedOperationException(); } }

Target:
public final Flowable<T> toFlowable(BackpressureStrategy strategy) { Flowable<T> o = new FlowableFromObservable<T>(this); switch (strategy) { case DROP: return o.onBackpressureDrop(); case LATEST: return o.onBackpressureLatest(); case NONE: return o; case ERROR: return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<T>(o)); default: return o.onBackpressureBuffer(); } }
Source:
void setSessionTimeout(int seconds) { if (seconds < 0) { throw new IllegalArgumentException(); } sessionTimeout = seconds; }

Target:
void setSessionTimeout(int seconds) { sessionTimeout = seconds; }
Source:
protected Compressor<ByteBuf> buildCompressor() { return (Compressor<ByteBuf>) Reflection.buildFromConfig( this, DefaultDriverOption.COMPRESSOR_CLASS, Compressor.class, "com.datastax.oss.driver.internal.core.protocol") .orElse(Compressor.none()); }

Target:
protected Compressor<ByteBuf> buildCompressor() { DriverConfigProfile defaultProfile = config().getDefaultProfile(); if (defaultProfile.isDefined(DefaultDriverOption.PROTOCOL_COMPRESSION)) { String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION); if (name.equalsIgnoreCase("lz4")) { return new Lz4Compressor(this); } else if (name.equalsIgnoreCase("snappy")) { return new SnappyCompressor(this); } else { throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } } else { return Compressor.none(); } }
Source:
public FeedbackTextResponseDetails(String answer) { super(FeedbackQuestionType.TEXT); this.answer = answer == null ? null : Sanitizer.sanitizeForRichText(answer); }

Target:
public FeedbackTextResponseDetails(String answer) { super(FeedbackQuestionType.TEXT); this.answer = Sanitizer.sanitizeForRichText(answer); }
Source:
public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { this(template, nodeDescription, cloud, labelStr); this.setRetentionStrategy(rs); }

Target:
public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { super(getSlaveName(template), nodeDescription, template.getRemoteFs(), 1, Node.Mode.NORMAL, labelStr == null ? null : labelStr, new JNLPLauncher(), rs, template.getNodeProperties()); this.cloud = cloud; }
Source:
public void setRelide(int value) { if (value < 0) { throw new IllegalArgumentException("`value' is negative"); } this.relide = value; }

Target:
public void setRelide(int value) { if (value < 0) { throw new IllegalArgumentException("value is negative"); } this.relide = value; }
Source:
void triggerWorkers() { logger.trace( "Trigger works now" ); while ( frontier.hasMore() ) { Map<RemoteRepository, List<RescanableResourceWrapper>> resources = frontier.remove( config.getBatchSize() ); logger.trace( "Start to trigger threads to download {}", resources ); boolean hasResourceDownload = false; for ( Map.Entry<RemoteRepository, List<RescanableResourceWrapper>> resource : resources.entrySet() ) { if ( resource.getValue() != null && !resource.getValue().isEmpty() ) { hasResourceDownload = true; break; } } if ( hasResourceDownload ) { prefetchExecutor.execute( new PrefetchWorker( transfers, frontier, resources, PrefetchManager.this, specialPathManager ) ); } } }

Target:
void triggerWorkers() { logger.trace( "Trigger works now" ); while ( frontier.hasMore() ) { Map<RemoteRepository, List<RescanableResourceWrapper>> resources = frontier.remove( config.getBatchSize() ); logger.trace( "Start to trigger threads to download {}", resources ); prefetchExecutor.execute( new PrefetchWorker( transfers, frontier, resources, PrefetchManager.this, specialPathManager ) ); } }
Source:
public String[] getCodecs() { return this.codecs.toArray(new String[]{}); }

Target:
public String[] getCodecs() { return this.codecs.toArray(new String[codecs.size()]); }
Source:
private boolean isFieldListHost(FormIndex index) { if (!(this.getModel().getForm().getChild(index) instanceof GroupDef)) { return false; } GroupDef gd = (GroupDef)this.getModel().getForm().getChild(index); return ("field-list".equalsIgnoreCase(gd.getAppearanceAttr())); }

Target:
public boolean isFieldListHost(FormIndex index) { if (!(this.getModel().getForm().getChild(index) instanceof GroupDef)) { return false; } GroupDef gd = (GroupDef)this.getModel().getForm().getChild(index); return (FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr())); }
Source:
public void layout(boolean changed) { super.requestLayout(); hookSashListeners(); }

Target:
public void layout(boolean changed) { super.layout(changed); hookSashListeners(); }
Source:
public void finishMemoryRevoke() { if (state == State.CONSUMING_INPUT) { index.clear(); operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); operatorContext.setRevocableMemoryReservation(0L); state = State.SPILLING_INPUT; return; } if (state == State.LOOKUP_SOURCE_BUILT) { lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle); lookupSourceNotNeeded = Optional.empty(); index.clear(); operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); operatorContext.setRevocableMemoryReservation(0L); state = State.LOOKUP_SOURCE_SPILLED; return; } long reservedRevocableBytes = operatorContext.getReservedRevocableBytes(); if (reservedRevocableBytes == 0) { return; } throw new IllegalStateException("Cannot finish unknown revoking"); }

Target:
public void finishMemoryRevoke() { checkState(finishMemoryRevoke.isPresent(), "Cannot finish unknown revoking"); finishMemoryRevoke.get().run(); finishMemoryRevoke = Optional.empty(); }
Source:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; System.out.println(getPatternsForMatch().size()); if (messageNeedsResolve(message)) { log.debug("Resolving virtual attribute value change for message: " + message); User user = perunSession.getPerunBl().getModulesUtilsBl().getUserFromMessage(perunSession, message); if (user != null) { Attribute attribute = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, getDestinationAttributeName()); @SuppressWarnings("unchecked") List<String> attributeValue = (ArrayList<String>) attribute.getValue(); String messageAttributeSet; if (attributeValue == null || attributeValue.isEmpty()) { AttributeDefinition attributeDefinition = new AttributeDefinition(attribute); messageAttributeSet = attributeDefinition.serializeToString() + " removed for " + user.serializeToString() + "."; } else { messageAttributeSet = attribute.serializeToString() + " set for " + user.serializeToString() + "."; } resolvingMessages.add(messageAttributeSet); } if(!resolvingMessages.isEmpty()) log.debug("These new messages will be generated: " + resolvingMessages); } return resolvingMessages; }

Target:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; if (messageNeedsResolve(message)) { log.debug("Resolving virtual attribute value change for message: " + message); User user = perunSession.getPerunBl().getModulesUtilsBl().getUserFromMessage(perunSession, message); if (user != null) { Attribute attribute = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, getDestinationAttributeName()); @SuppressWarnings("unchecked") List<String> attributeValue = (ArrayList<String>) attribute.getValue(); String messageAttributeSet; if (attributeValue == null || attributeValue.isEmpty()) { AttributeDefinition attributeDefinition = new AttributeDefinition(attribute); messageAttributeSet = attributeDefinition.serializeToString() + " removed for " + user.serializeToString() + "."; } else { messageAttributeSet = attribute.serializeToString() + " set for " + user.serializeToString() + "."; } resolvingMessages.add(messageAttributeSet); } if(!resolvingMessages.isEmpty()) log.debug("These new messages will be generated: " + resolvingMessages); } return resolvingMessages; }
Source:
public void endDocument() throws SAXException { for (PmcIngestAuthor pmcAuthor : currentAuthors) { Author author = Author.newBuilder() .setAffiliationPositions(Lists.newArrayList()) .setFullname(pmcAuthor.getSurname() + ", " + pmcAuthor.getGivenNames()) .setAffiliationPositions(pmcAuthor.getAffiliationPos()) .build(); builder.getAuthors().add(author); } }

Target:
public void endDocument() throws SAXException { for (JatsAuthor pmcAuthor : currentAuthors) { Author author = Author.newBuilder() .setFullname(pmcAuthor.getSurname() + ", " + pmcAuthor.getGivenNames()) .setAffiliationPositions(pmcAuthor.getAffiliationPos()) .build(); builder.getAuthors().add(author); } }
Source:
public InstructorCourseEnrollResultPageData(AccountAttributes account, String courseId, List<StudentAttributes>[] students, boolean hasSection, String enrollStudents) { super(account); this.courseId = courseId; this.students = students; this.hasSection = hasSection; this.enrollStudents = enrollStudents; enrollResultPanelList = new ArrayList<EnrollResultPanel>(); for (int i = 0; i < UpdateStatus.STATUS_COUNT; i++) { String panelClass = ""; if (i == UpdateStatus.ERROR.numericRepresentation) { panelClass = "panel panel-danger"; } else if (i == UpdateStatus.NEW.numericRepresentation) { panelClass = "panel panel-primary"; } else if (i == UpdateStatus.MODIFIED.numericRepresentation) { panelClass = "panel panel-warning"; } else if (i == UpdateStatus.UNMODIFIED.numericRepresentation) { panelClass = "panel panel-info"; } else if (i == UpdateStatus.NOT_IN_ENROLL_LIST.numericRepresentation) { panelClass = "panel panel-default"; } else { panelClass = "panel panel-danger"; } String messageForEnrollmentStatus = getMessageForEnrollmentStatus(i); EnrollResultPanel enrollResultPanel = new EnrollResultPanel(panelClass, messageForEnrollmentStatus, students[i]); enrollResultPanelList.add(enrollResultPanel); } }

Target:
public InstructorCourseEnrollResultPageData(AccountAttributes account, String courseId, List<StudentAttributes>[] students, boolean hasSection, String enrollStudents) { super(account); this.courseId = courseId; this.students = students; this.hasSection = hasSection; this.enrollStudents = enrollStudents; enrollResultPanelList = new ArrayList<EnrollResultPanel>(); for (int i = 0; i < UpdateStatus.STATUS_COUNT; i++) { String panelClass = ""; switch (UpdateStatus.enumRepresentation(i)) { case ERROR : panelClass = "panel-danger"; break; case NEW : panelClass = "panel-primary"; break; case MODIFIED : panelClass = "panel-warning"; break; case UNMODIFIED : panelClass = "panel-info"; break; case NOT_IN_ENROLL_LIST : panelClass = "panel-default"; break; case UNKNOWN : panelClass = "panel-danger"; break; default : log.severe("Unknown Enrollment status " + i); break; } String messageForEnrollmentStatus = getMessageForEnrollmentStatus(i); EnrollResultPanel enrollResultPanel = new EnrollResultPanel(panelClass, messageForEnrollmentStatus, students[i]); enrollResultPanelList.add(enrollResultPanel); } }
Source:
public Page<CollectionRest> findAuthorizedByCommunity( @Parameter(value = "uuid", required = true) UUID communityUuid, Pageable pageable, @Parameter(value = "query") String q) { try { Context context = obtainContext(); Community com = communityService.find(context, communityUuid); if (com == null) { throw new ResourceNotFoundException( CommunityRest.CATEGORY + "." + CommunityRest.NAME + " with id: " + communityUuid + " not found"); } List<Collection> collections = new LinkedList<Collection>(); DiscoverResult resp = discoverAuthorizedCollections(pageable, q, context, com); long tot = resp.getTotalSearchResults(); for (IndexableObject solrCollections : resp.getIndexableObjects()) { Collection c = ((IndexableCollection) solrCollections).getIndexedObject(); collections.add(c); } return converter.toRestPage(collections, pageable, tot , utils.obtainProjection()); } catch (SQLException | SearchServiceException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
public Page<CollectionRest> findAuthorizedByCommunity( @Parameter(value = "uuid", required = true) UUID communityUuid, Pageable pageable, @Parameter(value = "query") String q) { try { Context context = obtainContext(); Community com = communityService.find(context, communityUuid); if (com == null) { throw new ResourceNotFoundException( CommunityRest.CATEGORY + "." + CommunityRest.NAME + " with id: " + communityUuid + " not found"); } List<Collection> collections = cs.findAuthorizedCollectionsInSOLR(q, context, com, Math.toIntExact(pageable.getOffset()), Math.toIntExact(pageable.getOffset() + pageable.getPageSize())); int tot = cs.countAuthorizedCollectionsInSOLR(q, context, com); return converter.toRestPage(collections, pageable, tot , utils.obtainProjection()); } catch (SQLException | SearchServiceException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
private synchronized KeyPair getKeyPairFromAndroidKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); try { if (!keyStore.containsAlias(KEY_STORE_CERT_ALIAS)) { Logger.v(TAG, "Key entry is not available"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(getKeyPairGeneratorSpec(mContext, start.getTime(), end.getTime())); try { generator.generateKeyPair(); } catch (final IllegalStateException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Key entry is generated"); } else { Logger.v(TAG, "Key entry is available"); } } catch (final NullPointerException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Reading Key entry"); try { final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); } catch (RuntimeException e) { throw new KeyStoreException(e); } }

Target:
private synchronized KeyPair getKeyPairFromAndroidKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); final boolean isKeyStoreCertAliasExisted; try { isKeyStoreCertAliasExisted = keyStore.containsAlias(KEY_STORE_CERT_ALIAS); } catch (final NullPointerException exception) { throw new KeyStoreException(exception); } if (!isKeyStoreCertAliasExisted) { Logger.v(TAG, "Key entry is not available"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(getKeyPairGeneratorSpec(mContext, start.getTime(), end.getTime())); try { generator.generateKeyPair(); } catch (final IllegalStateException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Key entry is generated"); } else { Logger.v(TAG, "Key entry is available"); } Logger.v(TAG, "Reading Key entry"); try { final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); } catch (RuntimeException e) { throw new KeyStoreException(e); } }
Source:
public long getReadOperations() { return ioStatisticsStore.counters().get(StreamStatisticNames.STREAM_READ_OPERATIONS); }

Target:
public long getReadOperations() { return ioStatisticsStore.counters().get(STREAM_READ_OPERATIONS); }
Source:
public void dataSourcesAndDurations(JoinQuery query) { builder.setDimension( "dataSourcesAndDurations", DataSourceUtil.getMetricName(query.getDataSources()) ); }

Target:
public void dataSourcesAndDurations(JoinQuery query) { builder.setDimension( "dataSourcesAndDurations", query.getDataSources().stream() .map( spec -> "{dataSource=" + DataSourceUtil.getMetricName(spec.getDataSource()) + ",duration=" + query.getDuration(spec.getDataSource()) + "}" ) .toArray(String[]::new) ); }
Source:
public void init() { this.owner = new Owner(); this.owner.setId("test-owner-id"); this.translator = new StandardTranslator(mockConsumerTypeCurator, mockEnvironmentCurator, ownerCurator, entitlementCurator); i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.importer = new EntitlementImporter(certSerialCurator, cdnCurator, i18n, mockProductCurator, ec, translator); ConsumerType ctype = TestUtil.createConsumerType(); ctype.setId("test-ctype"); consumer = TestUtil.createConsumer(ctype, owner); consumerDTO = this.translator.translate(consumer, ConsumerDTO.class); consumerDTO.setUrlWeb(""); consumerDTO.setUrlApi(""); when(this.mockConsumerTypeCurator.getConsumerType(eq(consumer))).thenReturn(ctype); when(this.mockConsumerTypeCurator.get(eq(ctype.getId()))).thenReturn(ctype); cert = createEntitlementCertificate("my-test-key", "my-cert"); cert.setId("test-id"); reader = mock(Reader.class); meta = new Meta(); meta.setCdnLabel("test-cdn"); testCdn = new Cdn("test-cdn", "Test CDN", "<LINK_0>"); when(cdnCurator.getByLabel("test-cdn")).thenReturn(testCdn); }

Target:
public void init() { this.owner = new Owner(); this.owner.setId("test-owner-id"); this.translator = new StandardTranslator(mockConsumerTypeCurator, mockEnvironmentCurator, ownerCurator); i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.importer = new EntitlementImporter(certSerialCurator, cdnCurator, i18n, mockProductCurator, ec, translator); ConsumerType ctype = TestUtil.createConsumerType(); ctype.setId("test-ctype"); consumer = TestUtil.createConsumer(ctype, owner); consumerDTO = this.translator.translate(consumer, ConsumerDTO.class); consumerDTO.setUrlWeb(""); consumerDTO.setUrlApi(""); when(this.mockConsumerTypeCurator.getConsumerType(eq(consumer))).thenReturn(ctype); when(this.mockConsumerTypeCurator.get(eq(ctype.getId()))).thenReturn(ctype); cert = createEntitlementCertificate("my-test-key", "my-cert"); cert.setId("test-id"); reader = mock(Reader.class); meta = new Meta(); meta.setCdnLabel("test-cdn"); testCdn = new Cdn("test-cdn", "Test CDN", "<LINK_0>"); when(cdnCurator.getByLabel("test-cdn")).thenReturn(testCdn); }