auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean finish() { if (!fIsVisible) { boolean result = updateViewer(); if (!result) { return false; } } if (fCombo != null) { <START> int fProjectIndex = fCombo.getSelectionIndex(); if (fProjectIndex < 0) { handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_NoProjectSelectedError, null); return false; } IProject project = fProjects.get(fProjectIndex); IFolder traceFolder = project.getFolder(TmfTracesFolder.TRACES_FOLDER_NAME); if (!traceFolder.exists()) { handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_InvalidTracingProject, null); return false; } try { if (project.hasNature(TmfProjectNature.ID)) { TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true); fTmfTraceFolder = projectElement.getTracesFolder(); } } catch (CoreException ex) { handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_InvalidTracingProject, ex); return false; } <END> } Object[] elements = getElementViewer().getCheckedElements(); final RemoteImportTracesOperation importOperation = new RemoteImportTracesOperation(getContainer().getShell(), fTmfTraceFolder, elements, fOverwriteAll); try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { importOperation.run(monitor); monitor.done(); } }); } catch (InvocationTargetException e) { handleError( Messages.TracePackageExtractManifestOperation_ErrorReadingManifest, e); return false; } catch (InterruptedException e) { return false; } IStatus status = importOperation.getStatus(); if (status.getSeverity() == IStatus.ERROR) { handleErrorStatus(status); return false; } disconnectAllRemoteHosts(); return true; }</code><technical_language>this a separate method? I find finish a bit big. I feel strongly this</technical_language>

Target:
public boolean finish() { boolean result; if (!fIsVisible) { result = updateViewer(); if (!result) { return false; } } result = validateProject(); if (!result) { return false; } Object[] elements = getElementViewer().getCheckedElements(); final RemoteImportTracesOperation importOperation = new RemoteImportTracesOperation(getContainer().getShell(), fTmfTraceFolder, elements, fOverwriteAll); try { getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { importOperation.run(monitor); monitor.done(); } }); } catch (InvocationTargetException e) { handleError( Messages.TracePackageExtractManifestOperation_ErrorReadingManifest, e); return false; } catch (InterruptedException e) { return false; } IStatus status = importOperation.getStatus(); if (status.getSeverity() == IStatus.ERROR) { handleErrorStatus(status); return false; } disconnectAllRemoteHosts(); return true; }
Source:
<code>private void sendResponse(HttpServerExchange httpExchange, Exchange camelExchange) throws IOException, NoTypeConversionAvailableException { Object body = getResponseBody(httpExchange, camelExchange); Message answer; <START> if (camelExchange.hasOut()) { <END> answer = camelExchange.getOut(); } else { answer = camelExchange.getIn(); } this.handleNoContent(camelExchange, answer, httpExchange); if (body == null) { log.trace("No payload to send as reply for exchange: {}", camelExchange); httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt")); httpExchange.getResponseSender().send("No response available"); return; } if (getEndpoint().isUseStreaming() && (body instanceof InputStream)) { httpExchange.startBlocking(); try (InputStream input = (InputStream) body; OutputStream output = httpExchange.getOutputStream()) { IOHelper.copy(input, output, IOHelper.DEFAULT_BUFFER_SIZE, true); } } else { TypeConverter tc = getEndpoint().getCamelContext().getTypeConverter(); ByteBuffer bodyAsByteBuffer = tc.mandatoryConvertTo(ByteBuffer.class, body); httpExchange.getResponseSender().send(bodyAsByteBuffer); } }</code><technical_language>I hasOut is deprecated <LINK_0>, I is getMessage instead</technical_language>

Target:
private void sendResponse(HttpServerExchange httpExchange, Exchange camelExchange) throws IOException, NoTypeConversionAvailableException { Object body = getResponseBody(httpExchange, camelExchange); if (body == null) { String message = httpExchange.getStatusCode() == 500 ? "Exception" : "No response available"; log.trace("No payload to send as reply for exchange: {}", camelExchange); httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt")); httpExchange.getResponseSender().send(message); return; } if (getEndpoint().isUseStreaming() && (body instanceof InputStream)) { httpExchange.startBlocking(); try (InputStream input = (InputStream) body; OutputStream output = httpExchange.getOutputStream()) { IOHelper.copy(input, output, IOHelper.DEFAULT_BUFFER_SIZE, true); } } else { TypeConverter tc = getEndpoint().getCamelContext().getTypeConverter(); ByteBuffer bodyAsByteBuffer = tc.mandatoryConvertTo(ByteBuffer.class, body); httpExchange.getResponseSender().send(bodyAsByteBuffer); } }
Source:
<code>public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_gallery_item, container, false); unbinder = ButterKnife.bind(this, rootView); imageView.setOnClickListener(v -> { if (isAdded()) { ((GalleryActivity) requireActivity()).toggleControls(); } }); <START> imageView.setOnMatrixChangeListener(rect -> ((GalleryActivity) requireActivity()).setViewPagerEnabled(imageView.getScale() <= 1f)); <END> return rootView; }</code><technical_language>Adding a check for this listener? Caused by: java.lang.NullPointerException: Attempt invoke virtual method 'float com.github.chrisbanes.photoview.PhotoView.getScale()' a null object reference org.wikipedia.gallery.GalleryItemFragment.lambda$onCreateView$1$GalleryItemFragment(GalleryItemFragment.java:128) org.wikipedia.gallery.-$$Lambda$GalleryItemFragment$IT7mfODMYoIdODz3RDiJxJ5SW2c.onMatrixChanged(Unknown Source:2)</technical_language>

Target:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_gallery_item, container, false); unbinder = ButterKnife.bind(this, rootView); imageView.setOnClickListener(v -> { if (isAdded()) { ((GalleryActivity) requireActivity()).toggleControls(); } }); imageView.setOnMatrixChangeListener(rect -> { if (!isAdded() || imageView == null) { return; } ((GalleryActivity) requireActivity()).setViewPagerEnabled(imageView.getScale() <= 1f); }); return rootView; }
Source:
<code>public void setGlowing(Boolean glow) { <START> if(ReflectionUtils.hasMethod(e.getClass(), "setGlowing", null)) { END> e.setGlowing(glow); } }</code><technical_language>(glowing methods) added day 1 of 1.9 builds, check is required here</technical_language>

