auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void validatePropertySectionPropertyJavadocTokens(String fileName, String sectionName, AbstractJavadocCheck check, List<Node> columns) { assertEquals("javadoc tokens to check", columns.get(1).getTextContent(), fileName + " section '" + sectionName + "' should have the basic token javadoc description"); String acceptableTokenText = columns.get(2).getTextContent().trim(); final int removePrefixIdx = "subset of javadoc tokens".length(); acceptableTokenText = acceptableTokenText.substring(removePrefixIdx); assertFalse(isInvalidTokenPunctuation(acceptableTokenText), ", & . should be placed at beginning of the next corresponding lines " + "in " + fileName + " acceptable javadoc token section: " + sectionName); assertEquals(CheckUtil.getJavadocTokenText(check.getAcceptableJavadocTokens(), check.getRequiredJavadocTokens()).replaceAll("\\s+", ""), acceptableTokenText.replaceAll("\\s+", ""), fileName + " section '" + sectionName + "' should have all the acceptable javadoc tokens"); final String defaultTokenText = columns.get(3).getTextContent().trim(); assertFalse(isInvalidTokenPunctuation(defaultTokenText), ", & . should be placed at beginning of the next corresponding lines " + "in " + fileName + " default javadoc token section: " + sectionName); assertEquals(CheckUtil.getJavadocTokenText(check.getDefaultJavadocTokens(), check.getRequiredJavadocTokens()).replaceAll("\\s+", ""), defaultTokenText.replaceAll("\\s+", ""), fileName + " section '" + sectionName + "' should have all the default javadoc tokens"); }

Target:
private static void validatePropertySectionPropertyJavadocTokens(String fileName, String sectionName, AbstractJavadocCheck check, List<Node> columns) { assertEquals("javadoc tokens to check", columns.get(1).getTextContent(), fileName + " section '" + sectionName + "' should have the basic token javadoc description"); final String acceptableTokenText = columns.get(2).getTextContent().trim(); assertEquals("subset of javadoc tokens " + CheckUtil.getJavadocTokenText(check.getAcceptableJavadocTokens(), check.getRequiredJavadocTokens()), acceptableTokenText .replaceAll("\\s+", " ") .replaceAll("\\s,", ",") .replaceAll("\\s\\.", "."), fileName + " section '" + sectionName + "' should have all the acceptable javadoc tokens"); assertFalse(isInvalidTokenPunctuation(acceptableTokenText), fileName + "'s acceptable javadoc token section: " + sectionName + "should have ',' & '.' at beginning of the next corresponding lines."); final String defaultTokenText = columns.get(3).getTextContent().trim(); assertEquals(CheckUtil.getJavadocTokenText(check.getDefaultJavadocTokens(), check.getRequiredJavadocTokens()), defaultTokenText .replaceAll("\\s+", " ") .replaceAll("\\s,", ",") .replaceAll("\\s\\.", "."), fileName + " section '" + sectionName + "' should have all the default javadoc tokens"); assertFalse(isInvalidTokenPunctuation(defaultTokenText), fileName + "'s default javadoc token section: " + sectionName + "should have ',' & '.' at beginning of the next corresponding lines."); }
Source:
public XmlXYEntry(ITmfStateSystem stateSystem, String path, Element entryElement) { fStateSystem = stateSystem; fPath = path; switch (entryElement.getAttribute(TmfXmlStrings.TYPE)) { case TmfXmlUiStrings.DISPLAY_TYPE_DELTA: fType = DisplayType.DELTA; break; case TmfXmlUiStrings.DISPLAY_TYPE_ABSOLUTE: default: fType = DisplayType.ABSOLUTE; break; } }

Target:
public XmlXYEntry(ITmfStateSystem stateSystem, String path, Element entryElement) { fStateSystem = stateSystem; fPath = path; switch (entryElement.getAttribute(TmfXmlUiStrings.DISPLAY_TYPE)) { case TmfXmlUiStrings.DISPLAY_TYPE_DELTA: fType = DisplayType.DELTA; break; case TmfXmlUiStrings.DISPLAY_TYPE_ABSOLUTE: default: fType = DisplayType.ABSOLUTE; break; } }
Source:
private static String delft2grobidLabel(String label) { if (label.equals("O")) { label = TaggingLabels.OTHER_LABEL; } else if (label.startsWith(GenericTaggerUtils.START_ENTITY_LABEL_PREFIX_ALTERNATIVE)) { label = label.replace(GenericTaggerUtils.START_ENTITY_LABEL_PREFIX_ALTERNATIVE, GenericTaggerUtils.START_ENTITY_LABEL_PREFIX); } else if (label.startsWith(GenericTaggerUtils.START_ENTITY_LABEL_PREFIX)) { label = label.replace(GenericTaggerUtils.START_ENTITY_LABEL_PREFIX, ""); } return label; }

Target:
private static String delft2grobidLabel(String label) { if (label.equals(TaggingLabels.IOB_OTHER_LABEL)) { label = TaggingLabels.OTHER_LABEL; } else if (label.startsWith(TaggingLabels.IOB_START_ENTITY_LABEL_PREFIX)) { label = label.replace(TaggingLabels.IOB_START_ENTITY_LABEL_PREFIX, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX); } else if (label.startsWith(TaggingLabels.IOB_INSIDE_LABEL_PREFIX)) { label = label.replace(TaggingLabels.IOB_INSIDE_LABEL_PREFIX, TaggingLabels.GROBID_INSIDE_ENTITY_LABEL_PREFIX); } return label; }
Source:
public GitScm commitAuthorInChangelog() { CommitAuthorInChangelog behaviour = addBehaviour(CommitAuthorInChangelog.class); return this; }

Target:
public GitScm commitAuthorInChangelog() { addBehaviour(CommitAuthorInChangelog.class); return this; }
Source:
public void registerLifespanCompletionCallback(Consumer<Lifespan> callback) { checkState(lifespanCompletionCallback == null); this.lifespanCompletionCallback = callback; }

