auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public long write( String path, ReadableByteChannel data, ByteBuffer temporaryBuffer, boolean hasData, int requiredElementAlignment ) throws IOException { try { temporaryBuffer.clear(); File file = new File( basePath, path ); file.getParentFile().mkdirs(); String filename = file.getName(); monitor.startReceivingStoreFile( file ); try { boolean isDefaultFileSystem = pageCache.getCachedFileSystem() instanceof DefaultFileSystemAbstraction; if ( !isDefaultFileSystem && StoreType.shouldBeManagedByPageCache( filename ) ) { int filePageSize = filePageSize( requiredElementAlignment ); try ( PagedFile pagedFile = pageCache.map( file, filePageSize, CREATE, WRITE ) ) { final long written = writeDataThroughPageCache( pagedFile, data, temporaryBuffer, hasData ); addPageCacheMoveAction( file ); return written; } } return writeDataThroughFileSystem( file, data, temporaryBuffer, hasData ); } finally { monitor.finishReceivingStoreFile( file ); } } catch ( Throwable t ) { throw new IOException( t ); } }

Target:
public long write( String path, ReadableByteChannel data, ByteBuffer temporaryBuffer, boolean hasData, int requiredElementAlignment ) throws IOException { try { temporaryBuffer.clear(); File file = new File( basePath, path ); file.getParentFile().mkdirs(); String filename = file.getName(); monitor.startReceivingStoreFile( file ); try { if ( !pageCache.fileSystemSupportsFileOperations() && StoreType.canBeManagedByPageCache( filename ) ) { int filePageSize = filePageSize( requiredElementAlignment ); try ( PagedFile pagedFile = pageCache.map( file, filePageSize, CREATE, WRITE ) ) { final long written = writeDataThroughPageCache( pagedFile, data, temporaryBuffer, hasData ); addPageCacheMoveAction( file ); return written; } } return writeDataThroughFileSystem( file, data, temporaryBuffer, hasData ); } finally { monitor.finishReceivingStoreFile( file ); } } catch ( Throwable t ) { throw new IOException( t ); } }
Source:
public static Scope importAndCreateScope(String name, String encodedParent) { Tracer.SpanBuilder spanBuilder; Tracer tracer = GlobalTracer.get(); SpanContext parentSpan = null; if (encodedParent != null && encodedParent.length() > 0) { StringBuilder builder = new StringBuilder(); builder.append(encodedParent); try { parentSpan = tracer.extract(StringCodec.FORMAT, builder); } catch (Exception ex) { if (LOG.isDebugEnabled()) { LOG.debug("Can't extract tracing from the message.", ex); } else { LOG.warn( "Can't extract tracing from the message: " + ex.getMessage()); } } } if (parentSpan == null) { spanBuilder = tracer.buildSpan(name); } else { spanBuilder = tracer.buildSpan(name).asChildOf(parentSpan); } return spanBuilder.startActive(true); }

Target:
public static Scope importAndCreateScope(String name, String encodedParent) { Tracer.SpanBuilder spanBuilder; Tracer tracer = GlobalTracer.get(); SpanContext parentSpan = null; if (encodedParent != null && encodedParent.length() > 0) { StringBuilder builder = new StringBuilder(); builder.append(encodedParent); parentSpan = tracer.extract(StringCodec.FORMAT, builder); } if (parentSpan == null) { spanBuilder = tracer.buildSpan(name); } else { spanBuilder = tracer.buildSpan(name).asChildOf(parentSpan); } return spanBuilder.startActive(true); }
Source:
public static Bitmap getImage(String imageLocation) { Bitmap _image; if (mEnableCache) { _image = mCache.get(imageLocation); if (_image == null) { _image = BitmapFactory.decodeFile(imageLocation); if (_image != null) { mCache.put(imageLocation, _image); } } } else { _image = BitmapFactory.decodeFile(imageLocation); } return _image; }

Target:
public static Bitmap getImage(String imageLocation) { Bitmap image = null; if (mEnableCache) { image = getImageFromCache(imageLocation); } else { image = BitmapFactory.decodeFile(imageLocation); } return image; }
Source:
public void testIfDependentMethodsAreInvokedWhenRetrySucceeds() { TestNG testng = create(TestClassSampleWithTestMethodDependencies.class); InvokedMethodNameListener listener = new InvokedMethodNameListener(); testng.addListener(listener); testng.run(); assertThat(listener.getSucceedMethodNames()).containsExactly("a", "b"); assertThat(listener.getFailedMethodNames()).containsExactly("a"); assertThat(listener.getSkippedMethodNames()).containsExactly("a"); }