Target:
public void setGlowing(Boolean glow) { e.setGlowing(glow); }
Source:
<code>private List<HiddenFile> readFromJsonFile() { String jsonTxt = readPayloadsFile(); if (jsonTxt.isEmpty()) { return new ArrayList<>(); } try { JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt); JSONArray files = json.getJSONArray("files"); List<HiddenFile> hiddenFiles = new ArrayList<>(); for (int i = 0; i < files.size(); i++) { JSONObject hiddenFileObject = files.getJSONObject(i); HiddenFile hiddenFile = new HiddenFile( hiddenFileObject.getString("path"), getList(hiddenFileObject.getJSONArray("content")), <START> getList(hiddenFileObject.getJSONArray("not_content")), <END> hiddenFileObject.getString("bin_regex"), getList(hiddenFileObject.getJSONArray("links")), hiddenFileObject.getString("type")); hiddenFiles.add(hiddenFile); if (LOG.isDebugEnabled()) { LOG.debug( "File to be located: " + hiddenFile.getPath() + " Content: " + hiddenFile.getContent()); } } return hiddenFiles; } catch (JSONException jEx) { LOG.warn( "Failed to parse " + getName() + " payloads file due to JSON parsing issue. " + jEx.getMessage(), jEx); return new ArrayList<>(); } }</code><technical_language>This optional (same for other fields required), add properties entries</technical_language>

Target:
private List<HiddenFile> readFromJsonFile() { String jsonTxt = readPayloadsFile(); if (jsonTxt.isEmpty()) { return new ArrayList<>(); } try { JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt); JSONArray files = json.getJSONArray("files"); List<HiddenFile> hiddenFiles = new ArrayList<>(); for (int i = 0; i < files.size(); i++) { JSONObject hiddenFileObject = files.getJSONObject(i); HiddenFile hiddenFile = new HiddenFile( hiddenFileObject.getString("path"), getOptionalList(hiddenFileObject, "content"), getOptionalList(hiddenFileObject, "not_content"), getOptionalString(hiddenFileObject, "binary"), getOptionalList(hiddenFileObject, "links"), getOptionalString(hiddenFileObject, "type")); hiddenFiles.add(hiddenFile); if (LOG.isDebugEnabled()) { LOG.debug( "File to be located: " + hiddenFile.getPath() + " Content: " + hiddenFile.getContent()); } } return hiddenFiles; } catch (JSONException jEx) { LOG.warn( "Failed to parse " + getName() + " payloads file due to JSON parsing issue. " + jEx.getMessage(), jEx); return new ArrayList<>(); } }
Source:
<code>public void testUniqueIpFilterHandler() throws ExecutionException, InterruptedException { final CyclicBarrier barrier = new CyclicBarrier(2); <START> ExecutorService executorService = Executors.newFixedThreadPool(2); <END> for (int round = 0; round < 10000; round++) { System.out.println("round = " + round); final UniqueIpFilter handler = new UniqueIpFilter(); java.util.concurrent.Future<EmbeddedChannel> future1 = submit(handler, barrier, executorService); java.util.concurrent.Future<EmbeddedChannel> future2 = submit(handler, barrier, executorService); EmbeddedChannel channel1 = future1.get(); EmbeddedChannel channel2 = future2.get(); Assert.assertTrue(channel1.isActive() || channel2.isActive()); Assert.assertFalse(channel1.isActive() && channel2.isActive()); barrier.reset(); channel1.close().await(); channel2.close().await(); } }</code><technical_language>shutdown pool in a finally block</technical_language>

Target:
public void testUniqueIpFilterHandler() throws ExecutionException, InterruptedException { final CyclicBarrier barrier = new CyclicBarrier(2); ExecutorService executorService = Executors.newFixedThreadPool(2); try { for (int round = 0; round < 10000; round++) { final UniqueIpFilter ipFilter = new UniqueIpFilter(); Future<EmbeddedChannel> future1 = newChannelAsync(barrier, executorService, ipFilter); Future<EmbeddedChannel> future2 = newChannelAsync(barrier, executorService, ipFilter); EmbeddedChannel ch1 = future1.get(); EmbeddedChannel ch2 = future2.get(); Assert.assertTrue(ch1.isActive() || ch2.isActive()); Assert.assertFalse(ch1.isActive() && ch2.isActive()); barrier.reset(); ch1.close().await(); ch2.close().await(); } } finally { executorService.shutdown(); } }
Source:
<code>public String getLocalNameFromDelegate( AbstractLiteralIV<BigdataLiteral, ?> delegate) { final BigInteger bigintVal; if (delegate instanceof XSDIntegerIV) { bigintVal = ((XSDIntegerIV<?>)delegate).getInlineValue(); } else { final String intStr = super.getLocalNameFromDelegate(delegate); bigintVal = new BigInteger(intStr, 10); } String <START> localName = <END> toFixedWidthHexString(bigintVal); return localName; }</code><technical_language>localName inlined</technical_language>

Target:
public String getLocalNameFromDelegate( AbstractLiteralIV<BigdataLiteral, ?> delegate) { final BigInteger bigintVal; if (delegate instanceof XSDIntegerIV) { bigintVal = ((XSDIntegerIV<?>)delegate).getInlineValue(); } else { final String intStr = super.getLocalNameFromDelegate(delegate); bigintVal = new BigInteger(intStr, 10); } return toFixedWidthHexString(bigintVal); }
Source:
<code>public ServiceBuilder<ChannelFactory> build(ServiceTarget target) { Value<ChannelFactory> value = () -> new JChannelFactory(this); ServiceBuilder<ChannelFactory> builder = target.addService(this.getServiceName(), new ValueService<>(value)) .addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, this.environment) .setInitialMode(ServiceController.Mode.ON_DEMAND); for (ValueDependency<ProtocolConfiguration> protocol : protocols) { <START> if (protocol != null) protocol.register(builder); <END> } if (transport != null) transport.register(builder); if (relay != null) relay.register(builder); return builder; }</code><technical_language>This conditional is unnecessary. List element is null</technical_language>