Target:
public void registerLifespanCompletionCallback(Consumer<Lifespan> callback) { checkState(lifespanCompletionCallback == null, "lifespanCompletionCallback is already set"); this.lifespanCompletionCallback = requireNonNull(callback, "callback is null"); }
Source:
public Session get(SessionId id) throws NoSuchSessionException { Require.nonNull("Session ID", id); URI uri = null; Capabilities caps = null; try { ResultSet sessions = readSessionStatement(id).executeQuery(); while(sessions.next()) { String sessionIdAndURI = sessions.getString(sessionIdCol); String rawUri = sessionIdAndURI.split(separator)[1]; String rawCapabilities = sessions.getString(sessionCapsCol); caps = rawCapabilities == null ? new ImmutableCapabilities() : JSON.toType(rawCapabilities, Capabilities.class); try { uri = new URI(rawUri); } catch (URISyntaxException e) { throw new NoSuchSessionException(String.format("Unable to convert session id (%s) to uri: %s", id, rawUri), e); } } sessions.close(); if (uri == null) { throw new NoSuchSessionException("Unable to find URI for session " + id); } return new Session(id, uri, caps); } catch (SQLException e) { throw new JdbcException(e.getMessage()); } }

Target:
public Session get(SessionId id) throws NoSuchSessionException { Require.nonNull("Session ID", id); URI uri = null; Capabilities caps = null; String rawUri = null; try (ResultSet sessions = readSessionStatement(id).executeQuery()){ if (!sessions.next()) { throw new NoSuchSessionException("Unable to find..."); } rawUri = sessions.getString(SESSION_URI_COL); String rawCapabilities = sessions.getString(SESSION_CAPS_COL); caps = rawCapabilities == null ? new ImmutableCapabilities() : JSON.toType(rawCapabilities, Capabilities.class); try { uri = new URI(rawUri); } catch (URISyntaxException e) { throw new NoSuchSessionException(String.format("Unable to convert session id (%s) to uri: %s", id, rawUri), e); } return new Session(id, uri, caps); } catch (SQLException e) { throw new JdbcException(e); } }
Source:
private void AttachCd() { Guid storagePoolId = getVm().getstorage_pool_id(); boolean isIsoFound = (VmRunHandler.getInstance().findActiveISODomain(storagePoolId) != null); if (isIsoFound) { if (StringUtils.isEmpty(getVm().getCdPath())) { getVm().setCdPath(getVm().getiso_path()); GuestToolsVersionTreatment(); refreshBootSequenceParameter(getParameters()); if (getVm().getboot_sequence() == BootSequence.CD) { getVm().setCdPath(getVm().getiso_path()); } getVm().setCdPath(ImagesHandler.cdPathWindowsToLinux(getVm().getCdPath(), getVm().getstorage_pool_id())); } } else if (!StringUtils.isEmpty(getVm().getiso_path())) { getVm().setCdPath(""); setSucceeded(false); throw new VdcBLLException(VdcBllErrors.NO_ACTIVE_ISO_DOMAIN_IN_DATA_CENTER); } }

Target:
private void AttachCd() { Guid storagePoolId = getVm().getstorage_pool_id(); boolean isIsoFound = (getVmRunHandler().findActiveISODomain(storagePoolId) != null); if (isIsoFound) { if (StringUtils.isEmpty(getVm().getCdPath())) { getVm().setCdPath(getVm().getiso_path()); GuestToolsVersionTreatment(); refreshBootSequenceParameter(getParameters()); if (getVm().getboot_sequence() == BootSequence.CD) { getVm().setCdPath(getVm().getiso_path()); } getVm().setCdPath(ImagesHandler.cdPathWindowsToLinux(getVm().getCdPath(), getVm().getstorage_pool_id())); } } else if (!StringUtils.isEmpty(getVm().getiso_path())) { getVm().setCdPath(""); setSucceeded(false); throw new VdcBLLException(VdcBllErrors.NO_ACTIVE_ISO_DOMAIN_IN_DATA_CENTER); } }
Source:
public void writeResponse(ManagementCenterService mcs, JsonObject out) throws Exception { WanCheckConsistencyOperation operation = new WanCheckConsistencyOperation(schemeName, publisherName, mapName); InternalCompletableFuture<Object> future = mcs.callOnThis(operation); JsonObject result = new JsonObject(); Object operationResult; try { operationResult = future.get(); if (operationResult == null) { result.add("result", SUCCESS); } else { result.add("result", operationResult.toString()); } } catch (ExecutionException e) { result.add("result", e.getMessage()); result.add("stackTrace", ExceptionUtil.toString(e)); } out.add("result", result); }

Target:
public void writeResponse(ManagementCenterService mcs, JsonObject out) { out.add("result", mcs.syncCallOnThis( new WanCheckConsistencyOperation(schemeName, publisherName, mapName))); }
Source:
public void handleRequest(final Request request, final HttpRequestContext context) { LOGGER.info("ProxyEndpoint handles request {}", request); Exchange exchange = new Exchange(request, Origin.REMOTE) { @Override public void sendAccept() { } @Override public void sendReject() { } @Override public void sendResponse(Response response) { try { request.setResponse(response); responseProduced(request, response); context.handleRequestForwarding(response); LOGGER.info("HTTP returned {}", response); } catch (Exception e) { LOGGER.warn("Exception while responding to Http request {}", e); } } }; exchange.setRequest(request); Response response = null; if (request.getType() != Type.RST && request.getType() != Type.ACK && request.getOptions().hasProxyUri()) { response = cacheResource.getResponse(request); LOGGER.info("Cache returned {}", response); statsResource.updateStatistics(request, response != null); } if (response != null) { exchange.sendResponse(response); return; } else { if (request.getOptions().hasProxyUri()) { try { manageProxyUriRequest(request); LOGGER.info("after manageProxyUriRequest: {}", request); } catch (URISyntaxException e) { LOGGER.warn(String.format("Proxy-uri malformed: %s", request.getOptions().getProxyUri())); exchange.sendResponse(new Response(ResponseCode.BAD_OPTION)); } } proxyCoapResolver.forwardRequest(exchange); } }

