auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void popMessage(String processorName) throws AxisFault { SynapseConfiguration configuration = getSynapseConfiguration(); MessageConsumer messageConsumer = getMessageConsumer(configuration,processorName); try { popMessageFromQueue(messageConsumer); } catch (SynapseException e) { handleException(log, "Failed to get message : ", e); } messageConsumer.cleanup(); }

Target:
public void popMessage(String processorName) throws AxisFault { SynapseConfiguration configuration = getSynapseConfiguration(); MessageConsumer messageConsumer = getMessageConsumer(configuration,processorName); try { popMessageFromQueue(messageConsumer); } catch (SynapseException e) { handleException(log, "Failed to pop message from the queue: ", e); } finally { messageConsumer.cleanup(); } }
Source:
private static void reloadPrefs(Preferences prefs) { String loadConfigMethodString = "loadConfig"; String sessionConfigFieldString = "sessionConfig"; String userConfigFieldString = "userConfig"; try { Method loadConfigMethod = Preferences.class.getDeclaredMethod(loadConfigMethodString, String.class, String.class, Class.class); Field sessionConfigField = Preferences.class.getDeclaredField(sessionConfigFieldString); Field userConfigField = Preferences.class.getDeclaredField(userConfigFieldString); loadConfigMethod.setAccessible(true); sessionConfigField.setAccessible(true); userConfigField.setAccessible(true); sessionConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, SessionConfig.class)); userConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_USER_CONFIG_FILENAME, UserConfig.class)); } catch (NoSuchMethodException e) { fail(String.format("Problem invoking private method; does %s still exist? %s", loadConfigMethodString, e.toString())); } catch (NoSuchFieldException e) { fail(String.format("Problem accessing private field; do %s and %s still exist? %s", sessionConfigFieldString, userConfigFieldString, e.toString())); } catch (IllegalAccessException | InvocationTargetException e){ fail(String.format("Problem with invoking or accessing. %s", e.toString())); } }

Target:
private static void reloadPrefs(Preferences prefs) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException { String loadConfigMethodString = "loadConfig"; String sessionConfigFieldString = "sessionConfig"; String userConfigFieldString = "userConfig"; Method loadConfigMethod = Preferences.class.getDeclaredMethod(loadConfigMethodString, String.class, String.class, Class.class); Field sessionConfigField = Preferences.class.getDeclaredField(sessionConfigFieldString); Field userConfigField = Preferences.class.getDeclaredField(userConfigFieldString); loadConfigMethod.setAccessible(true); sessionConfigField.setAccessible(true); userConfigField.setAccessible(true); sessionConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, SessionConfig.class)); userConfigField.set(prefs, loadConfigMethod.invoke(prefs, TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, UserConfig.class)); }
Source:
private static void removeTestFiles() { File workingDir = new File(WORKING_DIRECTORY_LOCATION); if (workingDir.exists() == false) { workingDir.mkdirs(); } File[] testFiles = { new File(workingDir, "firefly.keystore"), new File(workingDir, "test.keystore"), new File(workingDir, "test-single-cert-reply.cert"), new File(workingDir, "test-cert-chain-reply.cert"), new File(workingDir, "test-exported.cert"), new File(workingDir, "test-trusted.cert"), new File(workingDir, "test-untrusted.cert"), new File(workingDir, "test-untrusted-cert-chain-reply.cert") }; for (File file : testFiles) { if (file.exists()) { file.delete(); } } }