Target:
public ServiceBuilder<ChannelFactory> build(ServiceTarget target) { Value<ChannelFactory> value = () -> new JChannelFactory(this); ServiceBuilder<ChannelFactory> builder = target.addService(this.getServiceName(), new ValueService<>(value)) .addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, this.environment) .setInitialMode(ServiceController.Mode.ON_DEMAND); for (ValueDependency<ProtocolConfiguration> protocol : protocols) { protocol.register(builder); } transport.register(builder); if (relay != null) relay.register(builder); return builder; }
Source:
<code>private static void loadTemplateSpecLazily() { if (caseDbSpecTemplate == null) { try { caseDbSpecTemplate = FormLoadingUtils.xmlToTreeElement("/casedb_instance_structure.xml"); } catch (InvalidStructureException e) { throw new RuntimeException("Failed to load casedb template spec"); } catch (IOException e) { <START> throw new RuntimeException("Failed to load casedb template spec"); <END> } } }</code><technical_language>agree. I this error very, explanatory people expect happen here</technical_language>

Target:
private static synchronized void loadTemplateSpecLazily() { final String errorMsg = TAG + ": Failed to load casedb template spec xml file " + "while checking if case related xpath follows the template structure."; if (caseDbSpecTemplate == null) { try { caseDbSpecTemplate = FormLoadingUtils.xmlToTreeElement("/casedb_instance_structure.xml"); } catch (InvalidStructureException e) { throw new RuntimeException(errorMsg); } catch (IOException e) { throw new RuntimeException(errorMsg); } } }
Source:
<code>public EvaluationResult evaluate(Trade trade, String firstToken, List<String> remainingTokens) { MetaBean metaBean = JodaBeanUtils.metaBean(trade.getClass()); Optional<String> tradePropertyName = metaBean.metaPropertyMap().keySet().stream() .filter(p -> p.equalsIgnoreCase(firstToken)) .findFirst(); if (tradePropertyName.isPresent()) { Object propertyValue = metaBean.metaProperty(tradePropertyName.get()).get((Bean) trade); return propertyValue != null ? EvaluationResult.success(propertyValue, remainingTokens) : EvaluationResult.failure("Property '{}' not set", firstToken); } Optional<String> tradeInfoPropertyName = trade.getInfo().propertyNames().stream() .filter(p -> p.equalsIgnoreCase(firstToken)) .findFirst(); if (tradeInfoPropertyName.isPresent()) { Object propertyValue = trade.getInfo().property(tradeInfoPropertyName.get()).get(); <START> return propertyValue != null ? EvaluationResult.success(propertyValue, remainingTokens) <END> : EvaluationResult.failure("Property '{}' not set", firstToken); } return invalidTokenFailure(trade, firstToken); }</code><technical_language>formatting easier understand</technical_language>

Target:
public EvaluationResult evaluate(Trade trade, String firstToken, List<String> remainingTokens) { MetaBean metaBean = JodaBeanUtils.metaBean(trade.getClass()); Optional<String> tradePropertyName = metaBean.metaPropertyMap().keySet().stream() .filter(p -> p.equalsIgnoreCase(firstToken)) .findFirst(); if (tradePropertyName.isPresent()) { Object propertyValue = metaBean.metaProperty(tradePropertyName.get()).get((Bean) trade); if (propertyValue == null) { return EvaluationResult.failure("Property '{}' not set", firstToken); } return EvaluationResult.success(propertyValue, remainingTokens); } Optional<String> tradeInfoPropertyName = trade.getInfo().propertyNames().stream() .filter(p -> p.equalsIgnoreCase(firstToken)) .findFirst(); if (tradeInfoPropertyName.isPresent()) { Object propertyValue = trade.getInfo().property(tradeInfoPropertyName.get()).get(); if (propertyValue == null) { return EvaluationResult.failure("Property '{}' not set", firstToken); } return EvaluationResult.success(propertyValue, remainingTokens); } return invalidTokenFailure(trade, firstToken); }
Source:
<code>public INDArray preOutput(boolean training) { applyDropOutIfNecessary(training); INDArray b = getParam(DefaultParamInitializer.BIAS_KEY); INDArray W = getParam(DefaultParamInitializer.WEIGHT_KEY); if ( input.columns() != W.columns()) { throw new DL4JInvalidInputException( "Input size (" + input.columns() + " columns; shape = " + Arrays.toString(input.shape()) + ") is invalid: does not match layer input size (layer # inputs = " + W.shapeInfoToString() + ") " + layerId()); } if (conf.isUseDropConnect() && training && layerConf().getDropOut() > 0) { <START> W = Dropout.applyDropConnect(this, DefaultParamInitializer.WEIGHT_KEY); <END> } INDArray ret = Nd4j.zeros(input.rows(),input.columns()); for(int row = 0; row<input.rows();row++){ ret.put(new INDArrayIndex[]{NDArrayIndex.point(row), NDArrayIndex.all()},input.getRow(row).mul(W).addRowVector(b)); } if (maskArray != null) { applyMask(ret); } return ret; }</code><technical_language>This dropout section is obsolete. Replace if statement content applyDropOutIfNecessary(training);</technical_language>

Target:
public INDArray preOutput(boolean training) { INDArray b = getParam(DefaultParamInitializer.BIAS_KEY); INDArray W = getParam(DefaultParamInitializer.WEIGHT_KEY); if ( input.columns() != W.columns()) { throw new DL4JInvalidInputException( "Input size (" + input.columns() + " columns; shape = " + Arrays.toString(input.shape()) + ") is invalid: does not match layer input size (layer # inputs = " + W.shapeInfoToString() + ") " + layerId()); } applyDropOutIfNecessary(training); INDArray ret = Nd4j.zeros(input.rows(),input.columns()); for(int row = 0; row<input.rows();row++){ ret.put(new INDArrayIndex[]{NDArrayIndex.point(row), NDArrayIndex.all()},input.getRow(row).mul(W).addRowVector(b)); } if (maskArray != null) { applyMask(ret); } return ret; }
Source:
<code>public Iterator iterator() { <START> queries.addAll(TestContext.getSessions().stream().map(s -> new HttpGet(uri + "/" + s.getId())).collect(Collectors.toList())); <END> return queries.iterator(); }</code><technical_language>propose populate queries in constructor init method</technical_language>