Target:
public void handleRequest(final Request request, final HttpRequestContext context) { LOGGER.info("ProxyEndpoint handles request {}", request); Exchange exchange = new Exchange(request, Origin.REMOTE) { @Override public void sendAccept() { } @Override public void sendReject() { } @Override public void sendResponse(Response response) { request.setResponse(response); responseProduced(request, response); context.handleRequestForwarding(response); LOGGER.info("HTTP returned {}", response); } }; exchange.setRequest(request); Response response = null; if (request.getType() != Type.RST && request.getType() != Type.ACK && request.getOptions().hasProxyUri()) { response = cacheResource.getResponse(request); LOGGER.info("Cache returned {}", response); statsResource.updateStatistics(request, response != null); } if (response != null) { exchange.sendResponse(response); return; } else { if (request.getOptions().hasProxyUri()) { try { manageProxyUriRequest(request); LOGGER.info("after manageProxyUriRequest: {}", request); } catch (URISyntaxException e) { LOGGER.warn(String.format("Proxy-uri malformed: %s", request.getOptions().getProxyUri())); exchange.sendResponse(new Response(ResponseCode.BAD_OPTION)); } } proxyCoapResolver.forwardRequest(exchange); } }
Source:
private SagaConfiguration(Class<S> sagaType) { String resourceInjectorName = sagaType.getSimpleName() + "ResourceInjector"; String managerName = sagaType.getSimpleName() + "Manager"; String processorName = sagaType.getSimpleName() + "Processor"; String repositoryName = sagaType.getSimpleName() + "Repository"; resourceInjector = new Component<>(() -> config, resourceInjectorName, c -> new NoResourceInjector()); sagaStore = new Component<>(() -> config, "sagaStore", c -> c.getComponent(SagaStore.class, InMemorySagaStore::new)); sagaRepository = new Component<>(() -> config, repositoryName, c -> new AnnotatedSagaRepository<>(sagaType, sagaStore.get(), resourceInjector.get())); sagaManager = new Component<>(() -> config, managerName, c -> new AnnotatedSagaManager<>(sagaType, sagaRepository.get())); processor = new Component<>(() -> config, processorName, c -> new SubscribingEventProcessor(managerName, sagaManager.get(), c.eventBus())); }

Target:
private SagaConfiguration(Class<S> sagaType) { String managerName = sagaType.getSimpleName() + "Manager"; String processorName = sagaType.getSimpleName() + "Processor"; String repositoryName = sagaType.getSimpleName() + "Repository"; sagaStore = new Component<>(() -> config, "sagaStore", c -> c.getComponent(SagaStore.class, InMemorySagaStore::new)); sagaRepository = new Component<>(() -> config, repositoryName, c -> new AnnotatedSagaRepository<>(sagaType, sagaStore.get(), c.resourceInjector())); sagaManager = new Component<>(() -> config, managerName, c -> new AnnotatedSagaManager<>(sagaType, sagaRepository.get())); processor = new Component<>(() -> config, processorName, c -> new SubscribingEventProcessor(managerName, sagaManager.get(), c.eventBus())); }
Source:
protected void configure() { bindPresenterWidget(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class); bind(new TypeLiteral<UiHandlersStrategy<HeaderUiHandlers>>() { }).to(new TypeLiteral<SetterUiHandlersStrategy<HeaderUiHandlers>>() { }); bind(HeaderUiHandlers.class).to(HeaderPresenter.class); }

Target:
protected void configure() { bindPresenterWidget(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class); }
Source:
public String toString() { return com.google.common.base.Objects.toStringHelper(this) .add("parent", super.toString()) .add("application", getApplication()) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .toString(); }
Source:
private File createLocalParserJar(ParserInfo parserInfo) throws IOException { ensureDirExists(localParserJarPath); File parserJar = null; do { parserJar = new File(localParserJarPath, parserInfo.getName().trim() + UUID.randomUUID()); } while (!parserJar.createNewFile()); parserJar.deleteOnExit(); return parserJar; }

Target:
private File createLocalParserJar(ParserInfo parserInfo) throws IOException { ensureDirExists(localParserJarPath); File parserJar = File.createTempFile(parserInfo.getName().trim(), "", new File(localParserJarPath)); parserJar.deleteOnExit(); return parserJar; }
Source:
public void onClick(View v){ if(v == targetEdit){ Intent myIntent = new Intent(); myIntent.setClass(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, ACTIVITY_FB_TARGET); } if(v == sourceEdit){ Intent myIntent = new Intent(); myIntent.setClass(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, ACTIVITY_FB_SOURCE); } if(v == mergeButton){ AMGUIUtility.doProgressTask(this, R.string.merging_title, R.string.merging_summary, new AMGUIUtility.ProgressTask(){ public void doHeavyTask() throws Exception { String targetPath = targetEdit.getText().toString(); String sourcePath = sourceEdit.getText().toString(); databaseUtil.mergeDatabases(targetPath, sourcePath); } public void doUITask(){ Toast.makeText(DatabaseMerger.this, getString(R.string.merge_success_message), Toast.LENGTH_LONG) .show(); finish(); } }); } if(v == cancelButton){ finish(); } }

Target:
public void onClick(View v){ if(v == targetEdit){ Intent myIntent = new Intent(); myIntent.setClass(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, ACTIVITY_FB_TARGET); } if(v == sourceEdit){ Intent myIntent = new Intent(); myIntent.setClass(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, ACTIVITY_FB_SOURCE); } if(v == mergeButton){ AMGUIUtility.doProgressTask(this, R.string.merging_title, R.string.merging_summary, new AMGUIUtility.ProgressTask(){ public void doHeavyTask() throws Exception { String targetPath = targetEdit.getText().toString(); String sourcePath = sourceEdit.getText().toString(); databaseUtil.mergeDatabases(targetPath, sourcePath); } public void doUITask(){ Toast.makeText(DatabaseMerger.this, getString(R.string.merge_success_message), Toast.LENGTH_LONG) .show(); Intent resultIntent = new Intent(); setResult(Activity.RESULT_OK, resultIntent); finish(); } }); } if(v == cancelButton){ finish(); } }
Source:
public Charset charsetForName(String charsetName) { if (charsets.containsKey(charsetName)) { return charsets.get(charsetName); } Iterator<Charset> it = charsets.values().iterator(); while (it.hasNext()) { Charset cs = it.next(); for (String alias : cs.aliases()) { if (alias.equals(charsetName)) { return cs; } } } return null; }

