auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setupImageSizeSeekBar() { mImageSizeKeyArray = getResources().getStringArray(R.array.image_size_key_array); mImageSizeLabelArray = getResources().getStringArray(R.array.image_size_label_array); if (mImageSizeKeyArray.length != mImageSizeLabelArray.length) { throw new RuntimeException("Length of Image Size Key and Label arrays is not same"); } int imageSizeKey = Arrays.asList(mImageSizeKeyArray).indexOf(mEditorImageMetaData.getSize()); if (imageSizeKey == -1) { imageSizeKey = mImageSizeLabelArray.length - 1; } mImageSizeSeekBarView.setMax(mImageSizeLabelArray.length - 1); mImageSizeSeekBarView.setProgress(imageSizeKey); mImageSizeView.setText(mImageSizeLabelArray[imageSizeKey]); mImageSizeSeekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mImageSizeView.setText(mImageSizeLabelArray[progress]); } }); }

Target:
private void setupImageSizeSeekBar() { mImageSizeKeyArray = getResources().getStringArray(R.array.image_size_key_array); mImageSizeLabelArray = getResources().getStringArray(R.array.image_size_label_array); if (mImageSizeKeyArray.length != mImageSizeLabelArray.length) { throw new RuntimeException("Length of Image Size Key and Label arrays is not same"); } int imageSizeKey = Arrays.asList(mImageSizeKeyArray).indexOf(mEditorImageMetaData.getSize()); if (imageSizeKey == -1) { imageSizeKey = mImageSizeLabelArray.length - 1; AppLog.w(AppLog.T.MEDIA, "Unrecognized image size class passed to MediaSettings from editor: " + mEditorImageMetaData.getSize()); } mImageSizeSeekBarView.setMax(mImageSizeLabelArray.length - 1); mImageSizeSeekBarView.setProgress(imageSizeKey); mImageSizeView.setText(mImageSizeLabelArray[imageSizeKey]); mImageSizeSeekBarView.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mImageSizeView.setText(mImageSizeLabelArray[progress]); } }); }
Source:
public static Set<PersistentResource> loadRecords(Class<?> loadClass, RequestScope requestScope, Optional<FilterExpression> filterExpression) { DataStoreTransaction tx = requestScope.getTransaction(); if (shouldSkipCollection(loadClass, ReadPermission.class, requestScope)) { return Collections.emptySet(); } Iterable list; Optional<FilterExpression> filter = filterExpression; if(filterExpression.isPresent()) { if(requestScope.getLoadFilterExpression(loadClass).isPresent()) { filter = Optional.of(new AndFilterExpression(filterExpression.get(), requestScope.getLoadFilterExpression(loadClass).get())); } } else { filter = requestScope.getLoadFilterExpression(loadClass); } list = tx.loadObjects(loadClass, filter, Optional.empty(), Optional.empty(), requestScope); Set<PersistentResource> resources = new PersistentResourceSet(list, requestScope); resources = filter(ReadPermission.class, resources, false); return resources; }

Target:
public static Set<PersistentResource> loadRecords(Class<?> loadClass, RequestScope requestScope, Optional<FilterExpression> filterExpression) { DataStoreTransaction tx = requestScope.getTransaction(); if (shouldSkipCollection(loadClass, ReadPermission.class, requestScope)) { return Collections.emptySet(); } Iterable list; Optional<FilterExpression> filter = filterExpression; Optional<FilterExpression> loadFilterExpression = requestScope.getLoadFilterExpression(loadClass); if(filterExpression.isPresent()) { if(loadFilterExpression.isPresent()) { filter = Optional.of(new AndFilterExpression(filterExpression.get(), loadFilterExpression.get())); } } else { filter = loadFilterExpression; } list = tx.loadObjects(loadClass, filter, Optional.empty(), Optional.empty(), requestScope); Set<PersistentResource> resources = new PersistentResourceSet(list, requestScope); resources = filter(ReadPermission.class, resources, false); return resources; }
Source:
public void store(Item item, String alias) { logger.debug("Storing item: " + item.getName()); if (item.getState() instanceof UnDefType) { return; } if(!JpaConfiguration.isInitialized) { logger.warn("Trying to create EntityManagerFactory but we don't have configuration yet!"); return; } String name = (alias != null) ? alias : item.getName(); JpaPersistentItem pItem = new JpaPersistentItem(); try { pItem.setValue(StateHelper.toString(item.getState())); } catch (Exception e1) { logger.error("Error on converting state value to string!"); logger.error(e1.getMessage(), e1); return; } pItem.setName(name); pItem.setRealName(item.getName()); pItem.setTimestamp(new Date()); EntityManager em = getEntityManagerFactory().createEntityManager(); try { logger.debug("Persisting item..."); em.getTransaction().begin(); em.persist(pItem); em.getTransaction().commit(); logger.debug("Persisting item...done"); } catch (Exception e) { logger.error("Error on persisting item! Rolling back!"); logger.error(e.getMessage(), e); em.getTransaction().rollback(); } finally { em.close(); } logger.debug("Storing item...done"); }