Target:
public void testIfDependentMethodsAreInvokedWhenRetrySucceeds() { TestNG testng = create(TestClassSampleWithTestMethodDependencies.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener(tla); testng.run(); assertThat(tla.getPassedTests() .stream() .map(RetryAnalyzerTest::methodName) .collect(Collectors.toList()) ).containsExactly("a", "b"); assertThat(tla.getFailedTests()).isEmpty(); assertThat(tla.getSkippedTests() .stream() .map(RetryAnalyzerTest::methodName) .collect(Collectors.toList()) ).containsExactly("a"); }
Source:
public void call(Subscriber<? super T> subscriber) { try { final Resource resource = resourceFactory.call(); final Action0 disposeOnceOnly = createOnceOnlyDisposeAction(resource); subscriber.add(Subscriptions.create(disposeOnceOnly)); final Observable<? extends T> source = observableFactory .call(resource); final Observable<? extends T> observable; if (disposeEagerly) observable = source .doOnTerminate(disposeOnceOnly); else observable = source; try { observable.unsafeSubscribe(subscriber); } catch (Throwable e) { Throwable disposeError = disposeEagerlyIfRequested(disposeOnceOnly); if (disposeError != null) subscriber.onError(new CompositeException(Arrays.asList(e, disposeError))); else subscriber.onError(e); } } catch (Throwable e) { subscriber.onError(e); } }

Target:
public void call(Subscriber<? super T> subscriber) { try { final Resource resource = resourceFactory.call(); final DisposeAction<Resource> disposeOnceOnly = new DisposeAction<Resource>(dispose, resource); subscriber.add(disposeOnceOnly); final Observable<? extends T> source = observableFactory .call(resource); final Observable<? extends T> observable; if (disposeEagerly) observable = source .doOnTerminate(disposeOnceOnly); else observable = source; try { observable.unsafeSubscribe(subscriber); } catch (Throwable e) { Throwable disposeError = disposeEagerlyIfRequested(disposeOnceOnly); if (disposeError != null) subscriber.onError(new CompositeException(Arrays.asList(e, disposeError))); else subscriber.onError(e); } } catch (Throwable e) { subscriber.onError(e); } }
Source:
public void removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) { Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null"); if (this.beforePublishPostProcessors != null) { this.beforePublishPostProcessors.remove(beforePublishPostProcessor); } }

Target:
public boolean removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) { Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null"); if (this.beforePublishPostProcessors != null) { return this.beforePublishPostProcessors.remove(beforePublishPostProcessor); } return false; }
Source:
public static void main(String[] args) { LOG.info("Starting PYAPEX with " + StringUtils.join(args,' ')); PropertyConfigurator.configure("./log.properties"); PyApex pythonEntryPoint = new PyApex(); GatewayServer gatewayServer = new GatewayServer(pythonEntryPoint); gatewayServer.start(); LOG.debug("Gateway Server Started"); }

Target:
public static void main(String[] args) { LOG.info("Starting PYAPEX with {}", StringUtils.join(args, ' ')); Options options = new Options(); Option input = new Option("m", "mode", true, "Launch Mode"); input.setRequired(false); options.addOption(input); Option pyfile = new Option("l", "launch-file", true, "Launch file"); pyfile.setRequired(false); options.addOption(pyfile); CommandLineParser parser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { LOG.error("Parsing Exception while parsing arguments",e); formatter.printHelp("utility-name", options); System.exit(1); return; } String launchModeValue = cmd.getOptionValue("mode"); PythonAppManager.LaunchMode mode = launchModeValue != null ? PythonAppManager.LaunchMode.valueOf(launchModeValue) : null; LOG.info("Starting PYAPEX with {}", mode); PyApex pythonEntryPoint = new PyApex(mode); GatewayServer gatewayServer = new GatewayServer(pythonEntryPoint); gatewayServer.start(); LOG.debug("Gateway Server Started"); }
Source:
public Survey createSurvey(Survey survey) { checkNotNull(survey, "Survey cannot be null"); survey.setGuid(BridgeUtils.generateGuid()); for (SurveyElement element : survey.getElements()) { element.setGuid(BridgeUtils.generateGuid()); } Set<String> dataGroups = Collections.emptySet(); if (survey.getStudyIdentifier() != null) { Study study = studyService.getStudy(survey.getStudyIdentifier()); dataGroups = study.getDataGroups(); } Validate.entityThrowingException(new SurveySaveValidator(dataGroups), survey); StudyIdentifier studyId = new StudyIdentifierImpl(survey.getStudyIdentifier()); String existingSurveyGuid = surveyDao.getSurveyGuidForIdentifier(studyId, survey.getIdentifier()); if (existingSurveyGuid != null) { String errMsg = "Survey identifier " + survey.getIdentifier() + " is already used by survey " + existingSurveyGuid; Map<String, Object> entityKeyMap = ImmutableMap.of(KEY_IDENTIFIER, survey.getIdentifier()); throw new EntityAlreadyExistsException(Survey.class, errMsg, entityKeyMap); } return surveyDao.createSurvey(survey); }

Target:
public Survey createSurvey(Survey survey) { checkNotNull(survey, "Survey cannot be null"); if (isNotBlank(survey.getStudyIdentifier()) && isNotBlank(survey.getIdentifier())) { StudyIdentifier studyId = new StudyIdentifierImpl(survey.getStudyIdentifier()); String existingSurveyGuid = surveyDao.getSurveyGuidForIdentifier(studyId, survey.getIdentifier()); if (existingSurveyGuid != null) { String errMsg = "Survey identifier " + survey.getIdentifier() + " is already used by survey " + existingSurveyGuid; Map<String, Object> entityKeyMap = ImmutableMap.of(KEY_IDENTIFIER, survey.getIdentifier()); throw new EntityAlreadyExistsException(Survey.class, errMsg, entityKeyMap); } } survey.setGuid(BridgeUtils.generateGuid()); for (SurveyElement element : survey.getElements()) { element.setGuid(BridgeUtils.generateGuid()); } Set<String> dataGroups = Collections.emptySet(); if (survey.getStudyIdentifier() != null) { Study study = studyService.getStudy(survey.getStudyIdentifier()); dataGroups = study.getDataGroups(); } Validate.entityThrowingException(new SurveySaveValidator(dataGroups), survey); return surveyDao.createSurvey(survey); }
Source:
protected void drawAll(Canvas canvas, int multilineWidth) { if (text.get() == null) { text.set(""); } if (text.get().equals("") && linesOfText == null) { text.set(hintText); isShowingHintText = true; } if (isShowingHintText) { setCursorPosition(0); if (!text.get().equals(hintText) && text.get().endsWith(hintText)) { text.set(text.get().substring(0, text.get().length() - hintText.length())); setCursorPosition(text.get().length()); isShowingHintText = false; } } lastFont = canvas.getCurrentStyle().getFont(); correctCursor(); String textToDraw = passwordMode ? buildPasswordString() : getText(); int widthForDraw = (multiline) ? multilineWidth : lastFont.getWidth(textToDraw); try (SubRegion ignored = canvas.subRegion(canvas.getRegion(), true); SubRegion ignored2 = canvas.subRegion(Rect2i.createFromMinAndSize(-offset, 0, widthForDraw + 1, Integer.MAX_VALUE), false)) { if (isShowingHintText && !readOnly) { canvas.drawTextRaw(textToDraw, lastFont, canvas.getCurrentStyle().getHintTextColor(), canvas.getRegion()); } else { canvas.drawText(textToDraw, canvas.getRegion()); } if (isFocused()) { if (hasSelection()) { drawSelection(canvas); } else { drawCursor(canvas); } } } }

Target:
protected void drawAll(Canvas canvas, int multilineWidth) { if (text.get() == null) { text.set(""); } if (text.get().equals("") && linesOfText.length > 0) { text.set(hintText); isShowingHintText = true; } if (isShowingHintText) { setCursorPosition(0); if (!text.get().equals(hintText) && text.get().endsWith(hintText)) { text.set(text.get().substring(0, text.get().length() - hintText.length())); setCursorPosition(text.get().length()); isShowingHintText = false; } } lastFont = canvas.getCurrentStyle().getFont(); correctCursor(); String textToDraw = passwordMode ? buildPasswordString() : getText(); int widthForDraw = (multiline) ? multilineWidth : lastFont.getWidth(textToDraw); try (SubRegion ignored = canvas.subRegion(canvas.getRegion(), true); SubRegion ignored2 = canvas.subRegion(Rect2i.createFromMinAndSize(-offset, 0, widthForDraw + 1, Integer.MAX_VALUE), false)) { if (isShowingHintText && !readOnly) { canvas.drawTextRaw(textToDraw, lastFont, canvas.getCurrentStyle().getHintTextColor(), canvas.getRegion()); } else { canvas.drawText(textToDraw, canvas.getRegion()); } if (isFocused()) { if (hasSelection()) { drawSelection(canvas); } else { drawCursor(canvas); } } } }
Source:
public static FileformatInterface parsePicaFormat(Node pica, PrefsInterface prefs) throws ReadException, PreferencesException, TypeNotAllowedForParentException { PicaPlusInterface pp = UghImplementation.INSTANCE.createPicaPlus(prefs); pp.read(pica); DigitalDocumentInterface dd = pp.getDigitalDocument(); FileformatInterface ff = UghImplementation.INSTANCE.createXStream(prefs); ff.setDigitalDocument(dd); DocStructTypeInterface dst = prefs.getDocStrctTypeByName("BoundBook"); DocStructInterface dsBoundBook = dd.createDocStruct(dst); dd.setPhysicalDocStruct(dsBoundBook); return ff; }

Target:
public static FileformatInterface parsePicaFormat(Node pica, PrefsInterface prefs) throws ReadException, PreferencesException { PicaPlusInterface pp = UghImplementation.INSTANCE.createPicaPlus(prefs); pp.read(pica); DigitalDocumentInterface dd = pp.getDigitalDocument(); FileformatInterface ff = UghImplementation.INSTANCE.createXStream(prefs); ff.setDigitalDocument(dd); DocStructTypeInterface dst = prefs.getDocStrctTypeByName("BoundBook"); DocStructInterface dsBoundBook = dd.createDocStruct(dst); dd.setPhysicalDocStruct(dsBoundBook); return ff; }
Source:
private static void accessLocation() { ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { long timeout = LOCATION_ACCESS_TIMEOUT_MILLIS; (new Handler()).postDelayed(() -> sContext.unbindService(this), timeout); } @Override public void onServiceDisconnected(ComponentName name) { } }; Intent testAppService = new Intent(); testAppService.setComponent(new ComponentName(TEST_APP_PKG, TEST_APP_SERVICE)); sContext.bindService(testAppService, connection, BIND_AUTO_CREATE); }

