auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Dialog onCreateDialog(Bundle savedInstanceState) { final MainActivity activity = (MainActivity) getActivity(); Bundle arguments = getArguments(); final int requestCode = arguments.getInt(EXTRA_REQUEST); final int title = arguments.getInt(EXTRA_TITLE); final Uri uri = arguments.getParcelable(EXTRA_URI); return new AlertDialog.Builder(activity, R.style.PocketPaintAlertDialog) .setTitle(title) .setMessage(R.string.closing_security_question) .setPositiveButton(R.string.save_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { MainActivityContracts.Presenter presenter = activity.getPresenter(); <START> switch (requestCode) { <END> case SAVE_IMAGE_EXIT_CATROID: presenter.checkPermissionAndForward(PERMISSION_EXTERNAL_STORAGE_SAVE_CONFIRMED_BACK_TO_PC, uri); break; case SAVE_IMAGE_FINISH: presenter.checkPermissionAndForward(PERMISSION_EXTERNAL_STORAGE_SAVE_CONFIRMED_FINISH, uri); break; } } }) .setNegativeButton(R.string.discard_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { activity.finish(); } }) .create(); }</code><technical_language>This moves logic presenter SaveBeforeFinishDialog. Please do this translation SaveImageRequestCode PermissionRequestCode in presenter, dialog dumb possible</technical_language>

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { final MainActivity activity = (MainActivity) getActivity(); Bundle arguments = getArguments(); final int requestCode = arguments.getInt(EXTRA_REQUEST); final int title = arguments.getInt(EXTRA_TITLE); final Uri uri = arguments.getParcelable(EXTRA_URI); return new AlertDialog.Builder(activity, R.style.PocketPaintAlertDialog) .setTitle(title) .setMessage(R.string.closing_security_question) .setPositiveButton(R.string.save_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { MainActivityContracts.Presenter presenter = activity.getPresenter(); presenter.checkPermissionAndForward(requestCode, uri); } }) .setNegativeButton(R.string.discard_button_text, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { activity.finish(); } }) .create(); }
Source:
<code>public List<ExecutableFlow> getRecentlyFinishedFlows() { List<ExecutableFlow> flows = new ArrayList<>(); try { flows = executorLoader.fetchRecentlyFinishedFlows( RECENTLY_FINISHED_LIFETIME.toMillis()); } catch(ExecutorManagerException e) { <START> logger.error(e); <END> } return flows; }</code><technical_language>This call void error(Object message) { log exception details call stack. this method log exception. void error(Object message, Throwable t) {</technical_language>

Target:
public List<ExecutableFlow> getRecentlyFinishedFlows() { List<ExecutableFlow> flows = new ArrayList<>(); try { flows = executorLoader.fetchRecentlyFinishedFlows( RECENTLY_FINISHED_LIFETIME); } catch(ExecutorManagerException e) { logger.error("Failed to fetch recently finished flows.", e); } return flows; }
Source:
<code>public void testCreate_OptionalGetter() { Map<String, Object> values = Maps.newHashMap(); values.put("name", Optional.fromNullable("MyName")); ClassGeneratorProvider provider = createProvider(); EventFactory<OptionalGetter> factory = provider.create(OptionalGetter.class, Object.class); OptionalGetter getter = factory.apply(values); assertThat(getter.getName().isPresent(), is(true)); assertThat(getter.getName().get(), is(Matchers.equalTo("MyName"))); <START> getter.setName(null); <END> assertThat(getter.getName().isPresent(), is(false)); }</code><technical_language>include a check for setName null values</technical_language>

Target:
public void testCreate_OptionalGetter() { Map<String, Object> values = Maps.newHashMap(); values.put("name", Optional.fromNullable("MyName")); ClassGeneratorProvider provider = createProvider(); EventFactory<OptionalGetter> factory = provider.create(OptionalGetter.class, Object.class); OptionalGetter getter = factory.apply(values); assertThat(getter.getName().isPresent(), is(true)); assertThat(getter.getName().get(), is(Matchers.equalTo("MyName"))); getter.setName(null); assertThat(getter.getName().isPresent(), is(false)); getter.setName("Aaron"); assertThat(getter.getName().isPresent(), is(true)); assertThat(getter.getName().get(), is(Matchers.equalTo("Aaron"))); }
Source:
<code>public static void initPageVariables(JellyContext context) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); String rootURL = currentRequest.getContextPath(); Functions h = new Functions(); context.setVariable("h", h); context.setVariable("rootURL", rootURL); <START> Jenkins jenkins = Jenkins.getActiveInstance(); <END> jenkins.setCachedRootUrl(jenkins.getRootUrlFromRequest()); context.setVariable("resURL",rootURL+getResourcePath()); context.setVariable("imagesURL",rootURL+getResourcePath()+"/images"); context.setVariable("userAgent", currentRequest.getHeader("User-Agent")); IconSet.initPageVariables(context); }</code><technical_language>bug: I suspect impact Jenkins startup. IIRC Jenkins is null open "Jenkins is loading page", <code> initPageVariables</code> is invoked for layout</technical_language>

Target:
public static void initPageVariables(JellyContext context) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); String rootURL = currentRequest.getContextPath(); Functions h = new Functions(); context.setVariable("h", h); context.setVariable("rootURL", rootURL); Jenkins jenkins = Jenkins.getInstance(); if (jenkins != null) { jenkins.setCachedRootUrl(jenkins.getRootUrlFromRequest()); } context.setVariable("resURL",rootURL+getResourcePath()); context.setVariable("imagesURL",rootURL+getResourcePath()+"/images"); context.setVariable("userAgent", currentRequest.getHeader("User-Agent")); IconSet.initPageVariables(context); }
Source:
<code>protected ISeries createSwtSeries(ChartSeries chartSeries, ISeriesSet swtSeriesSet, @NonNull Color color) { String title = chartSeries.getY().getLabel(); IBarSeries swtSeries = (IBarSeries) swtSeriesSet.createSeries(SeriesType.BAR, title); <START> swtSeries.setBarPadding(20); <END> swtSeries.setBarColor(color); return swtSeries; }</code><technical_language>extract a constant</technical_language>

