auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) { ICompilationUnit unit= context.getCompilationUnit(); if (unit == null) { return null; } IJavaProject javaProject= unit.getJavaProject(); if (javaProject == null) { return null; } if (context.getTextSelection().getLength() > 0) { return null; } CompletionContext coreContext= context.getCoreContext(); if (coreContext != null) { int tokenLocation= coreContext.getTokenLocation(); int tokenStart= coreContext.getTokenStart(); int tokenKind= coreContext.getTokenKind(); if ((tokenLocation == 0 && tokenStart > -1) || ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0 && tokenKind == CompletionContext.TOKEN_KIND_NAME && tokenStart > -1) || (tokenLocation == 0 && isAfterTrigger(context.getDocument(), context.getInvocationOffset()))) { analyzeCoreContext(context, coreContext); return postfixCompletionTemplateEngine; } } return null; }

Target:
protected TemplateEngine computeCompletionEngine(JavaContentAssistInvocationContext context) { ICompilationUnit unit= context.getCompilationUnit(); if (unit == null) { return null; } IJavaProject javaProject= unit.getJavaProject(); if (javaProject == null) { return null; } ITextSelection textSelection= context.getTextSelection(); if (textSelection != null && textSelection.getLength() > 0) { return null; } CompletionContext coreContext= context.getCoreContext(); if (coreContext != null) { int tokenLocation= coreContext.getTokenLocation(); int tokenStart= coreContext.getTokenStart(); int tokenKind= coreContext.getTokenKind(); if ((tokenLocation == 0 && tokenStart > -1) || ((tokenLocation & CompletionContext.TL_MEMBER_START) != 0 && tokenKind == CompletionContext.TOKEN_KIND_NAME && tokenStart > -1) || (tokenLocation == 0 && isAfterTrigger(context.getDocument(), context.getInvocationOffset()))) { analyzeCoreContext(context, coreContext); return postfixCompletionTemplateEngine; } } return null; }
Source:
AsyncTask download( final String fileURL, final String destinationPath, final ProgressBar progressBar ) { return new AsyncTask<Void, Integer, File>() { @Override protected File doInBackground( Void... voids ) { isCancelled(); return downloading( fileURL, destinationPath, new ProgressCallback() { @Override public void onProgress( double percent ) { publishProgress( (int) percent ); } } ); } @Override protected void onProgressUpdate( Integer... values ) { super.onProgressUpdate( values ); progressBar.setProgress( values[ 0 ] ); } }; }

Target:
AsyncTask download( final String fileURL, final String destinationPath, final ProgressBar progressBar ) { return new AsyncTask<Void, Double, File>() { @Override protected File doInBackground( Void... voids ) { return downloading( fileURL, destinationPath, new ProgressCallback() { @Override public void onProgress( double percent ) { publishProgress( percent ); } } ); } @Override protected void onProgressUpdate( Double... values ) { super.onProgressUpdate( values ); progressBar.setProgress( values[ 0 ].intValue() ); } }; }
Source:
public void onNext(T t) { Publisher<? extends R> p; try { p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); s.cancel(); onError(ex); return; } InnerQueuedSubscriber<R> inner = new InnerQueuedSubscriber<R>(this, prefetch); if (!cancelled) { subscribers.offer(inner); if (!cancelled) { p.subscribe(inner); if (cancelled) { inner.cancel(); } } else { drainAndCancel(); } } }

Target:
public void onNext(T t) { Publisher<? extends R> p; try { p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); s.cancel(); onError(ex); return; } InnerQueuedSubscriber<R> inner = new InnerQueuedSubscriber<R>(this, prefetch); if (cancelled) { return; } subscribers.offer(inner); if (cancelled) { return; } p.subscribe(inner); if (cancelled) { inner.cancel(); drainAndCancel(); } }
Source:
protected boolean canDoAction() { if(super.canDoAction()) { StorageServerConnections paramConnection = getParameters().getStorageServerConnection(); if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!InitializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return true; } return false; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } StorageServerConnections paramConnection = getParameters().getStorageServerConnection(); if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!InitializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return true; }
Source:
protected void run() throws UnloggedFailure { if (names != null && !names.isEmpty()) { try { loader.enablePlugins(Sets.newHashSet(names)); } catch (PluginInstallException e) { e.printStackTrace(stderr); throw die("plugin failed to install"); } } }

Target:
protected void run() throws UnloggedFailure { if (names != null && !names.isEmpty()) { try { loader.enablePlugins(Sets.newHashSet(names)); } catch (PluginInstallException e) { e.printStackTrace(stderr); throw die("plugin failed to enable"); } } }
Source:
public Map<String, String> getConfiguration() { Map<String, String> configMap = new HashMap<>(); try { TenantConfigDTO[] tenantConfigDTOs = stub.getConfiguration(); for (int i = 0; i < tenantConfigDTOs.length; i++) { TenantConfigDTO tenantConfigDTO = tenantConfigDTOs[i]; configMap.put(tenantConfigDTO.getProperty(), tenantConfigDTO.getPropertyValue()); } } catch (RemoteException e) { log.error("Error occurred when retrieving configuration details", e); } return configMap; }