Target:
private static void accessLocation() { sConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { } @Override public void onServiceDisconnected(ComponentName name) { } }; Intent testAppService = new Intent(); testAppService.setComponent(new ComponentName(TEST_APP_PKG, TEST_APP_SERVICE)); sContext.bindService(testAppService, sConnection, BIND_AUTO_CREATE); }
Source:
public void init(ComponentRegistry componentRegistry) { if(f instanceof CommandFunction) componentRegistry.wireDependencies(((CommandFunction)f).getRemappingFunction()); }

Target:
public void init(ComponentRegistry componentRegistry) { if (f instanceof InjectableComponent) { ((InjectableComponent) f).inject(componentRegistry); } }
Source:
public void testReplaceWidgetOnForm() { Form form = new Form(new PropertiesImpl("bar") { }, "foo"); Form nestedForm = new Form(new PropertiesImpl("foo") { }, "bar"); form.addRow(widget(newString("w1"))); form.addColumn(widget(newString("w2"))); form.addRow(widget(nestedForm)); assertEquals(form.getWidget("w2").getRow(), 1); assertEquals(form.getWidget("w2").getOrder(), 2); form.replaceRow("w2", widget(newString("w3"))); assertTrue(form.getWidget("w2") == null); assertEquals(form.getWidget("w3").getRow(), 1); assertEquals(form.getWidget("w3").getOrder(), 2); }

Target:
public void testReplaceWidgetOnForm() { Form form = new Form(new PropertiesWithReplaceables("bar") { }, "foo"); Form nestedForm = new Form(new PropertiesImpl("foo") { }, "bar"); form.addRow(widget(newString("w1"))); form.addColumn(widget(newString("w2"))); form.addRow(widget(nestedForm)); assertEquals(form.getWidget("w2").getRow(), 1); assertEquals(form.getWidget("w2").getOrder(), 2); Widget newWidget = widget(newString("w3")); form.replaceRow("w2", newWidget); assertTrue(form.getWidget("w2") == null); assertEquals(form.getWidget("w3").getRow(), 1); assertEquals(form.getWidget("w3").getOrder(), 2); assertTrue(newWidget.isCallAfter()); assertTrue(newWidget.isCallBeforePresent()); assertFalse(newWidget.isCallBeforeActivate()); assertFalse(newWidget.isCallValidate()); }
Source:
public void testHex() { assertThat(faker.random().hex(8), matchesRegularExpression("^[0-9A-F]{8}$")); }