Target:
protected ISeries createSwtSeries(ChartSeries chartSeries, ISeriesSet swtSeriesSet, @NonNull Color color) { String title = chartSeries.getY().getLabel(); IBarSeries swtSeries = (IBarSeries) swtSeriesSet.createSeries(SeriesType.BAR, title); swtSeries.setBarPadding(BAR_PADDING); swtSeries.setBarColor(color); return swtSeries; }
Source:
<code>protected Point getInitialSize() { if (!persistSize) { int defaultHeight = super.getInitialSize().y; persistSize = true; try { Point size = super.getInitialSize(); size.y = defaultHeight; <START> return size; <END> } finally { persistSize = false; } } return super.getInitialSize(); }</code><technical_language>I get this: result of getInitialSize() change invocation is called twice</technical_language>

Target:
protected Point getInitialSize() { if (!persistSize) { Point size = super.getInitialSize(); size.x = getPersistedSize().x; return size; } return super.getInitialSize(); }
Source:
<code><START> public Set<String> getTags() { <END> return Collections.unmodifiableSet(this.tags); }</code><technical_language>Entity#getTags returns original set. While I vanilla code of fact backing set is mutable, mods might. stupid for do so, might. Thankfully, is a easy sidestep this: this method return a Collection<String>! While Java vary return type, restriction exists JVM. method vanilla Set<String> getTags() method co-exist peacefully</technical_language>

Target:
public Collection<String> getTags() { return Collections.unmodifiableSet(this.tags); }
Source:
<code>private void editQuestion(FeedbackQuestionAttributes updatedQuestion) throws InvalidParametersException, EntityDoesNotExistException { String err = validateQuestionGiverRecipientVisibility(updatedQuestion); if (!err.isEmpty()) { statusToUser.add(new StatusMessage(err, StatusMessageColor.DANGER)); isError = true; } List<String> questionDetailsErrors = updatedQuestion.getQuestionDetails().validateQuestionDetails(); List<StatusMessage> questionDetailsErrorsMessages = new ArrayList<StatusMessage>(); for (String error : questionDetailsErrors) { questionDetailsErrorsMessages.add(new StatusMessage(error, StatusMessageColor.DANGER)); } if (!questionDetailsErrors.isEmpty()) { statusToUser.addAll(questionDetailsErrorsMessages); isError = true; } else { <START> logic.updateFeedbackQuestionNumber(updatedQuestion); <END> statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_QUESTION_EDITED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Question "+ updatedQuestion.questionNumber + " for session:<span class=\"bold\">(" + updatedQuestion.feedbackSessionName + ")</span> for Course <span class=\"bold\">[" + updatedQuestion.courseId + "]</span> edited.<br>" + "<span class=\"bold\">" + updatedQuestion.getQuestionDetails().getQuestionTypeDisplayName() + ":</span> " + updatedQuestion.getQuestionDetails().questionText; } }</code><technical_language>Is method, <code>updateFeedbackQuestion</code> in code</technical_language>

Target:
private void editQuestion(FeedbackQuestionAttributes updatedQuestion) throws InvalidParametersException, EntityDoesNotExistException { String err = validateQuestionGiverRecipientVisibility(updatedQuestion); if (!err.isEmpty()) { statusToUser.add(new StatusMessage(err, StatusMessageColor.DANGER)); isError = true; } FeedbackQuestionDetails updatedQuestionDetails = updatedQuestion.getQuestionDetails(); List<String> questionDetailsErrors = updatedQuestionDetails.validateQuestionDetails(); List<StatusMessage> questionDetailsErrorsMessages = new ArrayList<StatusMessage>(); for (String error : questionDetailsErrors) { questionDetailsErrorsMessages.add(new StatusMessage(error, StatusMessageColor.DANGER)); } if (!questionDetailsErrors.isEmpty()) { statusToUser.addAll(questionDetailsErrorsMessages); isError = true; } else { logic.updateFeedbackQuestionNumber(updatedQuestion); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_QUESTION_EDITED, StatusMessageColor.SUCCESS)); statusToAdmin = "Feedback Question "+ updatedQuestion.questionNumber + " for session:<span class=\"bold\">(" + updatedQuestion.feedbackSessionName + ")</span> for Course <span class=\"bold\">[" + updatedQuestion.courseId + "]</span> edited.<br>" + "<span class=\"bold\">" + updatedQuestionDetails.getQuestionTypeDisplayName() + ":</span> " + updatedQuestionDetails.questionText; } }
Source:
<code>public void start(PluginGuiceEnvironment env) throws Exception { <START> manager = new LifecycleManager(); <END> String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); manager.add(httpInjector); manager.start(); }</code><technical_language>Unnecessary. is in Guice world start stop</technical_language>

Target:
public void start(PluginGuiceEnvironment env) throws Exception { String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); }
Source:
<code><START> public void configure(Object obj, XmlParser.Node cfg, int i) throws Exception <END> { for (; i < cfg.size(); i++) { Object o = cfg.get(i); if (o instanceof String) continue; XmlParser.Node node = (XmlParser.Node)o; try { String tag = node.getTag(); switch (tag) { case "Arg": break; case "Set": set(obj, node); break; case "Put": put(obj, node); break; case "Call": call(obj, node); break; case "Get": get(obj, node); break; case "New": newObj(obj, node); break; case "Array": newArray(obj, node); break; case "Map": newMap(obj, node); break; case "Ref": refObj(node); break; case "Property": propertyObj(node); break; case "SystemProperty": systemPropertyObj(node); break; case "Env": envObj(node); break; default: throw new IllegalStateException("Unknown tag: " + tag + " in " + _configuration); } } catch (Exception e) { LOG.warn("Config error at " + node, e.toString() + " in " + _configuration); throw e; } } }</code><technical_language>weird in history! I thought idea of passing in index leading Args skipped</technical_language>