Target:
public Map<String, String> getConfiguration() { Map<String, String> configMap = new HashMap<>(); try { TenantConfigDTO[] tenantConfigDTOs = stub.getConfiguration(); for (TenantConfigDTO tenantConfigDTO : tenantConfigDTOs) { configMap.put(tenantConfigDTO.getProperty(), tenantConfigDTO.getPropertyValue()); } } catch (RemoteException e) { log.error("Error occurred when retrieving configuration details", e); } return configMap; }
Source:
private SelectConditionStep<Record> schemaQuery(long accountId, String role) { return create() .select() .from(DYNAMIC_SCHEMA).leftOuterJoin(DYNAMIC_SCHEMA_ROLE) .on(DYNAMIC_SCHEMA_ROLE.DYNAMIC_SCHEMA_ID.eq(DYNAMIC_SCHEMA.ID)) .where(DYNAMIC_SCHEMA.ACCOUNT_ID.eq(accountId) .and(DYNAMIC_SCHEMA_ROLE.ROLE.eq(role)) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))) .or(DYNAMIC_SCHEMA.ACCOUNT_ID.eq(accountId) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))) .or(DYNAMIC_SCHEMA_ROLE.ROLE.eq(role) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))); }

Target:
private SelectConditionStep<Record> schemaQuery(long accountId, String role) { return create() .select() .from(DYNAMIC_SCHEMA).leftOuterJoin(DYNAMIC_SCHEMA_ROLE) .on(DYNAMIC_SCHEMA_ROLE.DYNAMIC_SCHEMA_ID.eq(DYNAMIC_SCHEMA.ID)) .where(DYNAMIC_SCHEMA.ACCOUNT_ID.eq(accountId) .and(DYNAMIC_SCHEMA_ROLE.ROLE.eq(role)) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))) .or(DYNAMIC_SCHEMA.ACCOUNT_ID.eq(accountId) .and(DYNAMIC_SCHEMA_ROLE.ROLE.isNull()) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))) .or(DYNAMIC_SCHEMA_ROLE.ROLE.eq(role) .and(DYNAMIC_SCHEMA.ACCOUNT_ID.isNull()) .and(DYNAMIC_SCHEMA.STATE.ne(CommonStatesConstants.PURGED))); }
Source:
public void getAllTicketsWithTransportZero() { Ticket ticketWithoutPickup = ticketService.requestTicketOfType(TEST_TICKET, Collections.singletonList(CH_MEMBER_OPTION)); ticketWithoutPickup.setValid(true); testEntityManager.persist(ticketWithoutPickup); Collection<Ticket> tickets = ticketService.getAllTicketsWithTransport(); assertEquals(tickets, Collections.emptyList()); }

Target:
public void getAllTicketsWithTransportZero() { Ticket ticketWithoutPickup = ticketService.requestTicketOfType(TEST_TICKET, Collections.singletonList(CH_MEMBER_OPTION)); ticketWithoutPickup.setValid(true); testEntityManager.persist(ticketWithoutPickup); Collection<Ticket> tickets = ticketService.getAllTicketsWithTransport(); assertThat(tickets).isEmpty(); }
Source:
private void realTimeImpl$adjustForRealTimeGrowingUp(final EntityAgeable self, final int age) { if (((WorldBridge) this.world).bridge$isFake()) { this.setGrowingAge(age); return; } final int diff = (int) ((RealTimeTrackingBridge) this.world).realTimeBridge$getRealTimeTicks() - 1; final int new_age = age - (int) Math.signum(age) * diff; this.setGrowingAge((age ^ new_age) < 0 ? 0 : new_age); }

Target:
private void realTimeImpl$adjustForRealTimeGrowingUp(final EntityAgeable self, final int age) { if (((WorldBridge) this.world).bridge$isFake()) { this.setGrowingAge(age); return; } final int diff = (int) ((RealTimeTrackingBridge) this.world).realTimeBridge$getRealTimeTicks() - 1; if (diff == 0) { this.setGrowingAge(age); } else if (age > 0) { this.setGrowingAge(Math.max(0, age - diff)); } else { this.setGrowingAge(Math.min(0, age + diff)); } }
Source:
public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { super.fromData(in, context); this.bucketId = (int) InternalDataSerializer.readSignedVL(in); this.callbackArg = DataSerializer.readObject(in); this.regionEvent = DataSerializer.readObject(in); }

