auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public GitLabApiForm getQueryParams() { return (new GitLabApiForm() .withParam("iids", iids) .withParam("state", state) .withParam("order_by", orderBy) .withParam("sort", sort) .withParam("milestone", milestone) .withParam("view", (simpleView != null && simpleView ? "simple" : null)) .withParam("labels", (labels != null? String.join(",", labels) : null)) .withParam("created_after", createdAfter) .withParam("created_before", createdBefore) .withParam("updated_after", updatedAfter) .withParam("updated_before", updatedBefore) .withParam("scope", scope) .withParam("assignee_id", assigneeId) .withParam("my_reaction_emoji", myReactionEmoji) .withParam("source_branch", sourceBranch) .withParam("target_branch", targetBranch) .withParam("search", search) .withParam("in", in) .withParam("wip", wip)); }

Target:
public GitLabApiForm getQueryParams() { return (new GitLabApiForm() .withParam("iids", iids) .withParam("state", state) .withParam("order_by", orderBy) .withParam("sort", sort) .withParam("milestone", milestone) .withParam("view", (simpleView != null && simpleView ? "simple" : null)) .withParam("labels", (labels != null? String.join(",", labels) : null)) .withParam("created_after", createdAfter) .withParam("created_before", createdBefore) .withParam("updated_after", updatedAfter) .withParam("updated_before", updatedBefore) .withParam("scope", scope) .withParam("assignee_id", assigneeId) .withParam("my_reaction_emoji", myReactionEmoji) .withParam("source_branch", sourceBranch) .withParam("target_branch", targetBranch) .withParam("search", search) .withParam("in", in) .withParam("wip", (wip == null ? null : wip ? "yes" : "no"))); }
Source:
public String getRepositoryUrl() { if (repositoryUrl != null) { return repositoryUrl; } else { if (isBlank(apiUri) || "<LINK_0>".equals(apiUri)) return "<LINK_1>" + repoOwner + '/' + repository; else return String.format("%s/%s/%s", removeEnd(apiUri, API_V3), repoOwner, repository); } }

Target:
public String getRepositoryUrl() { if (repositoryUrl != null) { return repositoryUrl; } else { if (GITHUB_URL.equals(apiUri)) return "<LINK_1>" + repoOwner + '/' + repository; else return String.format("%s%s/%s", removeEnd(apiUri, API_V3), repoOwner, repository); } }
Source:
public TableRow createViewRow(TableRow rowView, Value value, int position) { CustomTextView questionTextView = (CustomTextView) rowView.findViewById( R.id.review_title_text); TextView answerText = (TextView) rowView.findViewById(R.id.review_answer); if ((value.getQuestionUId() != null)) { rowView.setTag(value.getQuestionUId()); String question = (QuestionDB.findByUID( value.getQuestionUId()).getInternationalizedCodeDe_Name()); if (!question.contains(TITLE_SEPARATOR)) { question = question + TITLE_SEPARATOR; } String answer = ((value.getInternationalizedName() != null) ? value.getInternationalizedName() : value.getValue()); if (answer.equals("")) { answer = (PreferencesState.getInstance().getContext().getString( R.string.empty_review_value)); } questionTextView.setText(question); answerText.setText(answer); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!DynamicTabAdapter.isClicked) { DynamicTabAdapter.isClicked = true; String questionUId = (String) v.getTag(); onClickListener.onClickOnValue(questionUId); } } }); rowView.setBackgroundColor( Color.parseColor(value.getBackgroundColor())); } return rowView; }

Target:
public TableRow createViewRow(TableRow rowView, Value value, int position) { CustomTextView questionTextView = (CustomTextView) rowView.findViewById( R.id.review_title_text); CustomTextView answerText = (CustomTextView) rowView.findViewById(R.id.review_answer); if ((value.getQuestionUId() != null)) { rowView.setTag(value.getQuestionUId()); String question = (QuestionDB.findByUID( value.getQuestionUId()).getInternationalizedCodeDe_Name()); if (!question.contains(TITLE_SEPARATOR)) { question = question + TITLE_SEPARATOR; } String answer = ((value.getInternationalizedName() != null) ? value.getInternationalizedName() : value.getValue()); if (answer.equals("")) { answer = (PreferencesState.getInstance().getContext().getString( R.string.empty_review_value)); } questionTextView.setText(question); answerText.setText(answer); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!DynamicTabAdapter.isClicked) { DynamicTabAdapter.isClicked = true; String questionUId = (String) v.getTag(); onClickListener.onClickOnValue(questionUId); } } }); rowView.setBackgroundColor( Color.parseColor(value.getBackgroundColor())); } return rowView; }
Source:
private SecretKey getMacKey(SecretKey key) { byte[] encodedKey = key.getEncoded(); if (encodedKey != null) return new SecretKeySpec(encodedKey, KEYSPEC_ALGORITHM); return key; }

Target:
private SecretKey getMacKey(SecretKey key) throws NoSuchAlgorithmException { byte[] encodedKey = key.getEncoded(); if (encodedKey != null) { MessageDigest digester = MessageDigest.getInstance(MAC_KEY_HASH_ALGORITHM); return new SecretKeySpec(digester.digest(encodedKey), KEYSPEC_ALGORITHM); } return key; }
Source:
public void testSimpleDuplicatesWithSecondaryAndSupplementaryRecords() throws IOException { final File input = new File(TEST_DATA_DIR, "dupes_with_sos.sam"); final File output = File.createTempFile("estimateLibraryComplexity",".els_metrics"); output.deleteOnExit(); final List<String> args =new ArrayList<String>(); args.add("INPUT=" + input.getAbsolutePath()); args.add("OUTPUT=" + output.getAbsolutePath()); args.add("MIN_GROUP_COUNT=1"); Assert.assertEquals(runPicardCommandLine(args), 0); examineMetricsFile(output, 2, 2); }

