auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static InternationalFixedDate resolvePreviousValid(final int prolepticYear, final int month, final int day) { if (month == 0 && day == 0) { return createYearDay(prolepticYear); } if (month == -1 && day == -1 && InternationalFixedChronology.INSTANCE.isLeapYear(prolepticYear)) { return createLeapDay(prolepticYear); } int monthR = month == -1 ? 7 : month == 0 ? InternationalFixedChronology.MONTHS_IN_YEAR : Math.min(month, InternationalFixedChronology.MONTHS_IN_YEAR); int dayR = day == -1 ? 1 : day == 0 ? InternationalFixedChronology.DAYS_IN_MONTH : Math.min(day, InternationalFixedChronology.DAYS_IN_MONTH); return of(prolepticYear, monthR, dayR); }

Target:
private static InternationalFixedDate resolvePreviousValid(final int prolepticYear, final int month, final int day) { if ((month == 0 && day == 0) || (month == -1 && day == -1 && INSTANCE.isLeapYear(prolepticYear))) { return create(prolepticYear, month, day); } int monthR = month == -1 ? 7 : month == 0 ? MONTHS_IN_YEAR : Math.min(month, MONTHS_IN_YEAR); int dayR = day == -1 ? 1 : day == 0 ? DAYS_IN_MONTH : Math.min(day, DAYS_IN_MONTH); return create(prolepticYear, monthR, dayR); }
Source:
private void pickFileVFS() { String prevName = jobMeta.environmentSubstitute( getPath() ); if ( !Utils.isEmpty( prevName ) ) { try { if ( KettleVFS.fileExists( prevName ) ) { selectJob( ProviderFilterType.LOCAL ); return; } else { if ( !prevName.endsWith( ".kjb" ) ) { prevName = getEntryName( Const.trim( getPath() ) + ".kjb" ); } if ( KettleVFS.fileExists( prevName ) ) { wPath.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; return; } else if ( askToCreateNewJob( prevName ) ) { return; } } } catch ( Exception e ) { } } selectJob( ProviderFilterType.LOCAL ); }

Target:
private void pickFileVFS() { String prevName = jobMeta.environmentSubstitute( getPath() ); if ( !Utils.isEmpty( prevName ) ) { try { if ( !KettleVFS.fileExists( prevName ) ) { if ( !prevName.endsWith( ".kjb" ) ) { prevName = getEntryName( Const.trim( getPath() ) + ".kjb" ); } if ( KettleVFS.fileExists( prevName ) ) { wPath.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; return; } else if ( askToCreateNewJob( prevName ) ) { return; } } } catch ( Exception e ) { } } selectJob( ProviderFilterType.LOCAL ); }
Source:
public static OptionalInt getConcurrentLifespansPerNode(Session session) { Integer result = session.getSystemProperty(CONCURRENT_LIFESPANS_PER_NODE, Integer.class); checkArgument(result >= 0, "Concurrent lifespans per node must be non-negative"); if (result == 0) { return OptionalInt.empty(); } else { return OptionalInt.of(result); } }

Target:
public static OptionalInt getConcurrentLifespansPerNode(Session session) { Integer result = session.getSystemProperty(CONCURRENT_LIFESPANS_PER_NODE, Integer.class); if (result == 0) { return OptionalInt.empty(); } else { checkArgument(result > 0, "Concurrent lifespans per node must be positive if set to non-zero"); return OptionalInt.of(result); } }
Source:
public String toString() { return super.toString() + ", " + "JdbcRuntimeInfo: {" + "driverClassName:" + driverClassName + "}"; }

Target:
public String toString() { return super.toString() + ", JdbcRuntimeInfo: {driverClassName:" + driverClassName + "}"; }
Source:
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(); switch (requestCode) { 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(); }

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:
public List<ExecutableFlow> getRecentlyFinishedFlows() { List<ExecutableFlow> flows = new ArrayList<>(); try { flows = executorLoader.fetchRecentlyFinishedFlows( RECENTLY_FINISHED_LIFETIME.toMillis()); } catch(ExecutorManagerException e) { logger.error(e); } return flows; }

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:
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)); }

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:
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.getActiveInstance(); 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); }

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:
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(20); swtSeries.setBarColor(color); return swtSeries; }

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:
protected Point getInitialSize() { if (!persistSize) { int defaultHeight = super.getInitialSize().y; persistSize = true; try { Point size = super.getInitialSize(); size.y = defaultHeight; return size; } finally { persistSize = false; } } return super.getInitialSize(); }