Target:
public Iterator iterator() { if (queries.isEmpty()) { queries.addAll(TestContext .getSessions() .stream() .map(s -> new JHttpQuery<String>().get().responseBodyType(SessionEntity.class).path(uri + "/" + s.getId())) .collect(Collectors.toList())); } return queries.iterator(); }
Source:
<code>public Object getAdapter( Object adaptableObject, Class adapterType ) { Object molecule = null; if ( adaptableObject instanceof SMILESMolecule ) { SMILESMolecule mol = (SMILESMolecule) adaptableObject; <START> if (adapterType.equals( SMILESMolecule.class )) { <END> try { molecule = Activator.getDefault() .getJavaCDKManager().fromSMILES( mol.toSMILES() ); } catch ( BioclipseException e ) { logger.debug( LogUtils.traceStringOf( e )); return null; } } } if(molecule !=null &&adapterType.isAssignableFrom( molecule.getClass())) return molecule; return null; }</code><technical_language>ICDKMolecule instead of SMILESMolecule adapterType is class is asked for in this case ICDKMolecule in plugin.xml</technical_language>

Target:
public Object getAdapter( Object adaptableObject, Class adapterType ) { Object molecule = null; if ( adaptableObject instanceof SMILESMolecule ) { SMILESMolecule mol = (SMILESMolecule) adaptableObject; if (adapterType.equals( ICDKMolecule.class )) { try { molecule = Activator.getDefault() .getJavaCDKManager().fromSMILES( mol.toSMILES() ); } catch ( BioclipseException e ) { logger.debug( LogUtils.traceStringOf( e )); return null; } } } if(molecule !=null &&adapterType.isAssignableFrom( molecule.getClass())) return molecule; return null; }
Source:
<code><START> public @NotNull Connection.Direction getPreferredDirection() { <END> return preferredDirection; }</code><technical_language>evidence this non-null (though might've original intent)</technical_language>

Target:
public Connection.Direction getPreferredDirection() { return preferredDirection; }
Source:
<code>public static void main(String[] args) throws Exception { log.info("Starting Azkaban Server"); if (args.length == 0) { <START> final File templateFolder = new File("test/local-conf-templates"); <END> final File localConfFolder = new File("local"); if (!localConfFolder.exists()) { FileUtils.copyDirectory(templateFolder, localConfFolder); log.info("Copied local conf templates from " + templateFolder.getAbsolutePath()); } log.info("Using conf at " + localConfFolder.getAbsolutePath() + "/conf"); args = new String[]{"-conf", "local/conf"}; } final Props props = AzkabanServer.loadProps(args); if (props == null) { log.error("Properties not found. Need it to connect to the db."); log.error("Exiting..."); return; } if (props.getBoolean(AzkabanDatabaseSetup.DATABASE_CHECK_VERSION, true)) { final boolean updateDB = props .getBoolean(AzkabanDatabaseSetup.DATABASE_AUTO_UPDATE_TABLES, true); final String scriptDir = props.getString(AzkabanDatabaseSetup.DATABASE_SQL_SCRIPT_DIR, "sql"); AzkabanDatabaseUpdater.runDatabaseUpdater(props, scriptDir, updateDB); } final Injector injector = Guice.createInjector( new AzkabanCommonModule(props), new AzkabanWebServerModule(), new AzkabanExecServerModule() ); SERVICE_PROVIDER.setInjector(injector); injector.getInstance(AzkabanSingleServer.class).launch(); }</code><technical_language>Put this logic in a separate method</technical_language>

Target:
public static void main(String[] args) throws Exception { log.info("Starting Azkaban Server"); if (args.length == 0) { args = prepareDefaultConf(); } final Props props = AzkabanServer.loadProps(args); if (props == null) { log.error("Properties not found. Need it to connect to the db."); log.error("Exiting..."); return; } if (props.getBoolean(AzkabanDatabaseSetup.DATABASE_CHECK_VERSION, true)) { final boolean updateDB = props .getBoolean(AzkabanDatabaseSetup.DATABASE_AUTO_UPDATE_TABLES, true); final String scriptDir = props.getString(AzkabanDatabaseSetup.DATABASE_SQL_SCRIPT_DIR, "sql"); AzkabanDatabaseUpdater.runDatabaseUpdater(props, scriptDir, updateDB); } final Injector injector = Guice.createInjector( new AzkabanCommonModule(props), new AzkabanWebServerModule(), new AzkabanExecServerModule() ); SERVICE_PROVIDER.setInjector(injector); injector.getInstance(AzkabanSingleServer.class).launch(); }
Source:
<code>public void should_discard_generics_metadata_when_serialized_then_disabling_deep_stubs_with_generics() throws Exception { ListContainer deep_stubbed = mock(ListContainer.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); when(deep_stubbed.iterator().hasNext()).thenReturn(true); ListContainer deserialized_deep_stub = serializeAndBack(deep_stubbed); try { when(deserialized_deep_stub.iterator().next().get(42)).thenReturn("no"); <START> fail("Expected an exception to be thrown as deep stubs and serialization does not play well together"); <END> } catch (ClassCastException e) { assertThat(e).hasMessageContaining("cannot be cast to java.util.List"); } }</code><technical_language>This is a regression. throw a CCE here? If not, re-introducing #357</technical_language>

Target:
public void should_discard_generics_metadata_when_serialized_then_disabling_deep_stubs_with_generics() throws Exception { ListContainer deep_stubbed = mock(ListContainer.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); when(deep_stubbed.iterator().hasNext()).thenReturn(true); ListContainer deserialized_deep_stub = serializeAndBack(deep_stubbed); try { when(deserialized_deep_stub.iterator().next().get(42)).thenReturn("no"); fail("Expected an exception to be thrown as deep stubs and serialization does not play well together"); } catch (NullPointerException e) { assertThat(e).hasMessage(null); } }
Source:
<code>private Component safetyGetComponentAt(final Container root, final int x, final int y){ if (!root.isVisible() || !root.contains(x, y)) { return null; } <START> List<Component> children = root.getChildrenAsList(true); <END> if (root.getLayout() instanceof LayeredLayout){ Collections.reverse(children); } for (Component currComponent : children) { if (currComponent.contains(x, y)) { if (!currComponent.isBlockLead() && currComponent instanceof Container) { currComponent = safetyGetComponentAt((Container)currComponent, x, y); } if (currComponent != null && currComponent.isVisible() && currComponent.isEnabled()) { return currComponent; } } } if (root.isEnabled() && (root.isFocusable() || root.isGrabsPointerEvents() || root.isDraggable())){ return root; } return null; }</code><technical_language>This is a bit expensive allocates array list for entry. drag events fire quickly impact performance need fast/low level APIs ideally trigger allocations. I suggest like: java int componentCount = getComponentCount(); int staringPoint = 0; int endPoint = componentCount; int direction = 1; if(root.getLayout() instanceof LayeredLayout){ direction = -1; endPoint = -1; staringPoint = componentCount - 1; } for(int iter = startingPoint ; iter != endPoint ; iter += direction) { Component currComponent = root.getComponentAt(iter); // ... }</technical_language>

Target:
private Component safetyGetComponentAt(final Container root, final int x, final int y){ if (!root.isVisible() || !root.contains(x, y)) { return null; } List<Component> children = root.getChildrenAsList(true); if (root.getLayout() instanceof LayeredLayout){ Collections.reverse(children); } int componentCount = root.getComponentCount(); int startingPoint = 0; int endPoint = componentCount; int direction = 1; if(root.getLayout() instanceof LayeredLayout){ direction = -1; endPoint = -1; startingPoint = componentCount - 1; } for(int iter = startingPoint ; iter != endPoint ; iter += direction) { Component currComponent = root.getComponentAt(iter); if (currComponent.contains(x, y)) { if (!currComponent.isBlockLead() && currComponent instanceof Container) { currComponent = safetyGetComponentAt((Container)currComponent, x, y); } if (currComponent != null && currComponent.isVisible() && currComponent.isEnabled()) { return currComponent; } } } if (root.isEnabled() && (root.isFocusable() || root.isGrabsPointerEvents() || root.isDraggable())){ return root; } return null; }
Source:
<code>protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: LOG.info("Reconnecting to Redis in response to exception", ex); final int reconAttempts = getReconnectAttempts(); if (!JedisUtils.reconnect(this.jedis, reconAttempts, RECONNECT_SLEEP_TIME)) { LOG.warn("Terminating in response to exception after " + reconAttempts + " to reconnect", ex); end(false); } else { authenticateAndSelectDB(); LOG.info("Reconnected to Redis"); try { loadRedisScripts(); } catch (IOException e) { <START> LOG.error("Failed to load redis scripts", e); <END> } } break; case TERMINATE: LOG.warn("Terminating in response to exception", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy + " while attempting to recover from the following exception; worker proceeding...", ex); break; } }</code><technical_language>Failed reload Lua scripts reconnect</technical_language>