Target:
public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { super.fromData(in, context); this.bucketId = (int) InternalDataSerializer.readSignedVL(in); this.regionEvent = DataSerializer.readObject(in); }
Source:
public static void registerBrixUnstructuredMixin(Workspace workspace) { String cnd = "[brix:unstructured] mixin" + " - * (undefined) multiple " + " - * (undefined) " + " + * (nt:base) sns version "; NodeTypeManager manager = null; try { manager = workspace.getNodeTypeManager(); if (manager.hasNodeType("brix:unstructured") == false) { CndImporter.registerNodeTypes(new StringReader(cnd), workspace.getSession()); } } catch (Exception e) { e.printStackTrace(); } }

Target:
public static void registerBrixUnstructuredMixin(Workspace workspace) { String cnd = "[brix:unstructured] mixin" + " - * (undefined) multiple " + " - * (undefined) " + " + * (nt:base) sns version "; try { NodeTypeManager manager = workspace.getNodeTypeManager(); if (manager.hasNodeType("brix:unstructured") == false) { CndImporter.registerNodeTypes(new StringReader(cnd), workspace.getSession()); } } catch (Exception e) { throw new RuntimeException("JCR error - could not create the brix:unstructured mixin", e); } }
Source:
public void testVpnMeterednessWithNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } Network wifi = ensureWifiConnected(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = null; String allowedApps = mPackageName; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, false); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertEquals(isNetworkMetered(wifi), isNetworkMetered(mNetwork)); assertEquals(isNetworkMetered(mNetwork), mCM.isActiveNetworkMetered()); }

Target:
public void testVpnMeterednessWithNullUnderlyingNetwork() throws Exception { if (!supportedHardware()) { return; } Network wifi = getWifiNetwork(); assertEquals(wifi, mCM.getActiveNetwork()); ArrayList<Network> underlyingNetworks = null; String allowedApps = mPackageName; startVpn( new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"}, new String[] {"0.0.0.0/0", "::/0"}, allowedApps, "", null, underlyingNetworks, false ); assertEquals(mNetwork, mCM.getActiveNetwork()); ensureVpnTransportContains(NetworkCapabilities.TRANSPORT_WIFI); assertEquals(isNetworkMetered(wifi), isNetworkMetered(mNetwork)); assertEquals(isNetworkMetered(mNetwork), mCM.isActiveNetworkMetered()); }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { GateKeeper.inst().verifyAdminPrivileges(account); BlobKey blobKey = new BlobKey(""); BlobInfo blobInfo = null; data = new AdminEmailComposePageData(account); blobInfo = extractImageKey(); if(blobInfo == null){ data.isFileUploaded = false; data.fileSrcUrl = null; log.info("Image Upload Failed"); statusToAdmin = "Image Upload Failed"; return createAjaxResult(data); } blobKey = blobInfo.getBlobKey(); data.isFileUploaded = true; data.fileSrcUrl = Const.ActionURIs.PUBLIC_EMAIL_FILE_SERVE + "?blob-key=" + blobKey.getKeyString(); log.info("New Image Uploaded : " + Config.APP_URL + data.fileSrcUrl); statusToAdmin = "New Image Uploaded : " + "<a href=" + data.fileSrcUrl + " target=blank>" + Config.APP_URL + data.fileSrcUrl + "</a>"; data.ajaxStatus = "Image Successfully Uploaded to Google Cloud Storage"; return createAjaxResult(data); }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { GateKeeper.inst().verifyAdminPrivileges(account); BlobKey blobKey = new BlobKey(""); BlobInfo blobInfo = null; data = new AdminEmailComposePageData(account); blobInfo = extractImageKey(); if(blobInfo == null){ data.isFileUploaded = false; data.fileSrcUrl = null; log.info("Image Upload Failed"); statusToAdmin = "Image Upload Failed"; return createAjaxResult(data); } blobKey = blobInfo.getBlobKey(); data.isFileUploaded = true; data.fileSrcUrl = Const.ActionURIs.PUBLIC_EMAIL_FILE_SERVE + "?blob-key=" + blobKey.getKeyString(); String absoluteFileSrcUrl = new Url(data.fileSrcUrl).toAbsoluteString(); log.info("New Image Uploaded : " + absoluteFileSrcUrl); statusToAdmin = "New Image Uploaded : " + "<a href=" + data.fileSrcUrl + " target=blank>" + absoluteFileSrcUrl + "</a>"; data.ajaxStatus = "Image Successfully Uploaded to Google Cloud Storage"; return createAjaxResult(data); }
Source:
public void runPreInstallCommand() { if (Strings.isNonBlank(getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_COMMAND)) || Strings.isNonBlank(getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND))) { executeCommand( getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_COMMAND), getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND), "pre-install", true); } if (entity.getConfig(VanillaWindowsProcess.PRE_INSTALL_REBOOT_REQUIRED)) { rebootAndWait(); } }