Target:
public void testSimpleDuplicatesWithSecondaryAndSupplementaryRecords() throws IOException { final File input = new File(TEST_DATA_DIR, "dupes_with_sos.sam"); final File output = File.createTempFile("estimateLibraryComplexity",".els_metrics"); output.deleteOnExit(); final List<String> args = new ArrayList<>(); args.add("INPUT=" + input.getAbsolutePath()); args.add("OUTPUT=" + output.getAbsolutePath()); args.add("MIN_GROUP_COUNT=1"); Assert.assertEquals(runPicardCommandLine(args), 0); examineMetricsFile(output, 2, 2); }
Source:
private void initMenuPopup(List<ActionButtonDefinition<T>> actions) { if (menuPopup == null) { menuPopup = new DropDownMenu(); } for (final ActionButtonDefinition<T> buttonDef : actions) { if (buttonDef instanceof UiMenuBarButtonDefinition) { UiMenuBarButtonDefinition<T> menuBarDef = (UiMenuBarButtonDefinition<T>) buttonDef; DropDownHeader subMenuHeader = new DropDownHeader(buttonDef.getText()); menuPopup.add(new Divider()); menuPopup.add(subMenuHeader); initMenuPopup(menuBarDef.getSubActions()); } else { AnchorListItem menuItem = new AnchorListItem(buttonDef.getText()); menuItem.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { buttonDef.onClick(selectedItemsProvider.getSelectedItems()); } }); updateMenuItem(menuItem, buttonDef, selectedItemsProvider.getSelectedItems()); menuPopup.add(menuItem); items.add(new Pair<>(menuItem, buttonDef)); } } add(menuPopup); }

Target:
private void initMenuPopup(List<ActionButtonDefinition<T>> actions) { if (menuPopup == null) { menuPopup = new DropDownMenu(); } for (final ActionButtonDefinition<T> buttonDef : actions) { if (buttonDef instanceof UiMenuBarButtonDefinition) { UiMenuBarButtonDefinition<T> menuBarDef = (UiMenuBarButtonDefinition<T>) buttonDef; DropDownHeader subMenuHeader = new DropDownHeader(buttonDef.getText()); menuPopup.add(new Divider()); menuPopup.add(subMenuHeader); initMenuPopup(menuBarDef.getSubActions()); } else { AnchorListItem menuItem = new AnchorListItem(buttonDef.getText()); menuItem.addClickHandler(e -> { buttonDef.onClick(selectedItemsProvider.getSelectedItems()); }); updateMenuItem(menuItem, buttonDef, selectedItemsProvider.getSelectedItems()); menuPopup.add(menuItem); items.add(new Pair<>(menuItem, buttonDef)); } } add(menuPopup); }
Source:
private MaxwellAbstractRowsEvent processRowsEvent(AbstractRowEvent e) throws SchemaSyncError { MaxwellAbstractRowsEvent ew; Table table; table = tableCache.getTable(e.getTableId()); if ( table == null && this.filter.hasTableBlacklist() ) { LOGGER.warn(String.format("couldn't find table in cache for table id: %d, assuming blacklisted table", e.getTableId())); return null; } else if ( table == null ) { throw new SchemaSyncError("couldn't find table in cache for table id: " + e.getTableId()); } switch (e.getHeader().getEventType()) { case MySQLConstants.WRITE_ROWS_EVENT: ew = new MaxwellWriteRowsEvent((WriteRowsEvent) e, table, filter); break; case MySQLConstants.WRITE_ROWS_EVENT_V2: ew = new MaxwellWriteRowsEvent((WriteRowsEventV2) e, table, filter); break; case MySQLConstants.UPDATE_ROWS_EVENT: ew = new MaxwellUpdateRowsEvent((UpdateRowsEvent) e, table, filter); break; case MySQLConstants.UPDATE_ROWS_EVENT_V2: ew = new MaxwellUpdateRowsEvent((UpdateRowsEventV2) e, table, filter); break; case MySQLConstants.DELETE_ROWS_EVENT: ew = new MaxwellDeleteRowsEvent((DeleteRowsEvent) e, table, filter); break; case MySQLConstants.DELETE_ROWS_EVENT_V2: ew = new MaxwellDeleteRowsEvent((DeleteRowsEventV2) e, table, filter); break; default: return null; } return ew; }

Target:
private MaxwellAbstractRowsEvent processRowsEvent(AbstractRowEvent e) throws SchemaSyncError { MaxwellAbstractRowsEvent ew; Table table; long tableId = e.getTableId(); if ( tableCache.isTableBlacklisted(tableId) ) { LOGGER.debug(String.format("ignoring row event for blacklisted table %s", tableCache.getBlacklistedTableName(tableId))); return null; } table = tableCache.getTable(tableId); if ( table == null ) { throw new SchemaSyncError("couldn't find table in cache for table id: " + tableId); } switch (e.getHeader().getEventType()) { case MySQLConstants.WRITE_ROWS_EVENT: ew = new MaxwellWriteRowsEvent((WriteRowsEvent) e, table, filter); break; case MySQLConstants.WRITE_ROWS_EVENT_V2: ew = new MaxwellWriteRowsEvent((WriteRowsEventV2) e, table, filter); break; case MySQLConstants.UPDATE_ROWS_EVENT: ew = new MaxwellUpdateRowsEvent((UpdateRowsEvent) e, table, filter); break; case MySQLConstants.UPDATE_ROWS_EVENT_V2: ew = new MaxwellUpdateRowsEvent((UpdateRowsEventV2) e, table, filter); break; case MySQLConstants.DELETE_ROWS_EVENT: ew = new MaxwellDeleteRowsEvent((DeleteRowsEvent) e, table, filter); break; case MySQLConstants.DELETE_ROWS_EVENT_V2: ew = new MaxwellDeleteRowsEvent((DeleteRowsEventV2) e, table, filter); break; default: return null; } return ew; }
Source:
public void testFilterWithCredentials() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("htto://localhost/foo").build(); Credentials credentials = LoginCredentials.builder().identity("foo").credential("bar").build(); AuthenticationFilter filter = new AuthenticationFilter(Suppliers.ofInstance(credentials)); HttpRequest filtered = filter.filter(request); String queryLine = filtered.getRequestLine().trim() .substring(filtered.getRequestLine().indexOf('?') + 1, filtered.getRequestLine().lastIndexOf(' ')); Multimap<String, String> params = queryParser().apply(queryLine); assertEquals(getOnlyElement(params.get(IDENTITY_PARAM)), "foo"); assertEquals(getOnlyElement(params.get(CREDENTIAL_PARAM)), "bar"); }