Target:
protected void recoverFromException(final String curQueue, final Exception ex) { final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, ex, curQueue); switch (recoveryStrategy) { case RECONNECT: LOG.info("Reconnecting to Redis in response to exception", ex); final int reconAttempts = getReconnectAttempts(); if (!JedisUtils.reconnect(this.jedis, reconAttempts, RECONNECT_SLEEP_TIME)) { LOG.warn("Terminating in response to exception after " + reconAttempts + " to reconnect", ex); end(false); } else { authenticateAndSelectDB(); LOG.info("Reconnected to Redis"); try { loadRedisScripts(); } catch (IOException e) { LOG.error("Failed to reload Lua scripts after reconnect", e); } } break; case TERMINATE: LOG.warn("Terminating in response to exception", ex); end(false); break; case PROCEED: this.listenerDelegate.fireEvent(WORKER_ERROR, this, curQueue, null, null, null, ex); break; default: LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy + " while attempting to recover from the following exception; worker proceeding...", ex); break; } }
Source:
<code>public void consolidate() throws IOException { if (getSnapshotFormat(desc) == SnapshotManifestV1.DESCRIPTOR_VERSION) { LOG.info("Using old Snapshot Format"); FSTableDescriptors.createTableDescriptorForTableDirectory(workingDirFs, workingDir, htd, false); } else { <START> LOG.debug("Convert to Single Snapshot Manifest for " + this.desc.getName()); <END> convertToV2SingleManifest(); } }</code><technical_language>nit: parameterized logging</technical_language>

Target:
public void consolidate() throws IOException { if (getSnapshotFormat(desc) == SnapshotManifestV1.DESCRIPTOR_VERSION) { LOG.info("Using old Snapshot Format"); FSTableDescriptors.createTableDescriptorForTableDirectory(workingDirFs, workingDir, htd, false); } else { LOG.debug("Convert to Single Snapshot Manifest for {}", this.desc.getName()); convertToV2SingleManifest(); } }
Source:
<code>public synchronized void persist(String key, String value) { if (!loadFromFile(_file)) { <START> s_logger.warn("Failed to load changes and then write to them"); <END> } _properties.setProperty(key, value); FileOutputStream output = null; try { output = new FileOutputStream(_file); _properties.store(output, _name); output.flush(); output.close(); } catch (IOException e) { s_logger.error("Uh-oh: ", e); } finally { IOUtils.closeQuietly(output); } }</code><technical_language>loadFromFile allready logs errors failures. is this warn (all) want do here? expect a return a throw of some sort</technical_language>