Target:
public void testHex() { assertThat(randomService.hex(8), matchesRegularExpression("^[0-9A-F]{8}$")); }
Source:
public Model get() { final HttpUriRequest request = new HttpGet(identifier); if (!"".equals(this.fedoraAuth)) { final String creds = this.fedoraUsername + ":" + this.fedoraPassword; LOGGER.debug("Adding BASIC authentication: {}...", creds); final String encoding = new String(Base64.encodeBase64(creds.getBytes())); request.setHeader("Authorization", this.fedoraAuth + " " + encoding); } request.addHeader("Accept", RDF_SERIALIZATION); LOGGER.debug("Retrieving RDF content from: {}...", request.getURI()); try { final HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == SC_OK) { try ( Reader r = new InputStreamReader( response.getEntity().getContent(), "UTF8")) { return createDefaultModel().read(r, "", "N3"); } } else { throw new HttpException(response.getStatusLine().toString()); } } catch (IOException | HttpException e) { throw propagate(e); } }

Target:
public Model get() { final HttpUriRequest request = new HttpGet(identifier); request.addHeader("Accept", RDF_SERIALIZATION); LOGGER.debug("Retrieving RDF content from: {}...", request.getURI()); try { final HttpResponse response = httpClient.execute(request, this.httpContext); if (response.getStatusLine().getStatusCode() == SC_OK) { try ( Reader r = new InputStreamReader( response.getEntity().getContent(), "UTF8")) { return createDefaultModel().read(r, "", "N3"); } } else { throw new HttpException(response.getStatusLine().toString()); } } catch (IOException | HttpException e) { throw propagate(e); } }
Source:
public HeartbeatDispatcher( ISarosSession sarosSession, UISynchronizer uiSynchronizer, ConcurrentDocumentClient cdClient) { this.sarosSession = sarosSession; this.uiSynchronizer = uiSynchronizer; this.clientDocs = cdClient.getJupiterClient().getClientDocs(); }

Target:
public HeartbeatDispatcher( ISarosSession sarosSession, UISynchronizer uiSynchronizer, ConcurrentDocumentClient cdClient) { this.sarosSession = sarosSession; this.uiSynchronizer = uiSynchronizer; this.jupiter = cdClient.getJupiterClient(); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("Entered SsoPostLoginFilter"); HttpServletRequest req = (HttpServletRequest) request; try { String engineSessionId = (String) req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (StringUtils.isEmpty(engineSessionId) && req.getSession(false) != null) { engineSessionId = (String) req.getSession(false).getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } if (StringUtils.isNotEmpty(engineSessionId)) { InitialContext ctx = new InitialContext(); try { String ssoToken = (String) runQuery(VdcQueryType.GetEngineSessionIdToken, engineSessionId, ctx); log.debug("Adding userInfo to session"); DbUser loggedInUser = (DbUser) runQuery(VdcQueryType.GetUserBySessionId, engineSessionId, ctx); req.getSession(true).setAttribute(ATTR_USER_INFO, getUserInfoObject(loggedInUser, ssoToken)); chain.doFilter(request, response); } finally { ctx.close(); } } else { log.info("No sessionId in request or session"); } } catch (Exception ex) { log.error("Unable to get token for engine session {}", ex.getMessage()); } log.debug("Exiting SsoPostLoginFilter"); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("Entered SsoPostLoginFilter"); HttpServletRequest req = (HttpServletRequest) request; try { String engineSessionId = (String) req.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (StringUtils.isEmpty(engineSessionId) && req.getSession(false) != null) { engineSessionId = (String) req.getSession(false). getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } if (StringUtils.isNotEmpty(engineSessionId)) { InitialContext ctx = new InitialContext(); try { String ssoToken = (String) runQuery(VdcQueryType.GetEngineSessionIdToken, engineSessionId, ctx); log.debug("Adding userInfo to session"); DbUser loggedInUser = (DbUser) runQuery(VdcQueryType.GetUserBySessionId, engineSessionId, ctx); req.getSession(true).setAttribute(ATTR_USER_INFO, getUserInfoObject(loggedInUser, ssoToken)); chain.doFilter(request, response); } finally { ctx.close(); } } else { log.info("Missing sessionId in either request or session scope. " + "Please configure SSO properly with SsoPostLoginServlet."); } } catch (Exception ex) { log.error("Unable to get token for engine session {}", ex.getMessage()); } log.debug("Exiting SsoPostLoginFilter"); }
Source:
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_feed, container, false); unbinder = ButterKnife.bind(this, view); feedView.set(coordinator.getCards()); ((AppCompatActivity) getActivity()).setSupportActionBar((Toolbar) view.findViewById(R.id.feed_toolbar)); ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); coordinator.setFeedUpdateListener(new FeedCoordinator.FeedUpdateListener() { @Override public void update(List<Card> cards) { feedView.update(); } }); coordinator.more(app.getSite()); return view; }

Target:
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_feed, container, false); unbinder = ButterKnife.bind(this, view); feedView.set(coordinator.getCards()); if (getCallback() != null) { getCallback().onAddToolbar(toolbar); } coordinator.setFeedUpdateListener(new FeedCoordinator.FeedUpdateListener() { @Override public void update(List<Card> cards) { if (isAdded()) { feedView.update(); } } }); coordinator.more(app.getSite()); return view; }
Source:
private Iterable<HostAndPort> getNodesHostAndPort() { Group group = Iterables.getFirst(getEntity().getGroups(), null); if (group == null) return Lists.newArrayList(); return Iterables.transform(group.getAttribute(CouchbaseCluster.COUCHBASE_CLUSTER_UP_NODES), new Function<Entity, HostAndPort>() { @Nullable @Override public HostAndPort apply(@Nullable Entity input) { return BrooklynAccessUtils.getBrooklynAccessibleAddress(input, input.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); } }); }