Target:
public void store(Item item, String alias) { logger.debug("Storing item: " + item.getName()); if (item.getState() instanceof UnDefType) { logger.debug("This item is of undefined type. Cannot perist it!"); return; } if(!JpaConfiguration.isInitialized) { logger.warn("Trying to create EntityManagerFactory but we don't have configuration yet!"); return; } String name = (alias != null) ? alias : item.getName(); JpaPersistentItem pItem = new JpaPersistentItem(); try { pItem.setValue(StateHelper.toString(item.getState())); } catch (Exception e1) { logger.error("Error on converting state value to string: {}", e1.getMessage()); return; } pItem.setName(name); pItem.setRealName(item.getName()); pItem.setTimestamp(new Date()); EntityManager em = getEntityManagerFactory().createEntityManager(); try { logger.debug("Persisting item..."); em.getTransaction().begin(); em.persist(pItem); em.getTransaction().commit(); logger.debug("Persisting item...done"); } catch (Exception e) { logger.error("Error on persisting item! Rolling back!"); logger.error(e.getMessage(), e); em.getTransaction().rollback(); } finally { em.close(); } logger.debug("Storing item...done"); }
Source:
void onPullRequestHook(PullRequest pr) throws IOException { GHPullRequest ghpr = pr.getPullRequest(); int number = pr.getNumber(); String action = pr.getAction(); boolean doSave = false; if ("closed".equals(action)) { pullRequests.remove(number); doSave = true; } else if (!trigger.isActive()) { LOGGER.log(Level.FINE, "Not processing Pull request since the build is disabled"); } else if ("edited".equals(action) || "labeled".equals(action) || "opened".equals(action) || "reopened".equals(action) || "synchronize".equals(action) || "unlabeled".equals(action)) { GhprbPullRequest pull = getPullRequest(ghpr, number); pull.check(ghpr, true); doSave = true; } else { LOGGER.log(Level.WARNING, "Unknown Pull Request hook action: {0}", action); } if (doSave) { try { this.save(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to save repository!", e); } } }

Target:
void onPullRequestHook(PullRequest pr) throws IOException { GHPullRequest ghpr = pr.getPullRequest(); int number = pr.getNumber(); String action = pr.getAction(); boolean doSave = false; if ("closed".equals(action)) { pullRequests.remove(number); doSave = true; } else if (!trigger.isActive()) { LOGGER.log(Level.FINE, "Not processing Pull request since the build is disabled"); } else if (ALLOWED_ACTIONS.contains(action)) { GhprbPullRequest pull = getPullRequest(ghpr, number); pull.check(ghpr, true); doSave = true; } else { LOGGER.log(Level.WARNING, "Unknown Pull Request hook action: {0}", action); } if (doSave) { try { this.save(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to save repository!", e); } } }
Source:
private void checkSensorValue(String sensorName, String expectedValue) { solo.clickOnText(sensorName); solo.clickOnView(solo.getView(R.id.formula_editor_keyboard_compute)); solo.waitForView(solo.getView(R.id.formula_editor_compute_dialog_textview)); TextView computeTextView = (TextView) solo.getView(R.id.formula_editor_compute_dialog_textview); String sensorValue = computeTextView.getText().toString(); boolean sensorContainsExpectedValue = sensorValue.equals(expectedValue); assertTrue("Sensor value is:" + sensorValue + " but should be:" + expectedValue, sensorContainsExpectedValue); solo.goBack(); solo.waitForView(solo.getView(R.id.formula_editor_edit_field)); solo.goBack(); }

Target:
private void checkSensorValue(String sensorName, String expectedValue) { solo.clickOnText(sensorName); solo.clickOnView(solo.getView(R.id.formula_editor_keyboard_compute)); solo.waitForView(solo.getView(R.id.formula_editor_compute_dialog_textview)); TextView computeTextView = (TextView) solo.getView(R.id.formula_editor_compute_dialog_textview); String sensorValue = computeTextView.getText().toString(); assertEquals(sensorValue, expectedValue); solo.goBack(); solo.waitForView(solo.getView(R.id.formula_editor_edit_field)); solo.goBack(); }
Source:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderBlocking() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final PreparedDelete<DeleteResults<TestItem>> preparedDelete = storIOContentResolver .delete() .objects(items) .prepare(); try { preparedDelete.executeAsBlocking(); fail(); } catch (StorIOException expected) { } verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAffectingContentProviderBlocking() { final StorIOContentResolver storIOContentResolver = mock(StorIOContentResolver.class); final StorIOContentResolver.Internal internal = mock(StorIOContentResolver.Internal.class); when(storIOContentResolver.internal()).thenReturn(internal); when(storIOContentResolver.delete()).thenReturn(new PreparedDelete.Builder(storIOContentResolver)); final List<TestItem> items = asList(TestItem.newInstance(), TestItem.newInstance()); final PreparedDelete<DeleteResults<TestItem>> preparedDelete = storIOContentResolver .delete() .objects(items) .prepare(); try { preparedDelete.executeAsBlocking(); fail(); } catch (StorIOException expected) { TestUtils.checkException(expected, IllegalStateException.class); } verify(storIOContentResolver).delete(); verify(storIOContentResolver).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).delete(any(DeleteQuery.class)); verifyNoMoreInteractions(storIOContentResolver, internal); }
Source:
protected AbstractId(final String canonical) { if (canonical == null || canonical.trim().isEmpty()) throw new IllegalArgumentException("Id string provided can't be empty or null."); this.canonical = canonical; }

Target:
protected AbstractId(final String canonical) { this.canonical = Objects.requireNonNull(canonical, "canonical cannot be null"); }
Source:
public boolean isDirectory() { boolean isDirectory; switch (mode) { case SFTP: return isDirectory(AppConfig.getInstance()); case SMB: SmbFile smbFile = getSmbFile(); try { isDirectory = smbFile != null && smbFile.isDirectory(); } catch (SmbException e) { isDirectory = false; } break; case FILE: isDirectory = getFile().isDirectory(); break; case ROOT: try { isDirectory = RootHelper.isDirectory(path, 5); } catch (ShellNotRunningException e) { e.printStackTrace(); isDirectory = false; } break; case OTG: isDirectory = false; break; default: isDirectory = getFile().isDirectory(); break; } return isDirectory; }

Target:
public boolean isDirectory() { boolean isDirectory; switch (mode) { case SFTP: return isDirectory(AppConfig.getInstance()); case SMB: SmbFile smbFile = getSmbFile(); try { isDirectory = smbFile != null && smbFile.isDirectory(); } catch (SmbException e) { e.printStackTrace(); isDirectory = false; } break; case FILE: isDirectory = getFile().isDirectory(); break; case ROOT: try { isDirectory = RootHelper.isDirectory(path, 5); } catch (ShellNotRunningException e) { e.printStackTrace(); isDirectory = false; } break; case OTG: isDirectory = false; break; default: isDirectory = getFile().isDirectory(); break; } return isDirectory; }
Source:
private static Optional<Method> getRemoveInputFunction(Class<?> clazz, Class<?> stateClass, Method inputFunction) { List<Method> removeInputFunctions = FunctionsParserHelper.findPublicStaticMethodsWithAnnotation(clazz, RemoveInputFunction.class).stream() .filter(method -> Arrays.equals(method.getParameterTypes(), inputFunction.getParameterTypes()) && Arrays.deepEquals(method.getParameterAnnotations(), inputFunction.getParameterAnnotations())) .collect(toImmutableList()); checkArgument(removeInputFunctions.size() <= 1, "Ambiguous aggregation removeInput functions"); if (removeInputFunctions.isEmpty()) { return Optional.empty(); } return Optional.of(removeInputFunctions.get(0)); }

Target:
private static Optional<Method> getRemoveInputFunction(Class<?> clazz, Class<?> stateClass, Method inputFunction) { List<Method> removeInputFunctions = FunctionsParserHelper.findPublicStaticMethodsWithAnnotation(clazz, RemoveInputFunction.class).stream() .filter(method -> Arrays.equals(method.getParameterTypes(), inputFunction.getParameterTypes()) && Arrays.deepEquals(method.getParameterAnnotations(), inputFunction.getParameterAnnotations())) .collect(toImmutableList()); checkState(removeInputFunctions.size() <= 1, "Ambiguous aggregation removeInput functions"); if (removeInputFunctions.isEmpty()) { return Optional.empty(); } return Optional.of(removeInputFunctions.get(0)); }
Source:
QueryResult<U> executeJoinQuery( @Nonnull final Table<K1, V1, M1> table1, @Nonnull final Table<K2, V2, M2> table2, @Nonnull final Predicate<CorfuStoreEntry<K1, V1, M1>> query1, @Nonnull final Predicate<CorfuStoreEntry<K2, V2, M2>> query2, @Nonnull final QueryOptions<K1, V1, M1, R> queryOptions1, @Nonnull final QueryOptions<K2, V2, M2, S> queryOptions2, @Nonnull final BiPredicate<R, S> joinPredicate, @Nonnull final BiFunction<R, S, T> joinFunction, final Function<T, U> joinProjection) { applyWritesForReadOnTable(table1); table1.getMetrics().incNumScans(); applyWritesForReadOnTable(table1); table1.getMetrics().incNumScans(); return Query.executeJoinQuery(table1, table2, query1, query2, queryOptions1, queryOptions2, joinPredicate, joinFunction, joinProjection); }

Target:
QueryResult<U> executeJoinQuery( @Nonnull final Table<K1, V1, M1> table1, @Nonnull final Table<K2, V2, M2> table2, @Nonnull final Predicate<CorfuStoreEntry<K1, V1, M1>> query1, @Nonnull final Predicate<CorfuStoreEntry<K2, V2, M2>> query2, @Nonnull final QueryOptions<K1, V1, M1, R> queryOptions1, @Nonnull final QueryOptions<K2, V2, M2, S> queryOptions2, @Nonnull final BiPredicate<R, S> joinPredicate, @Nonnull final BiFunction<R, S, T> joinFunction, final Function<T, U> joinProjection) { applyWritesForReadOnTable(table1); table1.getMetrics().incNumJoins(); applyWritesForReadOnTable(table1); table2.getMetrics().incNumJoins(); return Query.executeJoinQuery(table1, table2, query1, query2, queryOptions1, queryOptions2, joinPredicate, joinFunction, joinProjection); }
Source:
private void sendJsPlugin(File srcFile, ResourceKey key, HttpServletRequest req, HttpServletResponse res) throws IOException { if (srcFile.exists()) { res.setHeader("Content-Length", Long.toString(srcFile.length())); res.setContentType("application/javascript"); writeToResponse(res, new FileInputStream(srcFile)); } else { resourceCache.put(key, Resource.NOT_FOUND); Resource.NOT_FOUND.send(req, res); } }

Target:
private void sendJsPlugin(File srcFile, ResourceKey key, HttpServletRequest req, HttpServletResponse res) throws IOException { if (srcFile.exists()) { res.setHeader("Content-Length", Long.toString(srcFile.length())); if (srcFile.getName().endsWith(".js")) { res.setContentType("application/javascript"); } writeToResponse(res, new FileInputStream(srcFile)); } else { resourceCache.put(key, Resource.NOT_FOUND); Resource.NOT_FOUND.send(req, res); } }
Source:
protected void registerFilePidsIfNeeded(Dataset theDataset, CommandContext ctxt, boolean b) throws CommandException { String protocol = theDataset.getProtocol(); String authority = theDataset.getAuthority(); GlobalIdServiceBean idServiceBean = GlobalIdServiceBean.getBean(protocol, ctxt); String currentGlobalIdProtocol = ctxt.settings().getValueForKey(SettingsServiceBean.Key.Protocol, ""); String currentGlobalAuthority = ctxt.settings().getValueForKey(SettingsServiceBean.Key.Authority, ""); String dataFilePIDFormat = ctxt.settings().getValueForKey(SettingsServiceBean.Key.DataFilePIDFormat, "DEPENDENT"); boolean shouldRegister = ctxt.systemConfig().isFilePIDsEnabled() && !idServiceBean.registerWhenPublished() &&((currentGlobalIdProtocol.equals(protocol) && currentGlobalAuthority.equals(authority)) || dataFilePIDFormat.equals("INDEPENDENT")); logger.fine("IsFilePIDsEnabled: " + ctxt.systemConfig().isFilePIDsEnabled()); logger.fine("RegWhenPub: " + !idServiceBean.registerWhenPublished()); logger.fine("OK provider: " + ((currentGlobalIdProtocol.equals(protocol) && currentGlobalAuthority.equals(authority)) || dataFilePIDFormat.equals("INDEPENDENT"))); logger.fine("Should register: " + shouldRegister); for (DataFile dataFile : theDataset.getFiles()) { logger.fine(dataFile.getId() + " is registered?: " + dataFile.isIdentifierRegistered()); if (shouldRegister && !dataFile.isIdentifierRegistered()) { registerFileExternalIdentifier(dataFile, idServiceBean, ctxt, true); } } }

Target:
protected void registerFilePidsIfNeeded(Dataset theDataset, CommandContext ctxt, boolean b) throws CommandException { String protocol = theDataset.getProtocol(); String authority = theDataset.getAuthority(); GlobalIdServiceBean idServiceBean = GlobalIdServiceBean.getBean(protocol, ctxt); String currentGlobalIdProtocol = ctxt.settings().getValueForKey(SettingsServiceBean.Key.Protocol, ""); String currentGlobalAuthority = ctxt.settings().getValueForKey(SettingsServiceBean.Key.Authority, ""); String dataFilePIDFormat = ctxt.settings().getValueForKey(SettingsServiceBean.Key.DataFilePIDFormat, SystemConfig.DataFilePIDFormat.DEPENDENT.toString()); boolean shouldRegister = ctxt.systemConfig().isFilePIDsEnabled() && !idServiceBean.registerWhenPublished() &&((currentGlobalIdProtocol.equals(protocol) && currentGlobalAuthority.equals(authority)) || dataFilePIDFormat.equals(SystemConfig.DataFilePIDFormat.INDEPENDENT.toString())); logger.fine("IsFilePIDsEnabled: " + ctxt.systemConfig().isFilePIDsEnabled()); logger.fine("RegWhenPub: " + !idServiceBean.registerWhenPublished()); logger.fine("OK provider: " + ((currentGlobalIdProtocol.equals(protocol) && currentGlobalAuthority.equals(authority)) || dataFilePIDFormat.equals(SystemConfig.DataFilePIDFormat.INDEPENDENT.toString()))); logger.fine("Should register: " + shouldRegister); if (shouldRegister) { for (DataFile dataFile : theDataset.getFiles()) { logger.fine(dataFile.getId() + " is registered?: " + dataFile.isIdentifierRegistered()); if (!dataFile.isIdentifierRegistered()) { registerFileExternalIdentifier(dataFile, idServiceBean, ctxt, true); } } } }
Source:
private void visitSuper(Node node, Node parent) { Node exprRoot = node; for (; exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp(); exprRoot = exprRoot.getParent()) { if (exprRoot.getParent().getFirstChild() != exprRoot) { return; } } Node enclosingMemberDef = NodeUtil.getEnclosingNode( exprRoot, new Predicate<Node>() { @Override public boolean apply(Node n) { switch (n.getToken()) { case MEMBER_FUNCTION_DEF: case GETTER_DEF: case SETTER_DEF: case COMPUTED_PROP: return true; default: return false; } } }); if (exprRoot.getParent().isNew()) { compiler.report(JSError.make(node, INVALID_SUPER)); } else if (NodeUtil.isCallOrNewTarget(exprRoot) && (exprRoot.isSuper() || exprRoot.getFirstChild().isSuper())) { visitSuperCall(node, exprRoot, enclosingMemberDef); } else { visitSuperProperty(node, exprRoot, enclosingMemberDef); } }

Target:
private void visitSuper(Node node, Node parent) { Preconditions.checkState(node.isSuper()); Node exprRoot = node; if (exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp()) { exprRoot = exprRoot.getParent(); } Node enclosingMemberDef = NodeUtil.getEnclosingNode( exprRoot, new Predicate<Node>() { @Override public boolean apply(Node n) { switch (n.getToken()) { case MEMBER_FUNCTION_DEF: case GETTER_DEF: case SETTER_DEF: case COMPUTED_PROP: return true; default: return false; } } }); if (parent.isCall()) { visitSuperCall(node, parent, enclosingMemberDef); } else if (parent.isGetProp() || parent.isGetElem()) { if (parent.getFirstChild() == node) { if (parent.getParent().isCall() && NodeUtil.isCallOrNewTarget(parent)) { visitSuperPropertyCall(node, parent, enclosingMemberDef); } else { visitSuperPropertyAccess(node, parent, enclosingMemberDef); } } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } } else if (parent.isNew()) { compiler.report(JSError.make(node, INVALID_SUPER_CALL)); } else { compiler.report(JSError.make(node, CANNOT_CONVERT_YET, "Only calls to super or to a method of super are supported.")); } }
Source:
private void closeEventReceivers() { this.eventReceivers.forEach((receiver) -> { receiver.close(); }); }

Target:
private void closeEventReceivers() { this.eventReceivers.forEach(EventReceiver::close); }
Source:
public CommentedActionDialog(final String title, final String heading, AsyncCallback<T> callback) { super( false, true); this.callback = callback; setGlassEnabled(true); setText(title); addStyleName(Gerrit.RESOURCES.css().commentedActionDialog()); message = new NpTextArea(); message.setCharacterWidth(60); message.setVisibleLines(10); DOM.setElementPropertyBoolean(message.getElement(), "spellcheck", true); sendButton = new Button(Util.C.commentedActionButtonSend()); sendButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { enableButtons(false); onSend(); } }); cancelButton = new Button(Util.C.commentedActionButtonCancel()); DOM.setStyleAttribute(cancelButton.getElement(), "marginLeft", "300px"); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { hide(); } }); final FlowPanel mwrap = new FlowPanel(); mwrap.setStyleName(Gerrit.RESOURCES.css().commentedActionMessage()); mwrap.add(message); buttonPanel = new FlowPanel(); buttonPanel.add(sendButton); buttonPanel.add(cancelButton); panel = new FlowPanel(); panel.add(new SmallHeading(heading)); panel.add(mwrap); panel.add(buttonPanel); add(panel); callback = createCallback(); addCloseHandler(this); }

Target:
public CommentedActionDialog(final String title, final String heading, AsyncCallback<T> callback) { super( false, true); this.callback = callback; setGlassEnabled(true); setText(title); addStyleName(Gerrit.RESOURCES.css().commentedActionDialog()); message = new NpTextArea(); message.setCharacterWidth(60); message.setVisibleLines(10); DOM.setElementPropertyBoolean(message.getElement(), "spellcheck", true); sendButton = new Button(Util.C.commentedActionButtonSend()); sendButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { enableButtons(false); onSend(); } }); cancelButton = new Button(Util.C.commentedActionButtonCancel()); DOM.setStyleAttribute(cancelButton.getElement(), "marginLeft", "300px"); cancelButton.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { hide(); } }); final FlowPanel mwrap = new FlowPanel(); mwrap.setStyleName(Gerrit.RESOURCES.css().commentedActionMessage()); mwrap.add(message); buttonPanel = new FlowPanel(); buttonPanel.add(sendButton); buttonPanel.add(cancelButton); panel = new FlowPanel(); panel.add(new SmallHeading(heading)); panel.add(mwrap); panel.add(buttonPanel); add(panel); addCloseHandler(this); }
Source:
public static VirtualNetwork create(final String name, final String id, final String etag, final String location, final VirtualNetworkProperties properties, final Map<String, String> tags) { return new AutoValue_VirtualNetwork(name, id, etag, location, properties, tags == null ? ImmutableMap.<String, String>builder().build() : ImmutableMap.copyOf(tags)); }