Target:
public void configure(Object obj, XmlParser.Node cfg, int i) throws Exception { for (; i < cfg.size(); i++) { Object o = cfg.get(i); if (o instanceof String) continue; XmlParser.Node node = (XmlParser.Node)o; try { String tag = node.getTag(); switch (tag) { case "Arg": case "Class": case "Id": throw new IllegalStateException("Element '" + tag + "' not skipped"); case "Set": set(obj, node); break; case "Put": put(obj, node); break; case "Call": call(obj, node); break; case "Get": get(obj, node); break; case "New": newObj(obj, node); break; case "Array": newArray(obj, node); break; case "Map": newMap(obj, node); break; case "Ref": refObj(node); break; case "Property": propertyObj(node); break; case "SystemProperty": systemPropertyObj(node); break; case "Env": envObj(node); break; default: throw new IllegalStateException("Unknown tag: " + tag + " in " + _configuration); } } catch (Exception e) { LOG.warn("Config error at " + node, e.toString() + " in " + _configuration); throw e; } } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); <START> startService(new Intent(MainActivity.this, MessageService.class)); <END> }</code><technical_language>Extract this a method, called</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startMessageService(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCustomContent(R.layout.activity_filter); mConfig.put(Config.HELP_MESSAGE, "Select a filter for your photo!"); mConfig.put(Config.NAME, "Filter"); mOriginalAd = mAdCreationManager.getCurrentBitmap(); mFilteredAd = mOriginalAd; mAdView = (ImageView) this.findViewById(R.id.ad); ArrayList<ImageToLoad> images = new ArrayList<ImageToLoad>(); for(int i = 0; i < filterList.length; i++){ MapleFilter filter = null; try { <START> filter = (MapleFilter) filterList[i].newInstance(); <END> } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} filterInstances[i] = filter; int filterPictureId = filter.getPreview(); images.add(new ImageToLoadDrawableResource(filterPictureId)); } HorizontalImageScroller scroller = (HorizontalImageScroller) findViewById(R.id.filterScroller); scroller.setAdapter(new HorizontalImageScrollerAdapter(this, images)); scroller.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { if(mLastFilterSelected != null) mLastFilterSelected.setBackgroundColor(Color.TRANSPARENT); view.setBackgroundColor(Color.BLACK); mLastFilterSelected = view; mFilteredAd = filterResults[pos]; if(mFilteredAd == null){ mFilteredAd = filterInstances[pos].filterBitmap(mOriginalAd); filterResults[pos] = mFilteredAd; } mAdView.setImageBitmap(mFilteredAd); } }); mAdCreationManager.setup(this); }</code><technical_language>This is cool. do this in java</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCustomContent(R.layout.activity_filter); mConfig.put(Config.HELP_MESSAGE, "Select a filter for your photo!"); mConfig.put(Config.NAME, "Filter"); mOriginalAd = mAdCreationManager.getCurrentBitmap(); mFilteredAd = mOriginalAd; mAdView = (ImageView) this.findViewById(R.id.ad); ArrayList<ImageToLoad> images = new ArrayList<ImageToLoad>(); for(int i = 0; i < filterList.length; i++){ MapleFilter filter = null; try { filter = (MapleFilter) filterList[i].newInstance(); } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} filterInstances[i] = filter; int filterPictureId = filter.getPreview(); images.add(new ImageToLoadDrawableResource(filterPictureId)); } HorizontalImageScroller scroller = (HorizontalImageScroller) findViewById(R.id.filterScroller); scroller.setAdapter(new HorizontalImageScrollerAdapter(this, images)); scroller.setHighlightActiveImage(true); scroller.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { if(mLastFilterSelected != null) mLastFilterSelected.setBackgroundColor(Color.TRANSPARENT); view.setBackgroundColor(Color.BLACK); mLastFilterSelected = view; mFilteredAd = filterResults[pos]; if(mFilteredAd == null){ mFilteredAd = filterInstances[pos].filterBitmap(mOriginalAd); filterResults[pos] = mFilteredAd; } mAdView.setImageBitmap(mFilteredAd); } }); mAdCreationManager.setup(this); }
Source:
<code>public void scaleForErrorMarginReducesTimeoutSlightly() { assertThat(BlockingTimeouts.scaleForErrorMargin(ONE_MILLION)) .isLessThan(ONE_MILLION) <START> .isEqualTo(970_000); <END> }</code><technical_language>Calculate this ERROR_MARGIN constant, making visibleForTesting</technical_language>

Target:
public void scaleForErrorMarginReducesTimeoutSlightly() { assertThat(BlockingTimeouts.scaleForErrorMargin(ONE_MILLION, TEST_ERROR_MARGIN)) .isLessThan(ONE_MILLION) .isEqualTo(scaleForErrorMarginReferenceImplementation(ONE_MILLION, TEST_ERROR_MARGIN)); }
Source:
<code>@Override public MetadataMarshalled parseArguments0(CommandArgIterator argIter) { String opt = argIter.nextArg("--in"); if (!OPT_IN_FILE_NAME.equalsIgnoreCase(opt)) throw new IllegalArgumentException(""); Path inFile = FS.getPath(argIter.nextArg("input file name")); try (InputStream is = Files.newInputStream(inFile)) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; <START> while ((nRead = is.read(data, 0, data.length)) != -1) <END> buffer.write(data, 0, nRead); buffer.flush(); return new MetadataMarshalled(buffer.toByteArray(), null); } catch (IOException e) { throw new IllegalArgumentException("Cannot read metadata from " + inFile, e); } }</code><technical_language>FYI, a method for this: U.copy(in, out)</technical_language>