Target:
protected Point getInitialSize() { if (!persistSize) { Point size = super.getInitialSize(); size.x = getPersistedSize().x; return size; } return super.getInitialSize(); }
Source:
public Set<String> getTags() { return Collections.unmodifiableSet(this.tags); }

Target:
public Collection<String> getTags() { return Collections.unmodifiableSet(this.tags); }
Source:
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 { 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\">" + updatedQuestion.getQuestionDetails().getQuestionTypeDisplayName() + ":</span> " + updatedQuestion.getQuestionDetails().questionText; } }

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:
public void start(PluginGuiceEnvironment env) throws Exception { manager = new LifecycleManager(); String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); manager.add(httpInjector); manager.start(); }

Target:
public void start(PluginGuiceEnvironment env) throws Exception { String fileName = getSrcFile().getName(); httpInjector = Guice.createInjector(new StandaloneJsPluginModule(getName(), fileName)); }
Source:
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": 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; } } }

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:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(MainActivity.this, MessageService.class)); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startMessageService(); }
Source:
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.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); }

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:
public void scaleForErrorMarginReducesTimeoutSlightly() { assertThat(BlockingTimeouts.scaleForErrorMargin(ONE_MILLION)) .isLessThan(ONE_MILLION) .isEqualTo(970_000); }

Target:
public void scaleForErrorMarginReducesTimeoutSlightly() { assertThat(BlockingTimeouts.scaleForErrorMargin(ONE_MILLION, TEST_ERROR_MARGIN)) .isLessThan(ONE_MILLION) .isEqualTo(scaleForErrorMarginReferenceImplementation(ONE_MILLION, TEST_ERROR_MARGIN)); }
Source:
@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]; while ((nRead = is.read(data, 0, data.length)) != -1) 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); } }

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:
protected AbstractNamedPermission(final String name) { super(name); if (getName() == null) throw log.namedPermissionNameMustBeSet(getClass().getName()); }

Target:
protected AbstractNamedPermission(final String name) { super(Assert.checkNotNullParam("name", name)); }
Source:
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).stream() .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); } }); }

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:
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.toString()); } 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); }

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:
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; final int IV_LENGTH_BYTE = 12; 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); } }

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:
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); } return requestsToRemove; }

Target:
private List<LocationRequest> getRequestOnlyUsedBy(ClientCallbackWrapper wrapper) { List<LocationRequest> requestsToRemove = clientCallbackToLocationRequests.get(wrapper); if (requestsToRemove == null) { return null; } clientCallbackToLocationRequests.remove(wrapper); return requestsToRemove; }
Source:
public List<HudsonModelJob> getJobs(final List<String> ids, final IOperationMonitor monitor) 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); }

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:
public TargetDefinitionContent resolveContent(TargetDefinition definition) throws ResolutionException { try { return resolveContentWithExceptions(definition); } catch (TargetDefinitionSyntaxException e) { throw new RuntimeException("Invalid syntax in target definition " + definition.getOrigin() + ": " + e.getMessage(), e); } }

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:
public void doHandleDataDeleted(String path) { LOG.warn("Data deleted in path: " + path); }

Target:
public void doHandleDataDeleted(String path) { LOG.warn("Data deleted in path: " + path + " barrierVersion: " + barrierVersion); }
Source:
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); } } } } 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(); } }

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:
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); verify(le, times(1)).manage(esmCaptor.capture()); final ExecutorServiceManager esmCaptured = esmCaptor.getValue(); assertSame(this.execTracker, esmCaptured.getExecutor()); assertEquals(DEFAULT_SHUTDOWN_PERIOD, esmCaptured.getShutdownPeriod()); assertSame(poolName, esmCaptured.getPoolName()); }

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:
private void fillMissingFeaturesDetail(){ FeatureScenario[][] featuresDetail_ = new FeatureScenario[buildNumbers.length][]; FeatureScenario[] featureScenarios = new FeatureScenario[0]; Arrays.fill(featuresDetail_, featureScenarios); System.arraycopy(featuresDetail, 0, featuresDetail_, buildNumbers.length - featuresDetail.length, featuresDetail.length); featuresDetail = featuresDetail_; }

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:
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) { needsToPrepare = needsToRePrepare(throwable); 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; }

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:
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("Fail to read offset file of " + storePath, e); } } else { LOG.info("No offset file found in storage partition directory: {}", storePath); } return offset; }

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:
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) { logger.warn("'{}' is not a valid proxy port - using port 80 instead"); } } proxyUser = System.getProperty("http.proxyUser"); proxyPassword = System.getProperty("http.proxyPassword"); nonProxyHosts = System.getProperty("http.nonProxyHosts"); } }

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:
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()); final var ocflSubPath = resolveOCFLSubpath(fedoraResourceRoot, relativeSubPath) + (isRdf ? getRDFFileExtension() : ""); objectSession.delete(ocflSubPath); } }

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:
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())); email.setContent(emailBody); 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; }

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:
void onMoveItem(int oldPosition, int newPosition) { Collections.swap(wikipediaLanguages, oldPosition, newPosition); notifyItemMoved(oldPosition, newPosition); }