Target:
public static VirtualNetwork create(final String name, final String id, final String etag, final String location, final VirtualNetworkProperties properties, final Map<String, String> tags) { return new AutoValue_VirtualNetwork(name, id, etag, location, properties, tags == null ? null : ImmutableMap.copyOf(tags)); }
Source:
public PartTreeCouchbaseQuery(CouchbaseQueryMethod method, CouchbaseOperations operations, SpelExpressionParser expressionParser, QueryMethodEvaluationContextProvider evaluationContextProvider) { super(method, operations, expressionParser, evaluationContextProvider); this.processor = method.getResultProcessor(); for (PartTree.OrPart parts : this.tree = new PartTree(method.getName(), processor.getReturnedType().getDomainType())) this.context = operations.getConverter().getMappingContext(); this.converter = operations.getConverter(); }

Target:
public PartTreeCouchbaseQuery(CouchbaseQueryMethod method, CouchbaseOperations operations, SpelExpressionParser expressionParser, QueryMethodEvaluationContextProvider evaluationContextProvider) { super(method, operations, expressionParser, evaluationContextProvider); ResultProcessor processor = method.getResultProcessor(); this.tree = new PartTree(method.getName(), processor.getReturnedType().getDomainType()); this.converter = operations.getConverter(); }
Source:
public boolean equalsIdentity (Object obj) { if (obj == this) return true; if (!(obj instanceof IdentityMap)) return false; IdentityMap other = (IdentityMap)obj; if (other.size != size) return false; K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = 0, n = keyTable.length; i < n; i++) { K key = keyTable[i]; if (key != null && valueTable[i] != other.get(key, dummy)) return false; } return true; }