Target:
@Override public MetadataMarshalled parseArguments0(CommandArgIterator argIter) { String opt = argIter.nextArg(IN_FILE_NAME); if (!IN_FILE_NAME.equalsIgnoreCase(opt)) throw new IllegalArgumentException("The option '" + IN_FILE_NAME + "' is required"); Path inFile = FS.getPath(argIter.nextArg("input file name")); try (InputStream is = Files.newInputStream(inFile)) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); U.copy(is, buf); return new MetadataMarshalled(buf.toByteArray(), null); } catch (IOException e) { throw new IllegalArgumentException("Cannot read metadata from " + inFile, e); } }
Source:
<code>protected AbstractNamedPermission(final String name) { <START> super(name); <END> if (getName() == null) throw log.namedPermissionNameMustBeSet(getClass().getName()); }</code><technical_language>Instead super(Assert.checkNotNullParam("name", name));. want a new error code for null checking</technical_language>

Target:
protected AbstractNamedPermission(final String name) { super(Assert.checkNotNullParam("name", name)); }
Source:
<code>public SecurityHjsonIntegrationTestResourceConfig() { register(new AbstractBinder() { @Override protected void configure() { Map<String, Class<? extends Check>> map = new HashMap<>(TestCheckMappings.MAPPINGS); map.put(OperatorCheck.OPERTOR_CHECK, OperatorCheck.class); EntityDictionary dictionary = new EntityDictionary(map); try { <START> dictionary.addSecurityChecks(COMPILER.findAnnotatedClasses(SecurityCheck.class).stream() <END> .map(ClassType.class::cast) .map(ClassType::getCls) .collect(Collectors.toSet())); } catch (ClassNotFoundException e) { } Elide elide = new Elide(new ElideSettingsBuilder(getDataStore()) .withEntityDictionary(dictionary) .withAuditLogger(new TestAuditLogger()) .withISO8601Dates("yyyy-MM-dd'T'HH:mm'Z'", Calendar.getInstance().getTimeZone()) .build()); bind(elide).to(Elide.class).named("elide"); } }); register(new ContainerRequestFilter() { @Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(securityContextMock); } }); }</code><technical_language>leave compiler working normal java classes do this mapping here</technical_language>

Target:
public SecurityHjsonIntegrationTestResourceConfig() { register(new AbstractBinder() { @Override protected void configure() { Map<String, Class<? extends Check>> map = new HashMap<>(TestCheckMappings.MAPPINGS); map.put(OperatorCheck.OPERTOR_CHECK, OperatorCheck.class); EntityDictionary dictionary = new EntityDictionary(map); try { dictionary.addSecurityChecks(COMPILER.findAnnotatedClasses(SecurityCheck.class)); } catch (ClassNotFoundException e) { } Elide elide = new Elide(new ElideSettingsBuilder(getDataStore()) .withEntityDictionary(dictionary) .withAuditLogger(new TestAuditLogger()) .withISO8601Dates("yyyy-MM-dd'T'HH:mm'Z'", Calendar.getInstance().getTimeZone()) .build()); bind(elide).to(Elide.class).named("elide"); } }); register(new ContainerRequestFilter() { @Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(securityContextMock); } }); }
Source:
<code>protected ItemRest createAndReturn(Context context) throws AuthorizeException, SQLException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); String owningCollectionUuidString = req.getParameter("owningCollection"); ObjectMapper mapper = new ObjectMapper(); ItemRest itemRest = null; try { ServletInputStream input = req.getInputStream(); itemRest = mapper.readValue(input, ItemRest.class); } catch (IOException e1) { <START> throw new UnprocessableEntityException("Error parsing request body: " + e1.toString()); <END> } if (itemRest.getInArchive() == false) { throw new BadRequestException("InArchive attribute should not be set to false for the create"); } UUID owningCollectionUuid = UUIDUtils.fromString(owningCollectionUuidString); Collection collection = collectionService.find(context, owningCollectionUuid); if (collection == null) { throw new BadRequestException("The given owningCollection parameter is invalid: " + owningCollectionUuid); } WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false); Item item = workspaceItem.getItem(); item.setArchived(true); item.setOwningCollection(collection); item.setDiscoverable(itemRest.getDiscoverable()); item.setLastModified(itemRest.getLastModified()); dspaceObjectUtils.replaceMetadataValues(context, item, itemRest.getMetadata()); Item itemToReturn = installItemService.installItem(context, workspaceItem); return converter.fromModel(itemToReturn); }</code><technical_language>swallowing stacktrace, return full stracktrace. useful information in it. This be: throw new UnprocessableEntityException("Error parsing request body", e1);</technical_language>