Target:
public Charset charsetForName(String charsetName) { String name = charsetName.toLowerCase(); if (charsets.containsKey(name)) { return charsets.get(name); } Iterator<Charset> it = charsets.values().iterator(); while (it.hasNext()) { Charset cs = it.next(); for (String alias : cs.aliases()) { if (alias.toLowerCase().equals(name)) { return cs; } } } return null; }
Source:
public void activate() { m_isActive = true; setupExecutor(); }

Target:
public void activate() { setupExecutor(); }
Source:
private void checkMultiCoverage(ImageMosaicReader reader, String coverageName, double longitude, double latitude, String timestamp, double expected) throws Exception { ParameterValue<Boolean> useJai = AbstractGridFormat.USE_JAI_IMAGEREAD.createValue(); useJai.setValue(false); @SuppressWarnings("rawtypes") ParameterValue<List> time = ImageMosaicFormat.TIME.createValue(); time.setValue(Arrays.asList(new Date[] { parseTimeStamp(timestamp) })); GeneralParameterValue[] params = new GeneralParameterValue[] { useJai, time }; GridCoverage2D coverage = reader.read(coverageName, params); System.out.println(coverage.getProperties()); assertNotNull(coverage); assertEquals(expected, coverage.evaluate(new Point2D.Double(longitude, latitude), (double[]) null)[0], 0); }

Target:
private void checkMultiCoverage(ImageMosaicReader reader, String coverageName, double longitude, double latitude, String timestamp, double expected) throws Exception { ParameterValue<Boolean> useJai = AbstractGridFormat.USE_JAI_IMAGEREAD.createValue(); useJai.setValue(false); @SuppressWarnings("rawtypes") ParameterValue<List> time = ImageMosaicFormat.TIME.createValue(); time.setValue(Arrays.asList(new Date[] { parseTimeStamp(timestamp) })); GeneralParameterValue[] params = new GeneralParameterValue[] { useJai, time }; GridCoverage2D coverage = reader.read(coverageName, params); assertNotNull(coverage); assertEquals(expected, coverage.evaluate(new Point2D.Double(longitude, latitude), (double[]) null)[0], 0); }
Source:
protected List<Pojo> doInBackground(Void... voids) { boolean smartHistory = !prefs.getString("history-mode", "recency").equals("recency"); boolean excludeFavorites = prefs.getBoolean("exclude-favorites", false); int max_records = DEFAULT_MAX_RESULTS; try { max_records = Integer.parseInt(prefs.getString("number-of-history-items", DEFAULT_MAX_RESULTS+"")); } catch(Exception e) { } ArrayList<Pojo> favoritesPojo = new ArrayList<Pojo>(0); if(excludeFavorites){ favoritesPojo = KissApplication.getDataHandler(activity).getFavorites(activity.tryToRetrieve); } return KissApplication.getDataHandler(activity).getHistory(activity, max_records, smartHistory, favoritesPojo); }

Target:
protected List<Pojo> doInBackground(Void... voids) { boolean smartHistory = !prefs.getString("history-mode", "recency").equals("recency"); boolean excludeFavorites = prefs.getBoolean("exclude-favorites", false); int max_records = Integer.parseInt(prefs.getString("number-of-display-elements", String.valueOf(DEFAULT_MAX_RESULTS))); ArrayList<Pojo> favoritesPojo = new ArrayList<Pojo>(0); if(excludeFavorites){ favoritesPojo = KissApplication.getDataHandler(activity).getFavorites(activity.tryToRetrieve); } return KissApplication.getDataHandler(activity).getHistory(activity, max_records, smartHistory, favoritesPojo); }
Source:
private long getTransferSize(DiskImage image, Guid domainId) { if (getParameters().getTransferType() == TransferType.Download) { DiskImage imageInfoFromVdsm = imagesHandler.getVolumeInfoFromVdsm( image.getStoragePoolId(), domainId, image.getId(), image.getImageId()); return imageInfoFromVdsm.getApparentSizeInBytes(); } if (getParameters().getTransferSize() != 0) { return getParameters().getTransferSize(); } else { boolean isOnBlock = getDiskImage().getStorageTypes().get(0).isBlockDomain(); return isOnBlock ? getDiskImage().getActualSizeInBytes() : getDiskImage().getSize(); } }

Target:
private long getTransferSize(DiskImage image, Guid domainId) { if (getParameters().getTransferType() == TransferType.Download) { DiskImage imageInfoFromVdsm = imagesHandler.getVolumeInfoFromVdsm( image.getStoragePoolId(), domainId, image.getId(), image.getImageId()); return imageInfoFromVdsm.getApparentSizeInBytes(); } if (getParameters().getTransferSize() != 0) { return getParameters().getTransferSize(); } boolean isBlockDomain = getDiskImage().getStorageTypes().get(0).isBlockDomain(); return isBlockDomain ? getDiskImage().getActualSizeInBytes() : getDiskImage().getSize(); }
Source:
@Override protected DataSource getDatasourceImpl( String dataSourceName ) throws Exception { IDBDatasourceService datasourceService = PentahoSystem.getObjectFactory().get( IDBDatasourceService.class, null ); return datasourceService.getDataSource( dataSourceName ); }

Target:
protected DataSource getDatasourceImpl( String dataSourceName ) throws Exception { IDBDatasourceService datasourceService = PentahoSystem.getObjectFactory().get( IDBDatasourceService.class, null ); return datasourceService.getDataSource( dataSourceName ); }
Source:
public void testTCPtoHTTP() throws Exception { Axis2BackEndServerController axis2Server = getAxis2Server(); if (axis2Server == null) { fail("Failed to load the Axis2BackEndServerController"); } assertEquals(0, axis2Server.getMessageCount("SimpleStockQuoteService", "placeOrder")); String addUrl = "tcp://localhost:6060/services/StockQuoteProxy"; StockQuoteSampleClient client = getStockQuoteClient(); client.placeOrder(addUrl, null, null, "IBM"); Thread.sleep(2000); assertEquals(1, axis2Server.getMessageCount("SimpleStockQuoteService", "placeOrder")); }