Target:
public boolean equalsIdentity (Object obj) { if (obj == this) return true; if (!(obj instanceof ObjectMap)) return false; ObjectMap other = (ObjectMap)obj; if (other.size != size) return false; K[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = 0, n = keyTable.length; i < n; i++) { K key = keyTable[i]; if (key != null && valueTable[i] != other.get(key, dummy)) return false; } return true; }
Source:
public CompletionStage<T> execute(final ActorRef scheduler, final Instant scheduled) { final JobRepository<T> repo = _ref.getRepository(_injector); repo.jobStarted(_cached.getId(), _ref.getOrganization(), scheduled); return _cached.execute(scheduler, scheduled) .handle((result, error) -> { _lastRun = Optional.of(scheduled); if (error == null) { repo.jobSucceeded(_cached.getId(), _ref.getOrganization(), scheduled, result); } else { repo.jobFailed(_cached.getId(), _ref.getOrganization(), scheduled, error); } return null; }); }

Target:
public CompletionStage<T> execute(final ActorRef scheduler, final Instant scheduled) { return _cached.execute(scheduler, scheduled); }
Source:
private void writeNotes(Appendable sb, String notesJsonString) throws IOException, JSONException { JSONArray notesArray = new JSONArray(notesJsonString); int count = notesArray.length(); if (count == 0) { sb.append(""); } else { for (int i = 0; i < count; i++) { if (i != 0) { sb.append("<br><br>"); sb.append("---------------------------"); sb.append("<br><br>"); } JSONObject note = notesArray.getJSONObject(i); if (note.has("content")) { sb.append(note.getString("content")); } if (note.has("type")) { sb.append(" Type: "); sb.append(note.getString("type")); } if (note.has("dateString")) { sb.append("<br>"); sb.append(" Date "); sb.append("<br>"); sb.append(note.getString("dateString")); } } } }