Target:
public void runPreInstallCommand() { if (Strings.isNonBlank(getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_COMMAND)) || Strings.isNonBlank(getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND))) { executeCommandInTask( getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_COMMAND), getEntity().getConfig(VanillaWindowsProcess.PRE_INSTALL_POWERSHELL_COMMAND), "pre-install-command"); } if (entity.getConfig(VanillaWindowsProcess.PRE_INSTALL_REBOOT_REQUIRED)) { rebootAndWait(); } }
Source:
public Value decode(final BsonReader reader, final DecoderContext decoderContext) { Map<Value, Value> kvs = new LinkedHashMap<>(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String fieldName = reader.readName(); BsonType type = reader.getCurrentBsonType(); fieldName = normalize(fieldName); Value value; try { value = readValue(reader, decoderContext); kvs.put(newString(fieldName), value); if (incrementalField.isPresent() && incrementalField.get().contains(fieldName)) { this.lastRecord.put(fieldName, value); this.lastRecordType.put(fieldName, type.toString()); } } catch (UnknownTypeFoundException ex) { reader.skipValue(); if (stopOnInvalidRecord) { throw ex; } log.warn(String.format("Skipped document because field '%s' contains unsupported object type [%s]", fieldName, type)); } } reader.readEndDocument(); return newMap(kvs); }

Target:
public Value decode(final BsonReader reader, final DecoderContext decoderContext) { Map<Value, Value> kvs = new LinkedHashMap<>(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String originalFieldName = reader.readName(); BsonType type = reader.getCurrentBsonType(); String fieldName = normalize(originalFieldName); Value value; try { value = readValue(reader, decoderContext); kvs.put(newString(fieldName), value); if (incrementalField.isPresent() && incrementalField.get().contains(originalFieldName)) { this.lastRecord.put(originalFieldName, value); this.lastRecordType.put(originalFieldName, type.toString()); } } catch (UnknownTypeFoundException ex) { reader.skipValue(); if (stopOnInvalidRecord) { throw ex; } log.warn(String.format("Skipped document because field '%s' contains unsupported object type [%s]", fieldName, type)); } } reader.readEndDocument(); return newMap(kvs); }
Source:
public void showYesNoConfirmationDialog_tryYesAndNo_getCorrectValue() throws ExecutionException, InterruptedException { FutureTask<Boolean> yesTask = new FutureTask<>(() -> DialogMessage.showYesNoConfirmationDialog("Confirm", "Confirm Header", "Confirm Message", "yEs", "nO")); Platform.runLater(yesTask); waitUntilNodeAppears(hasText("Confirm Header")); assertNodeExists(hasText("Confirm Header")); clickOn("yEs"); assertEquals(true, yesTask.get()); FutureTask<Boolean> noTask = new FutureTask<>(() -> DialogMessage.showYesNoWarningDialog("Confirm", "Confirm Header", "Confirm Message", "yEs", "nO")); Platform.runLater(noTask); waitUntilNodeAppears(hasText("Confirm Message")); assertNodeExists(hasText("Confirm Message")); clickOn("nO"); assertEquals(false, noTask.get()); }

Target:
public void showYesNoConfirmationDialog_tryYesAndNo_getCorrectValue() throws ExecutionException, InterruptedException { FutureTask<Boolean> yesTask = new FutureTask<>(() -> DialogMessage.showYesNoConfirmationDialog("Confirm", "Confirm Header", "Confirm Message", "yes", "no")); Platform.runLater(yesTask); waitUntilNodeAppears(hasText("Confirm Header")); assertNodeExists(hasText("Confirm Header")); clickOn("yes"); assertEquals(true, yesTask.get()); FutureTask<Boolean> noTask = new FutureTask<>(() -> DialogMessage.showYesNoWarningDialog("Confirm", "Confirm Header", "Confirm Message", "Non-Standard-Yes", "Non-Standard-No")); Platform.runLater(noTask); waitUntilNodeAppears(hasText("Confirm Message")); assertNodeExists(hasText("Confirm Message")); clickOn("Non-Standard-No"); assertEquals(false, noTask.get()); }
Source:
public void beforeEach() throws Exception { String addonJSON = FileUtils.readFileToString(new File(testStore, "addon_remote.json")); String hotfixJSON = FileUtils.readFileToString(new File(testStore, "hotfix_remote.json")); String studioJSON = FileUtils.readFileToString(new File(testStore, "studio_remote.json")); NuxeoConnectClient.getConnectGatewayComponent().setTestConnector( new LocalConnectFakeConnector(addonJSON, hotfixJSON, studioJSON)); Environment.setDefault(null); FileUtils.deleteQuietly(nuxeoHome); nuxeoHome.mkdirs(); System.setProperty(Environment.NUXEO_HOME, nuxeoHome.getPath()); System.setProperty(TomcatConfigurator.TOMCAT_HOME, Environment.getDefault().getServerHome().getPath()); buildInitialPackageStore(); server.setHandler(new FakeConnectDownloadHandler()); environment = Environment.getDefault(); environment.setProperty(Environment.DISTRIBUTION_NAME, "server"); environment.setProperty(Environment.DISTRIBUTION_VERSION, "8.3"); environment.setProperty(ConnectBroker.LAUNCHER_CHANGED_PROPERTY, "false"); connectBroker = new ConnectBroker(environment); connectBroker.setPendingFile(environment.getData().toPath().resolve("installAfterRestart.log")); ((StandaloneCallbackHolder) NuxeoConnectClient.getCallBackHolder()).setTestMode(true); }