Target:
public void testTCPtoHTTP() throws Exception { String trpUrl = "tcp://localhost:6060/services/StockQuoteProxy"; StockQuoteSampleClient client = getStockQuoteClient(); SampleClientResult result = client.placeOrder(trpUrl, trpUrl, null, "IBM"); assertResponseReceived(result); }
Source:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mEmailLayout = view.findViewById(R.id.email_layout); mEmailEditText = view.findViewById(R.id.email); mEmailFieldValidator = new EmailFieldValidator(mEmailLayout); mEmailLayout.setOnClickListener(this); mEmailEditText.setOnClickListener(this); ImeHelper.setImeOnDoneListener(mEmailEditText, this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && getFlowParams().enableHints) { mEmailEditText.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO); } view.findViewById(R.id.button_next).setOnClickListener(this); TextView termsText = view.<TextView>findViewById(R.id.email_tos_and_pp_text); TextView footerText = view.<TextView>findViewById(R.id.email_footer_tos_and_pp_text); FlowParameters flowParameters = getFlowParams(); if (flowParameters.isSingleProviderFlow()) { PrivacyDisclosureUtils.setupTermsOfServiceAndPrivacyPolicyText(getContext(), getFlowParams(), termsText); } else { PrivacyDisclosureUtils.setupTermsOfServiceFooter(getContext(), getFlowParams(), footerText); } }

Target:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mEmailLayout = view.findViewById(R.id.email_layout); mEmailEditText = view.findViewById(R.id.email); mEmailFieldValidator = new EmailFieldValidator(mEmailLayout); mEmailLayout.setOnClickListener(this); mEmailEditText.setOnClickListener(this); ImeHelper.setImeOnDoneListener(mEmailEditText, this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && getFlowParams().enableHints) { mEmailEditText.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO); } view.findViewById(R.id.button_next).setOnClickListener(this); TextView termsText = view.findViewById(R.id.email_tos_and_pp_text); TextView footerText = view.findViewById(R.id.email_footer_tos_and_pp_text); FlowParameters flowParameters = getFlowParams(); if (flowParameters.isSingleProviderFlow()) { PrivacyDisclosureUtils.setupTermsOfServiceAndPrivacyPolicyText(getContext(), flowParameters, termsText); } else { termsText.setVisibility(View.GONE); PrivacyDisclosureUtils.setupTermsOfServiceFooter(getContext(), flowParameters, footerText); } }
Source:
public Map<Object, String> getConstantToAllLabels() { Map<Object, String> named = getConstantToNamedLabel(); Map<Object, Integer> numbered = getConstantToNumberedLabel(); Map<Object, String> combined = new HashMap<Object, String>(named); for (Map.Entry<Object, Integer> entry : numbered.entrySet()) { combined.put(entry.getValue(), entry.getValue().toString()); } return Collections.unmodifiableMap(combined); }

Target:
public Map<Object, String> getConstantToAllLabels() { Map<Object, String> namedLabels = getConstantToNamedLabel(); Map<Object, Integer> numberedLabels = getConstantToNumberedLabel(); Map<Object, String> allLabels = new HashMap<Object, String>(namedLabels); for (Map.Entry<Object, Integer> entry : numberedLabels.entrySet()) { allLabels.put(entry.getKey(), entry.getValue().toString()); } return unmodifiableMap(allLabels); }
Source:
public void fail_if_version_name_is_longer_then_100_characters() throws Exception { SnapshotDto snapshotDto = new SnapshotDto(); snapshotDto.setVersion(null); snapshotDto.setVersion("1.0"); snapshotDto.setVersion(IntStream.range(0, 100).mapToObj(i -> "a").collect(Collectors.joining())); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" is not a valid version name." + " The maximum length of version numbers is 100 characters."); snapshotDto.setVersion(IntStream.range(0, 101).mapToObj(i -> "a").collect(Collectors.joining())); }

Target:
public void fail_if_version_name_is_longer_then_100_characters() throws Exception { SnapshotDto snapshotDto = new SnapshotDto(); snapshotDto.setVersion(null); snapshotDto.setVersion("1.0"); snapshotDto.setVersion(repeat("a", 100)); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Event name length (101) is longer than the maximum authorized (100). " + "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); snapshotDto.setVersion(repeat("a", 101)); }
Source:
private void handle(SmartpayNotification notification) { if (shouldIgnore(notification)) { logger.info("{} notification ignored", PAYMENT_GATEWAY_NAME, notification); return; } logger.info("Verifying notification {}", PAYMENT_GATEWAY_NAME, notification); if (isBlank(notification.getTransactionId())) { logger.error("{} notification failed verification because it has no transaction ID", PAYMENT_GATEWAY_NAME, notification); return; } logger.info("Evaluating notification {}", PAYMENT_GATEWAY_NAME, notification); Optional<ChargeEntity> maybeCharge = chargeDao.findByProviderAndTransactionId(PAYMENT_GATEWAY_NAME, notification.getOriginalReference()); if (!maybeCharge.isPresent()) { logger.info("{} notification could not be evaluated (associated charge entity not found)", PAYMENT_GATEWAY_NAME, notification); return; } ChargeEntity charge = maybeCharge.get(); InterpretedStatus interpretedStatus = interpretStatus(notification, charge); if (interpretedStatus instanceof MappedChargeStatus) { chargeNotificationProcessor.invoke( notification.getPspReference(), charge, interpretedStatus.getChargeStatus(), notification.getEventDate() ); } else if (interpretedStatus instanceof MappedRefundStatus) { refundNotificationProcessor.invoke( SMARTPAY, interpretedStatus.getRefundStatus(), notification.getPspReference(), notification.getOriginalReference() ); } else { logger.error("{} notification unknown", PAYMENT_GATEWAY_NAME, notification); } }