Target:
private void writeNotes(Appendable sb, String notesJsonString) throws IOException, JSONException { JSONArray notesArray = new JSONArray(notesJsonString); int count = notesArray.length(); if (count == 0) { sb.append(""); } else { for (int i = 0; i < count; i++) { if (i != 0) { sb.append("<br><br>---------------------------<br><br>"); } JSONObject note = notesArray.getJSONObject(i); if (note.has("content")) { sb.append(note.getString("content")); } if (note.has("type")) { sb.append(String.format("<br><b>Type:</b><i>%s</i><br>", note.getString("type"))); } if (note.has("dateString")) { sb.append(note.getString("dateString")); } } } }
Source:
public void testTransactionManager(@ArquillianResource Bundle bundle) throws Exception { assertEquals("System Bundle ID", 0, context.getBundle().getBundleId()); bundle.start(); assertEquals("Bundle ACTIVE", Bundle.ACTIVE, bundle.getState()); BundleContext context = bundle.getBundleContext(); assertNotNull("BundleContext available", context); assertNotNull("TransactionManager reference available", context.getServiceReference(TransactionManager.class)); bundle.stop(); assertEquals("Bundle RESOLVED", Bundle.RESOLVED, bundle.getState()); }

Target:
public void testTransactionManager(@ArquillianResource Bundle bundle) throws Exception { assertEquals("System Bundle ID", 0, context.getBundle().getBundleId()); bundle.start(); assertEquals("Bundle ACTIVE", Bundle.ACTIVE, bundle.getState()); BundleContext context = bundle.getBundleContext(); assertNotNull("BundleContext available", context); ServiceReference<TransactionManager> serviceReference = context.getServiceReference(TransactionManager.class); assertNotNull("TransactionManager reference available", serviceReference); TransactionManager tm = context.getService(serviceReference); assertNotNull("TransactionManager service available", tm); tm.begin(); tm.commit(); bundle.stop(); assertEquals("Bundle RESOLVED", Bundle.RESOLVED, bundle.getState()); }
Source:
public void configure(Binder binder) { Jerseys.addResource(binder, ChatHandlerResource.class); LifecycleModule.register(binder, ChatHandlerResource.class); if (properties.containsKey(MAX_CHAT_REQUESTS_PROPERTY)) { final int maxRequests = Integer.parseInt(properties.getProperty(MAX_CHAT_REQUESTS_PROPERTY)); JettyBindings.addQosFilter(binder, "/druid/worker/v1/chat binder.bind(DruidNode.class).annotatedWith(RemoteChatHandler.class).to(Key.get(DruidNode.class, Self.class)); } binder.bind(ServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(ServerConfig.class)); binder.bind(TLSServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(TLSServerConfig.class)); }

Target:
public void configure(Binder binder) { Jerseys.addResource(binder, ChatHandlerResource.class); LifecycleModule.register(binder, ChatHandlerResource.class); if (properties.containsKey(MAX_CHAT_REQUESTS_PROPERTY)) { final int maxRequests = Integer.parseInt(properties.getProperty(MAX_CHAT_REQUESTS_PROPERTY)); JettyBindings.addQosFilter( binder, "/druid/worker/v1/chat binder.bind(DruidNode.class).annotatedWith(RemoteChatHandler.class).to(Key.get(DruidNode.class, Self.class)); binder.bind(ServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(ServerConfig.class)); binder.bind(TLSServerConfig.class).annotatedWith(RemoteChatHandler.class).to(Key.get(TLSServerConfig.class)); }
Source:
public DAnalysis getDAnalysis() { DAnalysis dAnalysis = null; DRepresentation representation = getRepresentation().get(); DRepresentationDescriptor representationDescriptor = new DRepresentationQuery(representation).getRepresentationDescriptor(); EObject rootContainer = EcoreUtil.getRootContainer(representationDescriptor, false); if (rootContainer instanceof DAnalysis) { dAnalysis = (DAnalysis) rootContainer; } return dAnalysis; }

Target:
public DAnalysis getDAnalysis() { DAnalysis dAnalysis = null; DRepresentation representation = getRepresentation().get(); if (representation != null) { DRepresentationDescriptor representationDescriptor = new DRepresentationQuery(representation).getRepresentationDescriptor(); EObject rootContainer = EcoreUtil.getRootContainer(representationDescriptor, false); if (rootContainer instanceof DAnalysis) { dAnalysis = (DAnalysis) rootContainer; } } return dAnalysis; }
Source:
void emit(long mreq, Producer mp, long mprod) { boolean newMp = false; if (mp != null) { newMp = true; currentProducer = mp; } else { mp = currentProducer; } long u = requested + mreq; if (u < 0) { u = Long.MAX_VALUE; } u -= mprod; if (u < 0) { throw new IllegalStateException("More produced than requested"); } requested = u; if (mreq > 0 && mp != null) { mp.request(mreq); } else if (newMp && u > 0) { mp.request(u); } }

Target:
void emit(long mreq, Producer mp, long mprod) { boolean newMp = false; if (mp != null) { newMp = true; currentProducer = mp; } else { mp = currentProducer; } long u = requested + mreq; if (u < 0) { u = Long.MAX_VALUE; } else if (u != Long.MAX_VALUE) { u -= mprod; if (u < 0) { throw new IllegalStateException("More produced than requested"); } } requested = u; if (mreq > 0 && mp != null) { mp.request(mreq); } else if (newMp && u > 0) { mp.request(u); } }
Source:
public SslCertResponse createCertResponse(final SslCertVO cert, final List<LoadBalancerCertMapVO> lbCertMap) { final SslCertResponse response = new SslCertResponse(); final Account account = _accountDao.findByIdIncludingRemoved(cert.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { final Project project = _projectMgr.findByProjectAccountIdIncludingRemoved(account.getId()); if (project != null) { response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); } } else { response.setAccountName(account.getAccountName()); } final DomainVO domain = _domainDao.findByIdIncludingRemoved(cert.getDomainId()); response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); response.setObjectName("sslcert"); response.setId(cert.getUuid()); response.setCertificate(cert.getCertificate()); response.setFingerprint(cert.getFingerPrint()); if (cert.getChain() != null) { response.setCertchain(cert.getChain()); } if (lbCertMap != null && !lbCertMap.isEmpty()) { final List<String> lbIds = new ArrayList<String>(); for (final LoadBalancerCertMapVO mapVO : lbCertMap) { final LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, mapVO.getLbId()); if (lb != null) { lbIds.add(lb.getUuid()); } } response.setLbIds(lbIds); } return response; }

Target:
public SslCertResponse createCertResponse(final SslCertVO cert, final List<LoadBalancerCertMapVO> lbCertMap) { Preconditions.checkNotNull(cert); final SslCertResponse response = new SslCertResponse(); final Account account = _accountDao.findByIdIncludingRemoved(cert.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { final Project project = _projectMgr.findByProjectAccountIdIncludingRemoved(account.getId()); if (project != null) { response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); } } else { response.setAccountName(account.getAccountName()); } final DomainVO domain = _domainDao.findByIdIncludingRemoved(cert.getDomainId()); response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); response.setObjectName("sslcert"); response.setId(cert.getUuid()); response.setCertificate(cert.getCertificate()); response.setFingerprint(cert.getFingerPrint()); if (cert.getChain() != null) { response.setCertchain(cert.getChain()); } if (lbCertMap != null && !lbCertMap.isEmpty()) { final List<String> lbIds = new ArrayList<String>(); for (final LoadBalancerCertMapVO mapVO : lbCertMap) { final LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, mapVO.getLbId()); if (lb != null) { lbIds.add(lb.getUuid()); } } response.setLbIds(lbIds); } return response; }
Source:
public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.commons.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20 * 1024 * 1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange("store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getIntInRange("store.max.number.of.entries.to.return.from.journal", 5000, 1, 10000); storeDeletedMessageRetentionDays = verifiableProperties.getInt("store.deleted.message.retention.days", 7); storeHardDeleteBytesPerSec = verifiableProperties.getInt("store.hard.delete.bytes.per.sec", 1 * 1024 * 1024); storeEnableHardDelete = verifiableProperties.getBoolean("store.enable.hard.delete", false); storeSegmentSizeInBytes = verifiableProperties.getLongInRange("store.segment.size.in.bytes", Long.MAX_VALUE, 1, Long.MAX_VALUE); storeHardDeleterSleepTimeWhenCaughtUpInMs = verifiableProperties.getLong("store.hard.deleter.sleep.time.when.caught.up.in.ms", 10000); }

Target:
public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.commons.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20 * 1024 * 1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange("store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getIntInRange("store.max.number.of.entries.to.return.from.journal", 5000, 1, 10000); storeDeletedMessageRetentionDays = verifiableProperties.getInt("store.deleted.message.retention.days", 7); storeHardDeleteBytesPerSec = verifiableProperties.getInt("store.hard.delete.bytes.per.sec", 1 * 1024 * 1024); storeEnableHardDelete = verifiableProperties.getBoolean("store.enable.hard.delete", false); storeSegmentSizeInBytes = verifiableProperties.getLongInRange("store.segment.size.in.bytes", Long.MAX_VALUE, 1, Long.MAX_VALUE); }
Source:
public void start(final BundleContext context) throws Exception { super.start(context); pluginId = context.getBundle().getSymbolicName(); Dictionary<String, String> props = new Hashtable<String, String>(4); props.put(DebugOptions.LISTENER_SYMBOLICNAME, pluginId); context.registerService(DebugOptionsListener.class.getName(), this, props); repositoryCache = new RepositoryCache(); indexDiffCache = new IndexDiffCache(); try { GitProjectData.reconfigureWindowCache(); } catch (RuntimeException e) { logError(CoreText.Activator_ReconfigureWindowCacheError, e); } GitProjectData.attachToWorkspace(true); IEclipsePreferences node = InstanceScope.INSTANCE.getNode(Activator.getPluginId()); String gitPrefix = node.get(GitCorePreferences.core_gitPrefix, null); if (gitPrefix != null) FS.DETECTED.setGitPrefix(new File(gitPrefix)); repositoryUtil = new RepositoryUtil(); secureStore = new EGitSecureStore(SecurePreferencesFactory.getDefault()); registerAutoShareProjects(); if (egitChangeListener == null) { egitChangeListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { IResource project = event.getResource(); if (project != null && project instanceof IProject) { GitProjectData.reconfigureWindowCache(); } } }; ResourcesPlugin.getWorkspace().addResourceChangeListener(egitChangeListener, IResourceChangeEvent.PRE_DELETE); } }

Target:
public void start(final BundleContext context) throws Exception { super.start(context); pluginId = context.getBundle().getSymbolicName(); Dictionary<String, String> props = new Hashtable<String, String>(4); props.put(DebugOptions.LISTENER_SYMBOLICNAME, pluginId); context.registerService(DebugOptionsListener.class.getName(), this, props); repositoryCache = new RepositoryCache(); indexDiffCache = new IndexDiffCache(); try { GitProjectData.reconfigureWindowCache(); } catch (RuntimeException e) { logError(CoreText.Activator_ReconfigureWindowCacheError, e); } GitProjectData.attachToWorkspace(true); IEclipsePreferences node = InstanceScope.INSTANCE.getNode(Activator.getPluginId()); String gitPrefix = node.get(GitCorePreferences.core_gitPrefix, null); if (gitPrefix != null) FS.DETECTED.setGitPrefix(new File(gitPrefix)); repositoryUtil = new RepositoryUtil(); secureStore = new EGitSecureStore(SecurePreferencesFactory.getDefault()); registerAutoShareProjects(); if (egitChangeListener == null) { egitChangeListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { IResource project = event.getResource(); if (project != null && project instanceof IProject) GitProjectData.reconfigureWindowCache(); } }; ResourcesPlugin.getWorkspace().addResourceChangeListener(egitChangeListener, IResourceChangeEvent.PRE_DELETE); } }
Source:
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { logger.trace("Reading on channel {}", ctx.channel()); if (obj instanceof HttpRequest) { if (requestInProgress) { logDurations(); logMessage.append(" : Received request while another request in progress. Resetting log message."); logger.error(logMessage.toString()); } this.requestInProgress = true; this.logMessage = new StringBuilder(); this.requestArrivalTimeInMs = System.currentTimeMillis(); this.requestLastChunkArrivalTimeInMs = INVALID_CHUNK_TIME; this.responseFirstChunkStartTimeInMs = INVALID_CHUNK_TIME; this.request = (HttpRequest) obj; logMessage.append(ctx.channel().remoteAddress()).append(" "); logMessage.append(request.getMethod().toString()).append(" "); logMessage.append(request.getUri()).append(", "); logHeaders("Request", request, publicAccessLogger.getRequestHeaders()); logMessage.append(", "); } else if (obj instanceof HttpContent) { HttpContent httpContent = (HttpContent) obj; if (httpContent instanceof LastHttpContent) { requestLastChunkArrivalTimeInMs = System.currentTimeMillis(); } } else { logger.error("Receiving request (messageReceived) that is not of type HttpRequest or HttpChunk. " + "Receiving request from " + ctx.channel().remoteAddress() + ". " + "Request is of type " + obj.getClass() + ". " + "No action being taken other than logging this unexpected state."); } super.channelRead(ctx, obj); }

Target:
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { logger.trace("Reading on channel {}", ctx.channel()); if (obj instanceof HttpRequest) { if (request != null) { logDurations(); logMessage.append(" : Received request while another request in progress. Resetting log message."); logger.error(logMessage.toString()); } reset(); requestArrivalTimeInMs = System.currentTimeMillis(); request = (HttpRequest) obj; logMessage.append(ctx.channel().remoteAddress()).append(" "); logMessage.append(request.getMethod().toString()).append(" "); logMessage.append(request.getUri()).append(", "); logHeaders("Request", request, publicAccessLogger.getRequestHeaders()); logMessage.append(", "); } else if (obj instanceof LastHttpContent) { requestLastChunkArrivalTimeInMs = System.currentTimeMillis(); } else if(!(obj instanceof HttpContent)){ logger.error("Receiving request (messageReceived) that is not of type HttpRequest or HttpContent. " + "Receiving request from " + ctx.channel().remoteAddress() + ". " + "Request is of type " + obj.getClass() + ". " + "No action being taken other than logging this unexpected state."); } super.channelRead(ctx, obj); }
Source:
public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); }