Target:
protected ItemRest createAndReturn(Context context) throws AuthorizeException, SQLException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); String owningCollectionUuidString = req.getParameter("owningCollection"); ObjectMapper mapper = new ObjectMapper(); ItemRest itemRest = null; try { ServletInputStream input = req.getInputStream(); itemRest = mapper.readValue(input, ItemRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("Error parsing request body", e1); } if (itemRest.getInArchive() == false) { throw new BadRequestException("InArchive attribute should not be set to false for the create"); } UUID owningCollectionUuid = UUIDUtils.fromString(owningCollectionUuidString); Collection collection = collectionService.find(context, owningCollectionUuid); if (collection == null) { throw new BadRequestException("The given owningCollection parameter is invalid: " + owningCollectionUuid); } WorkspaceItem workspaceItem = workspaceItemService.create(context, collection, false); Item item = workspaceItem.getItem(); item.setArchived(true); item.setOwningCollection(collection); item.setDiscoverable(itemRest.getDiscoverable()); item.setLastModified(itemRest.getLastModified()); dspaceObjectUtils.replaceMetadataValues(context, item, itemRest.getMetadata()); Item itemToReturn = installItemService.installItem(context, workspaceItem); return converter.fromModel(itemToReturn); }
Source:
<code>private static String encryptString(Object o1, Object o2, Object o3) { String message = FunctionUtils.toString(o1); String key = FunctionUtils.toString(o2); String algorithm = FunctionUtils.toString(o3); final String ENCRYPT_ALGO = "AES/GCM/NoPadding"; final int TAG_LENGTH_BIT = 128; <START> final int IV_LENGTH_BYTE = 12; <END> final int KEY_LENGTH_BIT = 256; if (!algorithm.equals("AES")) { throw new XPathException("Unknown algorithm \"" + algorithm + "\" for " + NAME); } Base64.Decoder keyDecoder = Base64.getUrlDecoder(); byte[] keyBytes = keyDecoder.decode(key); if (8 * keyBytes.length != KEY_LENGTH_BIT) { throw new XPathException("Key should be " + KEY_LENGTH_BIT + " bits long, not " + 8 * keyBytes.length); } SecretKey secret = new SecretKeySpec(keyBytes, "AES"); byte[] iv = new byte[IV_LENGTH_BYTE]; new SecureRandom().nextBytes(iv); try { Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO); cipher.init(Cipher.ENCRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv)); byte[] encryptedMessage = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8)); byte[] ivPlusMessage = ByteBuffer.allocate(iv.length + encryptedMessage.length) .put(iv) .put(encryptedMessage) .array(); Base64.Encoder outputEncoder = Base64.getUrlEncoder(); return outputEncoder.encodeToString(ivPlusMessage); } catch (Exception ex) { throw new XPathException("Exception during encryption: " + ex); } }</code><technical_language>Question: normal 16 bytes for IV GCM do I wrong</technical_language>

Target:
private static String encryptString(Object o1, Object o2, Object o3) { String message = FunctionUtils.toString(o1); String key = FunctionUtils.toString(o2); String algorithm = FunctionUtils.toString(o3); final String ENCRYPT_ALGO = "AES/GCM/NoPadding"; final int IV_LENGTH_BYTE = 12; final int KEY_LENGTH_BIT = 256; if (!algorithm.equals("AES")) { throw new XPathException("Unknown algorithm \"" + algorithm + "\" for " + NAME); } byte[] keyBytes; try { keyBytes = Base64.decode(key); } catch (Base64DecoderException e) { XPathException throwable = new XPathException("Encryption key base 64 encoding is invalid"); throwable.initCause(e); throw throwable; } if (8 * keyBytes.length != KEY_LENGTH_BIT) { throw new XPathException("Key should be " + KEY_LENGTH_BIT + " bits long, not " + 8 * keyBytes.length); } SecretKey secret = new SecretKeySpec(keyBytes, "AES"); try { Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO); cipher.init(Cipher.ENCRYPT_MODE, secret); byte[] encryptedMessage = cipher.doFinal(message.getBytes(Charset.forName("UTF-8"))); byte[] iv = cipher.getIV(); if (iv.length != IV_LENGTH_BYTE) { throw new XPathException("Initialization vector should be " + IV_LENGTH_BYTE + " bytes long, not " + iv.length); } byte[] ivPlusMessage = ByteBuffer.allocate(iv.length + encryptedMessage.length) .put(iv) .put(encryptedMessage) .array(); return Base64.encode(ivPlusMessage); } catch (Exception ex) { throw new XPathException("Exception during encryption: " + ex); } }
Source:
<code>private Set<LocationRequest> getRequestOnlyUsedBy(ClientCallbackWrapper wrapper) { Set<LocationRequest> requestsToRemove = clientCallbackToLocationRequests.get(wrapper); if (requestsToRemove == null) { return requestsToRemove; } clientCallbackToLocationRequests.remove(wrapper); for (ClientCallbackWrapper w : clientCallbackToLocationRequests.keySet()) { Set<LocationRequest> requests = clientCallbackToLocationRequests.get(w); requestsToRemove.removeAll(requests); } <START> return requestsToRemove; <END> }</code><technical_language>I guess rule out possibility of more client registering request kind of gross. if a LocationRequest generated a unique internal id for based time registered? simplify logic here</technical_language>

Target:
private List<LocationRequest> getRequestOnlyUsedBy(ClientCallbackWrapper wrapper) { List<LocationRequest> requestsToRemove = clientCallbackToLocationRequests.get(wrapper); if (requestsToRemove == null) { return null; } clientCallbackToLocationRequests.remove(wrapper); return requestsToRemove; }
Source:
<code><START> public List<HudsonModelJob> getJobs(final List<String> ids, final IOperationMonitor monitor) <END> throws HudsonException { if (ids != null && ids.isEmpty()) { return Collections.emptyList(); } convertJobNameIdsIntoUrlIds(); if (ids != null) { Map<String, List<String>> jobNamesByFolderUrl = hudsonUrlUtil.groupJobNamesByFolderUrl(ids); List<HudsonModelJob> jobs = new ArrayList<HudsonModelJob>(); for (String folderUrl : jobNamesByFolderUrl.keySet()) { List<String> jobNames = jobNamesByFolderUrl.get(folderUrl); jobs.addAll(this.getJobsFromFolder(folderUrl, jobNames, monitor)); } return jobs; } HudsonConfiguration configuration = new HudsonConfiguration(); configuration.jobNameById = new HashMap<String, String>(); setConfiguration(configuration); return this.getJobsFromFolder(hudsonUrlUtil.baseUrl(), ids, monitor); }</code><technical_language>this method reset configuration 3 times, strange. I ivalidating configuration cache for reason. Instead of overwriting configuration time udpate map information? This if other part of code a reference configuration is date. ie. instead of setting configuration clear putAll configuration's map. This applies in this class is calling setConfiguration</technical_language>