Target:
private Iterable<HostAndPort> getNodesHostAndPort() { Group group = Iterables.getFirst(getEntity().getGroups(), null); if (group == null) return Lists.newArrayList(); return Iterables.transform(group.getAttribute(CouchbaseCluster.COUCHBASE_CLUSTER_UP_NODES), new Function<Entity, HostAndPort>() { @Override public HostAndPort apply(Entity input) { return BrooklynAccessUtils.getBrooklynAccessibleAddress(input, input.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); } }); }
Source:
public void removeTokenForOwnerStats(TokenIdent id) { String realOwner = getTokenRealOwner(id); if (tokenOwnerStats.containsKey(realOwner)) { if (tokenOwnerStats.get(realOwner) <= 1) { tokenOwnerStats.remove(realOwner); } else { tokenOwnerStats.put(realOwner, tokenOwnerStats.get(realOwner)-1); } } }

Target:
private void removeTokenForOwnerStats(TokenIdent id) { String realOwner = getTokenRealOwner(id); if (tokenOwnerStats.containsKey(realOwner)) { if (tokenOwnerStats.get(realOwner) <= 1) { tokenOwnerStats.remove(realOwner); } else { tokenOwnerStats.put(realOwner, tokenOwnerStats.get(realOwner)-1); } } }
Source:
public static long skipLines( LogChannelInterface log, InputStreamReader reader, EncodingType encodingType, int fileFormatType, StringBuilder line, int nrLinesToSkip, String regex, long lineNumberInFile ) throws KettleFileException { String[] oGetline = getLine( log, reader, encodingType, fileFormatType, line, regex, lineNumberInFile ); int skipped = 1; while ( oGetline[0] != null && skipped < nrLinesToSkip ) { oGetline = getLine( log, reader, encodingType, fileFormatType, line, regex, Long.parseLong( oGetline[ 1 ] ) ); skipped++; } return Long.parseLong( oGetline[ 1 ] ); }

Target:
public static long skipLines( LogChannelInterface log, InputStreamReader reader, EncodingType encodingType, int fileFormatType, StringBuilder line, int nrLinesToSkip, String regex, long lineNumberInFile ) throws KettleFileException { TextFileLine textFileLine = getLine( log, reader, encodingType, fileFormatType, line, regex, lineNumberInFile ); int skipped = 1; while ( textFileLine.line != null && skipped < nrLinesToSkip ) { textFileLine = getLine( log, reader, encodingType, fileFormatType, line, regex, textFileLine.lineNumber ); skipped++; } return textFileLine.lineNumber; }
Source:
protected void prepare(List<? extends Modification> mods, GlobalTransaction tx) throws CacheLoaderException { if (trace) log.tracef("preparing transaction %s", tx); try { transactionRunner.prepare(new ModificationsTransactionWorker(this, mods)); Transaction txn = currentTransaction.getTransaction(); if (trace) log.tracef("transaction %s == sleepycat transaction %s", tx, txn); txnMap.put(tx, txn); try { ThreadLocal<Object> tl = (ThreadLocal<Object>) ReflectionUtil.getValue(currentTransaction, "localTrans"); tl.remove(); } catch (Exception e) { log.warn("Unable to clean up BerkeleyDB thread locals."); } } catch (Exception e) { throw convertToCacheLoaderException("Problem preparing transaction", e); } }

Target:
protected void prepare(List<? extends Modification> mods, GlobalTransaction tx) throws CacheLoaderException { if (trace) log.tracef("preparing transaction %s", tx); try { transactionRunner.prepare(new ModificationsTransactionWorker(this, mods)); Transaction txn = currentTransaction.getTransaction(); if (trace) log.tracef("transaction %s == sleepycat transaction %s", tx, txn); txnMap.put(tx, txn); try { ThreadLocal<Object> tl = (ThreadLocal<Object>) ReflectionUtil.getValue(currentTransaction, "localTrans"); tl.remove(); } catch (Exception e) { log.warn("Unable to clean up BDBJE transaction thread locals."); throw convertToCacheLoaderException("Unable to clean up BDBJE transaction", e); } } catch (Exception e) { throw convertToCacheLoaderException("Problem preparing transaction", e); } }
Source:
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log.info("consumer has been shutdown unexpectedly: " + consumerTag); if ((this.shutdownHandler != null) && !queue.isCancelled()) { shutdownHandler.handle(sig); } }

Target:
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log.debug("consumer has been shutdown unexpectedly: " + consumerTag); if ((this.shutdownHandler != null) && !queue.isCancelled()) { shutdownHandler.handle(sig); } }
Source:
public String getUuid(AutoGenerationOption autoGenerationOption) { return autoGenerationOption.getIdentifierType().getUuid(); }

Target:
public String getUuid(AutoGenerationOption autoGenerationOption) { return autoGenerationOption.getUuid(); }
Source:
public MultiChannelMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint) throws CreateException { super(connector, flowConstruct, endpoint); asyncConsumersStartup = toBoolean(getProperty(MULE_ASYNC_CONSUMERS_STARTUP, "false")); this.amqpConnector = (AmqpConnector) connector; declarator = new AmqpDeclarer(); numberOfChannels = new AmqpEndpointUtil().getNumberOfChannels(endpoint); }