Target:
void onMoveItem(int oldPosition, int newPosition) { Collections.swap(wikipediaLanguages, oldPosition - NUM_HEADERS, newPosition - NUM_FOOTERS); notifyItemMoved(oldPosition, newPosition); }
Source:
void processSpartanDbFile(String eseDumperPath, List<AbstractFile> spartanFiles) throws IOException, TskCoreException { for (AbstractFile spartanFile : spartanFiles) { if (context.dataSourceIngestIsCancelled()) { return; } String tempSpartanFileName = EDGE_WEBCACHE_PREFIX + Integer.toString((int) spartanFile.getId()) + EDGE_WEBCACHE_EXT; File tempSpartanFile = new File(RAImageIngestModule.getRATempPath(currentCase, EDGE), tempSpartanFileName); try { ContentUtils.writeToFile(spartanFile, tempSpartanFile, context::dataSourceIngestIsCancelled); } catch (IOException ex) { throw new IOException("Error writingToFile: " + spartanFile, ex); } File resultsDir = new File(moduleTempResultPath.toAbsolutePath() + Integer.toString((int) spartanFile.getId())); resultsDir.mkdirs(); try { executeDumper(eseDumperPath, tempSpartanFile.getAbsolutePath(), resultsDir.getAbsolutePath()); if (context.dataSourceIngestIsCancelled()) { return; } this.getBookmark(spartanFile, resultsDir); } finally { tempSpartanFile.delete(); resultsDir.delete(); } } }

Target:
void processSpartanDbFile(String eseDumperPath, List<AbstractFile> spartanFiles) throws IOException, TskCoreException { for (AbstractFile spartanFile : spartanFiles) { if (context.dataSourceIngestIsCancelled()) { return; } String tempSpartanFileName = EDGE_WEBCACHE_PREFIX + Integer.toString((int) spartanFile.getId()) + EDGE_WEBCACHE_EXT; File tempSpartanFile = new File(RAImageIngestModule.getRATempPath(currentCase, EDGE), tempSpartanFileName); try { ContentUtils.writeToFile(spartanFile, tempSpartanFile, context::dataSourceIngestIsCancelled); } catch (IOException ex) { throw new IOException("Error writingToFile: " + spartanFile, ex); } File resultsDir = new File(moduleTempResultPath.toAbsolutePath() + Integer.toString((int) spartanFile.getId())); resultsDir.mkdirs(); try { executeDumper(eseDumperPath, tempSpartanFile.getAbsolutePath(), resultsDir.getAbsolutePath()); if (context.dataSourceIngestIsCancelled()) { return; } this.getBookmarks(spartanFile, resultsDir); } finally { tempSpartanFile.delete(); resultsDir.delete(); } } }
Source:
public void rearrangeCategories(String eventName, List<CategoryOrdinalModification> categories, String username) { var optionalEvent = getOptionalEventAndOrganizationIdByName(eventName, username); if(optionalEvent.isPresent()) { var parameterSources = categories.stream() .map(category -> new MapSqlParameterSource("ordinal", category.getOrdinal()).addValue("id", category.getId())) .toArray(MapSqlParameterSource[]::new); int[] results = jdbcTemplate.batchUpdate(ticketCategoryRepository.updateOrdinal(), parameterSources); Validate.isTrue(IntStream.of(results).sum() == categories.size(), "Unexpected result from update."); } else { log.warn("unauthorized access to event {}", eventName); } }

Target:
public void rearrangeCategories(String eventName, List<CategoryOrdinalModification> categories, String username) { var optionalEvent = getOptionalEventAndOrganizationIdByName(eventName, username); if(optionalEvent.isPresent()) { int eventId = optionalEvent.get().getId(); var parameterSources = categories.stream() .map(category -> new MapSqlParameterSource("ordinal", category.getOrdinal()) .addValue("id", category.getId()) .addValue("eventId", eventId)) .toArray(MapSqlParameterSource[]::new); int[] results = jdbcTemplate.batchUpdate(ticketCategoryRepository.updateOrdinal(), parameterSources); Validate.isTrue(IntStream.of(results).sum() == categories.size(), "Unexpected result from update."); } else { log.warn("unauthorized access to event {}", eventName); } }