Target:
public void beforeEach() throws Exception { String addonJSON = FileUtils.readFileToString(new File(testStore, "addon_remote.json"), UTF_8); String hotfixJSON = FileUtils.readFileToString(new File(testStore, "hotfix_remote.json"), UTF_8); String studioJSON = FileUtils.readFileToString(new File(testStore, "studio_remote.json"), UTF_8); NuxeoConnectClient.getConnectGatewayComponent().setTestConnector( new LocalConnectFakeConnector(addonJSON, hotfixJSON, studioJSON)); Environment.setDefault(null); FileUtils.deleteQuietly(nuxeoHome); nuxeoHome.mkdirs(); System.setProperty(Environment.NUXEO_HOME, nuxeoHome.getPath()); System.setProperty(TomcatConfigurator.TOMCAT_HOME, Environment.getDefault().getServerHome().getPath()); buildInitialPackageStore(); server.setHandler(new FakeConnectDownloadHandler()); environment = Environment.getDefault(); environment.setProperty(Environment.DISTRIBUTION_NAME, "server"); environment.setProperty(Environment.DISTRIBUTION_VERSION, "8.3"); environment.setProperty(ConnectBroker.LAUNCHER_CHANGED_PROPERTY, "false"); connectBroker = new ConnectBroker(environment); connectBroker.setPendingFile(environment.getData().toPath().resolve("installAfterRestart.log")); ((StandaloneCallbackHolder) NuxeoConnectClient.getCallBackHolder()).setTestMode(true); }
Source:
public OpenTSDBWriter build() throws LifecycleException, UnknownHostException { return new OpenTSDBWriter( typeNames.build(), booleanAsNumber, debugEnabled, host, port, tags.build(), tagName, mergeTypeNamesTags, metricNamingExpression, (addHostnameTag == null) ? true : addHostnameTag, null ); }

Target:
public OpenTSDBWriter build() throws LifecycleException, UnknownHostException { return new OpenTSDBWriter( typeNames.build(), booleanAsNumber, debugEnabled, host, port, tags.build(), tagName, mergeTypeNamesTags, metricNamingExpression, addHostnameTag, null ); }
Source:
public void updateNotMatchingIDsInJSONAndURL() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat1 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 1") .build(); BitstreamFormat bitstreamFormat2 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 2") .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat1); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setId(bitstreamFormat2.getID()); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat1.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isBadRequest()); }

Target:
public void updateNotMatchingIDsInJSONAndURL() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat1 = BitstreamFormatBuilder.createBitstreamFormat(context) .withShortDescription("Test short") .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 1") .build(); BitstreamFormat bitstreamFormat2 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 2") .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat1); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setId(bitstreamFormat2.getID()); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat1.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isBadRequest()); getClient().perform(get("/api/core/bitstreamformats/" + bitstreamFormat1.getID())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", Matchers.is( BitstreamFormatMatcher .matchBitstreamFormat(bitstreamFormat1.getID(), bitstreamFormat1.getMIMEType(), bitstreamFormat1.getDescription(), bitstreamFormat1.getShortDescription()) ))); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_save_page: if (item.getTitle().equals(WikipediaApp.getInstance().getString(R.string.menu_refresh_saved_page))) { refreshPage(true); } else { savePage(); app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); } return true; case R.id.menu_share_page: shareHandler.shareWithoutSelection(); return true; case R.id.menu_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_find_in_page: showFindInPage(); return true; case R.id.menu_themechooser: getPageActivity().showThemeChooser(); return true; case R.id.menu_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_page_save: if (item.getTitle().equals(getString(R.string.menu_refresh_saved_page))) { refreshPage(true); } else { savePage(); app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); } return true; case R.id.menu_page_share: shareHandler.shareWithoutSelection(); return true; case R.id.menu_page_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_page_find_in_page: showFindInPage(); return true; case R.id.menu_page_font_and_theme: getPageActivity().showThemeChooser(); return true; case R.id.menu_page_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
public void testApplication() { try { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); XmlDataEmitterOperator input = dag.addOperator("data", new XmlDataEmitterOperator()); XmlParser parser = dag.addOperator("xmlparser", new XmlParser()); ResultCollector rc = dag.addOperator("rc", new ResultCollector()); dag.getMeta(parser).getMeta(parser.out).getAttributes().put(Context.PortContext.TUPLE_CLASS, com.datatorrent.lib.parser.XmlParserTest.EmployeeBean.class); ConsoleOutputOperator xmlObjectOp = dag.addOperator("xmlObjectOp", new ConsoleOutputOperator()); xmlObjectOp.setDebug(true); dag.addStream("input", input.output, parser.in); dag.addStream("output", parser.parsedOutput, xmlObjectOp.input); dag.addStream("pojo", parser.out,rc.input); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return TupleCount == 1; } }); lc.run(30000); Assert.assertEquals(1,TupleCount); Assert.assertEquals("john", obj.getName()); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }

Target:
public void testApplication() { try { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); XmlDataEmitterOperator input = dag.addOperator("data", new XmlDataEmitterOperator()); XmlParser parser = dag.addOperator("xmlparser", new XmlParser()); ResultCollector rc = dag.addOperator("rc", new ResultCollector()); dag.getMeta(parser).getMeta(parser.out).getAttributes().put(Context.PortContext.TUPLE_CLASS, com.datatorrent.lib.parser.XmlParserTest.EmployeeBean.class); ConsoleOutputOperator xmlObjectOp = dag.addOperator("xmlObjectOp", new ConsoleOutputOperator()); xmlObjectOp.setDebug(true); dag.addStream("input", input.output, parser.in); dag.addStream("output", parser.parsedOutput, xmlObjectOp.input); dag.addStream("pojo", parser.out,rc.input); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return TupleCount == 1; } }); lc.run(10000); Assert.assertEquals(1,TupleCount); Assert.assertEquals("john", obj.getName()); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { Repository repo = getRepository(); try { return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } finally { repo.close(); } }

Target:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { try (Repository repo = getRepository()) { return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } }
Source:
public String getIdentifier() { return "org.eclipse.ltk.core.refactoring.renameResourceProcessor"; }

Target:
public String getIdentifier() { return "org.eclipse.ltk.core.refactoring.moveRenameResourceProcessor"; }
Source:
public void testCompareWithChangedNewComponents() throws IOException { final String newConceptId = createNewConcept(branchPath); final ImmutableMap<String, Object> compareRequest = createCompareRequest(parentBranch, branchPath); final InputStream responseInputStream = givenAuthenticatedRequest(SCT_API) .contentType(ContentType.JSON) .accept(ContentType.JSON) .body(compareRequest) .post("/compare") .asInputStream(); final ObjectMapper mapper = new ObjectMapper(); final CompareResult compareResult = mapper.readValue(responseInputStream, CompareResult.class); final Set<ComponentIdentifier> newIds = prepareNewChanges(newConceptId, branchPath); assertThat(compareResult.getNewComponents()).containsAll(newIds); assertThat(compareResult.getChangedComponents()).doesNotContainAnyElementsOf(newIds); assertThat(compareResult.getDeletedComponents()).isEmpty(); }

Target:
public void testCompareWithChangedNewComponents() throws IOException { final String newConceptId = createNewConcept(branchPath); final CompareResult compareResult = getCompareResult(parentBranch.getPath(), branchPath.getPath()); final Set<ComponentIdentifier> newIds = prepareNewChanges(newConceptId, branchPath); assertThat(compareResult.getNewComponents()).containsAll(newIds); assertThat(compareResult.getChangedComponents()).doesNotContainAnyElementsOf(newIds); assertThat(compareResult.getDeletedComponents()).isEmpty(); }
Source:
void handleExpiredRequest(String processorId, String preferredHost, SamzaResourceRequest request) { boolean resourceAvailableOnAnyHost = hasAllocatedResource(ResourceRequestState.ANY_HOST); if (hostAffinityEnabled && standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleExpiredResourceRequest(processorId, request, Optional.ofNullable(peekAllocatedResource(ResourceRequestState.ANY_HOST)), this, resourceRequestState); } else if (resourceAvailableOnAnyHost) { LOG.info("Request for Processor ID: on host: has expired. Running on ANY_HOST", processorId, preferredHost); runStreamProcessor(request, ResourceRequestState.ANY_HOST); } else { LOG.info("Request for Processor ID: on host: has expired. Requesting additional resources on ANY_HOST.", processorId, preferredHost); resourceRequestState.cancelResourceRequest(request); requestResource(processorId, ResourceRequestState.ANY_HOST); } }

Target:
void handleExpiredRequest(String processorId, String preferredHost, SamzaResourceRequest request) { boolean resourceAvailableOnAnyHost = hasAllocatedResource(ResourceRequestState.ANY_HOST); if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleExpiredResourceRequest(processorId, request, Optional.ofNullable(peekAllocatedResource(ResourceRequestState.ANY_HOST)), this, resourceRequestState); } else if (resourceAvailableOnAnyHost) { LOG.info("Request for Processor ID: on host: has expired. Running on ANY_HOST", processorId, preferredHost); runStreamProcessor(request, ResourceRequestState.ANY_HOST); } else { LOG.info("Request for Processor ID: on host: has expired. Requesting additional resources on ANY_HOST.", processorId, preferredHost); resourceRequestState.cancelResourceRequest(request); requestResource(processorId, ResourceRequestState.ANY_HOST); } }
Source:
public static String format(String fmt, Object... objects) { List<String> strings = new ArrayList<String>(); for (Object object : objects) { strings.add(object.toString()); } String result = fmt; for (int i = 0; i < strings.size(); i += 2) { String pattern = "{" + strings.get(i) + "}"; String replacement = strings.get(i + 1); result = result.replaceAll(pattern, replacement); } return result; }