Target:
public MultiChannelMessageReceiver(Connector connector, FlowConstruct flowConstruct, InboundEndpoint endpoint) throws CreateException { super(connector, flowConstruct, endpoint); asyncConsumersStartup = getBoolean(MULE_ASYNC_CONSUMERS_STARTUP); this.amqpConnector = (AmqpConnector) connector; declarator = new AmqpDeclarer(); numberOfChannels = new AmqpEndpointUtil().getNumberOfChannels(endpoint); }
Source:
private void validateTargetedSequencing(LibraryDilution dilution) { if (!isTargetedSequencingInLibrary(dilution)) { throw new IllegalArgumentException("Dilution Targeted Sequencing not contained in parent library"); } }

Target:
private void validateTargetedSequencing(LibraryDilution dilution) { TargetedSequencing ts = dilution.getTargetedSequencing(); Library library = dilution.getLibrary(); if (ts == null) { if (isTargetedSequencingRequired(library)) { throw new IllegalArgumentException("Targeted sequencing value is required"); } } else { if (!isTargetedSequencingCompatible(ts, library)) { throwTargetedSequencingIncompatible(ts, library.getKitDescriptor()); } } }
Source:
public int getValue() { return intValue; }

Target:
public int getValue() { return id; }
Source:
PartitionId getRandomWritablePartition(String partitionClass, List<PartitionId> partitionsToExclude) { PartitionId selectedPartition = null; PartitionId anyWritablePartition = null; List<PartitionId> partitionsInClass = getPartitionsInClass(partitionClass, true); int workingSize = partitionsInClass.size(); while(true) { if(workingSize == 0) break; int randomIndex = ThreadLocalRandom.current().nextInt(workingSize); PartitionId selected = partitionsInClass.get(randomIndex); if(partitionsToExclude == null || partitionsToExclude.size() == 0 || !partitionsToExclude.contains(selected)) { if (selected.getPartitionState() == PartitionState.READ_WRITE) { anyWritablePartition = selected; if(areAllReplicasForPartitionUp(selected)) { selectedPartition = selected; break; } } } if (randomIndex != workingSize - 1) { partitionsInClass.set(randomIndex, partitionsInClass.get(workingSize - 1)); } workingSize--; } return (selectedPartition == null) ? anyWritablePartition : selectedPartition; }