Target:
public List<HudsonModelJob> getJobs(final List<String> ids, final IOperationMonitor monitor) throws HudsonException { if (ids != null && ids.isEmpty()) { return Collections.emptyList(); } List<HudsonModelJob> jobs = new ArrayList<HudsonModelJob>(); if (ids != null) { Map<String, List<String>> jobNamesByFolderUrl = hudsonUrlUtil.groupJobNamesByFolderUrl(ids); for (String folderUrl : jobNamesByFolderUrl.keySet()) { List<String> jobNames = jobNamesByFolderUrl.get(folderUrl); jobs.addAll(this.getJobsFromFolder(folderUrl, jobNames, monitor)); } } else { jobs = this.getJobsFromFolder(hudsonUrlUtil.baseUrl(), ids, monitor); this.updateConfiguration(jobs); } return jobs; }
Source:
<code><START> public TargetDefinitionContent resolveContent(TargetDefinition definition) throws ResolutionException { <END> try { return resolveContentWithExceptions(definition); } catch (TargetDefinitionSyntaxException e) { throw new RuntimeException("Invalid syntax in target definition " + definition.getOrigin() + ": " + e.getMessage(), e); } }</code><technical_language>ResolutionExceptions thrown lacking information definition.getOrigin(). type TargetDefinitionResolutionException is (any more) referenced this class, in fact replaced a type, class private. message get useful</technical_language>

Target:
public TargetDefinitionContent resolveContent(TargetDefinition definition) { try { return resolveContentWithExceptions(definition); } catch (TargetDefinitionSyntaxException e) { throw new BuildFailureException("Invalid syntax in target definition " + definition.getOrigin() + ": " + e.getMessage(), e); } catch (TargetDefinitionResolutionException e) { throw new BuildFailureException("Failed to resolve target definition " + definition.getOrigin(), e); } }
Source:
<code>public void doHandleDataDeleted(String path) { <START> LOG.warn("Data deleted in path: " + path); <END> }</code><technical_language>Minor: This message sound alarming in logs. add more context wrong</technical_language>

Target:
public void doHandleDataDeleted(String path) { LOG.warn("Data deleted in path: " + path + " barrierVersion: " + barrierVersion); }
Source:
<code>public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { try { nettyMetrics.processorExceptionCaughtCount.inc(); if (request != null && request.isOpen() && cause instanceof Exception) { responseChannel.onResponseComplete((Exception) cause); } else { <START> if (cause instanceof RestServiceException) { <END> RestServiceErrorCode errorCode = ((RestServiceException) cause).getErrorCode(); if (ResponseStatus.getResponseStatus(errorCode) == ResponseStatus.BadRequest) { logger.debug("Swallowing error on channel {}", ctx.channel(), errorCode, cause); } else { logger.error("Swallowing error on channel {}", ctx.channel(), errorCode, cause); } } else { logger.error("Swallowing error on channel {}", ctx.channel(), cause); if (!(cause instanceof Exception)) { ctx.fireExceptionCaught(cause); } } } } catch (Exception e) { String uri = (request != null) ? request.getUri() : null; nettyMetrics.exceptionCaughtTasksError.inc(); logger.error("Swallowing exception during exceptionCaught tasks on channel for request {}", ctx.channel(), uri, e); ctx.close(); } }</code><technical_language>understand this. I get it. "Else" executed for throwable instance of Exception. RestServiceException is a subclass of Exception right. I missing here</technical_language>

Target:
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { try { nettyMetrics.processorExceptionCaughtCount.inc(); if (request != null && request.isOpen() && cause instanceof Exception) { responseChannel.onResponseComplete((Exception) cause); } else { if (cause instanceof RestServiceException) { RestServiceErrorCode errorCode = ((RestServiceException) cause).getErrorCode(); if (ResponseStatus.getResponseStatus(errorCode) == ResponseStatus.BadRequest) { logger.debug("Swallowing error on channel {}", ctx.channel(), errorCode, cause); } else { logger.error("Swallowing error on channel {}", ctx.channel(), errorCode, cause); } } else { logger.error("Swallowing error on channel {}", ctx.channel(), cause); if (!(cause instanceof Exception)) { ctx.fireExceptionCaught(cause); } } ctx.close(); } } catch (Exception e) { String uri = (request != null) ? request.getUri() : null; nettyMetrics.exceptionCaughtTasksError.inc(); logger.error("Swallowing exception during exceptionCaught tasks on channel for request {}", ctx.channel(), uri, e); ctx.close(); } }
Source:
<code>public void testRemoveOnCancelTrue() { final LifecycleEnvironment le = mock(LifecycleEnvironment.class); final String poolName = this.getClass().getSimpleName(); final ScheduledExecutorServiceBuilder test = new ScheduledExecutorServiceBuilder(le, poolName, false); this.execTracker = test.removeOnCancelPolicy(true).build(); assertTrue(this.execTracker instanceof ScheduledThreadPoolExecutor); final ScheduledThreadPoolExecutor castedExec = (ScheduledThreadPoolExecutor) this.execTracker; assertTrue(castedExec.getRemoveOnCancelPolicy()); final ArgumentCaptor<ExecutorServiceManager> esmCaptor = ArgumentCaptor.forClass(ExecutorServiceManager.class); <START> verify(le, times(1)).manage(esmCaptor.capture()); <END> final ExecutorServiceManager esmCaptured = esmCaptor.getValue(); assertSame(this.execTracker, esmCaptured.getExecutor()); assertEquals(DEFAULT_SHUTDOWN_PERIOD, esmCaptured.getShutdownPeriod()); assertSame(poolName, esmCaptured.getPoolName()); }</code><technical_language>avoid times(1) default behavior of verify call</technical_language>