Target:
private void handle(SmartpayNotification notification) { if (shouldIgnore(notification)) { logger.info("{} notification ignored", PAYMENT_GATEWAY_NAME, notification); return; } logger.info("Verifying notification {}", PAYMENT_GATEWAY_NAME, notification); if (isBlank(notification.getTransactionId())) { logger.error("{} notification failed verification because it has no transaction ID", PAYMENT_GATEWAY_NAME, notification); return; } logger.info("Evaluating notification {}", PAYMENT_GATEWAY_NAME, notification); Optional<ChargeEntity> maybeCharge = chargeDao.findByProviderAndTransactionId(PAYMENT_GATEWAY_NAME, notification.getOriginalReference()); if (!maybeCharge.isPresent()) { logger.error("{} notification could not be evaluated (associated charge entity not found)", PAYMENT_GATEWAY_NAME, notification); return; } ChargeEntity charge = maybeCharge.get(); InterpretedStatus interpretedStatus = interpretStatus(notification, charge); if (interpretedStatus instanceof MappedChargeStatus) { chargeNotificationProcessor.invoke( notification.getPspReference(), charge, interpretedStatus.getChargeStatus(), notification.getEventDate() ); } else if (interpretedStatus instanceof MappedRefundStatus) { refundNotificationProcessor.invoke( SMARTPAY, interpretedStatus.getRefundStatus(), notification.getPspReference(), notification.getOriginalReference() ); } else { logger.error("{} notification unknown", PAYMENT_GATEWAY_NAME, notification); } }
Source:
private void loadMaps() throws CachePersistenceException { try { for (File file : dataDirectory.listFiles((dir, name) -> name.endsWith(HOLDER_FILE_SUFFIX))) { try (FileInputStream fis = new FileInputStream(file)) { try (ObjectInputStream oin = new ObjectInputStream(fis)) { String name = (String) oin.readObject(); Tuple tuple = (Tuple) oin.readObject(); if (nextIndex.get() <= tuple.index) { nextIndex.set(tuple.index + 1); } knownHolders.put(name, tuple); } } } } catch (Exception e) { knownHolders.clear(); throw new CachePersistenceException("Failed to load existing StateRepository data", e); } }

Target:
private void loadMaps() throws CachePersistenceException { try { for (File file : dataDirectory.listFiles((dir, name) -> name.endsWith(HOLDER_FILE_SUFFIX))) { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream oin = new ObjectInputStream(fis)) { String name = (String) oin.readObject(); Tuple tuple = (Tuple) oin.readObject(); if (nextIndex.get() <= tuple.index) { nextIndex.set(tuple.index + 1); } knownHolders.put(name, tuple); } } } catch (Exception e) { knownHolders.clear(); throw new CachePersistenceException("Failed to load existing StateRepository data", e); } }
Source:
private void waitForService(Configuration sourceConfig) throws NotCompliantMBeanException { await("Waiting for service: " + sourceConfig.getPid()) .atMost(MANAGED_SERVICE_TIMEOUT, TimeUnit.MILLISECONDS) .pollDelay(CONFIG_UPDATE_WAIT_INTERVAL_MILLIS, TimeUnit.MILLISECONDS) .until( () -> adminConfig .getAdminConsoleService() .listServices() .stream() .map(Service::getId) .anyMatch( id -> id.equals(sourceConfig.getPid()) || id.equals(sourceConfig.getFactoryPid()))); }

Target:
private void waitForService(Configuration sourceConfig) throws NotCompliantMBeanException { await("Waiting for service: " + sourceConfig.getPid()) .atMost(MANAGED_SERVICE_TIMEOUT, TimeUnit.MILLISECONDS) .pollDelay(CONFIG_UPDATE_WAIT_INTERVAL_MILLIS, TimeUnit.MILLISECONDS) .until(() -> isServiceReady(sourceConfig)); }
Source:
public void managePrestartedVmsInAllVmPools() { getVmPoolDao().getAll() .stream() .filter(pool -> pool.getPrestartedVms() > 0) .forEach(this::managePrestartedVmsInPool); }

Target:
public void managePrestartedVmsInAllVmPools() { vmPoolDao.getAll() .stream() .filter(pool -> pool.getPrestartedVms() > 0) .forEach(this::managePrestartedVmsInPool); }
Source:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); } catch (Exception e) { log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info(spec.toString()); log.info("Started KafkaSupervisor[%s], first run in [%s]", dataSource, ioConfig.getStartDelay()); } }

Target:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Exception e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); } catch (Exception e) { log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], first run in [%s], with spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); } }
Source:
private IBrandingAdvice getBrandingAdvice() { Collection<IBrandingAdvice> advice = info.getAdvice(configSpec, true, null, null, IBrandingAdvice.class); for (IBrandingAdvice iBrandingAdvice : advice) return iBrandingAdvice; return null; }

Target:
private IBrandingAdvice getBrandingAdvice() { Collection<IBrandingAdvice> advices = info.getAdvice(configSpec, true, null, null, IBrandingAdvice.class); for (IBrandingAdvice advice : advices) return advice; return null; }
Source:
Iterable<ClusterNetworkModel> getNetworksTableItems() { ListModel<ClusterNetworkModel> tableModel = networks.asEditor().flush(); return tableModel != null ? tableModel.getItems() : new ArrayList<ClusterNetworkModel>(); }

Target:
Iterable<ClusterNetworkModel> getNetworksTableItems() { ClusterNetworkManageModel tableModel = networks.asEditor().flush(); return tableModel != null ? tableModel.getItems() : new ArrayList<ClusterNetworkModel>(); }
Source:
private SelectQuery incrementQueryPagination(SelectQuery query, SelectResultValue prevResult) { Map<String, Integer> pagingIdentifiers = prevResult.getPagingIdentifiers(); Map<String, Integer> newPagingIdentifers = new HashMap<>(); for (Map.Entry<String, Integer> entry : pagingIdentifiers.entrySet()) { String segmentId = entry.getKey(); int newOffset = pagingIdentifiers.get(segmentId) + 1; newPagingIdentifers.put(segmentId, newOffset); } return query.withPagingSpec(new PagingSpec(newPagingIdentifers, pagingThreshold)); }