Target:
public void testFilterWithCredentials() { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http://localhost/foo").build(); Credentials credentials = LoginCredentials.builder().identity("foo").credential("bar").build(); AuthenticationFilter filter = new AuthenticationFilter(Suppliers.ofInstance(credentials)); HttpRequest filtered = filter.filter(request); String queryLine = filtered.getRequestLine().trim() .substring(filtered.getRequestLine().indexOf('?') + 1, filtered.getRequestLine().lastIndexOf(' ')); Multimap<String, String> params = queryParser().apply(queryLine); assertEquals(getOnlyElement(params.get(IDENTITY_PARAM)), "foo"); assertEquals(getOnlyElement(params.get(CREDENTIAL_PARAM)), "bar"); }
Source:
public List<TaskInfo> getActiveTaskInfo() { return getConnector().retryWithHandle( handle -> { return handle.createQuery( StringUtils.format( "SELECT id, status_payload, datasource, created_date FROM %s WHERE active = TRUE ORDER BY created_date", entryTable ) ).map(new TaskMapper()).list(); } ); }

Target:
public List<TaskInfo<EntryType>> getActiveTaskInfo() { return getConnector().retryWithHandle( handle -> { return handle.createQuery( StringUtils.format( "SELECT id, status_payload, payload, datasource, created_date FROM %s WHERE active = TRUE ORDER BY created_date", entryTable ) ).map(new TaskInfoMapper()).list(); } ); }
Source:
public void setMainTabSelectedItem(Erratum selectedItem) { logger.info("setMainTabSelectedItem"); updateErrataDetailFormPanel(selectedItem); }

Target:
public void setMainTabSelectedItem(Erratum selectedItem) { updateErrataDetailFormPanel(selectedItem); }
Source:
public void testNonZeroExitCodeException() { DoNothingWinRmSoftwareProcessDriver nativeWindowsScriptRunner = mock(DoNothingWinRmSoftwareProcessDriver.class); when(nativeWindowsScriptRunner.executeCommand(any(Map.class), any(String.class), any(String.class), any(String.class), any(Boolean.class))).thenReturn(1); WinRmExecuteHelper scriptHelper = new WinRmExecuteHelper(nativeWindowsScriptRunner, "test-zero-code-task") .failOnNonZeroResultCode() .setCommand(NON_ZERO_CODE_COMMAND); Asserts.assertTrue(scriptHelper.executeInternal() != 0, "WinRmExecuteHelper return zero code for non-zero code task"); }

Target:
public void testNonZeroExitCodeException() { DoNothingWinRmSoftwareProcessDriver nativeWindowsScriptRunner = mock(DoNothingWinRmSoftwareProcessDriver.class); when(nativeWindowsScriptRunner.executeNativeOrPsCommand(any(Map.class), any(String.class), any(String.class), any(String.class), any(Boolean.class))).thenReturn(1); WinRmExecuteHelper scriptHelper = new WinRmExecuteHelper(nativeWindowsScriptRunner, "test-zero-code-task") .failOnNonZeroResultCode() .setCommand(NON_ZERO_CODE_COMMAND); scriptHelper.executeInternal(); }
Source:
private static Collection<?> typeScriptExtensions() { return Arrays.asList( TypeScriptLanguage.class, PropertyDefinition.builder(TypeScriptLanguage.FILE_SUFFIXES_KEY) .defaultValue(TypeScriptLanguage.FILE_SUFFIXES_DEFVALUE) .name("File Suffixes") .description("Comma-separated list of suffixes for files to analyze.") .subCategory(GENERAL_SUBCATEGORY) .category(TYPESCRIPT_CATEGORY) .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build() ); }

Target:
private static Collection<?> typeScriptExtensions() { return Arrays.asList( TypeScriptLanguage.class, PropertyDefinition.builder(TypeScriptLanguage.FILE_SUFFIXES_KEY) .defaultValue(TypeScriptLanguage.FILE_SUFFIXES_DEFVALUE) .name(FILE_SUFFIXES_NAME) .description(FILE_SUFFIXES_DESCRIPTION) .subCategory(GENERAL) .category(TYPESCRIPT_CATEGORY) .onQualifiers(Qualifiers.PROJECT) .multiValues(true) .build() ); }
Source:
private void detectSlaveChanges() { for (VdsNetworkInterface newIface : params.getInterfaces()) { if (!isBond(newIface) && newIface.getVlanId() == null) { String bondNameInNewIface = newIface.getBondName(); String bondNameInOldIface = getExistingIfaces().get(newIface.getName()).getBondName(); if (!StringUtils.equals(bondNameInNewIface, bondNameInOldIface)) { if (bondNameInNewIface != null && !modifiedBonds.containsKey(bondNameInNewIface)) { modifiedBonds.put(bondNameInNewIface, getExistingIfaces().get(bondNameInNewIface)); } if (bondNameInOldIface != null && !removedBonds.contains(bondNameInOldIface)) { modifiedBonds.put(bondNameInOldIface, getExistingIfaces().get(bondNameInOldIface)); } } } } }

Target:
private void detectSlaveChanges() { for (VdsNetworkInterface newIface : params.getInterfaces()) { if (!isBond(newIface) && newIface.getVlanId() == null) { String bondNameInNewIface = newIface.getBondName(); String bondNameInOldIface = getExistingIfaces().get(newIface.getName()).getBondName(); if (!StringUtils.equals(bondNameInNewIface, bondNameInOldIface)) { if (bondNameInNewIface != null && !modifiedBonds.containsKey(bondNameInNewIface)) { modifiedBonds.put(bondNameInNewIface, getExistingIfaces().get(bondNameInNewIface)); } if (bondNameInOldIface != null && !modifiedBonds.containsKey(bondNameInNewIface) && !removedBonds.contains(bondNameInOldIface)) { modifiedBonds.put(bondNameInOldIface, getExistingIfaces().get(bondNameInOldIface)); } } } } }
Source:
public CommandResult<?> execute(final Object context, final CommandManager commandManager) { if (registry.isEmpty()) { return null; } final C last = registry.peek(); return commandManager.execute(context, last); }

Target:
public CommandResult<?> execute(final Object context, final CommandManager commandManager) { if (registry.isEmpty()) { throw new IllegalStateException("Not possible to execute a command: no commands to redo."); } final C last = registry.peek(); return commandManager.execute(context, last); }
Source:
private void find() { Path venv = baseDir.resolve(venvDirectoryName); if(Files.isDirectory(venv)) { LOG.info(String.format("Looking for a Python environment in %s", venv)); Path config = venv.resolve(configName); Path binary = venv.resolve(binaryName); if(Files.isRegularFile(config) && Files.isRegularFile(binary)) { try { version = Files.lines(config) .filter(l -> l.startsWith(versionPrefix)) .map(l -> l.substring(versionPrefix.length())) .findFirst(); } catch (IOException e) { LOG.warn(String.format("An error occurred while reading %s", config), e); } LOG.info(String.format("Found Python version %s at %s", version.orElse("unknown"), venv)); PythonInterpreterInfo result = new PythonInterpreterInfo(); result.setBinary(venv.resolve(binaryName).toString()); result.setChroot(venv.toString()); environment = Optional.of(result); } } }

Target:
private void find() { Path venv = baseDir.resolve(venvDirectoryName); if(Files.isDirectory(venv)) { LOG.info(String.format("Looking for a Python environment in %s", venv)); Path config = venv.resolve(configName); Path binary = venv.resolve(binaryName); if(Files.isRegularFile(config) && Files.isRegularFile(binary)) { try { version = Files.lines(config) .filter(l -> l.startsWith(versionPrefix)) .map(l -> l.substring(versionPrefix.length())) .findFirst(); } catch (IOException e) { LOG.error(String.format("An error occurred while reading %s", config), e); } LOG.info(String.format("Found Python version %s at %s", version.orElse("unknown"), venv)); PythonInterpreterInfo result = new PythonInterpreterInfo(); result.setBinary(venv.resolve(binaryName).toString()); result.setChroot(venv.toString()); environment = Optional.of(result); } } }
Source:
ItemDefinition getItemDefinitionWithItemComponent(final ItemDefinition itemDefinition) { if (itemDefinition.getTypeRef() != null) { final Optional<ItemDefinition> definition = findByName(itemDefinition.getTypeRef().getLocalPart()); if (definition.isPresent()) { return getItemDefinitionWithItemComponent(definition.get()); } } return itemDefinition; }

Target:
ItemDefinition getItemDefinitionWithItemComponent(final ItemDefinition itemDefinition) { if (itemDefinition.getTypeRef() != null) { final Optional<ItemDefinition> definition = findByName(itemDefinitionType(itemDefinition)); if (definition.isPresent()) { return getItemDefinitionWithItemComponent(definition.get()); } } return itemDefinition; }
Source:
public static void loginOnBehalf(HttpServletRequest request, String username) throws Exception { log.debug("Entered AuthenticationUtils.loginOnBehalf"); int index = username.lastIndexOf("@"); String profile = null; if (index != -1) { profile = username.substring(index + 1); username = username.substring(0, index); } if (StringUtils.isEmpty(username) || StringUtils.isEmpty(profile)) { throw new AuthenticationException("Please provide username and profile."); } ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false) .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); mapper.getDeserializationConfig().addMixInAnnotations(ExtMap.class, JsonExtMapMixIn.class); login(request, new Credentials(username, null, profile, SSOUtils.getSsoContext(request).getSsoProfiles().contains(profile)), mapper.readValue(SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_AUTH_RECORD), ExtMap.class)); }