Target:
public static String format(String fmt, Object... objects) { List<String> strings = new ArrayList<String>(); for (Object object : objects) { strings.add(object.toString()); } String result = fmt; for (int i = 0; i < strings.size(); i += 2) { String target = "{" + strings.get(i) + "}"; String replacement = strings.get(i + 1); result = result.replace(target, replacement); } return result; }
Source:
public Stream<PojoPropertyModel<?>> getDeclaredProperties() { return Arrays.stream( declaredBeanInfo.getPropertyDescriptors() ) .map( this::createProperty ); }

Target:
public Stream<PojoPropertyModel<?>> getDeclaredProperties() { return declaredProperties.values().stream() .map( this::createProperty ); }
Source:
private boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); if (lun.getLunType() == StorageType.UNKNOWN) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); return false; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); return false; } return true; }

Target:
private boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); } for (storage_server_connections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } return true; }
Source:
private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); if (getMarshallerType() == Marshaller.NEW) { assertNotNull(executionSet.getCancelActivity()); assertEquals(isCancelling, executionSet.getCancelActivity().getValue()); assertNotNull(executionSet.getSlaDueDate()); assertEquals(slaDueDate, executionSet.getSlaDueDate().getValue()); } assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); }

Target:
private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); assertEventCancelActivity(executionSet, isCancelling); assertTimerEventSlaDueDate(executionSet, slaDueDate); }
Source:
protected ESClient createRestClient(ElasticSearchClientConfig config) { String addressList = config.getOption("addressList", ""); if (addressList.isEmpty()) { throw new IllegalArgumentException("No addressList option provided cannot connect RestClient"); } String[] hosts = addressList.split(","); HttpHost[] httpHosts = new HttpHost[hosts.length]; int i = 0; for (String host : hosts) { try { int hostPort = DEFAULT_HOST_PORT; if (!host.startsWith("http")) { host = DEFAULT_SCHEMA_HTTP +host; } URL hostUrl = new URL(host); if (hostUrl.getPort() != -1) { hostPort = hostUrl.getPort(); } httpHosts[i++] = new HttpHost(hostUrl.getHost(), hostPort, hostUrl.getProtocol()); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid host "+host+ " "+e.getMessage()); } } RestClientBuilder builder = RestClient.builder(httpHosts) .setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectTimeout( getConnectTimeoutMs(config)).setSocketTimeout( getSocketTimeoutMs(config))) .setMaxRetryTimeoutMillis(getConnectTimeoutMs(config)); if (StringUtils.isNotBlank(config.getOption(AUTH_USER_OPT)) || StringUtils.isNotBlank(config.getOption(KEYSTORE_PATH_OPT))) { addClientCallback(config, builder); } RestClient lowLevelRestClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient); return new ESRestClient(lowLevelRestClient, client); }

Target:
protected ESClient createRestClient(ElasticSearchClientConfig config) { String addressList = config.getOption("addressList", ""); if (addressList.isEmpty()) { throw new IllegalArgumentException("No addressList option provided cannot connect RestClient"); } String[] hosts = addressList.split(","); HttpHost[] httpHosts = new HttpHost[hosts.length]; int i = 0; for (String host : hosts) { httpHosts[i++] = HttpHost.create(host); } RestClientBuilder builder = RestClient.builder(httpHosts) .setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectTimeout( getConnectTimeoutMs(config)).setSocketTimeout( getSocketTimeoutMs(config))) .setMaxRetryTimeoutMillis(getConnectTimeoutMs(config)); if (StringUtils.isNotBlank(config.getOption(AUTH_USER_OPT)) || StringUtils.isNotBlank(config.getOption(KEYSTORE_PATH_OPT))) { addClientCallback(config, builder); } RestClient lowLevelRestClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient); return new ESRestClient(lowLevelRestClient, client); }
Source:
protected void open() throws XBeeException { logger.info(toString() + "Opening the connection interface..."); if (isRemote()) throw new RuntimeException("Remote devices cannot be open."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); logger.info(toString() + "Connection interface open."); dataReader = new DataReader(connectionInterface, operatingMode, (XBeeDevice)this); dataReader.start(); try { Thread.sleep(10); } catch (InterruptedException e) if (connectionInterface.getConnectionType() == ConnectionType.BLUETOOTH) { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); try { logger.info(toString() + "Starting Bluetooth authentication..."); BluetoothAuthentication auth = new BluetoothAuthentication((XBeeDevice)this, bluetoothPassword); auth.authenticate(); ((AbstractBluetoothInterface) connectionInterface).setEncryptionKeys(auth.getKey(), auth.getTxNonce(), auth.getRxNonce()); logger.info(toString() + "Authentication finished successfully."); } catch (BluetoothAuthenticationException e) { close(); throw e; } } else { if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineOperatingMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } } try { readDeviceInfo(); } catch (ATCommandException e) { throw new XBeeException("Error reading device information.", e); } }