Target:
public synchronized void persist(String key, String value) { if (!loadFromFile(_file)) { s_logger.error("Failed to load changes and then write to them"); } _properties.setProperty(key, value); FileOutputStream output = null; try { output = new FileOutputStream(_file); _properties.store(output, _name); output.flush(); output.close(); } catch (IOException e) { s_logger.error("Uh-oh: ", e); } finally { IOUtils.closeQuietly(output); } }
Source:
<code><START> protected void setFontForHeight(int pixels, GC gc) { <END> int height = Math.max(pixels * PPI / DPI, 1); Font font = fFonts.computeIfAbsent(height, fontHeight -> { FontData fontData = gc.getFont().getFontData()[0]; fontData.setHeight(fontHeight); return new Font(gc.getDevice(), fontData); }); gc.setFont(font); }</code><technical_language>I if this API is good enough, consider vertical zooming (Ctrl+PLUS Ctrl+MINUS). entry's font is set, rely height vary due vertical zooming. need is a maximum font height for time graph control (for tall entries and/or large vertical zoom). this handled internally (as a bug fix/improvement) need a new API. a good maximum font height though, need configurable</technical_language>

Target:
protected void setFontForHeight(int pixels, GC gc) { int height = Math.max(pixels * PPI / DPI, 1); Font font = getCachedFont(height, fontHeight -> { FontData fontData = gc.getFont().getFontData()[0]; fontData.setHeight(fontHeight); return new Font(gc.getDevice(), fontData); }); gc.setFont(font); }
Source:
<code>public void start() { Duration[] defaultLatchIntervals = {Duration.apply(1, TimeUnit.MINUTES)}; @SuppressWarnings("deprecation") AdminServiceFactory adminServiceFactory = new AdminServiceFactory( this.mPort, 20, List$.MODULE$.<StatsFactory>empty(), Option.<String>empty(), List$.MODULE$.<Regex>empty(), <START> new Map.Map1<>("/prometheus", new PrometheusHandler()), <END> JavaConversions .asScalaBuffer(Arrays.asList(defaultLatchIntervals)).toList() ); RuntimeEnvironment runtimeEnvironment = new RuntimeEnvironment(this); adminServiceFactory.apply(runtimeEnvironment); try { Properties properties = new Properties(); properties.load(this.getClass().getResource("build.properties").openStream()); String buildRevision = properties.getProperty("build_revision", "unknown"); LOG.info("build.properties build_revision: {}", properties.getProperty("build_revision", "unknown")); StatsUtil.setLabel("secor.build_revision", buildRevision); } catch (Throwable t) { LOG.error("Failed to load properties from build.properties", t); } }</code><technical_language>this line conditioned prometheus is enabled</technical_language>

Target:
public void start() { Duration[] defaultLatchIntervals = {Duration.apply(1, TimeUnit.MINUTES)}; Map<String, CustomHttpHandler> handlers = mPrometheusEnabled ? new Map.Map1<>("/prometheus", new PrometheusHandler()) : Map$.MODULE$.empty(); @SuppressWarnings("deprecation") AdminServiceFactory adminServiceFactory = new AdminServiceFactory( this.mPort, 20, List$.MODULE$.<StatsFactory>empty(), Option.<String>empty(), List$.MODULE$.<Regex>empty(), handlers, JavaConversions .asScalaBuffer(Arrays.asList(defaultLatchIntervals)).toList() ); RuntimeEnvironment runtimeEnvironment = new RuntimeEnvironment(this); adminServiceFactory.apply(runtimeEnvironment); try { Properties properties = new Properties(); properties.load(this.getClass().getResource("build.properties").openStream()); String buildRevision = properties.getProperty("build_revision", "unknown"); LOG.info("build.properties build_revision: {}", properties.getProperty("build_revision", "unknown")); StatsUtil.setLabel("secor.build_revision", buildRevision); } catch (Throwable t) { LOG.error("Failed to load properties from build.properties", t); } }
Source:
<code>private Optional<OperatingSystem> tryExtractOperatingSystemFrom(VirtualGuestBlockDeviceTemplateGroup image) { return FluentIterable.from(image.getChildren()) .transformAndConcat(new BlockDeviceTemplateGroupToBlockDeviceTemplateIterable()) .filter(new IsBootableDevice()) .transformAndConcat(new VirtualGuestBlockDeviceTemplateIterableFunction()) .transform(new DiskImageSoftwareToSoftwareDescription()) .filter(new IsOperatingSystem()) <START> .transform(new SoftwareDescriptionToOperatingSystem(image.getGlobalIdentifier())) <END> .first(); }</code><technical_language>Do functions passed need instantiated time? a singleton for them</technical_language>

Target:
private Optional<OperatingSystem> tryExtractOperatingSystemFrom(VirtualGuestBlockDeviceTemplateGroup image) { return FluentIterable.from(image.getChildren()) .transformAndConcat(new BlockDeviceTemplateGroupToBlockDeviceTemplateIterable()) .filter(new IsBootableDevice()) .transformAndConcat(new BlockDeviceTemplateToDiskImageSoftware()) .transform(new DiskImageSoftwareToSoftwareDescription()) .filter(new IsOperatingSystem()) .transform(new SoftwareDescriptionToOperatingSystem(image.getGlobalIdentifier())) .first(); }
Source:
<code>private void purgeExpiredDevices() { Calendar deadline = Calendar.getInstance(); deadline.add(Calendar.YEAR, TWO_YEARS_AGO); log.info("Starting scan for Devices not seen since: " + deadline.getTime()); DeviceDAO deviceDao = new DeviceDAO(); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); DeviceFileJobQueueDAO dfjqDao = new DeviceFileJobQueueDAO(); SurveyAssignmentDAO saDao = new SurveyAssignmentDAO(); List<Device> deviceList = deviceDao.listAllWithBeaconBefore(deadline.getTime()); log.info("Found " + deviceList.size() + " old Devices"); for (Device d: deviceList) { List<DeviceSurveyJobQueue> djql = dsjqDao.get(d.getPhoneNumber(), d.getEsn(), d.getAndroidId()); if (djql.size() > 0) { log.fine("Deleting " + djql.size() + " form assignments for device " + d.getKey().getId()); dsjqDao.delete(djql); } <START> List<DeviceFileJobQueue> dfql = dfjqDao.listByDeviceId(d.getKey().getId()); <END> if (dfql.size() > 0) { log.fine("Deleting " + dfql.size() + " file requests for device " + d.getKey().getId()); dfjqDao.delete(dfql); } int affected = saDao.removeDevice(d.getKey().getId()); log.fine("Removed device " + d.getKey().getId() + " from " + affected + " assignments."); } deviceDao.delete(deviceList); }</code><technical_language>extract d.getKey().getId() var</technical_language>