Target:
public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); inspector.visit("lgK", lgK); }
Source:
private void removeFromList(Map source, TypeDefinition value) { List<TypeDefinition> list = (List<TypeDefinition>) source.get(value.getName()); if (list == null) return; list.remove(value); }

Target:
private void removeFromList(Map source, TypeDefinition value) { List<TypeDefinition> list = (List<TypeDefinition>) source.get(value.getName()); if (list == null) { return; } list.remove(value); }
Source:
public boolean checkImages() { boolean allReviewed = true; for (MapillaryImage img : changeset) { allReviewed &= img.isReviewed(); } return allReviewed; }

Target:
public boolean checkImages() { return changeset.stream().allMatch(MapillaryImage::isReviewed); }
Source:
protected Jedis getJedis(int db) { int timeoutCount = 0; Jedis jedis; while (true) { try { jedis = getJedisPool().getResource(); if (StringUtils.isNotEmpty(getRedisPassword())) { jedis.auth(getRedisPassword()); } jedis.select(db); break; } catch (JedisConnectionException e) { logger.error(e.getLocalizedMessage(), e); if (++timeoutCount >= 3) { throw e; } } } return jedis; }

Target:
protected Jedis getJedis(int db) { int timeoutCount = 0; Jedis jedis; while (true) { try { jedis = getJedisPool().getResource(); if (StringUtils.isNotEmpty(getRedisPassword())) { jedis.auth(getRedisPassword()); } jedis.select(db); break; } catch (JedisConnectionException e) { logger.error(MessageFormat.format("fetch jedis failed on {0} times", String.valueOf(timeoutCount + 1)), e); if (++timeoutCount >= 3) { logger.error("Get Redis pool failure more than 3 times.",e); throw e; } } } return jedis; }
Source:
public void testWithMissingOsInExplicitTargetEnvironment() throws Exception { try { File basedir = getBasedir("projects/explicitenvironment/missingOs"); List<MavenProject> projects = getSortedProjects(basedir); assertEquals(1, projects.size()); assertEquals("missingOs", projects.get(0).getArtifactId()); DefaultTargetPlatformConfigurationReader resolver = lookup(DefaultTargetPlatformConfigurationReader.class); MavenSession session = newMavenSession(projects.get(0), projects); resolver.getTargetPlatformConfiguration(session, session.getCurrentProject()); fail("RuntimeException must be thrown when <os> is missing in the target configuration (environment element)"); } catch (RuntimeException e) { assertTrue(true); } }

Target:
public void testWithMissingOsInExplicitTargetEnvironment() throws Exception { File basedir = getBasedir("projects/explicitenvironment/missingOs"); try { getSortedProjects(basedir); fail("RuntimeException must be thrown when <os> is missing in the target configuration (environment element)"); } catch (RuntimeException e) { assertTrue(e.getMessage().contains( "target-platform-configuration error in project explicitenvironment:missingos:eclipse-plugin")); Throwable cause = e; while (cause.getCause() != null) { cause = cause.getCause(); } assertTrue(cause instanceof TargetPlatformConfigurationException); assertEquals("<os> element is missing within target-platform-configuration (element <environment>)", cause.getMessage()); } }