Target:
PartitionId getRandomWritablePartition(String partitionClass, List<PartitionId> partitionsToExclude) { PartitionId anyWritablePartition = null; List<PartitionId> partitionsInClass = getPartitionsInClass(partitionClass, true); int workingSize = partitionsInClass.size(); while (workingSize > 0) { int randomIndex = ThreadLocalRandom.current().nextInt(workingSize); PartitionId selected = partitionsInClass.get(randomIndex); if (partitionsToExclude == null || partitionsToExclude.size() == 0 || !partitionsToExclude.contains(selected)) { if (selected.getPartitionState() == PartitionState.READ_WRITE) { anyWritablePartition = selected; if(areEnoughReplicasForPartitionUp(selected)) { return selected; } } } if (randomIndex != workingSize - 1) { partitionsInClass.set(randomIndex, partitionsInClass.get(workingSize - 1)); } workingSize--; } return anyWritablePartition; }
Source:
public T produce(CreationalContext<T> ctx) { T context; if (getDelegate() instanceof ContextCreateStrategyInjectionTarget) { context = super.produce(ctx); } else { ContextCreateStrategy contextCreateStrategy = getReference(manager, ContextCreateStrategy.class, extension.getContextCreateStrategy()); ContextCreateAction action = new ContextCreateAction(() -> super.produce(ctx), getAnnotatedClassLoader(annotated)); context = (T) contextCreateStrategy.createCamelContext(action); } if (context.getNameStrategy() instanceof DefaultCamelContextNameStrategy) { context.setNameStrategy(nameStrategy(annotated)); } if (context instanceof DefaultCamelContext) { DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class); adapted.setRegistry(new CdiCamelRegistry(manager)); adapted.setInjector(new CdiCamelInjector(context.getInjector(), manager)); } else { throw new InjectionException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext"); } Set<Annotation> qualifiers = annotated.getAnnotations().stream() .filter(isAnnotationType(Named.class).negate() .and(q -> manager.isQualifier(q.annotationType()))) .collect(toSet()); qualifiers.add(ANY); if (qualifiers.size() == 1) { qualifiers.add(DEFAULT); } qualifiers.retainAll(extension.getObserverEvents()); if (!qualifiers.isEmpty()) { context.getManagementStrategy().addEventNotifier(new CdiEventNotifier(manager, qualifiers)); } return context; }

Target:
public T produce(CreationalContext<T> ctx) { T context = createCamelContextWithTCCL(() -> super.produce(ctx), annotated); if (context.getNameStrategy() instanceof DefaultCamelContextNameStrategy) { context.setNameStrategy(nameStrategy(annotated)); } if (context instanceof DefaultCamelContext) { DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class); adapted.setRegistry(new CdiCamelRegistry(manager)); adapted.setInjector(new CdiCamelInjector(context.getInjector(), manager)); } else { throw new InjectionException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext"); } Set<Annotation> qualifiers = annotated.getAnnotations().stream() .filter(isAnnotationType(Named.class).negate() .and(q -> manager.isQualifier(q.annotationType()))) .collect(toSet()); qualifiers.add(ANY); if (qualifiers.size() == 1) { qualifiers.add(DEFAULT); } qualifiers.retainAll(extension.getObserverEvents()); if (!qualifiers.isEmpty()) { context.getManagementStrategy().addEventNotifier(new CdiEventNotifier(manager, qualifiers)); } return context; }
Source:
public void execute(BasicMessageWithExtraData<ResourcePathDestination> message, WsCommandContext context) throws Exception { ResourcePathDestination request = message.getBasicMessage(); String rawResourcePath = request.getResourcePath(); if (rawResourcePath == null) { throw new IllegalStateException(request.getClass().getName() + ".resourcePath must not be null"); } log.tracef("%s is about to execute the request [%s] ", getClass().getName(), request); CanonicalPath resourcePath = CanonicalPath.fromString(rawResourcePath); String feedId = resourcePath.ids().getFeedId(); try (ConnectionContextFactory ccf = new ConnectionContextFactory(context.getConnectionFactory())) { Endpoint topic = Constants.FEED_COMMAND_QUEUE; ProducerConnectionContext pcc = ccf.createProducerConnectionContext(topic); MessageId mid = new MessageProcessor().send(pcc, message, Collections.singletonMap(Constants.HEADER_FEEDID, feedId)); log.debugf("Message [%s] forwarded to bus endpoint [%s]", request.getClass().getName(), topic.getName()); GenericSuccessResponse response = new GenericSuccessResponse(); response.setMessage("The request has been forwarded to feed [" + feedId + "] (MessageId=" + mid + ")"); BasicMessageWithExtraData<GenericSuccessResponse> result = new BasicMessageWithExtraData<>(response, null); new WebSocketHelper().sendSync(context.getSession(), result); } }

Target:
public void execute(BasicMessageWithExtraData<ResourcePathDestination> message, WsCommandContext context) throws Exception { ResourcePathDestination request = message.getBasicMessage(); String rawResourcePath = request.getResourcePath(); if (rawResourcePath == null) { throw new IllegalStateException(request.getClass().getName() + ".resourcePath must not be null"); } log.tracef("%s is about to execute the request [%s] ", getClass().getName(), request); CanonicalPath resourcePath = CanonicalPath.fromString(rawResourcePath); String feedId = resourcePath.ids().getFeedId(); try (ConnectionContextFactory ccf = new ConnectionContextFactory(context.getConnectionFactory())) { Endpoint endpoint = Constants.FEED_COMMAND_QUEUE; ProducerConnectionContext pcc = ccf.createProducerConnectionContext(endpoint); MessageId mid = new MessageProcessor().send(pcc, message, Collections.singletonMap(Constants.HEADER_FEEDID, feedId)); log.debugf("Message [%s] forwarded to bus endpoint [%s]", request.getClass().getName(), endpoint.getName()); GenericSuccessResponse response = new GenericSuccessResponse(); response.setMessage("The request has been forwarded to feed [" + feedId + "] (MessageId=" + mid + ")"); BasicMessageWithExtraData<GenericSuccessResponse> result = new BasicMessageWithExtraData<>(response, null); new WebSocketHelper().sendSync(context.getSession(), result); } }
Source:
public String getVendorThingID() throws ThingIFException { return thingIfApi.getVendorThingID(); }

Target:
public String getVendorThingID() throws ThingIFException { return this.thingIfApi.getVendorThingID(); }
Source:
public static void checkAnyPermission(AccessControlled ac, Permission[] permissions) { if (permissions == null) { return; } boolean failed = true; for (Permission permission : permissions) { if (ac.hasPermission(permission)) { failed = false; } } if (failed) { ac.checkPermission(permissions[0]); } }

Target:
public static void checkAnyPermission(AccessControlled ac, Permission[] permissions) { if (permissions == null || permissions.length == 0) { return; } ac.checkAnyPermission(permissions); }
Source:
public void testAllDomainsHaveSpaceForNewDisksSuccess() { setUpGeneralValidations(); setUpDiskValidations(); List disksList = getNonEmptyDiskList(); doReturn(disksList).when(cmd).getDisksList(); doReturn(ValidationResult.VALID).when(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); assertTrue(cmd.canDoAction()); verify(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); }

Target:
public void testAllDomainsHaveSpaceForNewDisksSuccess() { setUpGeneralValidations(); setUpDiskValidations(); List<DiskImage> disksList = getNonEmptyDiskList(); doReturn(disksList).when(cmd).getDisksList(); doReturn(ValidationResult.VALID).when(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); CanDoActionTestUtils.runAndAssertCanDoActionSuccess(cmd); verify(multipleStorageDomainsValidator).allDomainsHaveSpaceForNewDisks(disksList); }
Source:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { @SuppressWarnings("unchecked") List<Integer> statusCodes = (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); return statusCodes != null ? statusCodes : Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE); }

Target:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { return (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); }
Source:
public void populateViewCache(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.populateViewCache(rowView, viewCache, value.getSectionHeader()); return; } itemRenderer.populateViewCache(rowView, viewCache, value.getData()); }

Target:
public void populateViewCache(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.populateViewCache(rowView, viewCache, value.getSectionHeader()); } else { itemRenderer.populateViewCache(rowView, viewCache, value.getData()); } }
Source:
public void testYieldProjection() throws Exception { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR)))); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(new SliceArrayBlock(slices.length, slices)); PageProcessorOutput output = pageProcessor.process(SESSION, yieldSignal, inputPage); for (int i = 0; i < columns * 2 - 1; i++) { assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); if (yieldSignal.isSet()) { yieldSignal.reset(); } } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); Block[] blocks = new Block[columns]; Arrays.fill(blocks, new SliceArrayBlock(rows, slices)); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }

Target:
public void testYieldProjection() throws Exception { int rows = 128; int columns = 20; DriverYieldSignal yieldSignal = new DriverYieldSignal(); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), Collections.nCopies(columns, new YieldPageProjection(new InputPageProjection(0, VARCHAR)))); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(new SliceArrayBlock(slices.length, slices)); PageProcessorOutput output = pageProcessor.process(SESSION, yieldSignal, inputPage); for (int i = 0; i < columns - 1; i++) { assertTrue(output.hasNext()); assertNull(output.next().orElse(null)); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); } assertTrue(output.hasNext()); Page actualPage = output.next().orElse(null); assertNotNull(actualPage); assertTrue(yieldSignal.isSet()); yieldSignal.reset(); Block[] blocks = new Block[columns]; Arrays.fill(blocks, new SliceArrayBlock(rows, slices)); Page expectedPage = new Page(blocks); assertPageEquals(Collections.nCopies(columns, VARCHAR), actualPage, expectedPage); assertFalse(output.hasNext()); }
Source:
protected Command getResizeChildrenCommand(ChangeBoundsRequest request) { CompoundCommand result = new CompoundCommand(); result.add(super.getResizeChildrenCommand(request)); TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) getHost()).getEditingDomain(); ShiftEdgeIdentityAnchorOperation operation = new ShiftEdgeIdentityAnchorOperation(request); ICommand command = CommandFactory.createICommand(editingDomain, operation); result.add(new ICommandProxy(command)); return result; }