Target:
public static void loginOnBehalf(HttpServletRequest request, String username) throws Exception { log.debug("Entered AuthenticationUtils.loginOnBehalf"); int index = username.lastIndexOf("@"); String profile = null; if (index != -1) { profile = username.substring(index + 1); username = username.substring(0, index); } if (StringUtils.isEmpty(username) || StringUtils.isEmpty(profile)) { throw new AuthenticationException("Please provide username and profile."); } ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false) .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); mapper.getDeserializationConfig().addMixInAnnotations(ExtMap.class, JsonExtMapMixIn.class); String authRecordJson = SSOUtils.getRequestParameter(request, SSOConstants.HTTP_PARAM_AUTH_RECORD, ""); ExtMap authRecord; if (StringUtils.isNotEmpty(authRecordJson)) { authRecord = mapper.readValue(authRecordJson, ExtMap.class); } else { authRecord = new ExtMap().mput(Authn.AuthRecord.PRINCIPAL, username); } SSOSession ssoSession = login(request, new Credentials(username, null, profile, SSOUtils.getSsoContext(request).getSsoProfiles().contains(profile)), authRecord); log.info("User {}@{} successfully logged in using login-on-behalf with client id : and scopes : {}", username, profile, ssoSession.getClientId(), ssoSession.getScope()); }
Source:
public AdbQrcodeScannerFragment() { super(); mIntentFilter = new IntentFilter(AdbManager.WIRELESS_DEBUG_PAIRING_RESULT_ACTION); }

Target:
public AdbQrcodeScannerFragment() { super(); }
Source:
public int getFinishedMappersCount() { return finishedMappers; }

Target:
public int getFinishedMappersCount() { return finishedMappersCount; }
Source:
public void close() { selector.close(); }

Target:
public void close() { isOpen = false; }
Source:
public List<Attribute> getAttributes(PerunSession sess, Member member, Group group) throws InternalErrorException { try { return jdbc.query("select " + getAttributeMappingSelectQuery("mem") + " from attr_names " + "left join member_group_attr_values mem on attr_names.id=mem.attr_id and mem.group_id=? and member_id=? " + "where namespace in (?,?) and (mem.attr_value is not null or mem.attr_value_text is not null)", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), AttributesManager.NS_MEMBER_GROUP_ATTR_DEF, AttributesManager.NS_MEMBER_GROUP_ATTR_OPT); } catch(EmptyResultDataAccessException ex) { log.debug("No attribute for member-group combination exists."); return new ArrayList<Attribute>(); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }

Target:
public List<Attribute> getAttributes(PerunSession sess, Member member, Group group) throws InternalErrorException { try { return jdbc.query("select " + getAttributeMappingSelectQuery("mem_gr") + " from attr_names " + "left join member_group_attr_values mem_gr on attr_names.id=mem_gr.attr_id and mem_gr.group_id=? and member_id=? " + "where namespace in (?,?) and (mem_gr.attr_value is not null or mem_gr.attr_value_text is not null)", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), AttributesManager.NS_MEMBER_GROUP_ATTR_DEF, AttributesManager.NS_MEMBER_GROUP_ATTR_OPT); } catch(EmptyResultDataAccessException ex) { log.debug("No attribute for member-group combination exists."); return new ArrayList<Attribute>(); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
private synchronized StreamObserver<QueryProviderOutbound> getSubscriberObserver() { if (outboundStreamObserver == null) { logger.info("Create new subscriber"); StreamObserver<QueryProviderInbound> queryProviderInboundStreamObserver = new StreamObserver<QueryProviderInbound>() { @Override public void onNext(QueryProviderInbound inboundRequest) { RequestCase requestCase = inboundRequest.getRequestCase(); queryHandlers.getOrDefault(requestCase, Collections.emptySet()) .forEach(consumer -> consumer.accept(inboundRequest)); switch (requestCase) { case CONFIRMATION: break; case QUERY: queryQueue.add(inboundRequest.getQuery()); break; } } @Override public void onError(Throwable throwable) { logger.warn("Received error from server: {}", throwable.getMessage()); outboundStreamObserver = null; resubscribe(); } @Override public void onCompleted() { logger.debug("Received completed from server"); outboundStreamObserver = null; } }; StreamObserver<QueryProviderOutbound> stream = platformConnectionManager.getQueryStream(queryProviderInboundStreamObserver, interceptors); outboundStreamObserver = new FlowControllingStreamObserver<>(stream, configuration, flowControl -> QueryProviderOutbound.newBuilder().setFlowControl(flowControl).build(), t -> t.getRequestCase().equals(QueryProviderOutbound.RequestCase.QUERYRESPONSE)).sendInitialPermits(); } return outboundStreamObserver; }

Target:
private synchronized StreamObserver<QueryProviderOutbound> getSubscriberObserver() { if (outboundStreamObserver == null) { logger.info("Create new subscriber"); StreamObserver<QueryProviderInbound> queryProviderInboundStreamObserver = new StreamObserver<QueryProviderInbound>() { @Override public void onNext(QueryProviderInbound inboundRequest) { RequestCase requestCase = inboundRequest.getRequestCase(); queryHandlers.getOrDefault(requestCase, Collections.emptySet()) .forEach(consumer -> consumer.accept(inboundRequest)); switch (requestCase) { case CONFIRMATION: break; case QUERY: queryQueue.add(inboundRequest.getQuery()); break; } } @Override public void onError(Throwable ex){ logger.warn("Received error from server: {}", ex.getMessage()); outboundStreamObserver = null; if (ex instanceof StatusRuntimeException && ((StatusRuntimeException) ex).getStatus().getCode().equals(Status.UNAVAILABLE.getCode())) { return; } resubscribe(); } @Override public void onCompleted() { logger.debug("Received completed from server"); outboundStreamObserver = null; } }; StreamObserver<QueryProviderOutbound> stream = platformConnectionManager.getQueryStream(queryProviderInboundStreamObserver, interceptors); outboundStreamObserver = new FlowControllingStreamObserver<>(stream, configuration, flowControl -> QueryProviderOutbound.newBuilder().setFlowControl(flowControl).build(), t -> t.getRequestCase().equals(QueryProviderOutbound.RequestCase.QUERYRESPONSE)).sendInitialPermits(); } return outboundStreamObserver; }
Source:
protected byte[] json2fleece(String json) throws LiteCoreException { boolean commit = false; db.beginTransaction(); FLSliceResult body = null; try { body = db.encodeJSON(json5(json).getBytes()); byte[] bytes = body.getBuf(); commit = true; return bytes; } finally { if (body != null) body.free();; db.endTransaction(commit); } }

Target:
protected byte[] json2fleece(String json) throws LiteCoreException { boolean commit = false; db.beginTransaction(); FLSliceResult body = null; try { body = db.encodeJSON(json5(json).getBytes()); byte[] bytes = body.getBuf(); commit = true; return bytes; } finally { if (body != null) body.free(); db.endTransaction(commit); } }
Source:
private void showSelectTagsDialog() { final List<String> checkedTags = new ArrayList<>(); final String[] availableTags = tags.toArray(new String[tags.size()]); new AlertDialog.Builder(this) .setTitle(R.string.upload_tag_dialog_title) .setMultiChoiceItems(availableTags, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { if (isChecked) { if (checkedTags.size() >= MAX_NUMBER_OF_TAGS_CHECKED) { ((AlertDialog) dialog).getListView().setItemChecked(indexSelected, false); } else { checkedTags.add(availableTags[indexSelected]); } } else { checkedTags.remove(availableTags[indexSelected]); } } }) .setPositiveButton(getText(R.string.next), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { project.setTags(checkedTags); showProgressDialogAndUploadProject(); } }) .setNegativeButton(getText(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Utils.invalidateLoginTokenIfUserRestricted(ProjectUploadActivity.this); setShowProgressBar(false); setNextButtonEnabled(true); } }) .setCancelable(false) .show(); }