Target:
private static void removeTestFiles() { File[] testFiles = { FIREFLY_FILE, TEST_FILE, TEST_SINGLE_CERT_REPLY_FILE, TEST_CERT_CHAIN_REPLY_FILE, TEST_EXPORTED_FILE, TEST_TRUSTED_FILE, TEST_UNTRUSTED_FILE, TEST_UNTRUSTED_CERT_CHAIN_REPLY_FILE }; for (File file : testFiles) { if (file.exists()) { file.delete(); } } }
Source:
protected Injector setupInjector() { return Initialization.makeInjectorWithModules( GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", null, null, new ServerConfig()) ); binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class); Multibinder<ServletFilterHolder> multibinder = Multibinder.newSetBinder( binder, ServletFilterHolder.class ); multibinder.addBinding().toInstance( new ServletFilterHolder() { @Override public String getPath() { return "/*"; } @Override public Map<String, String> getInitParameters() { return null; } @Override public Class<? extends Filter> getFilterClass() { return DummyAuthFilter.class; } @Override public Filter getFilter() { return null; } @Override public EnumSet<DispatcherType> getDispatcherType() { return null; } }); Jerseys.addResource(binder, SlowResource.class); Jerseys.addResource(binder, ExceptionResource.class); Jerseys.addResource(binder, DefaultResource.class); binder.bind(AuthorizationManager.class).toInstance(new AuthorizationManager() { @Override public Access authorize( String identity, Resource resource, Action action ) { return new Access(true); } }); LifecycleModule.register(binder, Server.class); } } ) ); }

Target:
protected Injector setupInjector() { return Initialization.makeInjectorWithModules( GuiceInjectors.makeStartupInjector(), ImmutableList.<Module>of( new Module() { @Override public void configure(Binder binder) { JsonConfigProvider.bindInstance( binder, Key.get(DruidNode.class, Self.class), new DruidNode("test", "localhost", null, null, new ServerConfig()) ); binder.bind(JettyServerInitializer.class).to(JettyServerInit.class).in(LazySingleton.class); Multibinder<ServletFilterHolder> multibinder = Multibinder.newSetBinder( binder, ServletFilterHolder.class ); multibinder.addBinding().toInstance( new ServletFilterHolder() { @Override public String getPath() { return "/*"; } @Override public Map<String, String> getInitParameters() { return null; } @Override public Class<? extends Filter> getFilterClass() { return DummyAuthFilter.class; } @Override public Filter getFilter() { return null; } @Override public EnumSet<DispatcherType> getDispatcherType() { return null; } }); Jerseys.addResource(binder, SlowResource.class); Jerseys.addResource(binder, ExceptionResource.class); Jerseys.addResource(binder, DefaultResource.class); binder.bind(AuthorizerMapper.class).toInstance(AuthTestUtils.TEST_AUTHORIZER_MAPPER); LifecycleModule.register(binder, Server.class); } } ) ); }
Source:
private void buildIfRequested(final IProject project, IProgressMonitor monitor) throws CoreException { if (!closeProjectsAfterImport && rebuildProjectsAfterImport) { project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); } }

Target:
private void buildIfRequested(final IProject project, IProgressMonitor monitor) throws CoreException { if (rebuildProjectsAfterImport) { project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor); IWorkspace workspace = project.getWorkspace(); boolean isAutoBuilding = workspace.isAutoBuilding(); if (!isAutoBuilding) { project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); } } }
Source:
public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { requireNonNull(columnHandles, "columnHandle is null"); requireNonNull(config, "config is null"); this.columnHandles = columnHandles; this.maxHits = config.getMaxHits(); this.timeout = config.getRequestTimeout(); for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } this.builder = new ElasticsearchQueryBuilder(columnHandles, config, split); this.searchHits = sendElasticsearchQuery(builder).iterator(); }

Target:
public ElasticsearchRecordCursor(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { requireNonNull(columnHandles, "columnHandle is null"); requireNonNull(config, "config is null"); this.columnHandles = columnHandles; this.maxHits = config.getMaxHits(); this.requestTimeout = config.getRequestTimeout(); this.maxAttempts = config.getMaxRequestRetries(); this.maxRetryTime = config.getMaxRetryTime(); for (int i = 0; i < columnHandles.size(); i++) { jsonPathToIndex.put(columnHandles.get(i).getColumnJsonPath(), i); } this.builder = new ElasticsearchQueryBuilder(columnHandles, config, split); this.searchHits = sendElasticsearchQuery(builder).iterator(); }
Source:
public void deleteCommentsByInstructorEmail(String courseId, String email) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); getCommentsForGiverQuery(courseId, email).deletePersistentAll(); getPm().flush(); }

Target:
public void deleteCommentsByInstructorEmail(String courseId, String email) { Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId); Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, email); getCommentsForGiverQuery(courseId, email) .deletePersistentAll(); }
Source:
protected ModelAndView handleNotFound(HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpStatus.NOT_FOUND.value()); Site site = siteResolver.resolveSite(request); if (site == null) { if (request.getServletPath().equals("/")) { ModelAndView mav = new ModelAndView(" mav.addObject("siteKeys", siteSet.getSiteKeys()); try { mav.addObject("imageCode", getResourceAsBase64("/WEB-INF/themes/root/app/wombat.jpg")); } catch (IOException e) return mav; } else { return new ModelAndView(" } } else { return new ModelAndView(site.getKey() + "/ftl/notFound"); } }

Target:
protected ModelAndView handleNotFound(HttpServletRequest request, HttpServletResponse response) { Site site = siteResolver.resolveSite(request); if (site == null && request.getServletPath().equals("/")) { return serveAppRoot(); } response.setStatus(HttpStatus.NOT_FOUND.value()); String viewName = (site == null) ? " return new ModelAndView(viewName); }
Source:
private BuildAssignment(BuildCause buildCause, File buildWorkingDirectory, List<Builder> builder, JobPlan plan) { this.buildWorkingDirectory = buildWorkingDirectory; this.builders = builder; this.plan = plan; for (MaterialRevision materialRevision : buildCause.getMaterialRevisions()) { ArrayList<Modification> modifications = new ArrayList<>(); for (Modification modification : materialRevision.getModifications()) { Modification modificationForAgent = new Modification(modification); modificationForAgent.unsetModifiedFiles(); modifications.add(modificationForAgent); } materialRevisions.addRevision(new MaterialRevision(materialRevision.getMaterial(), materialRevision.isChanged(), modifications)); } approver = buildCause.getApprover(); }

Target:
private BuildAssignment(BuildCause buildCause, File buildWorkingDirectory, List<Builder> builder, JobPlan plan) { this.buildWorkingDirectory = buildWorkingDirectory; this.builders = builder; this.plan = plan; for (MaterialRevision materialRevision : buildCause.getMaterialRevisions()) { ArrayList<Modification> modifications = new ArrayList<>(); for (Modification modification : materialRevision.getModifications()) { modifications.add(new Modification(modification, false)); } materialRevisions.addRevision(new MaterialRevision(materialRevision.getMaterial(), materialRevision.isChanged(), modifications)); } approver = buildCause.getApprover(); }
Source:
public int numberOfInserts() { final Integer cachedValue = numberOfInsertsCache; if (cachedValue != null) { return cachedValue; } int numberOfInserts = 0; for (T object : results.keySet()) { if (results.get(object) != null && results.get(object).wasInserted()) { numberOfInserts++; } } numberOfInsertsCache = numberOfInserts; return numberOfInserts; }

Target:
public int numberOfInserts() { final Integer cachedValue = numberOfInsertsCache; if (cachedValue != null) { return cachedValue; } int numberOfInserts = 0; for (T object : results.keySet()) { assert results.get(object) != null; if (results.get(object).wasInserted()) { numberOfInserts++; } } numberOfInsertsCache = numberOfInserts; return numberOfInserts; }
Source:
public JSONRPC2Response process(Object params) { JSONRPC2Response resp = null; try { List<Object> hosts = new LinkedList<Object>(); OVXMap map = OVXMap.getInstance(); Collection<OVXNetwork> vnets = map.listVirtualNetworks().values(); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Host.class, new PhysicalHostSerializer()); mapper.registerModule(module); for (OVXNetwork vnet : vnets) { hosts.addAll(mapper.convertValue(vnet.getHosts(), List.class)); } resp = new JSONRPC2Response(hosts, 0); } catch (ClassCastException e) { resp = new JSONRPC2Response( new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), this.cmdName() + ": Unable to fetch host list : " + e.getMessage()), 0); } return resp; }

Target:
public JSONRPC2Response process(Object params) { JSONRPC2Response resp = null; try { List<Object> result; result = mapper.convertValue(hs.getPhysicalHosts(), List.class); resp = new JSONRPC2Response(result, 0); } catch (ClassCastException e) { resp = new JSONRPC2Response( new JSONRPC2Error(JSONRPC2Error.INVALID_PARAMS.getCode(), this.cmdName() + ": Unable to fetch host list : " + e.getMessage()), 0); } return resp; }
Source:
protected EPersonRest createAndReturn(Context context) throws AuthorizeException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); EPersonRest epersonRest = null; try { epersonRest = mapper.readValue(req.getInputStream(), EPersonRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("error parsing the body... maybe this is not the right error code"); } String token = req.getParameter("token"); if (StringUtils.isNotBlank(token)) { try { return createAndReturn(context, epersonRest, token); } catch (SQLException e) { log.error(e.getMessage(), e); throw new RuntimeException("Something with wrong in the creation of an EPerson with token: " + token); } } EPerson eperson = createEPersonFromRestObject(context, epersonRest); return converter.toRest(eperson, utils.obtainProjection()); }

Target:
protected EPersonRest createAndReturn(Context context) throws AuthorizeException { HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest(); ObjectMapper mapper = new ObjectMapper(); EPersonRest epersonRest = null; try { epersonRest = mapper.readValue(req.getInputStream(), EPersonRest.class); } catch (IOException e1) { throw new UnprocessableEntityException("error parsing the body... maybe this is not the right error code"); } String token = req.getParameter("token"); if (StringUtils.isNotBlank(token)) { try { return createAndReturn(context, epersonRest, token); } catch (SQLException e) { log.error("Something went wrong in the creation of an EPerson with token: " + token, e); throw new RuntimeException("Something went wrong in the creation of an EPerson with token: " + token); } } EPerson eperson = createEPersonFromRestObject(context, epersonRest); return converter.toRest(eperson, utils.obtainProjection()); }
Source:
public void readFields(DataInput arg0) throws IOException { int len = arg0.readInt(); byte[] bytes = new byte[len]; arg0.readFully(bytes); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>)ois.readObject(); Field[] fields = this.getClass().getFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if (properties.containsKey(fieldName)) { field.set(this, properties.get(fieldName)); } } ois.close(); } catch (Exception e) { final Path path = Files.createTempFile("dt-", ".ser"); logger.error("Failed to de-serialize {}. Writing raw data to {}.", this.getClass().getName(), path, e); Files.write(path, bytes); throw new IOException(e); } }

Target:
public void readFields(DataInput arg0) throws IOException { int len = arg0.readInt(); byte[] bytes = new byte[len]; arg0.readFully(bytes); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>)ois.readObject(); Field[] fields = this.getClass().getFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if (properties.containsKey(fieldName)) { field.set(this, properties.get(fieldName)); } } ois.close(); } catch (Exception e) { final Path path = Files.createTempFile("apex-rpc-raw-dump-", ".ser"); logger.error("Failed to de-serialize {}. Writing raw data to {}.", this.getClass().getName(), path, e); Files.write(path, bytes); throw new IOException(e); } }
Source:
private void waitPlanExecuting() { while (orchestrator.isPlanExecuting()) { try { Thread.sleep(10); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting the completion of plan execution"); } } }

Target:
private void waitPlanExecuting() { int numLoop = 0; while (orchestrator.isPlanExecuting() && numLoop < MAX_WAIT_LOOP) { ++numLoop; try { Thread.sleep(WAIT_TIME); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while waiting the completion of plan execution"); } } }
Source:
public AbstractValidatedWidgetWithLabel(W contentWidget) { this(contentWidget, new VisibilityRenderer.SimpleVisibilityRenderer()); addStateUpdateHandler(); }

Target:
public AbstractValidatedWidgetWithLabel(W contentWidget) { this(contentWidget, new VisibilityRenderer.SimpleVisibilityRenderer()); }
Source:
public final void setExecutor(ExecutorService executor) { this.executor = executor; }

Target:
public void setExecutor(ExecutorService executor) { this.executor = executor; }
Source:
public void testClusterSnapshotWithExplicitPath() throws Exception { File exSnpDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), "ex_snapshots", true); try { IgniteEx ignite = null; for (int i = 0; i < 2; i++) { IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(i))); cfg.setSnapshotPath(exSnpDir.getAbsolutePath()); ignite = startGrid(cfg); } ignite.cluster().baselineAutoAdjustEnabled(false); ignite.cluster().state(ACTIVE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ignite.cache(DEFAULT_CACHE_NAME).put(i, i); forceCheckpoint(); ignite.snapshot().createSnapshot(SNAPSHOT_NAME) .get(); stopAllGrids(); IgniteEx snp = startGridsFromSnapshot(2, cfg -> exSnpDir.getAbsolutePath(), SNAPSHOT_NAME, true); assertSnapshotCacheKeys(snp.cache(dfltCacheCfg.getName())); } finally { stopAllGrids(); U.delete(exSnpDir); } }

Target:
public void testClusterSnapshotWithExplicitPath() throws Exception { File exSnpDir = U.resolveWorkDirectory(U.defaultWorkDirectory(), "ex_snapshots", true); try { IgniteEx ignite = null; for (int i = 0; i < 2; i++) { IgniteConfiguration cfg = optimize(getConfiguration(getTestIgniteInstanceName(i))); cfg.setSnapshotPath(exSnpDir.getAbsolutePath()); ignite = startGrid(cfg); } ignite.cluster().baselineAutoAdjustEnabled(false); ignite.cluster().state(ACTIVE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ignite.cache(DEFAULT_CACHE_NAME).put(i, i); ignite.snapshot().createSnapshot(SNAPSHOT_NAME) .get(); stopAllGrids(); IgniteEx snp = startGridsFromSnapshot(2, cfg -> exSnpDir.getAbsolutePath(), SNAPSHOT_NAME, true); assertSnapshotCacheKeys(snp.cache(dfltCacheCfg.getName())); } finally { stopAllGrids(); U.delete(exSnpDir); } }
Source:
public EventTypeValidator getValidator(final String name) throws InternalNakadiException, NoSuchEventTypeException { return getCached(name).map(CachedValue::getEventTypeValidator).orElse(null); }

Target:
public EventTypeValidator getValidator(final String name) throws InternalNakadiException, NoSuchEventTypeException { return getCached(name).map(CachedValue::getEventTypeValidator) .orElseThrow(() -> new NoSuchEventTypeException("Event type " + name + " does not exists")); }
Source:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); waitForServerState(api(), serverId, State.PENDING_CHANGE, 30 * 60 * 1000, "Error"); waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }

Target:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }
Source:
private static Constraint getConstraint(LiteralTree literal) { Constraint result = null; if (literal.is(Kind.BOOLEAN_LITERAL)) { result = "true".equals(literal.value()) ? Constraint.TRUE : Constraint.FALSE; } if (literal.is(Kind.STRING_LITERAL)) { result = literal.value().length() > 2 ? Constraint.TRUTHY_STRING_PRIMITIVE : Constraint.EMPTY_STRING_PRIMITIVE; } if (literal.is(Kind.NUMERIC_LITERAL)) { result = isTruthyNumeric(literal) ? Constraint.POSITIVE_NUMBER_PRIMITIVE : Constraint.ZERO; } if (literal.is(Kind.REGULAR_EXPRESSION_LITERAL)) { result = Constraint.REGEXP; } if (result != null) { return result; } throw new IllegalStateException("Unknown literal: " + literal); }

Target:
private static Constraint getConstraint(LiteralTree literal) { Constraint result = null; if (literal.is(Kind.BOOLEAN_LITERAL)) { result = "true".equals(literal.value()) ? Constraint.TRUE : Constraint.FALSE; } if (literal.is(Kind.STRING_LITERAL)) { result = literal.value().length() > 2 ? Constraint.TRUTHY_STRING_PRIMITIVE : Constraint.EMPTY_STRING_PRIMITIVE; } if (literal.is(Kind.NUMERIC_LITERAL)) { result = isZero(literal) ? Constraint.ZERO : Constraint.POSITIVE_NUMBER_PRIMITIVE; } if (literal.is(Kind.REGULAR_EXPRESSION_LITERAL)) { result = Constraint.REGEXP; } if (result != null) { return result; } throw new IllegalStateException("Unknown literal: " + literal); }
Source:
private static Document parseInputStream( final InputStream instream ) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true ); dbf.setFeature( "<LINK_0>", true ); final DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse( new InputSource( instream ) ); }

Target:
private static Document parseInputStream( final InputStream instream ) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory(); final DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse( new InputSource( instream ) ); }
Source:
private void onWsAgentConnectionIsLost() { eventBus.fireEvent(new WsAgentServerStoppedEvent(devMachineName)); Workspace workspace = appContext.getWorkspace(); if (workspace == null || workspace.getStatus() != WorkspaceStatus.RUNNING) { return; } dialogFactory .createChoiceDialog( localizationConstant.wsAgentNotRespondingDialogTitle(), localizationConstant.wsAgentNotRespondingDialogMessage(), localizationConstant.wsAgentNotRespondingDialogRestart(), localizationConstant.wsAgentNotRespondingDialogClose(), () -> { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, event -> reloadPage(false)); actionManager.performAction(STOP_WORKSPACE, emptyMap()); }, null) .show(); }

Target:
private void onWsAgentConnectionIsLost() { WorkspaceImpl workspace = appContext.getWorkspace(); if (workspace.getStatus() != WorkspaceStatus.RUNNING) { return; } wsAgentServerUtilProvider .get() .getWsAgentServerMachine() .ifPresent(machine -> eventBus.fireEvent(new WsAgentServerStoppedEvent(machine.getName()))); dialogFactory .createChoiceDialog( localizationConstant.wsAgentNotRespondingDialogTitle(), localizationConstant.wsAgentNotRespondingDialogMessage(), localizationConstant.wsAgentNotRespondingDialogRestart(), localizationConstant.wsAgentNotRespondingDialogClose(), () -> { eventBus.addHandler(WorkspaceStoppedEvent.TYPE, event -> reloadPage(false)); actionManager.performAction(STOP_WORKSPACE, emptyMap()); }, null) .show(); }
Source:
public void validateImpl(Query parameter) { List<String> validationErrors = new ArrayList<>(); if(CollectionUtils.isNullOrEmpty(parameter.getTable())) { validationErrors.add("table name cannot be null or empty"); } if(parameter.getSort() == null) { validationErrors.add("sort order needs to be specified"); } if(parameter.getFrom() < 0) { validationErrors.add("from must be non-negative integer"); } if(parameter.getLimit() <= 0) { validationErrors.add("limit must be positive integer"); } if (parameter.getLimit() >= elasticsearchTuningConfig.getDocumentsLimitAllowed()){ validationErrors.add(String.format("Limit more than %s is not supported", elasticsearchTuningConfig.getDocumentsLimitAllowed())); } if(!CollectionUtils.isNullOrEmpty(validationErrors)) { throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors); } }

Target:
public void validateImpl(Query parameter) { List<String> validationErrors = new ArrayList<>(); if(CollectionUtils.isNullOrEmpty(parameter.getTable())) { validationErrors.add("table name cannot be null or empty"); } if(parameter.getSort() == null) { validationErrors.add("sort order needs to be specified"); } if(parameter.getFrom() < 0) { validationErrors.add("from must be non-negative integer"); } if(parameter.getLimit() <= 0) { validationErrors.add("limit must be positive integer"); } if (parameter.getLimit() > elasticsearchTuningConfig.getDocumentsLimitAllowed()){ validationErrors.add(String.format("Limit more than %s is not supported", elasticsearchTuningConfig.getDocumentsLimitAllowed())); } if(!CollectionUtils.isNullOrEmpty(validationErrors)) { throw FoxtrotExceptions.createMalformedQueryException(parameter, validationErrors); } }
Source:
public void formatFilenameFromFormNameTest() { assertNull(FormNameUtils.formatFilenameFromFormName(null)); assertEquals("simple", FormNameUtils.formatFilenameFromFormName("simple")); assertEquals("CamelCase", FormNameUtils.formatFilenameFromFormName("CamelCase")); assertEquals("01234566789", FormNameUtils.formatFilenameFromFormName("01234566789")); assertEquals("trimWhitespace", FormNameUtils.formatFilenameFromFormName(" trimWhitespace ")); assertEquals("keep internal spaces", FormNameUtils.formatFilenameFromFormName("keep internal spaces")); assertEquals("other whitespace", FormNameUtils.formatFilenameFromFormName("other\n\twhitespace")); assertEquals("repeated whitespace", FormNameUtils.formatFilenameFromFormName("repeated whitespace")); assertEquals("Turkish İ kept", FormNameUtils.formatFilenameFromFormName("Turkish İ kept")); assertEquals("registered symbol stripped", FormNameUtils.formatFilenameFromFormName("registered symbol ® stripped")); assertEquals("unicode fragment stripped", FormNameUtils.formatFilenameFromFormName("unicode fragment \ud800 stripped")); }

Target:
public void formatFilenameFromFormNameTest() { assertThat(formatFilenameFromFormName(null), is(nullValue())); assertThat(formatFilenameFromFormName("simple"), is("simple")); assertThat(formatFilenameFromFormName("CamelCase"), is("CamelCase")); assertThat(formatFilenameFromFormName("01234566789"), is("01234566789")); assertThat(formatFilenameFromFormName(" trimWhitespace "), is("trimWhitespace")); assertThat(formatFilenameFromFormName("keep internal spaces"), is("keep internal spaces")); assertThat(formatFilenameFromFormName("other\n\twhitespace"), is("other whitespace")); assertThat(formatFilenameFromFormName("repeated whitespace"), is("repeated whitespace")); assertThat(formatFilenameFromFormName("Turkish İ kept"), is("Turkish İ kept")); assertThat(formatFilenameFromFormName("registered symbol ® stripped"), is("registered symbol stripped")); assertThat(formatFilenameFromFormName("unicode fragment \ud800 stripped"), is("unicode fragment stripped")); }
Source:
private int calculateDropdownTop() { int ddTop; DropdownPosition dropdownPosition = options.getDropdownPosition(); switch (dropdownPosition.getPosition()) { case DOWN: ddTop = positionDown(); break; case UP: ddTop = positionUp(); break; case AUTO: if (dropdownPosition.getBoundaries() == null) { ddTop = positionRelativeToWindow(); } else { ddTop = positionRelativeToBoundaries(); } break; default: ddTop = 0; break; } return ddTop; }

Target:
private int calculateDropdownTop() { int ddTop; DropdownPosition dropdownPosition = options.getDropdownPosition(); switch (dropdownPosition.getPosition()) { case BELOW: ddTop = positionBelow(); break; case ABOVE: ddTop = positionAbove(); break; case AUTO: if (dropdownPosition.getBoundaries() == null) { ddTop = positionRelativeToWindow(); } else { ddTop = positionRelativeToBoundaries(); } break; default: ddTop = positionBelow(); break; } return ddTop; }
Source:
protected boolean engineVerify(final String algorithm, final Password password, final char[] guess) throws InvalidKeyException { if (password instanceof AbstractPasswordImpl) { final AbstractPasswordImpl abstractPassword = (AbstractPasswordImpl) password; if (algorithm.equals(abstractPassword.getAlgorithm())) { return abstractPassword.verify(guess); } } switch (algorithm) { case ALGORITHM_SHA256CRYPT: case ALGORITHM_SHA512CRYPT: { if (password instanceof UnixSHACryptPassword) { try { return UnixSHACryptPasswordUtil.verify(password, guess); } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Cannot verify password", e); } } else { break; } } } throw new InvalidKeyException(); }

Target:
protected boolean engineVerify(final String algorithm, final Password password, final char[] guess) throws InvalidKeyException { if (password instanceof AbstractPasswordImpl) { final AbstractPasswordImpl abstractPassword = (AbstractPasswordImpl) password; if (algorithm.equals(abstractPassword.getAlgorithm())) { return abstractPassword.verify(guess); } } throw new InvalidKeyException(); }
Source:
public void run() { if (!getDRepresentationToExport().isEmpty()) { super.run(); } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Export representations", "The selected resource does not contain any representation to export."); } }

Target:
public void run() { if (!getDRepresentationToExport().isEmpty()) { super.run(); } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Export representations", "The selected elements do not contain any representation to export."); } }
Source:
private byte[] instrument(final byte[] source) { final long classId = CRC64.classId(source); final int originalVersion = BytecodeVersion.read(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(originalVersion, source); final ClassReader reader = new ClassReader(b); final ClassWriter writer = new ClassWriter(reader, 0) { @Override protected String getCommonSuperClass(final String type1, final String type2) { throw new IllegalStateException(); } }; final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(classId, reader, accessorGenerator); final ClassVisitor visitor = new ClassProbesAdapter( new ClassInstrumenter(strategy, writer), true); reader.accept(visitor, ClassReader.EXPAND_FRAMES); final byte[] instrumented = writer.toByteArray(); BytecodeVersion.set(instrumented, originalVersion); return instrumented; }

Target:
private byte[] instrument(final byte[] source) { final long classId = CRC64.classId(source); final int originalVersion = BytecodeVersion.get(source); final byte[] b = BytecodeVersion.downgradeIfNeeded(originalVersion, source); final ClassReader reader = new ClassReader(b); final ClassWriter writer = new ClassWriter(reader, 0) { @Override protected String getCommonSuperClass(final String type1, final String type2) { throw new IllegalStateException(); } }; final IProbeArrayStrategy strategy = ProbeArrayStrategyFactory .createFor(classId, reader, accessorGenerator); final ClassVisitor visitor = new ClassProbesAdapter( new ClassInstrumenter(strategy, writer), true); reader.accept(visitor, ClassReader.EXPAND_FRAMES); final byte[] instrumented = writer.toByteArray(); BytecodeVersion.set(instrumented, originalVersion); return instrumented; }
Source:
public void testFileBatchInputFormatAvro() throws Exception { File fileAvro = new File(temporaryFolder.newFolder(), "test.avro"); String outputDatasetName = "test-filesource-avro"; ApplicationManager appManager = createSourceAndDeployApp(fileAvro, "avro", outputDatasetName, RECORD_SCHEMA); org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(RECORD_SCHEMA.toString()); GenericRecord record = new GenericRecordBuilder(avroSchema) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.getAbsolutePath()) .build(); DataSetManager<TimePartitionedFileSet> inputManager = getDataset("TestFile"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(avroSchema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(avroSchema, fileAvro); dataFileWriter.append(record); dataFileWriter.close(); inputManager.flush(); workflowStartAndWait(appManager); List<StructuredRecord> expected = ImmutableList.of( StructuredRecord.builder(RECORD_SCHEMA) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.toURI().toString()) .build() ); DataSetManager<Table> outputManager = getDataset(outputDatasetName); List<StructuredRecord> output = MockSink.readOutput(outputManager); Assert.assertEquals(output, expected); }

Target:
public void testFileBatchInputFormatAvro() throws Exception { File fileAvro = new File(temporaryFolder.newFolder(), "test.avro"); String outputDatasetName = "test-filesource-avro"; String appName = "FileSourceAvro"; ApplicationManager appManager = createSourceAndDeployApp(appName, fileAvro, "avro", outputDatasetName, RECORD_SCHEMA); org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(RECORD_SCHEMA.toString()); GenericRecord record = new GenericRecordBuilder(avroSchema) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.getAbsolutePath()) .build(); DataSetManager<TimePartitionedFileSet> inputManager = getDataset("TestFile"); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(avroSchema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(avroSchema, fileAvro); dataFileWriter.append(record); dataFileWriter.close(); inputManager.flush(); workflowStartAndWait(appManager); List<StructuredRecord> expected = ImmutableList.of( StructuredRecord.builder(RECORD_SCHEMA) .set("i", Integer.MAX_VALUE) .set("l", Long.MAX_VALUE) .set("file", fileAvro.toURI().toString()) .build() ); DataSetManager<Table> outputManager = getDataset(outputDatasetName); List<StructuredRecord> output = MockSink.readOutput(outputManager); Assert.assertEquals(output, expected); }
Source:
public static MapillaryImportedImage createInstance(final ImageEntry geoImage) { if (geoImage == null) { return null; } if (geoImage.getFile() == null) { throw new IllegalArgumentException("Can't create an imported image from an ImageEntry without associated file."); } final CachedLatLon cachedCoord = geoImage.getPos(); LatLon coord = cachedCoord == null ? null : cachedCoord.getRoundedToOsmPrecision(); if (coord == null) { final MapView mv = MapillaryPlugin.getMapView(); coord = mv == null ? new LatLon(0, 0) : mv.getProjection().eastNorth2latlon(mv.getCenter()); } final double ca = geoImage.getExifImgDir() == null ? 0 : geoImage.getExifImgDir(); final long time = geoImage.hasGpsTime() ? geoImage.getGpsTime().getTime() : geoImage.hasExifTime() ? geoImage.getExifTime().getTime() : System.currentTimeMillis(); final double width = geoImage.getWidth(); final double height = geoImage.getHeight(); final boolean pano = (width >= 4096) && (width == height * 2); return new MapillaryImportedImage(coord, ca, geoImage.getFile(), pano, time); }

Target:
public static MapillaryImportedImage createInstance(final ImageEntry geoImage) { if (geoImage == null) { return null; } if (geoImage.getFile() == null) { throw new IllegalArgumentException("Can't create an imported image from an ImageEntry without associated file."); } final CachedLatLon cachedCoord = geoImage.getPos(); LatLon coord = cachedCoord == null ? null : cachedCoord.getRoundedToOsmPrecision(); if (coord == null) { final MapView mv = MapillaryPlugin.getMapView(); coord = mv == null ? new LatLon(0, 0) : mv.getProjection().eastNorth2latlon(mv.getCenter()); } final double ca = geoImage.getExifImgDir() == null ? 0 : geoImage.getExifImgDir(); final long time = geoImage.hasGpsTime() ? geoImage.getGpsTime().getTime() : geoImage.hasExifTime() ? geoImage.getExifTime().getTime() : System.currentTimeMillis(); boolean pano = false; try (FileInputStream fis = new FileInputStream(geoImage.getFile())) { pano = ImageMetaDataUtil.isPanorama(fis); } catch(IOException ex) { Logging.trace(ex); } return new MapillaryImportedImage(coord, ca, geoImage.getFile(), pano, time); }
Source:
private static void loadProperties(File file, Properties props, String listKey) throws IOException { String[] keys = getArray(props, listKey); for (String key : keys) { File scannerFile = new File(file.getParent(), key + ".properties"); try (InputStream pluginFis = Files.newInputStream(scannerFile.toPath())) { Properties p = new Properties(); p.load(pluginFis); for (Map.Entry<Object, Object> prop : p.entrySet()) { props.put(key + "." + prop.getKey(), prop.getValue()); } } } }

Target:
private static void loadProperties(File file, Properties props, String listKey) throws IOException { String[] keys = getArray(props, listKey); for (String key : keys) { File propFile = new File(file.getParent(), key + ".properties"); try (InputStream fileInputStream = Files.newInputStream(propFile.toPath())) { Properties p = new Properties(); p.load(fileInputStream); for (Map.Entry<Object, Object> prop : p.entrySet()) { props.put(key + "." + prop.getKey(), prop.getValue()); } } } }
Source:
public boolean tick() { SerializationBehavior serializationBehavior = ((WorldProperties) this.world.getWorldInfo()).getSerializationBehavior(); if (serializationBehavior != SerializationBehaviors.AUTOMATIC) { return false; } if (this.canSave() && !((WorldBridge) this.world).bridge$isFake()) { ((WorldServerBridge) this.world).bridge$getTimingsHandler().doChunkUnload.startTiming(); final Iterator<Chunk> iterator = this.loadedChunks.values().iterator(); int chunksUnloaded = 0; final long now = System.currentTimeMillis(); while (chunksUnloaded < this.impl$maxChunkUnloads && iterator.hasNext()) { final Chunk chunk = iterator.next(); final ChunkBridge spongeChunk = (ChunkBridge) chunk; if (chunk != null && chunk.unloadQueued && !spongeChunk.bridge$isPersistedChunk()) { if (this.bridge$getChunkUnloadDelay() > 0) { if ((now - spongeChunk.bridge$getScheduledForUnload()) < this.impl$chunkUnloadDelay) { continue; } spongeChunk.bridge$setScheduledForUnload(-1); } chunk.onUnload(); this.saveChunkData(chunk); this.saveChunkExtraData(chunk); iterator.remove(); chunksUnloaded++; } } ((WorldServerBridge) this.world).bridge$getTimingsHandler().doChunkUnload.stopTiming(); } this.chunkLoader.chunkTick(); return false; }

Target:
public boolean tick() { final SerializationBehavior behavior = ((WorldProperties) this.world.getWorldInfo()).getSerializationBehavior(); if (behavior != SerializationBehaviors.AUTOMATIC) { return false; } if (this.shadow$canSave() && !((WorldBridge) this.world).bridge$isFake()) { ((WorldServerBridge) this.world).bridge$getTimingsHandler().doChunkUnload.startTiming(); final Iterator<Chunk> iterator = this.loadedChunks.values().iterator(); int chunksUnloaded = 0; final long now = System.currentTimeMillis(); while (chunksUnloaded < this.impl$maxChunkUnloads && iterator.hasNext()) { final Chunk chunk = iterator.next(); final ChunkBridge spongeChunk = (ChunkBridge) chunk; if (chunk != null && chunk.unloadQueued && !spongeChunk.bridge$isPersistedChunk()) { if (this.bridge$getChunkUnloadDelay() > 0) { if ((now - spongeChunk.bridge$getScheduledForUnload()) < this.impl$chunkUnloadDelay) { continue; } spongeChunk.bridge$setScheduledForUnload(-1); } chunk.onUnload(); this.saveChunkData(chunk); this.saveChunkExtraData(chunk); iterator.remove(); chunksUnloaded++; } } ((WorldServerBridge) this.world).bridge$getTimingsHandler().doChunkUnload.stopTiming(); } this.chunkLoader.chunkTick(); return false; }
Source:
ExecutionPath addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); Symbol newTrackSymbol = newTrackedSymbol(edge); Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, learnedConstraints); flowBuilder.addAll(lcFlow); if (isMethodInvocationNode(edge.parent)) { List<JavaFileScannerContext.Location> yieldsFlow = flowFromYields(edge); flowBuilder.addAll(yieldsFlow); } return new ExecutionPath(edge, visited.add(edge), newTrackSymbol, flowBuilder.build(), visitedAllParents(edge) || shouldTerminate(learnedConstraints)); }

Target:
Stream<ExecutionPath> addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); Symbol newTrackSymbol = newTrackedSymbol(edge); Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, learnedConstraints); flowBuilder.addAll(lcFlow); boolean endOfPath = visitedAllParents(edge) || shouldTerminate(learnedConstraints); List<JavaFileScannerContext.Location> currentFlow = flowBuilder.build(); Set<List<JavaFileScannerContext.Location>> yieldsFlows = flowFromYields(edge); return yieldsFlows.stream() .map(yieldFlow -> ImmutableList.<JavaFileScannerContext.Location>builder().addAll(currentFlow).addAll(yieldFlow).build()) .map(f -> new ExecutionPath(edge, visited.add(edge), newTrackSymbol, f, endOfPath)); }
Source:
private void requestReadMoreItems(final LayoutInflater layoutInflater) { new SuggestionsTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle.getPrefixedText()) { @Override public void onFinish(FullSearchResults results) { readMoreItems = results; if (readMoreItems.getResults().size() > 0) { setupReadMoreSection(layoutInflater, readMoreItems); } else { readMoreContainer.setVisibility(View.GONE); } layoutContent(); } @Override public void onCatch(Throwable caught) { Log.w(TAG, "Error while fetching Read More titles.", caught); layoutContent(); } }.execute(); }

Target:
private void requestReadMoreItems(final LayoutInflater layoutInflater) { new SuggestionsTask(app.getAPIForSite(pageTitle.getSite()), pageTitle.getSite(), pageTitle.getPrefixedText()) { @Override public void onFinish(FullSearchResults results) { readMoreItems = results; if (readMoreItems.getResults().size() > 0) { setupReadMoreSection(layoutInflater, readMoreItems); readMoreContainer.setVisibility(View.VISIBLE); } else { readMoreContainer.setVisibility(View.GONE); } layoutContent(); } @Override public void onCatch(Throwable caught) { Log.w(TAG, "Error while fetching Read More titles.", caught); layoutContent(); } }.execute(); }
Source:
public CompletableFuture<byte[]> renderPngForPanel(Dashboard dashboard, Panel panel, int width, int height, long from, long to, Map<String, String> variables) { final HttpUrl.Builder builder = baseUrl.newBuilder() .addPathSegment("render") .addPathSegment("d-solo") .addPathSegment(dashboard.getUid()) .addPathSegments("z"); builder.addQueryParameter("panelId", Integer.toString(panel.getId())) .addQueryParameter("from", Long.toString(from)) .addQueryParameter("to", Long.toString(to)) .addQueryParameter("width", Integer.toString(width)) .addQueryParameter("height", Integer.toString(height)) .addQueryParameter("theme", "light"); variables.forEach((k,v) -> builder.addQueryParameter("var-"+ k, v)); final Request request = new Request.Builder() .url(builder.build()) .addHeader("Authorization", "Bearer " + config.getApiKey()) .build(); final CompletableFuture<byte[]> future = new CompletableFuture<>(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { future.completeExceptionally(new IOException("Request failed: " + response)); } try (InputStream is = responseBody.byteStream()) { future.complete(inputStreamToByteArray(is)); } catch (IOException e) { future.completeExceptionally(e); } } } }); return future; }

Target:
public CompletableFuture<byte[]> renderPngForPanel(Dashboard dashboard, Panel panel, int width, int height, long from, long to, Map<String, String> variables) { final HttpUrl.Builder builder = baseUrl.newBuilder() .addPathSegment("render") .addPathSegment("d-solo") .addPathSegment(dashboard.getUid()) .addPathSegments(dashboard.getMeta().getSlug()); builder.addQueryParameter("panelId", Integer.toString(panel.getId())) .addQueryParameter("from", Long.toString(from)) .addQueryParameter("to", Long.toString(to)) .addQueryParameter("width", Integer.toString(width)) .addQueryParameter("height", Integer.toString(height)) .addQueryParameter("theme", "light"); variables.forEach((k,v) -> builder.addQueryParameter("var-"+ k, v)); final Request request = new Request.Builder() .url(builder.build()) .addHeader("Authorization", "Bearer " + config.getApiKey()) .build(); final CompletableFuture<byte[]> future = new CompletableFuture<>(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { future.completeExceptionally(new IOException("Request failed: " + response)); } try (InputStream is = responseBody.byteStream()) { future.complete(inputStreamToByteArray(is)); } catch (IOException e) { future.completeExceptionally(e); } } } }); return future; }
Source:
protected void onDisplay(NavigateEvent navigateEvent) { isHandlingEvent = true; try { if (navigateEvent instanceof OpenCustomGamesEvent) { playRootTabPane.getSelectionModel().select(customGamesTab); customGamesController.display(navigateEvent); lastTab = customGamesController; } else if (navigateEvent instanceof Open1v1Event) { playRootTabPane.getSelectionModel().select(ladderTab); ladderController.display(navigateEvent); lastTab = ladderController; } else if (navigateEvent instanceof OpenCoopEvent) { playRootTabPane.getSelectionModel().select(coopTab); coopController.display(navigateEvent); lastTab = coopController; } else if (Objects.equals(navigateEvent.getClass(), NavigateEvent.class)) { lastTab.display(navigateEvent); } } finally { isHandlingEvent = false; } }

Target:
protected void onDisplay(NavigateEvent navigateEvent) { isHandlingEvent = true; try { if (navigateEvent instanceof OpenCustomGamesEvent) { playRootTabPane.getSelectionModel().select(customGamesTab); customGamesController.display(navigateEvent); } if (navigateEvent instanceof Open1v1Event) { playRootTabPane.getSelectionModel().select(ladderTab); ladderController.display(navigateEvent); } if (navigateEvent instanceof OpenCoopEvent) { playRootTabPane.getSelectionModel().select(coopTab); coopController.display(navigateEvent); } } finally { isHandlingEvent = false; } }