Target:
private SelectQuery incrementQueryPagination(SelectQuery query, SelectResultValue prevResult) { Map<String, Integer> pagingIdentifiers = prevResult.getPagingIdentifiers(); Map<String, Integer> newPagingIdentifers = new HashMap<>(); for (Map.Entry<String, Integer> entry : pagingIdentifiers.entrySet()) { int newOffset = entry.getValue() + 1; pagingIdentifiers.replaceAll((id, offset) -> offset + 1); } return query.withPagingSpec(new PagingSpec(newPagingIdentifers, pagingThreshold)); }
Source:
private void printStream(InputStream inputStream, String messageType, Level logLevel) { try { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); for (String line = br.readLine(); line != null; line = br.readLine()) { if (Level.DEBUG == logLevel) { logger.debug("token: " + this.token + " " + messageType + ":" + line); } if (Level.WARN == logLevel) { logger.warn("token: " + this.token + " " + messageType + ":" + line); } } } catch (IOException ioe) { } }

Target:
private void printStream(InputStream inputStream, String messageType, Level logLevel) { try { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); for (String line = br.readLine(); line != null; line = br.readLine()) { logger.log(logLevel, "token: " + this.token + " " + messageType + ":" + line); } } catch (IOException ioe) { } }
Source:
public BoxPage clickSave() { saveButton.click(); waitWithTimeout().until(titleContains("Box ")); return new BoxPage(getDriver()); }

Target:
public BoxPage clickSave() { WebElement html = getHtmlElement(); saveButton.click(); waitForPageRefresh(html); return new BoxPage(getDriver()); }
Source:
public void processStreamControl(String exportSource, List<String> exportTargets, OperationMode operation, VoltTable results) { exportLog.info("Export " + operation + " source:" + exportSource + " targets:" + exportTargets); synchronized (m_dataSourcesByPartition) { for (Map.Entry<Integer, Map<String, ExportDataSource>> partitionDataSourceMap : m_dataSourcesByPartition.entrySet()) { Integer partition = partitionDataSourceMap.getKey(); for (ExportDataSource source : partitionDataSourceMap.getValue().values()) { if (!StringUtil.isEmpty(exportSource) && !source.getTableName().equalsIgnoreCase(exportSource)) { continue; } if (!exportTargets.isEmpty() && !exportTargets.contains(source.getTarget())) { continue; } if (source.processStreamControl(operation)) { results.addRow(source.getTableName(), source.getTarget(), partition, "SUCCESS", ""); } } } } }

Target:
public void processStreamControl(String exportSource, List<String> exportTargets, OperationMode operation, VoltTable results) { exportLog.info("Export " + operation + " source:" + exportSource + " targets:" + exportTargets); synchronized (m_dataSourcesByPartition) { for (Map.Entry<Integer, Map<String, ExportDataSource>> partitionDataSourceMap : m_dataSourcesByPartition.entrySet()) { Integer partition = partitionDataSourceMap.getKey(); for (ExportDataSource source : partitionDataSourceMap.getValue().values()) { if (!source.getTableName().equalsIgnoreCase(exportSource)) { continue; } if (!exportTargets.contains(source.getTarget())) { continue; } if (source.processStreamControl(operation)) { results.addRow(source.getTableName(), source.getTarget(), partition, "SUCCESS", ""); } } } } }
Source:
int getReservedMemoryMb(VirtualMachineTO vmSpec) { if (vmSpec.getDetails().get(VMwareGuru.VmwareReserveMemory.key()).equalsIgnoreCase("true")) { return (int)(vmSpec.getMinRam() / (1024 * 1024)); } return 0; }

Target:
int getReservedMemoryMb(VirtualMachineTO vmSpec) { if (vmSpec.getDetails().get(VMwareGuru.VmwareReserveMemory.key()).equalsIgnoreCase("true")) { return (int)(vmSpec.getMinRam() / ResourceType.bytesToMiB); } return 0; }
Source:
public static void deleteAll(final SQLiteDatabase db) { db.execSQL("DELETE FROM " + TABLE_NAME); }

Target:
public static void deleteAll(final SQLiteDatabase db) { DatabaseUtils.truncate(db, TABLE_NAME); }
Source:
private void logTimeTakenByPhase(GraphContext graphContext, RulePhase phase, int timeTaken) { if (!timeTakenByPhase.containsKey(phase)) { RulePhaseExecutionStatisticsModel model = graphContext.getService(RulePhaseExecutionStatisticsModel.class) .create(); model.setRulePhase(phase == null ? "Implicit" : phase.toString()); model.setTimeTaken(timeTaken); timeTakenByPhase.put(phase, model); } else { RulePhaseExecutionStatisticsModel model = timeTakenByPhase.get(phase); int prevTimeTaken = model.getTimeTaken(); model.setTimeTaken(prevTimeTaken + timeTaken); } }

Target:
private void logTimeTakenByPhase(GraphContext graphContext, RulePhase phase, int timeTaken) { if (!timeTakenByPhase.containsKey(phase)) { RulePhaseExecutionStatisticsModel model = graphContext.getService(RulePhaseExecutionStatisticsModel.class) .create(); model.setRulePhase(phase.toString()); model.setTimeTaken(timeTaken); timeTakenByPhase.put(phase, model); } else { RulePhaseExecutionStatisticsModel model = timeTakenByPhase.get(phase); int prevTimeTaken = model.getTimeTaken(); model.setTimeTaken(prevTimeTaken + timeTaken); } }
Source:
public RowMap deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); JsonNode type = node.get("type"); JsonNode database = node.get("database"); JsonNode table = node.get("table"); JsonNode ts = node.get("ts"); JsonNode xid = node.get("xid"); JsonNode data = node.get("data"); JsonNode oldData = node.get("old"); RowMap rowMap = new RowMap( type == null ? null : type.asText(), database == null ? null : database.asText(), table == null ? null : table.asText(), ts == null ? null : ts.asLong(), new ArrayList<String>(), null ); if (xid != null) { rowMap.setXid(xid.asLong()); } if (data instanceof ObjectNode) { Iterator keys = data.fieldNames(); if (keys != null) { while (keys.hasNext()) { String key = (String) keys.next(); JsonNode value = data.get(key); if (value.isValueNode()) { ValueNode valueNode = (ValueNode) value; rowMap.putData(key, getValue(valueNode)); } } } } if (oldData instanceof ObjectNode) { Iterator keys = oldData.fieldNames(); if (keys != null) { while (keys.hasNext()) { String key = (String) keys.next(); JsonNode value = oldData.get(key); if (value.isValueNode()) { ValueNode valueNode = (ValueNode) value; rowMap.putOldData(key, getValue(valueNode)); } } } } return rowMap; }