Target:
private void showSelectTagsDialog() { final List<String> checkedTags = new ArrayList<>(); final String[] availableTags = tags.toArray(new String[tags.size()]); new AlertDialog.Builder(this) .setTitle(R.string.upload_tag_dialog_title) .setMultiChoiceItems(availableTags, null, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { if (isChecked) { if (checkedTags.size() >= MAX_NUMBER_OF_TAGS_CHECKED) { ((AlertDialog) dialog).getListView().setItemChecked(indexSelected, false); } else { checkedTags.add(availableTags[indexSelected]); } } else { checkedTags.remove(availableTags[indexSelected]); } } }) .setPositiveButton(getText(R.string.next), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { project.setTags(checkedTags); showProgressDialogAndUploadProject(); } }) .setNegativeButton(getText(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Utils.invalidateLoginTokenIfUserRestricted(ProjectUploadActivity.this); setShowProgressBar(false); setNextButtonEnabled(true); } }) .setCancelable(false) .show(); }
Source:
public String docs() { return "void {[world], name, array(locationArrayPos1, locationArrayPos2, [[locationArrayPosN]...])} Update position of a given region. Don't change anything else like owners, members, priority etc."; }

Target:
public String docs() { return "void {[world], name, array(locationArrayPos1, locationArrayPos2, [[locationArrayPosN]...])} Updates the location of a given region to the new location. Other properties of the region, like owners, members, priority, etc are unaffected."; }
Source:
public void handleMessage(Message theMessage) throws MessagingException { if (!(theMessage.getPayload() instanceof ResourceDeliveryMessage)) { ourLog.warn("Unexpected payload type: {}", theMessage.getPayload()); return; } ResourceDeliveryMessage msg = (ResourceDeliveryMessage) theMessage.getPayload(); String subscriptionId = msg.getSubscription().getIdElement(myFhirContext).getValue(); ActiveSubscription updatedSubscription = mySubscriptionRegistry.get(msg.getSubscription().getIdElement(myFhirContext).getIdPart()); if (updatedSubscription != null) { msg.setSubscription(updatedSubscription.getSubscription()); } try { if (!myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_BEFORE_DELIVERY, msg, msg.getSubscription())) { return; } handleMessage(msg); myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_AFTER_DELIVERY, msg, msg.getSubscription()); } catch (Exception e) { if (!myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_AFTER_DELIVERY_FAILED, msg, msg.getSubscription(), e)) { return; } String errorMsg = "Failure handling subscription payload for subscription: " + subscriptionId; ourLog.error(errorMsg, e); throw new MessagingException(theMessage, errorMsg, e); } }

Target:
public void handleMessage(Message theMessage) throws MessagingException { if (!(theMessage.getPayload() instanceof ResourceDeliveryMessage)) { ourLog.warn("Unexpected payload type: {}", theMessage.getPayload()); return; } ResourceDeliveryMessage msg = (ResourceDeliveryMessage) theMessage.getPayload(); String subscriptionId = msg.getSubscriptionId(myFhirContext); ActiveSubscription updatedSubscription = mySubscriptionRegistry.get(msg.getSubscription().getIdElement(myFhirContext).getIdPart()); if (updatedSubscription != null) { msg.setSubscription(updatedSubscription.getSubscription()); } try { if (!myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_BEFORE_DELIVERY, msg, msg.getSubscription())) { return; } handleMessage(msg); myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_AFTER_DELIVERY, msg, msg.getSubscription()); } catch (Exception e) { String errorMsg = "Failure handling subscription payload for subscription: " + subscriptionId; ourLog.error(errorMsg, e); if (!myInterceptorBroadcaster.callHooks(Pointcut.SUBSCRIPTION_AFTER_DELIVERY_FAILED, msg, msg.getSubscription(), e)) { return; } throw new MessagingException(theMessage, errorMsg, e); } }
Source:
public ConjureStartTransactionsResponse startTransactions(AuthHeader authHeader, String namespace, ConjureStartTransactionsRequest request) { long timeCreated = System.currentTimeMillis(); ConjureStartTransactionsResponse response = dialogueDelegate.startTransactions(authHeader, namespace, request); long microsSinceCreation = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis() - timeCreated); this.conjureTimelockServiceBlockingMetrics.startTransactions().update(microsSinceCreation, TimeUnit.MICROSECONDS); return response; }

Target:
public ConjureStartTransactionsResponse startTransactions(AuthHeader authHeader, String namespace, ConjureStartTransactionsRequest request) { return executeInTimerContext(() -> dialogueDelegate.startTransactions(authHeader, namespace, request)); }
Source:
protected long getTimeStampFutureTTL() { try { return PropertyAccessor.getInstance().getPropertyLong(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.TIMESTAMP_FUTURE_TIME_TO_LIVE); } catch (PropertyAccessException pae) { LOG.warn("Failed to determine timestamp future TTL in gateway.properties, will use default value: {}", pae.getLocalizedMessage()); LOG.trace("Get Timestamp future TTL exception: {}", pae.getLocalizedMessage(), pae); } return INVALID_LONG_VALUE; }

Target:
protected long getTimeStampFutureTTL() { try { return PropertyAccessor.getInstance().getPropertyLong(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.TIMESTAMP_FUTURE_TIME_TO_LIVE); } catch (PropertyAccessException pae) { LOG.error("Failed to determine timestamp future TTL in gateway.properties, will use default value: {}", pae.getLocalizedMessage(), pae); } return INVALID_LONG_VALUE; }
Source:
public void canReturnTheCassandraMetricsFromTheCassandraMetricService() throws Exception { when(healthMetricSupplier.get()).thenReturn(ImmutableList.of( getCassandraMetric(METRIC_TYPE_1, METRIC_NAME_1, METRIC_ATTRIBUTE_1), getCassandraMetric(METRIC_TYPE_2, METRIC_NAME_2, METRIC_ATTRIBUTE_2))); when(cassandraMetricClient.getMetric(METRIC_TYPE_1, METRIC_NAME_1, METRIC_ATTRIBUTE_1, ImmutableMap.of())) .thenReturn(METRIC_VALUE_1); when(cassandraMetricClient.getMetric(METRIC_TYPE_2, METRIC_NAME_2, METRIC_ATTRIBUTE_2, ImmutableMap.of())) .thenReturn(METRIC_VALUE_2); scheduledExecutorService.tick(3, TimeUnit.SECONDS); List<CassandraHealthMetricMeasurement> cassandraHealthMetricMeasurements = cassandraMetricMeasurementsLoader.getCassandraHealthMetricMeasurements(); List<CassandraHealthMetricMeasurement> expectedCassandraHealthMetricMeasurements = ImmutableList.of(getCassandraMetricMeasurement(METRIC_VALUE_1), getCassandraMetricMeasurement(METRIC_VALUE_2)); assertThat(expectedCassandraHealthMetricMeasurements).isEqualTo(cassandraHealthMetricMeasurements); }