Target:
private void purgeExpiredDevices() { Calendar deadline = Calendar.getInstance(); deadline.add(Calendar.YEAR, ONE_YEAR_AGO); log.info("Starting scan for Devices not seen since: " + deadline.getTime()); DeviceDAO deviceDao = new DeviceDAO(); DeviceSurveyJobQueueDAO dsjqDao = new DeviceSurveyJobQueueDAO(); DeviceFileJobQueueDAO dfjqDao = new DeviceFileJobQueueDAO(); SurveyAssignmentDAO saDao = new SurveyAssignmentDAO(); List<Device> deviceList = deviceDao.listAllWithBeaconBefore(deadline.getTime()); log.info("Found " + deviceList.size() + " old Devices"); for (Device d: deviceList) { long did = d.getKey().getId(); List<DeviceSurveyJobQueue> djql = dsjqDao.get(d.getPhoneNumber(), d.getEsn(), d.getAndroidId()); if (djql.size() > 0) { log.fine("Deleting " + djql.size() + " form assignments for device " + did); dsjqDao.delete(djql); } List<DeviceFileJobQueue> dfql = dfjqDao.listByDeviceId(did); if (dfql.size() > 0) { log.fine("Deleting " + dfql.size() + " file requests for device " + did); dfjqDao.delete(dfql); } int affected = saDao.removeDevice(did); log.fine("Removed device " + did + " from " + affected + " assignments."); } deviceDao.delete(deviceList); }
Source:
<code>private void testModerationHint() throws Exception { ______TS("verify moderation hint"); submitPage = loginToInstructorEditStudentFeedbackPage("IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.verifyHtmlPart(By.className("navbar"), "/instructorEditStudentFeedbackHintLess.html"); submitPage.click(By.id("moderationHintButton")); <START> submitPage.verifyHtmlPart(By.className("navbar"), "/instructorEditStudentFeedbackHintMore.html"); <END> submitPage.click(By.id("moderationHintButton")); submitPage.verifyHtmlPart(By.className("navbar"), "/instructorEditStudentFeedbackHintLess.html"); }</code><technical_language>Verifying html able element is displayed not. For that, need isElementVisible() method provided in AppPage.java (perhaps extract a method isModerationHintVisible in FeedbackSubmitPage.java). In this case, simply need 1 html verification ensure html is correct, 2 visibility checks test button works intended show hide hint</technical_language>

Target:
private void testModerationHint() throws Exception { ______TS("verify moderation hint"); submitPage = loginToInstructorEditStudentFeedbackPage("IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.verifyModerationHeaderHtml("/instructorEditStudentFeedbackHint.html"); submitPage.clickModerationHintButton(); assertTrue(submitPage.isModerationHintVisible()); assertEquals("[Less]", submitPage.getModerationHintButtonText()); submitPage.clickModerationHintButton(); assertFalse(submitPage.isModerationHintVisible()); assertEquals("[More]", submitPage.getModerationHintButtonText()); }
Source:
<code>void deleteView(View view) throws IOException; Collection<View> getViews(); <START> default Collection<View> getAllViews() { <END> final Collection<View> views = new LinkedHashSet<>(getViews()); for (View view : getViews()) { if (view instanceof ViewGroup) { views.addAll(((ViewGroup) view).getAllViews()); } } return views; }</code><technical_language>suggestion default @Nonnull Collection<View> getAllViews() {</technical_language>

Target:
void deleteView(View view) throws IOException; Collection<View> getViews(); @Nonnull default Collection<View> getAllViews() { final Collection<View> views = new LinkedHashSet<>(getViews()); for (View view : getViews()) { if (view instanceof ViewGroup) { views.addAll(((ViewGroup) view).getAllViews()); } } return views; }
Source:
<code>SmartHttpPushConnection(final InputStream advertisement) throws TransportException { super(TransportHttp.this); <START> init(advertisement, new OutputStream() { <END> @Override public void write(int b) throws IOException { throw new IllegalStateException("Writing not permitted"); } }); outNeedsEnd = false; try { readAdvertisedRefs(); } catch (IOException err) { close(); throw new TransportException(uri, "remote hung up unexpectedly", err); } }</code><technical_language>This a pre-defined (static final) instance of a static class, instance class instantiated anew time</technical_language>

Target:
SmartHttpPushConnection(final InputStream advertisement) throws TransportException { super(TransportHttp.this); init(advertisement, DisabledOutputStream.INSTANCE); outNeedsEnd = false; try { readAdvertisedRefs(); } catch (IOException err) { close(); throw new TransportException(uri, "remote hung up unexpectedly", err); } }
Source:
<code>private Set<String> findDependentEntitlementsByProvidedProduct(Iterable<String> entitlementIds) { String queryStr = "SELECT DISTINCT e2.id " + "FROM cp_entitlement e1 " + "JOIN cp2_pool_provided_products ppp1 ON ppp1.pool_id = e1.pool_id " + "JOIN cp2_products p ON p.uuid = ppp1.product_uuid " + "JOIN cp2_content_modified_products cmp ON cmp.element = p.product_id " + "JOIN cp2_product_content pc ON pc.content_uuid = cmp.content_uuid " + "JOIN cp2_pool_provided_products ppp2 ON ppp2.product_uuid = pc.product_uuid " + "JOIN cp_entitlement e2 ON e2.pool_id = ppp2.pool_id " + "WHERE e1.consumer_id = e2.consumer_id " + " AND e1.id != e2.id " + " AND e2.dirty = false " + " AND e1.id IN (:entitlement_ids)" + " AND e2.id NOT IN (:entitlement_ids)"; Query query = getEntityManager().createNativeQuery(queryStr); Set<String> result = new HashSet<String>(); if (entitlementIds == null || !entitlementIds.iterator().hasNext()) { return result; } <START> int blockSize = Math.min(this.getInBlockSize(), this.getQueryParameterLimit()); <END> for (List<String> block : Iterables.partition(entitlementIds, blockSize)) { result.addAll(query.setParameter("entitlement_ids", block).getResultList()); } return result; }</code><technical_language>This query, however, *does* need division two, blocks of params in query</technical_language>

Target:
private Set<String> findDependentEntitlementsByProvidedProduct(Iterable<String> entitlementIds) { String queryStr = "SELECT DISTINCT e2.id " + "FROM cp_entitlement e1 " + "JOIN cp2_pool_provided_products ppp1 ON ppp1.pool_id = e1.pool_id " + "JOIN cp2_products p ON p.uuid = ppp1.product_uuid " + "JOIN cp2_content_modified_products cmp ON cmp.element = p.product_id " + "JOIN cp2_product_content pc ON pc.content_uuid = cmp.content_uuid " + "JOIN cp2_pool_provided_products ppp2 ON ppp2.product_uuid = pc.product_uuid " + "JOIN cp_entitlement e2 ON e2.pool_id = ppp2.pool_id " + "WHERE e1.consumer_id = e2.consumer_id " + " AND e1.id != e2.id " + " AND e2.dirty = false " + " AND e1.id IN (:entitlement_ids)" + " AND e2.id NOT IN (:entitlement_ids)"; Query query = getEntityManager().createNativeQuery(queryStr); Set<String> result = new HashSet<String>(); if (entitlementIds == null || !entitlementIds.iterator().hasNext()) { return result; } int blockSize = Math.min(this.getInBlockSize(), this.getQueryParameterLimit() / 2); for (List<String> block : Iterables.partition(entitlementIds, blockSize)) { result.addAll(query.setParameter("entitlement_ids", block).getResultList()); } return result; }
Source:
<code>public Builder flumeConfiguration(String resource) { <START> serviceConfig.set(FLUME_CONFIGURATION, resource); <END> return this; }</code><technical_language>In descriptor builder, read file immediately fail fast. I move reader code for reason. reused more easily</technical_language>

Target:
public Builder flumeConfiguration(String resource) { serviceConfig.set(FLUME_CONFIGURATION, toUrl(resource).toExternalForm()); return this; }
Source:
<code>public T findById(String id) throws NotFoundException { CircuitBreaker breaker = circuitBreakerRegistry.circuitBreaker( getClass().getSimpleName() + "-findById", CircuitBreakerConfig.custom() .ignoreException(e -> e instanceof NotFoundException) .build()); Supplier<T> recoverableSupplier = SupplierUtils.recover( () -> service.loadObject(objectType, buildObjectKey(id)), e -> <START> Optional.ofNullable(allItemsCache.get()).orElse(new HashSet<>()).stream() <END> .filter(item -> item.getId().equalsIgnoreCase(id)) .findFirst() .orElseThrow( () -> new NotFoundException( String.format( "No item found in cache with id of %s", id == null ? "null" : id.toLowerCase())))); return breaker.executeSupplier(recoverableSupplier); }</code><technical_language>suggestion Optional.ofNullable(allItemsCache.get()).orElseGet(HashSet::new).stream() Small optimization</technical_language>

Target:
public T findById(String id) throws NotFoundException { CircuitBreaker breaker = circuitBreakerRegistry.circuitBreaker( getClass().getSimpleName() + "-findById", CircuitBreakerConfig.custom() .ignoreException(e -> e instanceof NotFoundException) .build()); Supplier<T> recoverableSupplier = SupplierUtils.recover( () -> service.loadObject(objectType, buildObjectKey(id)), e -> Optional.ofNullable(allItemsCache.get()).orElseGet(HashSet::new).stream() .filter(item -> item.getId().equalsIgnoreCase(id)) .findFirst() .orElseThrow( () -> new NotFoundException( String.format( "No item found in cache with id of %s", id == null ? "null" : id.toLowerCase())))); return breaker.executeSupplier(recoverableSupplier); }
Source:
<code>private void configureHyperLinkSupport(FormText richText, ScrolledForm form) { Display disaply = form.getDisplay(); HyperlinkGroup group = new HyperlinkGroup(disaply); group.setForeground(disaply.getSystemColor(SWT.COLOR_BLUE)); group.setActiveForeground(disaply.getSystemColor(SWT.COLOR_BLUE)); richText.setHyperlinkSettings(group); richText.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { String href = (String) e.getHref(); if (href.startsWith("http")) { int browserStyle = IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.AS_EXTERNAL | IWorkbenchBrowserSupport.STATUS | IWorkbenchBrowserSupport.NAVIGATION_BAR; IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); try { browserSupport.createBrowser(browserStyle, null, null, null).openURL(new URL(href)); } catch (Exception ex) { <START> Status status = new Status(Status.ERROR, null, "Unable to open external web browser: " + ex.getMessage(), ex); <END> StatusManager.getManager().handle(status, StatusManager.SHOW); } } } }); }</code><technical_language>externalize this String messages.properties this class displayed user</technical_language>

Target:
private void configureHyperLinkSupport(FormText richText, ScrolledForm form) { Display disaply = form.getDisplay(); HyperlinkGroup group = new HyperlinkGroup(disaply); group.setForeground(disaply.getSystemColor(SWT.COLOR_BLUE)); group.setActiveForeground(disaply.getSystemColor(SWT.COLOR_BLUE)); richText.setHyperlinkSettings(group); richText.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { String href = (String) e.getHref(); if (href.startsWith("http")) { int browserStyle = IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.AS_EXTERNAL | IWorkbenchBrowserSupport.STATUS | IWorkbenchBrowserSupport.NAVIGATION_BAR; IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); try { browserSupport.createBrowser(browserStyle, null, null, null).openURL(new URL(href)); } catch (Exception ex) { Status status = new Status(Status.ERROR, null, MessageFormat.format(Messages.DescriptionDialog_exernal_browser_error, ex.getMessage()), ex); StatusManager.getManager().handle(status, StatusManager.SHOW); } } } }); }