Target:
public void testRemoveOnCancelTrue() { final String poolName = this.getClass().getSimpleName(); final ScheduledExecutorServiceBuilder test = new ScheduledExecutorServiceBuilder(this.le, poolName, false); this.execTracker = test.removeOnCancelPolicy(true).build(); assertThat(this.execTracker).isInstanceOf(ScheduledThreadPoolExecutor.class); final ScheduledThreadPoolExecutor castedExec = (ScheduledThreadPoolExecutor) this.execTracker; assertThat(castedExec.getRemoveOnCancelPolicy()).isTrue(); final ArgumentCaptor<ExecutorServiceManager> esmCaptor = ArgumentCaptor.forClass(ExecutorServiceManager.class); verify(this.le).manage(esmCaptor.capture()); final ExecutorServiceManager esmCaptured = esmCaptor.getValue(); assertThat(esmCaptured.getExecutor()).isSameAs(this.execTracker); assertThat(esmCaptured.getShutdownPeriod()).isEqualTo(DEFAULT_SHUTDOWN_PERIOD); assertThat(esmCaptured.getPoolName()).isSameAs(poolName); }
Source:
<code>private void fillMissingFeaturesDetail(){ <START> FeatureScenario[][] featuresDetail_ = new FeatureScenario[buildNumbers.length][]; <END> FeatureScenario[] featureScenarios = new FeatureScenario[0]; Arrays.fill(featuresDetail_, featureScenarios); System.arraycopy(featuresDetail, 0, featuresDetail_, buildNumbers.length - featuresDetail.length, featuresDetail.length); featuresDetail = featuresDetail_; }</code><technical_language>I _ convention</technical_language>

Target:
private void fillMissingFeaturesDetail(){ FeatureScenario[][] extendedFeaturesDetail = new FeatureScenario[buildNumbers.length][]; FeatureScenario[] featureScenarios = new FeatureScenario[0]; Arrays.fill(extendedFeaturesDetail, featureScenarios); System.arraycopy(featuresDetail, 0, extendedFeaturesDetail, buildNumbers.length - featuresDetail.length, featuresDetail.length); featuresDetail = extendedFeaturesDetail; }
Source:
<code>private Object localPrepare(TxInvocationContext ctx, PrepareCommand command) throws Throwable { boolean needsToPrepare = true; Object retVal = null; while (needsToPrepare) { try { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); command.setTopologyId(cacheTopology.getTopologyId()); if (log.isTraceEnabled()) { log.tracef("Local transaction received %s. setting topology Id to %s", command.getGlobalTransaction().prettyPrint(), command.getTopologyId()); } retVal = invokeNextInterceptor(ctx, command); needsToPrepare = false; } catch (Throwable throwable) { <START> needsToPrepare = needsToRePrepare(throwable); <END> if (log.isDebugEnabled()) { log.tracef("Exception caught while preparing transaction %s (cause = %s). Needs to retransmit? %s", command.getGlobalTransaction().prettyPrint(), throwable.getCause(), needsToPrepare); } if (!needsToPrepare) { throw throwable; } } } return retVal; }</code><technical_language>I need call StateTransferLock.waitForTopology(command.getTopologyId() + 1) avoid resending prepare topology id. In 5.1 a similar retry mechanism StateTransferInProgressException a field expected topology in it, topology differences > 1 rare overkill</technical_language>

Target:
private Object localPrepare(TxInvocationContext ctx, PrepareCommand command) throws Throwable { boolean needsToPrepare = true; Object retVal = null; while (needsToPrepare) { try { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); command.setTopologyId(cacheTopology.getTopologyId()); if (log.isTraceEnabled()) { log.tracef("Local transaction received %s. setting topology Id to %s", command.getGlobalTransaction().globalId(), command.getTopologyId()); } retVal = invokeNextInterceptor(ctx, command); needsToPrepare = false; } catch (Throwable throwable) { needsToPrepare = needsToRePrepare(throwable); if (log.isDebugEnabled()) { log.tracef("Exception caught while preparing transaction %s (cause = %s). Needs to retransmit? %s", command.getGlobalTransaction().globalId(), throwable.getCause(), needsToPrepare); } if (!needsToPrepare) { throw throwable; } } } return retVal; }
Source:
<code>public static String readOffsetFile(File storagePartitionDir, String offsetFileName) { String offset = null; File offsetFileRef = new File(storagePartitionDir, offsetFileName); String storePath = storagePartitionDir.getPath(); if (offsetFileRef.exists()) { LOG.info("Found offset file in storage partition directory: {}", storePath); try { offset = FileUtil.readWithChecksum(offsetFileRef); } catch (Exception e) { <START> LOG.warn("Fail to read offset file of " + storePath, e); <END> } } else { LOG.info("No offset file found in storage partition directory: {}", storePath); } return offset; }</code><technical_language>Minor: For consistency: LOG.warn("Failed read offset file in storage partition directory: {}", offsetFileName, storepath, e)</technical_language>

Target:
public static String readOffsetFile(File storagePartitionDir, String offsetFileName) { String offset = null; File offsetFileRef = new File(storagePartitionDir, offsetFileName); String storePath = storagePartitionDir.getPath(); if (offsetFileRef.exists()) { LOG.info("Found offset file in storage partition directory: {}", storePath); try { offset = FileUtil.readWithChecksum(offsetFileRef); } catch (Exception e) { LOG.warn("Failed to read offset file in storage partition directory: {}", storePath, e); } } else { LOG.info("No offset file found in storage partition directory: {}", storePath); } return offset; }
Source:
<code>private static void prepareProxyParams() { String proxySet = System.getProperty("http.proxySet"); if ("true".equalsIgnoreCase(proxySet)) { proxyHost = System.getProperty("http.proxyHost"); String proxyPortString = System.getProperty("http.proxyPort"); if (StringUtils.isNotBlank(proxyPortString)) { try { proxyPort = Integer.valueOf(proxyPortString); } catch (NumberFormatException e) { <START> logger.warn("'{}' is not a valid proxy port - using port 80 instead"); <END> } } proxyUser = System.getProperty("http.proxyUser"); proxyPassword = System.getProperty("http.proxyPassword"); nonProxyHosts = System.getProperty("http.nonProxyHosts"); } }</code><technical_language>Parameter missing (@lolodomo I send a PR a small change -- a -- this fix.)</technical_language>