Target:
public void canReturnTheCassandraMetricsFromTheCassandraMetricService() throws Exception { scheduledExecutorService.tick(3, TimeUnit.SECONDS); List<CassandraHealthMetricMeasurement> cassandraHealthMetricMeasurements = cassandraMetricMeasurementsLoader.getCassandraHealthMetricMeasurements(); List<CassandraHealthMetricMeasurement> expectedCassandraHealthMetricMeasurements = ImmutableList.of(getCassandraMetricMeasurement(METRIC_VALUE_1), getCassandraMetricMeasurement(METRIC_VALUE_2)); assertThat(expectedCassandraHealthMetricMeasurements).isEqualTo(cassandraHealthMetricMeasurements); }
Source:
private LookupSourceFactory benchmarkBuildHash(BuildContext buildContext, List<Integer> outputChannels) { DriverContext driverContext = buildContext.createTaskContext().addPipelineContext(0, true, true).addDriverContext(); HashBuilderOperatorFactory hashBuilderOperatorFactory = new HashBuilderOperatorFactory( HASH_BUILD_OPERATOR_ID, TEST_PLAN_NODE_ID, buildContext.getTypes(), outputChannels, ImmutableMap.of(), buildContext.getHashChannels(), buildContext.getHashChannel(), false, Optional.empty(), 10_000, 1, new PagesIndex.TestingFactory()); Operator operator = hashBuilderOperatorFactory.createOperator(driverContext); for (Page page : buildContext.getBuildPages()) { operator.addInput(page); } operator.finish(); ListenableFuture<LookupSourceProvider> lookupSourceProvider = hashBuilderOperatorFactory.getLookupSourceFactory().createLookupSourceProvider(); if (!lookupSourceProvider.isDone()) { throw new AssertionError("Expected lookup source to be done"); } getFutureValue(lookupSourceProvider).close(); return hashBuilderOperatorFactory.getLookupSourceFactory(); }

Target:
private LookupSourceFactory benchmarkBuildHash(BuildContext buildContext, List<Integer> outputChannels) { DriverContext driverContext = buildContext.createTaskContext().addPipelineContext(0, true, true).addDriverContext(); HashBuilderOperatorFactory hashBuilderOperatorFactory = new HashBuilderOperatorFactory( HASH_BUILD_OPERATOR_ID, TEST_PLAN_NODE_ID, buildContext.getTypes(), outputChannels, ImmutableMap.of(), buildContext.getHashChannels(), buildContext.getHashChannel(), false, Optional.empty(), 10_000, 1, new PagesIndex.TestingFactory(), false, SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory()); Operator operator = hashBuilderOperatorFactory.createOperator(driverContext); for (Page page : buildContext.getBuildPages()) { operator.addInput(page); } operator.finish(); ListenableFuture<LookupSourceProvider> lookupSourceProvider = hashBuilderOperatorFactory.getLookupSourceFactory().createLookupSourceProvider(); if (!lookupSourceProvider.isDone()) { throw new AssertionError("Expected lookup source provider to be ready"); } getFutureValue(lookupSourceProvider).close(); return hashBuilderOperatorFactory.getLookupSourceFactory(); }
Source:
public void handleTag(final boolean opening, final String tag, Editable output, final XMLReader xmlReader) { if (tag.equals("ul") || tag.equals("ol") || tag.equals("dd")) { if (opening) { mListParents.add(tag); } else { mListParents.remove(tag); } mListItemCount = 0; } else if (tag.equals("li") && !opening) { handleListTag(output); } }

Target:
public void handleTag(final boolean opening, final String tag, Editable output, final XMLReader xmlReader) { if (tag != null) { if (tag.equals("ul") || tag.equals("ol") || tag.equals("dd")) { if (opening) { mListParents.add(tag); } else { mListParents.remove(tag); } mListItemCount = 0; } else if (tag.equals("li") && !opening) { handleListTag(output); } } }
Source:
String getDescription() { return "Cannot exceed max partitions on node"; }

Target:
String getDescription() { return "Cannot exceed the maximum number of partitions limitation on node"; }
Source:
public void clearCache() { cacheManager.getCache().clear(); TestingUtil.recursiveFileRemove(indexDir); }

Target:
public void clearCache() { if (cacheManager != null) { cacheManager.getCache().clear(); } TestingUtil.recursiveFileRemove(indexDir); }
Source:
protected String normalizePattern( String pattern, String wildcard, String singleChar, String escapeChar) { StringBuilder sb = new StringBuilder(pattern.length()); for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == escapeChar.charAt(0)) { if (i + 1 < pattern.length()) { i++; String next = Character.toString(pattern.charAt(i)); if ("*".equals(next) || "?".equals(next) || "\\".equals(next)) { sb.append("\\"); sb.append(next); } else { sb.append(next); } } } else if (c == singleChar.charAt(0)) { sb.append("?"); } else if (c == wildcard.charAt(0)) { sb.append("*"); } else { sb.append(c); } } return sb.toString(); }

Target:
protected String normalizePattern( String pattern, String wildcard, String singleChar, String escapeChar) { StringBuilder sb = new StringBuilder(pattern.length()); for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == escapeChar.charAt(0)) { if (i + 1 < pattern.length()) { i++; char next = pattern.charAt(i); if ('*' == next || '?' == next || '\\' == next) { sb.append("\\"); sb.append(next); } else { sb.append(next); } } } else if (c == singleChar.charAt(0)) { sb.append("?"); } else if (c == wildcard.charAt(0)) { sb.append("*"); } else { sb.append(c); } } return sb.toString(); }
Source:
private String createAndGetLockPath() throws InterruptedException, KeeperException { if (zk.exists(lockPath.toString(), false) == null) { try { Util.mkdir(zk, lockPath.toString(), ZooDefs.Ids.OPEN_ACL_UNSAFE); } catch (CloudnameException e) { log.log( java.util.logging.Level.INFO, "CloudnameException while trying to get lock path " + absoluteLockPath, e); } } return lockPath + "/" + lockName; }