Target:
public RowMap deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); JsonNode type = node.get("type"); if (type == null) { throw new ParseException("`type` is required and cannot be null."); } JsonNode database = node.get("database"); if (database == null) { throw new ParseException("`database` is required and cannot be null."); } JsonNode table = node.get("table"); if (table == null) { throw new ParseException("`table` is required and cannot be null."); } JsonNode ts = node.get("ts"); if (ts == null) { throw new ParseException("`ts` is required and cannot be null."); } JsonNode xid = node.get("xid"); JsonNode data = node.get("data"); JsonNode oldData = node.get("old"); RowMap rowMap = new RowMap( type.asText(), database.asText(), table.asText(), ts.asLong(), new ArrayList<String>(), null ); if (xid != null) { rowMap.setXid(xid.asLong()); } if (data instanceof ObjectNode) { Iterator keys = data.fieldNames(); if (keys != null) { while (keys.hasNext()) { String key = (String) keys.next(); JsonNode value = data.get(key); if (value.isValueNode()) { ValueNode valueNode = (ValueNode) value; rowMap.putData(key, getValue(valueNode)); } } } } else { throw new ParseException("`data` is required and cannot be null."); } if (oldData instanceof ObjectNode) { Iterator keys = oldData.fieldNames(); if (keys != null) { while (keys.hasNext()) { String key = (String) keys.next(); JsonNode value = oldData.get(key); if (value.isValueNode()) { ValueNode valueNode = (ValueNode) value; rowMap.putOldData(key, getValue(valueNode)); } } } } return rowMap; }
Source:
long getWord(int index) { if (index == 0) { return elements; } else { return 0L; } }

Target:
long getWord(int index) { if (index == 0) { return elements; } else { throw new IndexOutOfBoundsException(); } }
Source:
public Object[] getElements(Object inputElement) { if (inputElement instanceof IWorkspaceRoot) { IWorkspaceRoot root = (IWorkspaceRoot) inputElement; List<IProject> projectList = new ArrayList<>(); IProject[] workspaceProjects = root.getProjects(); for (IProject workspaceProject : workspaceProjects) { if (isProjectExportable(workspaceProject)) { projectList.add(workspaceProject); } } return projectList.toArray(new IProject[projectList.size()]); } else if (inputElement instanceof IWorkingSetManager){ IWorkingSetManager manager = (IWorkingSetManager) inputElement; IWorkingSet[] allSets = manager.getAllWorkingSets(); ArrayList<IWorkingSet> resourceSets = new ArrayList<>(); for (IWorkingSet allSet : allSets) { if (isWorkingSetSupported(allSet)) { resourceSets.add(allSet); } } return resourceSets.toArray(new IWorkingSet[resourceSets.size()]); } else if (inputElement instanceof IAdaptable){ IProject[] tempProjects = getProjectsForObject(inputElement); if (tempProjects != null) return tempProjects; } else if (inputElement instanceof IAdaptable[]){ IAdaptable[] tempAdaptable = (IAdaptable[]) inputElement; return getProjectsForAdaptables(tempAdaptable); } else if (inputElement instanceof HashSet){ Set<IProject> tempList = new HashSet<>(); HashSet inputElementSet = (HashSet) inputElement; for (Iterator iterator = inputElementSet.iterator(); iterator.hasNext();) { IProject[] projects = getProjectsForObject(iterator.next()); if (projects != null) tempList.addAll(Arrays.asList(projects)); } return tempList.toArray(new IProject[tempList.size()]); } return null; }

Target:
public Object[] getElements(Object inputElement) { if (inputElement instanceof IWorkspaceRoot) { IWorkspaceRoot root = (IWorkspaceRoot) inputElement; List<IProject> projectList = new ArrayList<>(); IProject[] workspaceProjects = root.getProjects(); for (IProject workspaceProject : workspaceProjects) { if (isProjectExportable(workspaceProject)) { projectList.add(workspaceProject); } } return projectList.toArray(new IProject[projectList.size()]); } else if (inputElement instanceof IWorkingSetManager){ IWorkingSetManager manager = (IWorkingSetManager) inputElement; IWorkingSet[] allSets = manager.getAllWorkingSets(); ArrayList<IWorkingSet> resourceSets = new ArrayList<>(); for (IWorkingSet set : allSets) { if (isWorkingSetSupported(set)) { resourceSets.add(set); } } return resourceSets.toArray(new IWorkingSet[resourceSets.size()]); } else if (inputElement instanceof IAdaptable){ IProject[] tempProjects = getProjectsForObject(inputElement); if (tempProjects != null) return tempProjects; } else if (inputElement instanceof IAdaptable[]){ IAdaptable[] tempAdaptable = (IAdaptable[]) inputElement; return getProjectsForAdaptables(tempAdaptable); } else if (inputElement instanceof HashSet){ Set<IProject> tempList = new HashSet<>(); HashSet inputElementSet = (HashSet) inputElement; for (Iterator iterator = inputElementSet.iterator(); iterator.hasNext();) { IProject[] projects = getProjectsForObject(iterator.next()); if (projects != null) tempList.addAll(Arrays.asList(projects)); } return tempList.toArray(new IProject[tempList.size()]); } return null; }