Target:
protected void open() throws XBeeException { logger.info(toString() + "Opening the connection interface..."); if (isRemote()) throw new OperationNotSupportedException("Remote devices cannot be open."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); logger.info(toString() + "Connection interface open."); dataReader = new DataReader(connectionInterface, operatingMode, (XBeeDevice)this); dataReader.start(); try { Thread.sleep(10); } catch (InterruptedException e) if (connectionInterface.getConnectionType() == ConnectionType.BLUETOOTH) { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); try { logger.info(toString() + "Starting Bluetooth authentication..."); BluetoothAuthentication auth = new BluetoothAuthentication((XBeeDevice)this, bluetoothPassword); auth.authenticate(); ((AbstractBluetoothInterface) connectionInterface).setEncryptionKeys(auth.getKey(), auth.getTxNonce(), auth.getRxNonce()); logger.info(toString() + "Authentication finished successfully."); } catch (BluetoothAuthenticationException e) { close(); throw e; } } else { if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineOperatingMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } } try { readDeviceInfo(); } catch (ATCommandException e) { throw new XBeeException("Error reading device information.", e); } }
Source:
protected boolean canDoAction() { VDSGroup cluster = getDbFacade().getVdsGroupDao().get(getVds().getVdsGroupId()); if (!cluster.supportsGlusterService() || !GlusterFeatureSupported.glusterDiskProvisioning(cluster.getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_PROVISIONING_NOT_SUPPORTED_BY_CLUSTER); } VdsValidator validator = new VdsValidator(getVds()); return validate(validator.isUp()); }

Target:
protected boolean canDoAction() { VDSGroup cluster = getVdsGroup(); if (!cluster.supportsGlusterService() || !GlusterFeatureSupported.glusterBrickProvisioning(cluster.getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_PROVISIONING_NOT_SUPPORTED_BY_CLUSTER); } VdsValidator validator = new VdsValidator(getVds()); return validate(validator.isUp()); }
Source:
static Optional<String> getFailureReason(ResponseInfo responseInfo) { Throwable failure = responseInfo.getFailureCause(); if (failure == null) { return Optional.empty(); } String className = failure.getClass().getSimpleName().toUpperCase(); if (className.endsWith("EXCEPTION")) { return Optional.of(className.substring(0, className.lastIndexOf("EXCEPTION"))); } return Optional.of(className); }

Target:
static Optional<String> getFailureReason(ResponseInfo responseInfo) { Optional<Throwable> failure = responseInfo.getFailureCause(); if (!failure.isPresent()) { return Optional.empty(); } String className = failure.get().getClass().getSimpleName().toUpperCase(Locale.US); if (className.endsWith("EXCEPTION")) { return Optional.of(className.substring(0, className.lastIndexOf("EXCEPTION"))); } return Optional.of(className); }
Source:
public @ResponseBody Map<String, Object> reviewJSON(@RequestBody RunEnhancementsRequest data, HttpServletRequest request, HttpServletResponse response) { Map<String, Object> result = new HashMap<>(); AccessGroupSet groups = GroupsThreadStore.getGroups(); for (String pid : data.getPids()) { if (!aclService.hasAccess(new PID(pid), groups, Permission.editAccessControl)) { result.put("error", "Insufficient permissions to perform operation"); return result; } } Job job = new Job(RunEnhancementsTreeJob.class.getName(), data.getPids(), data.isForce()); jesqueClient.enqueue(runEnhancementQueueName, job); if (data.isForce()) { result.put("message", "Forced enhancement of " + data.getPids().size() + " object(s) and their children has begun"); } else { result.put("message", "Enhancement of " + data.getPids().size() + " object(s) and their children has begun"); } result.put("success", true); return result; }

Target:
public @ResponseBody Map<String, Object> reviewJSON(@RequestBody RunEnhancementsRequest data, HttpServletRequest request, HttpServletResponse response) { Map<String, Object> result = new HashMap<>(); AccessGroupSet groups = GroupsThreadStore.getGroups(); for (String pid : data.getPids()) { if (!aclService.hasAccess(new PID(pid), groups, Permission.editAccessControl)) { result.put("error", "Insufficient permissions to perform operation"); return result; } } Job job = new Job(RunEnhancementsTreeJob.class.getName(), data.getPids(), data.isForce()); jesqueClient.enqueue(runEnhancementQueueName, job); result.put("message", "Enhancement of " + data.getPids().size() + " object(s) and their children has begun"); result.put("success", true); return result; }