Target:
private String createAndGetLockPath() throws InterruptedException, KeeperException { if (zk.exists(lockPath, false) == null) { try { Util.mkdir(zk, lockPath, ZooDefs.Ids.OPEN_ACL_UNSAFE); } catch (CloudnameException e) { log.log( java.util.logging.Level.INFO, "CloudnameException while trying to get lock path " + absoluteLockPath, e); } } return lockPath + "/" + lockName; }
Source:
String getFullRemoteReference() { if (!remoteBranchNameText.getText().startsWith(Constants.R_REFS)) { return Constants.R_HEADS + remoteBranchNameText.getText(); } else { return remoteBranchNameText.getText(); } }

Target:
String getFullRemoteReference() { if (!remoteBranchNameText.getText().startsWith(Constants.R_REFS)) return Constants.R_HEADS + remoteBranchNameText.getText(); else return remoteBranchNameText.getText(); }
Source:
public void init() { try (InputStream inputStream = new FileInputStream(profilesFilePath)) { String json = IOUtils.toString(inputStream, StandardCharsets.UTF_8); this.profiles = GSON.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType()); } catch (IOException e) { LOGGER.debug("Could not find profiles.json during installation: ", e); this.profiles = new HashMap<>(); } availableClaimsMap = propertiesFileReader.loadSinglePropertiesFile(availableClaimsFile); }

Target:
public void init() { try (InputStream inputStream = new FileInputStream(profilesFilePath)) { this.profiles = GSON.fromJson(new InputStreamReader(inputStream), MAP_STRING_TO_OBJECT_TYPE); } catch (IOException e) { LOGGER.debug("Could not find profiles.json during installation: ", e); this.profiles = new HashMap<>(); } availableClaimsMap = propertiesFileReader.loadSinglePropertiesFile(availableClaimsFile); }
Source:
static public void printIndexStats(final File inputBamFile) { try { final BAMFileReader bam = new BAMFileReader(inputBamFile, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory()); if (!bam.hasIndex() || bam.getIndexType() == null) { throw new SAMException("No index for bam file " + inputBamFile); } BAMIndexMetaData[] data = null; if (bam.getIndexType().equals(SamIndexes.BAI) || bam.getIndexType().equals(SamIndexes.CSI)) { data = getIndexStats(bam); } if (data == null) { throw new SAMException("Exception in getting index statistics"); } int nRefs = bam.getFileHeader().getSequenceDictionary().size(); for (int i = 0; i < nRefs; i++) { final SAMSequenceRecord seq = bam.getFileHeader().getSequence(i); if (seq == null) continue; final String sequenceName = seq.getSequenceName(); final int sequenceLength = seq.getSequenceLength(); System.out.print(sequenceName + ' ' + "length=\t" + sequenceLength); if (data[i] == null) { System.out.println(); continue; } System.out.println("\tAligned= " + data[i].getAlignedRecordCount() + "\tUnaligned= " + data[i].getUnalignedRecordCount()); } System.out.println("NoCoordinateCount= " + data[0].getNoCoordinateRecordCount()); } catch (IOException e) { throw new SAMException("Exception in getting index statistics", e); } }

Target:
static public void printIndexStats(final File inputBamFile) { try { final BAMFileReader bam = new BAMFileReader(inputBamFile, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory()); if (!bam.hasIndex() || bam.getIndexType() == null) { throw new SAMException("No index for bam file " + inputBamFile); } BAMIndexMetaData[] data = getIndexStats(bam); if (data == null) { throw new SAMException("Exception in getting index statistics"); } int nRefs = bam.getFileHeader().getSequenceDictionary().size(); for (int i = 0; i < nRefs; i++) { final SAMSequenceRecord seq = bam.getFileHeader().getSequence(i); if (seq == null) continue; final String sequenceName = seq.getSequenceName(); final int sequenceLength = seq.getSequenceLength(); System.out.print(sequenceName + ' ' + "length=\t" + sequenceLength); if (data[i] == null) { System.out.println(); continue; } System.out.println("\tAligned= " + data[i].getAlignedRecordCount() + "\tUnaligned= " + data[i].getUnalignedRecordCount()); } System.out.println("NoCoordinateCount= " + data[0].getNoCoordinateRecordCount()); } catch (IOException e) { throw new SAMException("Exception in getting index statistics", e); } }
Source:
public void shouldNotCreate_withItem() { final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); doThrow(RuntimeException.class).when(mockTable).putItem(any(PutItemSpec.class)); exception.expect(RuntimeException.class); dynamoDocumentStoreTemplate.create(stubItem); }

Target:
public void shouldNotCreate_withItem() { final ItemId itemId = new ItemId(randomId()); final StubItem stubItem = generateRandomStubItem(itemId); final ItemConfiguration itemConfiguration = new ItemConfiguration(StubItem.class, tableName); final Collection<ItemConfiguration> itemConfigurations = Arrays.asList(itemConfiguration); when(mockDatabaseSchemaHolder.itemConfigurations()).thenReturn(itemConfigurations); final Table mockTable = mock(Table.class); when(mockDynamoDBClient.getTable(any(String.class))).thenReturn(mockTable); final DynamoDocumentStoreTemplate dynamoDocumentStoreTemplate = new DynamoDocumentStoreTemplate( mockDatabaseSchemaHolder); dynamoDocumentStoreTemplate.initialize(mockAmazonDynamoDbClient); final Item mockTableItem = mock(Item.class); when(mockTableItem.toJSON()).thenReturn(dynamoDocumentStoreTemplate.itemToString(stubItem)); doThrow(RuntimeException.class).when(mockTable).putItem(any(PutItemSpec.class)); RuntimeException thrownException = null; try { dynamoDocumentStoreTemplate.create(stubItem); } catch (final RuntimeException runtimeException) { thrownException = runtimeException; } assertNotNull(thrownException); }