Target:
protected Command getResizeChildrenCommand(ChangeBoundsRequest request) { Command superCommand = super.getResizeChildrenCommand(request); EditPart host = getHost(); if (host instanceof IGraphicalEditPart) { TransactionalEditingDomain editingDomain = ((IGraphicalEditPart) host).getEditingDomain(); CompositeTransactionalCommand ctc = new CompositeTransactionalCommand(editingDomain, "Resize Children"); ctc.add(new CommandProxy(superCommand)); ShiftEdgeIdentityAnchorOperation operation = new ShiftEdgeIdentityAnchorOperation(request); ICommand command = CommandFactory.createICommand(editingDomain, operation); ctc.add(command); } return superCommand; }
Source:
public void test_fetch_upload_id_finds_file() throws IOException { val dir = new File(getClass().getClassLoader().getResource("fixtures/upload/placeholder-upload-file.txt").getFile()); Optional<String> result = UploadStateStore.fetchUploadId(dir, "valid-upload-id"); if (result.isPresent()) { System.out.println(result.get()); } else { System.out.println("not there"); } assertEquals("this-is-my-uploadId", result.get()); }

Target:
public void test_fetch_upload_id_finds_file() throws IOException { val dir = getTestResourceRoot(); Optional<String> result = UploadStateStore.fetchUploadId(dir, "valid-upload-id"); assertThat(result.get()).isEqualTo("this-is-my-uploadId"); }
Source:
private boolean validateImageAvailability(DiskImage image, Guid imageGroupId) { boolean imageAvailable = false; for (Guid storageDomainId : image.getStorageIds()) { DiskImage fromIrs = null; try { log.debug("Validating that image '{}/{}' is available in storage domain {}.", imageGroupId, image.getImageId(), storageDomainId); fromIrs = (DiskImage) runVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(getStoragePoolId(), storageDomainId, imageGroupId, image.getImageId())).getReturnValue(); } catch (Exception e) { log.debug("Unable to get image info from storage", e); } if (fromIrs == null) { log.warn("Disk image '{}/{}' doesn't exist on storage domain '{}'", imageGroupId, image.getImageId(), storageDomainId); } else { imageAvailable = true; } } return imageAvailable; }

Target:
private boolean validateImageAvailability(DiskImage image, Guid imageGroupId) { boolean imageAvailable = false; for (Guid storageDomainId : image.getStorageIds()) { DiskImage fromIrs = null; try { log.info("Validating that image '{}/{}' is available in storage domain {}.", imageGroupId, image.getImageId(), storageDomainId); fromIrs = (DiskImage) runVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(getStoragePoolId(), storageDomainId, imageGroupId, image.getImageId())).getReturnValue(); } catch (Exception e) { log.debug("Unable to get image info from storage", e); } if (fromIrs == null) { log.warn("Disk image '{}/{}' doesn't exist on storage domain '{}'", imageGroupId, image.getImageId(), storageDomainId); } else if (!imageAvailable) { imageAvailable = true; } } return imageAvailable; }
Source:
UmiAwareMarkDuplicatesWithMateCigarTester(final boolean allowMissingUmis) { this.allowMissingUmis = allowMissingUmis; if(allowMissingUmis) { addArg("ALLOW_MISSING_UMIS=" + allowMissingUmis); } }

Target:
UmiAwareMarkDuplicatesWithMateCigarTester(final boolean allowMissingUmis) { if (allowMissingUmis) { addArg("ALLOW_MISSING_UMIS=" + true); } }
Source:
private void openFileInEditor(FileDiff d) { RevCommit commit; ObjectId blob; ObjectId[] blobs = d.getBlobs(); if (d.getChange().equals(ChangeType.DELETE)) { commit = d.getCommit().getParent(0); blob = blobs[0]; } else { commit = d.getCommit(); blob = blobs[blobs.length - 1]; } try { IFileRevision rev = CompareUtils.getFileRevision(d.getNewPath(), commit, getRepository(), blob); if (rev != null) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(page, rev, new NullProgressMonitor()); } else { String message = NLS.bind( UIText.CommitFileDiffViewer_notContainedInCommit, d .getNewPath(), d.getCommit().getId().getName()); Activator.showError(message, null); } } catch (IOException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } }

Target:
private void openFileInEditor(FileDiff d) { RevCommit commit; ObjectId blob; ObjectId[] blobs = d.getBlobs(); if (d.getChange().equals(ChangeType.DELETE)) { commit = d.getCommit().getParent(0); blob = blobs[0]; } else { commit = d.getCommit(); blob = blobs[blobs.length - 1]; } try { IFileRevision rev = CompareUtils.getFileRevision(d.getNewPath(), commit, getRepository(), blob); if (rev != null) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); EgitUiEditorUtils.openEditor(page, rev, new NullProgressMonitor()); } else { String message = NLS.bind( UIText.CommitFileDiffViewer_notContainedInCommit, d .getNewPath(), commit.getName()); Activator.showError(message, null); } } catch (IOException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } catch (CoreException e) { Activator.logError(UIText.GitHistoryPage_openFailed, e); Activator.showError(UIText.GitHistoryPage_openFailed, null); } }