Target:
private static ProxyParams prepareProxyParams() { final ProxyParams proxyParams = new ProxyParams(); String proxySet = System.getProperty("http.proxySet"); if ("true".equalsIgnoreCase(proxySet)) { proxyParams.proxyHost = System.getProperty("http.proxyHost"); String proxyPortString = System.getProperty("http.proxyPort"); if (StringUtils.isNotBlank(proxyPortString)) { try { proxyParams.proxyPort = Integer.valueOf(proxyPortString); } catch (NumberFormatException e) { logger.warn("'{}' is not a valid proxy port - using default port ({}) instead", proxyPortString, proxyParams.proxyPort); } } proxyParams.proxyUser = System.getProperty("http.proxyUser"); proxyParams.proxyPassword = System.getProperty("http.proxyPassword"); proxyParams.nonProxyHosts = System.getProperty("http.nonProxyHosts"); } return proxyParams; }
Source:
<code>public void persist(final OCFLPersistentStorageSession session, final ResourceOperation operation) throws PersistentStorageException { final var mapping = getMapping(operation.getResourceId()); final var fedoraResourceRoot = mapping.getRootObjectIdentifier(); final var resourceId = operation.getResourceId(); final var objectSession = session.findOrCreateSession(mapping.getOcflObjectId()); final var isRdf = ((DeleteResourceOperation) operation).isRdf(); log.debug("Deleting from {}", resourceId, mapping.getOcflObjectId()); if (fedoraResourceRoot.equals(resourceId)) { objectSession.deleteObject(); } else { final var relativeSubPath = relativizeSubpath(fedoraResourceRoot, operation.getResourceId()); <START> final var ocflSubPath = resolveOCFLSubpath(fedoraResourceRoot, relativeSubPath) + <END> (isRdf ? getRDFFileExtension() : ""); objectSession.delete(ocflSubPath); } }</code><technical_language>This done Utils class reused other places if needed</technical_language>

Target:
public void persist(final OCFLPersistentStorageSession session, final ResourceOperation operation) throws PersistentStorageException { final var mapping = getMapping(operation.getResourceId()); final var fedoraResourceRoot = mapping.getRootObjectIdentifier(); final var resourceId = operation.getResourceId(); final var objectSession = session.findOrCreateSession(mapping.getOcflObjectId()); log.debug("Deleting from {}", resourceId, mapping.getOcflObjectId()); if (fedoraResourceRoot.equals(resourceId)) { objectSession.deleteObject(); } else { final var relativeSubPath = relativizeSubpath(fedoraResourceRoot, operation.getResourceId()); final var ocflSubPath = resolveOCFLSubpath(fedoraResourceRoot, relativeSubPath); final var headers = readHeaders(objectSession, ocflSubPath); final var filePath = resolveExtensions(ocflSubPath, !Objects.equals(NON_RDF_SOURCE.toString(), headers.getInteractionModel()) ); objectSession.delete(filePath); } }
Source:
<code>private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { String template = EmailTemplates.USER_FEEDBACK_SESSION_CLOSED; String subject = EmailType.FEEDBACK_CLOSED.getSubject(); List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); for (InstructorAttributes instructor : instructors) { String emailBody = Templates.populateTemplate(template, "${userName}", instructor.name, "${courseName}", course.getName(), "${courseId}", course.getId(), "${feedbackSessionName}", session.getFeedbackSessionName(), "${deadline}", TimeHelper.formatTime12H(session.getEndTime()), "${supportEmail}", Config.SUPPORT_EMAIL); EmailWrapper email = getEmptyEmailAddressedToEmail(instructor.email); email.setSubject(String.format(subject, course.getName(), session.getFeedbackSessionName())); <START> email.setContent(emailBody); <END> emails.add(email); } for (StudentAttributes student : students) { String emailBody = Templates.populateTemplate(template, "${userName}", student.name, "${courseName}", course.getName(), "${courseId}", course.getId(), "${feedbackSessionName}", session.getFeedbackSessionName(), "${deadline}", TimeHelper.formatTime12H(session.getEndTime()), "${supportEmail}", Config.SUPPORT_EMAIL); EmailWrapper email = getEmptyEmailAddressedToEmail(student.email); email.setSubject(String.format(subject, course.getName(), session.getFeedbackSessionName())); email.setContent(emailBody); emails.add(email); } return emails; }</code><technical_language>if extract a smaller method generate email for instructor/student. e.g. for (...){ emails.add(FeedbackSessionClosedEmailForInstructor(...)); }</technical_language>

Target:
private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); for (InstructorAttributes instructor : instructors) { emails.add(generateFeedbackSessionClosedEmail(course, session, instructor.name, instructor.email)); } for (StudentAttributes student : students) { emails.add(generateFeedbackSessionClosedEmail(course, session, student.name, student.email)); } return emails; }
Source:
<code>void onMoveItem(int oldPosition, int newPosition) { Collections.swap(wikipediaLanguages, <START> oldPosition, newPosition); <END> notifyItemMoved(oldPosition, newPosition); }</code><technical_language>oldPosition - NUM_HEADERS, newPosition - NUM_HEADERS</technical_language>

Target:
void onMoveItem(int oldPosition, int newPosition) { Collections.swap(wikipediaLanguages, oldPosition - NUM_HEADERS, newPosition - NUM_FOOTERS); notifyItemMoved(oldPosition, newPosition); }