auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void reset(OutputStream out) throws IOException { this.out = out; }

Target:
This should have been: ``` this.out.close(); ```
Source:
public ArrayBufferInput(byte[] arr, int offset, int length) { this.buffer = MessageBuffer.wrap(checkNotNull(arr, "input array is null")).slice(offset, length); checkArgument(length <= arr.length); this.length = length; }

Target:
We need to check `offset + length <= arr.length`?
Source:
public boolean skipValue() throws IOException { // NOTE: This implementation must be as efficient as possible int remainingValues = 1; while(remainingValues > 0) { MessageFormat f = getNextFormat(); if(f == MessageFormat.EOF) return false; remainingValues += f.skip(this); remainingValues--; } return true; }

Target:
Does this method just check if it can skip? If so, "canSkipValue()" or something is a better method name?
Source:
public String toString() { return String.format("double@0x%x=%s", Pointer.nativeValue(getPointer()), Double.toString(getValue())); }

Target:
The explicit call to `Double#toString` is not necessary, String#format can directly be invoked with a primitive boolean
Source:
public String toString() { return String.format("float@0x%x=%s", Pointer.nativeValue(getPointer()), Float.toString(getValue())); }

Target:
See DoubleByReference
Source:
public byte getValueIfPresent(PointerType key, PointerByReference value) { return INSTANCE.CFDictionaryGetValueIfPresent(this, key, value); }

Target:
Would it make sense to convert the return of `CFDictionaryGetValueIfPresent` directly to a boolean?
Source:
public void testGetCurrentThread() { HANDLE h = Kernel32.INSTANCE.GetCurrentThread(); assertNotNull("No current thread handle", h); assertFalse("Null current thread handle", h.getPointer().equals(Pointer.NULL)); }

Target:
Please make this ```java assertNotNull("Null current thread handle", h.getValue()); ``` Your version will raise a `NullPointerException` in the failure case. I consider `Pointer.NULL` a very bad idea - it gives the illusion as if it were an object, in fact it is `null`. If you want to keep your version, it needs to be: ```java assertFalse("Null current thread handle", h.getPointer() == Pointer.NULL); ```
Source:
public static boolean registryValueExists(HKEY root, String key, String value) { return registryValueExists(root, key, value, WinNT.REG_NONE); }

Target:
Please don't use `WinNT.REG_NONE` for this use-case. `WinNT.REG_NONE` is a type, not an access level. There is no "NONE" access level for the registry. I would just use 0 here. I would not invent a constant.
Source:
private String _evtGetExtendedStatus(String query) { EVT_HANDLE handle = null; String result; try { handle = Wevtapi.INSTANCE.EvtQuery(null, "Application", query, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath); result = WevtapiUtil.EvtGetExtendedStatus(); } finally { if (handle != null) { Wevtapi.INSTANCE.EvtClose(handle); } } System.out.println(result); return result; }

Target:
This looks like an artifact from debugging. I was surprised when I saw the output and could not directly place it. Please remove.
Source:
protected List getFieldOrder() { return Arrays.asList(new String[] { "dwStructSize", "lpszSourceUrlName", "lpszLocalFileName", "CacheEntryType", "dwUseCount", "dwHitRate", "dwSizeLow", "dwSizeHigh", "LastModifiedTime", "ExpireTime", "LastAccessTime", "LastSyncTime", "lpHeaderInfo", "dwHeaderInfoSize", "lpszFileExtension", "u", "additional" }); }

Target:
Don't suppress the warning and no need to allocate _new String[]_ - use ``` java @Override protected List<String> getFieldOrder() { return Arrays.asList("field1", "field2", ...); } ```
Source:
public static final void addSearchPathSuffix(String libraryName, String pathSuffix) { File ps = new File(pathSuffix); // only accept the suffix if it is not an absolute path if (!ps.isAbsolute()) { synchronized (pathSuffixes) { List customPaths = (List) pathSuffixes.get(libraryName); if (customPaths == null) { customPaths = Collections.synchronizedList(new LinkedList()); pathSuffixes.put(libraryName, customPaths); } customPaths.add(pathSuffix); } } }

Target:
Let's use generics since we are using Java 1.5+
Source:
public void testSHGetKnownFolderPath() { int flags = ShlObj.KNOWN_FOLDER_FLAG.NONE.getFlag(); PointerByReference outPath = new PointerByReference(); HANDLE token = null; GUID guid = KnownFolders.FOLDERID_Fonts; HRESULT hr = Shell32.INSTANCE.SHGetKnownFolderPath(guid, flags, token, outPath); Ole32.INSTANCE.CoTaskMemFree(new LPVOID(outPath.getPointer().getLong(0))); assertTrue(W32Errors.SUCCEEDED(hr.intValue())); }

Target:
Does declaring a `CoTaskMemFree` that takes `Pointer` work by itself? It's likely that JNA will marshal that appropriately. Otherwise I would declare another version of `CoTaskMemFree` which takes a Pointer, wrapping the LPVOID one.
Source:
public COMLateBindingBaseObject(IDispatch dispatch) { // enable JNA protected mode Native.setProtected(true); // transfer the value this.iDispatch = dispatch; }

Target:
This defaults to aon for windows, so I think you can drop it from here and any other COM-related instances.
Source:
public void testVariantClear() { System.out.println("------------------------------------------"); VARIANT variant = new VARIANT(new SHORT(33333)); HRESULT hr = OleAuto.INSTANCE.VariantClear(variant.getPointer()); assertTrue("hr: " + hr.intValue(), hr.intValue() == 0); System.out.println(variant.toString(true)); System.out.println("------------------------------------------"); }

Target:
Please convert these tests to use assertions rather than simply printing output. In general, unit tests should produce no output and only make assertions. It is also recommended that you use the message form of assertion, e.g. ``` // prefer this assertTrue("The number of matches should be greater than zero", matches > 0); // to this assertTrue(matches > 0); ```
Source:
private void newAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.uCallbackMessage.setValue( WM_USER + 1); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_NEW); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); assertNotNull(result ); }

Target:
Extra space after `result`.
Source:
public void htmlFlag(){ String results = (String) Eclim.execute(new String[]{ "java_element_doc", "-p", Jdt.TEST_PROJECT, "-f", TEST_FILE, "-o", "255", "-l", "11", "-e", "utf-8", "-h", "true" }); Assert.assertTrue("HTML Format expected", results.startsWith("<html><head>")); }

Target:
Can you stick with the existing coding style and omit the `Assert.` prefix here.
Source:
public void emit(ErrorType etype, ANTLRMessage msg) { switch ( etype.severity ) { case WARNING_ONE_OFF: case ERROR_ONE_OFF: if ( errorTypes.contains(etype) ) break; // fall thru case WARNING: warnings++; tool.warning(msg); break; case ERROR: errors++; tool.error(msg); break; } errorTypes.add(etype); }

Target:
❗ this is not correct
Source:
public boolean templatesExist() { String groupFileName = CodeGenerator.TEMPLATE_ROOT + "/" + getLanguage() + "/" + getLanguage() + STGroup.GROUP_FILE_EXTENSION; URL url = Thread.currentThread().getContextClassLoader().getResource(groupFileName); STGroup result = null; try { result = new STGroupFile(url); } catch (IllegalArgumentException iae) { result = null; } return result!=null; }

Target:
It looks to me as though STGroupFile's ctor calls `getURL()` which does exactly that getResource thing. What additional functionality are you providing? i.e., where does ST4 go wrong? Maybe we shoulda fixed that in ST4 :)
Source:
public Token match(int ttype) throws RecognitionException { Token t = getCurrentToken(); if ( t.getType()==ttype ) { if ( t.getType()==Token.EOF ) { matchedEOF = true; } _errHandler.reportMatch(this); consume(); } else { t = _errHandler.recoverInline(this); if ( _buildParseTrees && t.getTokenIndex()==-1 ) { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx.addErrorNode(t); } } return t; }

Target:
:bulb: `t.getType()` could be replaced by `ttype` for efficiency.
Source:
public IntegerList(int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } if (capacity > MAX_ARRAY_SIZE) throw new IllegalArgumentException(); if (capacity == 0) { _data = EMPTY_DATA; } else { _data = new int[capacity]; } }

Target:
:bulb: Considering `ArrayList` omits this check, I think it's safe for us to as well.
Source:
public final int binarySearch(int fromIndex, int toIndex, int key) { if (fromIndex < 0 || toIndex < 0 || fromIndex > _size || toIndex > _size) { throw new IndexOutOfBoundsException(); } if (fromIndex > toIndex) throw new IllegalArgumentException(); return Arrays.binarySearch(_data, fromIndex, toIndex, key); }

Target:
I think this condition makes sense. Can you update the code to match the surrounding formatting (hard tabs, and use braces)?
Source:
public ATNSimulator setProfile(boolean profile) { ParserATNSimulator previous = getInterpreter(); if ( profile ) { setInterpreter(new ProfilingATNSimulator(this)); } else { if ( previous!=null ) { ParserATNSimulator interp = new ParserATNSimulator(this, getATN(), previous.decisionToDFA, previous.getSharedContextCache()); setInterpreter(interp); } } return previous; }

Target:
I think that would be more consistent with other `set` methods. Mutating methods that return an instance are generally used for chained calls (`StringBuilder.append`) or atomic updates (`AtomicInteger.getAndSet`), neither of which apply here.
Source:
public STGroup getTemplates() { STGroup templates = getTarget().getTemplates(); ST version = templates.getInstanceOf("VERSION"); if ( version==null || !version.render().equals(Tool.VERSION) ) { tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } return templates; }

Target:
The version check would be much easier as a method in the `Target` class, especially considering the `Target` implementation is responsible for loading its own template files.
Source:
public void dumpTrailer(PrintStream p, String indent, boolean noArmor) { if (!noArmor) { p.print ("\n}\n"); } }

Target:
'indent' is not used in this method
Source:
public boolean shouldCaptureBuildInfo(@NotNull TaskContext taskContext) { boolean shouldCaptureBuildInfo = false; if (isCaptureBuildInfo()) { shouldCaptureBuildInfo = true; } else { if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { shouldCaptureBuildInfo = true; resetPublishBuildInfo(); } } } return shouldCaptureBuildInfo; }

Target:
I suggest simplifying the code of the above method to: ``` if (isCaptureBuildInfo()) { return true; } if (isPublishBuildInfo()) { // First check if there is a publish build info task. if there is then use aggregation List<? extends TaskDefinition> taskDefinitions = taskContext.getBuildContext().getRuntimeTaskDefinitions(); if (TaskDefinitionHelper.isBuildPublishTaskExists(taskDefinitions)) { resetPublishBuildInfo(); return true; } } return false; ```
Source:
protected AbstractArtifactoryConfiguration(String builderContextPrefix, @Nullable String capabilityPrefix) { serverConfigManager = ServerConfigManager.getInstance(); if (administrationConfiguration == null) { administrationConfiguration = (AdministrationConfiguration) ContainerManager.getComponent("administrationConfiguration"); } this.builderContextPrefix = builderContextPrefix; this.capabilityPrefix = capabilityPrefix; this.taskConfiguratorHelper = new TaskConfiguratorHelperImpl(); }

Target:
Can we initialise the instance when it is declared?
Source:
public static TaskDefinition findReleaseTaskDefinition(List<? extends TaskDefinition> taskDefinitions) { if (taskDefinitions != null) { for (TaskDefinition taskDefinition : taskDefinitions) { if (taskDefinition.isEnabled()) { AbstractBuildContext config = AbstractBuildContext.createContextFromMap(taskDefinition.getConfiguration()); // Check the release management is enabled if ((config != null) && config.releaseManagementContext.isReleaseMgmtEnabled()) { return taskDefinition; } } } } return null; }

Target:
Redundant parentheses around ```(config != null)```. Also, this method is also identical to the ```getTaskConfiguration``` method. I suggest reusing the code.
Source:
public void showError() { Snackbar snackbar = SnackBarHandler.create(coordinatorLayout, getString(no_account_signed_in)); snackbar.show(); }

Target:
No need to save in a variable. Directly call show
Source:
private void handleEditorImage(Intent data) { String newFilePath = data.getStringExtra(EditImageActivity.EXTRA_OUTPUT); boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false); if (isImageEdit) { } else {//Or use the original unedited pictures newFilePath = data.getStringExtra(EditImageActivity.FILE_PATH); ; } //System.out.println("newFilePath---->" + newFilePath); //File file = new File(newFilePath); //System.out.println("newFilePath size ---->" + (file.length() / 1024)+"KB"); Log.d("image is edit", isImageEdit + ""); LoadImageTask loadTask = new LoadImageTask(); loadTask.execute(newFilePath); }

Target:
Why is an extra semicolon placed here? Also, try not to refactor code until and unless it is absolutely required.
Source:
private void handleZoom(MotionEvent event, Camera.Parameters params) { int maxZoom = params.getMaxZoom(); int zoom = params.getZoom(); float newDist = getFingerSpacing(event); if (newDist > mDist) { //zoom in if (zoom < maxZoom) zoom+=6; } else if (newDist < mDist) { //zoom out if (zoom > 0) zoom-=6; } mDist = newDist; params.setZoom(zoom); mCamera.setParameters(params); }

Target:
This condition can be combined
Source:
public void selectAllImages() { for(ImageItem imageItem : localImageList) { imageItem.isSelected = true; deletableList.add(imageItem.path); } notifyDataSetChanged(); }

Target:
Move the brace in the same line of the function
Source:
public ImageAdapter(Context c) { mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); path = imagelist.split("#"); if (path.length > 0) { noPhotos.setVisibility(View.GONE); Log.e("Hi", "Removing"); } }

Target:
Remove the unwanted log or make it logical
Source:
private boolean entitySupportRetry(HttpRequest request) { boolean entitySupportRetry = true; if (request.getEntity() != null) { if (request.getEntity() instanceof InputStreamHttpEntity) { // If input stream is not 'mark supported' can not be consumed again so retry is not supported entitySupportRetry = ((InputStreamHttpEntity) request.getEntity()).getInputStream().markSupported(); } } return entitySupportRetry; }

Target:
unify the conditions to make this method clearer. Return true or false according to that.
Source:
private Throwable getExceptionCause(Throwable throwable) { // For subclasses of ModuleException, we use it as it already contains additional information if (throwable.getClass().equals(ModuleException.class)) { return throwable.getCause() != null ? suppressIfPresent(throwable.getCause(), MessagingException.class) : new MuleRuntimeException(createStaticMessage(throwable.getMessage())); } else { return throwable; } }

Target:
this doesn't look correct. You're doing this ONLY when the exception is a `ModuleException`. You're ignoring all subclasses (which is what's more frequently used).
Source:
private FlowRefFactoryBean createDynamicFlowRefFactoryBean(Processor target, Object targetBuilder, ApplicationContext applicationContext) throws Exception { if (targetBuilder != null) { doReturn(targetBuilder).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } else { doReturn(target).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } return createFlowRefFactoryBean(FlowRefFactoryBeanTestCase.DYNAMIC_REFERENCED_FLOW, "flow", applicationContext); }

Target:
static import
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CaseInsensitiveMultiMap)) return false; if (!super.equals(o)) return false; CaseInsensitiveMultiMap that = (CaseInsensitiveMultiMap) o; return optimized == that.optimized; }

Target:
use braces even for one line blocks
Source:
HttpRequestBuilder(boolean preserveHeadersCase) { headers = new LazyValue<>(() -> new CaseInsensitiveMultiMap(!preserveHeadersCase)); }

Target:
why the lazy? this will eventually always be called when `build` is called
Source:
protected ExecutionMediator createExecutionMediator() { if (executionMediatorFactory != null) { return executionMediatorFactory.get(); } return new DefaultExecutionMediator(extensionModel, componentModel, connectionManager, muleContext.getErrorTypeRepository()); }

Target:
What if you always use a supplier, but when creating the instance, you create the default supplier?
Source:
private Map<Integer, Integer> getTypeIndexesPerLevel() { if (this.typeIndexesPerLevel == null) { this.typeIndexesPerLevel = new SmallMap<>(); } return this.typeIndexesPerLevel; }

Target:
`forSize(4)`
Source:
public void testDontDeserializeOtherThanMuleSession() throws MuleException { DefaultMuleMessage message = new DefaultMuleMessage("Test Message", muleContext); SessionHandler handler = new SerializeAndEncodeSessionHandler(); String encodedSet = new String(Base64.encode(SerializationUtils.serialize(new HashSet<String>()))); message.setInboundProperty(MULE_SESSION_PROPERTY, encodedSet); MuleSession session = handler.retrieveSessionInfoFromMessage(message); assertNull(session); }

Target:
static import Base64.encode and SerializationUtils.serialize
Source:
public ClassSpecificObjectInputStream(ClassLoader classLoader, InputStream inputStream, Class classToAccept) throws IOException, StreamCorruptedException { super(classLoader, inputStream); this.classToAccept = classToAccept; this.firstClass = true; }

Target:
set the true value in the field declaration.
Source:
public synchronized void open(String partitionName) throws ObjectStoreException { lock.lock(); try { super.open(partitionName); } finally { lock.unlock(); } }

Target:
use `ConcurrencyUtils#withLock`
Source:
public void nullMessageProcessPhaseInRegistry() throws Exception { when(mockMuleContext.getTransactionManager()).thenReturn(null); when(mockMuleContext.getConfiguration().getId()).thenReturn("appName"); processAndVerifyDefaultPhasesUsingRegistryPhases(null); }

Target:
move this to a `@Before` method
Source:
public CaseInsensitiveHashMap<K, V> toImmutableCaseInsensitiveMap() { if (this instanceof ImmutableCaseInsensitiveHashMap) { return this; } if (this.isEmpty() && EMPTY_MAP != null) { return EMPTY_MAP; } return new ImmutableCaseInsensitiveHashMap<>(this); }

Target:
Can this check be avoided using polymorphism?
Source:
public ClassLoaderModel build() { Optional<Plugin> pluginOptional = empty(); if (processSharedLibraries || processAdditionalPluginLibraries) { pluginOptional = findMuleMavenPluginDeclaration(); } if (processSharedLibraries) { pluginOptional.ifPresent(this::exportSharedLibrariesResourcesAndPackages); } if (processAdditionalPluginLibraries) { pluginOptional.ifPresent(this::processAdditionalPluginLibraries); } // do the filtering of local packages and resources after exported and processed sharedRuntimeLibraries and additionalPluginDependencies localPackages.removeAll(packages); localResources.removeAll(resources); return super.build(); }

Target:
delegate
Source:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { ((BaseEventContext) response.getContext()).success(); }

Target:
I believe this is not necessary. This should happen autoamtically in the pipeline. Verify that and if that's the case remove
Source:
private void doPoll() { try { InternalEvent internalEvent = InternalEvent.builder(EventContextFactory.create(flowConstruct, getLocation())).message(Message.of(null)).build(); setCurrentEvent(internalEvent); messageProcessingManager .processMessage(flowProcessingTemplate, flowProcessContext); } catch (Exception e) { muleContext.getExceptionListener().handleException(e); } }

Target:
inline
Source:
public void testActionIndifferentConfig() throws Exception { MuleTransactionConfig config = new MuleTransactionConfig(TransactionConfig.ACTION_INDIFFERENT); ExecutionTemplate executionTemplate = createExecutionTemplate(config); Object result = executionTemplate.execute(getEmptyTransactionCallback()); assertThat(result, is(RETURN_VALUE)); assertThat(TransactionCoordination.getInstance().getTransaction(), IsNull.nullValue()); }

Target:
static import
Source:
private LocalTxQueueTransactionContext createLocalTxContext(LocalTxQueueTransactionJournal txLog, QueueProvider provider) throws InterruptedException { Lock lock = mock(Lock.class); when(lock.tryLock(anyLong(), eq(TimeUnit.MILLISECONDS))).thenAnswer((Answer<Boolean>) invocationOnMock -> { sleep(invocationOnMock.getArgument(0, Long.class) / 2); return true; }); return new LocalTxQueueTransactionContext(txLog, provider, lock); }

Target:
static import
Source:
protected void addInInterceptorCorrectingInterceptors(ServerFactoryBean sfb) { if (isProxy() && isProxyEnvelope() && CxfUtils.interceptorOfClassIsPresent(sfb.getInInterceptors(), SAAJInInterceptor.class)) { sfb.getInInterceptors().add(new SAAJEnvelopeCorrectionInterceptor()); } }

Target:
static import
Source:
private boolean isRootProcessorScope(ComponentModel componentModel) { ComponentIdentifier identifier = componentModel.getIdentifier(); return identifier.equals(FLOW_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_SUITE_IDENTIFIER) || identifier.equals(SUBFLOW_IDENTIFIER) || identifier.equals(CHOICE_WHEN_COMPONENT_IDENTIFIER) || identifier.equals(CHOICE_OTHERWISE_COMPONENT_IDENTIFIER) || identifier.equals(MUNIT_BEFORE_TEST_IDENTIFIER) || identifier.equals(MUNIT_AFTER_SUITE_IDENTIFIER) || identifier.equals(MUNIT_AFTER_TEST_IDENTIFIER); }

Target:
create an issue and add a TODO to review this situation with other components (try and scatter-gather pop into my mind right now.)
Source:
public void doNotExpireDynamicConfigWithCustomExpirationUsedBySource() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpirationForSource", "heisenbergWithCustomExpirationForSource", "Walter Blanco"); try { assertExpired(config, 10000, 1000); fail("Config should not have been expired"); } catch (AssertionError e) { assertThat(e.getMessage(), is(not("Config should not have been expired"))); } assertInitialised(config); sourceWithDynamicConfig.stop(); assertExpired(config, 6000, 100); }

Target:
not at all elegant. Just throw an illegalStateException instead of using fail
Source:
public void authenticateWithoutProvider() throws SecurityException, SecurityProviderNotFoundException { expected.expect(SecurityProviderNotFoundException.class); manager.authenticate(authentication); verify(provider).authenticate(authentication); verifyZeroInteractions(provider); }

Target:
isn't this contradictory with the line right above?
Source:
protected void checkWithFailDropStrategy(CoreEvent event) throws FlowBackPressureException { if (!abstractPipeline.getProcessingStrategy().checkBackpressureEmitting(event)) { FlowBackPressureException exception = new FlowBackPressureException(abstractPipeline.getName()); throw exception; } }

Target:
inline
Source:
public void check(CoreEvent event) throws FlowBackPressureException { if (abstractPipeline.getSource().getBackPressureStrategy() == MessageSource.BackPressureStrategy.WAIT) { checkWithWaitStrategy(event); } else { checkWithFailDropStrategy(event); } }

Target:
static import
Source:
private static void setMaxAttributeSizeProperty(XMLInputFactory factory) { String maxAttributeSizeProperty = getProperty(MULE_MAX_ATTRIBUTE_SIZE); if(maxAttributeSizeProperty != null) { Integer maxAttributeSize = parseInt(maxAttributeSizeProperty); if(maxAttributeSize > 0) { factory.setProperty(P_MAX_ATTRIBUTE_SIZE, maxAttributeSizeProperty); return; } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Invalid " + P_MAX_ATTRIBUTE_SIZE + " property value"); } } factory.setProperty(P_MAX_ATTRIBUTE_SIZE, MAX_VALUE); }

Target:
make this a WARN
Source:
private BiConsumer<Throwable, Object> completeWithErrorPropagate() { return (error, event) -> { final PrivilegedEvent errorEvent = (PrivilegedEvent) ((MessagingException) error).getEvent(); System.out.println("propagating error... " + errorEvent.getContext().getDepthLevel()); errorEvent.getContext().error(error); }; }

Target:
Remove
Source:
private BiConsumer<Throwable, Object> completeWithErrorContinue() { return (error, event) -> { final PrivilegedEvent errorEvent = (PrivilegedEvent) ((MessagingException) error).getEvent(); System.out.println("continuing after error... " + errorEvent.getContext().getDepthLevel()); (errorEvent.getContext()).success(errorEvent); }; }

Target:
Remove
Source:
private PolicyInstance initPolicyInstance() throws InitialisationException { if (policyContext == null) { initPolicyContext(); } return policyContext.getRegistry().lookupByType(PolicyInstance.class).get(); }

Target:
this should be set already, why do you need to add this?
Source:
public static boolean deleteFile(File file) { boolean shouldFailIfOpen = DefaultMuleConfiguration.shouldFailIfDeleteOpenFile(); if (shouldFailIfOpen) { if (isFileOpen(file)) { Message message = MessageFactory.createStaticMessage("Attempting to delete an open file: " + file); throw new MuleRuntimeException(message); } } else if (shouldLogWarningIfDeleteOpenFile()) { if (isFileOpen(file)) { logger.warn("Attempting to delete an open file: " + file); } } return file.delete(); }

Target:
static import
Source:
public void fileIsOpenWhenUsingAFileOutputStream() throws IOException { File file = FileUtils.newFile(TEST_FILE); assertThat(FileUtils.isFileOpen(file), is(false)); FileOutputStream outputStream = new FileOutputStream(file); assertThat(FileUtils.isFileOpen(file), is(true)); outputStream.close(); assertThat(FileUtils.isFileOpen(file), is(false)); }

Target:
static importa
Source:
private CoreEvent addContextToEvent(CoreEvent event, Context ctx) { final CoreEvent eventWithContext; if (ctx.hasKey(POLICY_NEXT_OPERATION)) { return quickCopy(event, singletonMap(INNER_CHAIN_CTX_MAPPING, (Function<Context, Context>) (innerChainCtx -> innerChainCtx .put(POLICY_NEXT_OPERATION, ctx.get(POLICY_NEXT_OPERATION))))); } else { return event; } }

Target:
![Code Smell](https://sonarsource.github.io/sonar-github/code_smell.png 'Code Smell') Code Smell: Remove this unused "eventWithContext" local variable. ([squid:S1481](https://sonarqube.kbuild.msap.io/coding_rules#rule_key=squid%3AS1481)) [See it in SonarQube](https://sonarqube.kbuild.msap.io/project/issues?id=mule-runtime-mule&pullRequest=7661&issues=AWjOiDKKotIXnmsUmtMc&open=AWjOiDKKotIXnmsUmtMc) [ISSUE_KEY]: AWjOiDKKotIXnmsUmtMc
Source:
public static boolean isOfType(DetailAST ast, int... types) { return ast != null && Arrays.stream(types).anyMatch(tokenType -> tokenType == ast.getType()); }

Target:
please reuse function you wrote above
Source:
public void visitToken(DetailAST arrayInit) { final DetailAST rcurly = arrayInit.findFirstToken(TokenTypes.RCURLY); final DetailAST previousSibling = rcurly.getPreviousSibling(); if (arrayInit.getChildCount() != 1 && (alwaysDemandTrailingComma || !TokenUtil.areOnSameLine(rcurly, previousSibling)) && (alwaysDemandTrailingComma || !TokenUtil.areOnSameLine(arrayInit, previousSibling)) && previousSibling.getType() != TokenTypes.COMMA) { log(previousSibling, MSG_KEY); } }

Target:
I wonder if it would be easier/harder to read if pulling out `alwaysDemandTrailingComma`, e.g. ```java && (alwaysDemandTrailingComma || (!TokenUtil.areOnSameLine(rcurly, previousSibling) && !TokenUtil.areOnSameLine(arrayInit, previousSibling))) ```
Source:
public void testOne() throws Exception { final File fileToProcess = new File( getPath("SuppressionXpathRegressionMissingLeadingAsterisk.java")); final DefaultConfiguration moduleConfig = createModuleConfig(MissingLeadingAsteriskCheck.class); final String[] expectedViolation = { "3:1: " + getCheckMessage(JavadocStyleCheck.class, MissingLeadingAsteriskCheck.MSG_MISSING_ASTERISK), }; final List<String> expectedXpathQueries = Collections.singletonList( "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionMissingLeadingAsterisk']]" + "/MODIFIERS/BLOCK_COMMENT_BEGIN"); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }

Target:
why `JavadocStyleCheck.class`?
Source:
private static boolean isColonOfCaseOrDefault(DetailAST colonAst) { boolean result = false; final DetailAST parent = colonAst.getParent(); if (parent.getType() == TokenTypes.LITERAL_CASE || parent.getType() == TokenTypes.LITERAL_DEFAULT) { result = true; } return result; }

Target:
```java boolean result = false; final DetailAST parent = colonAst.getParent(); if (parent.getType() == TokenTypes.LITERAL_CASE || parent.getType() == TokenTypes.LITERAL_DEFAULT) { result = true; } return result; ``` ----> ```java final DetailAST parent = colonAst.getParent(); return parent.getType() == TokenTypes.LITERAL_CASE || parent.getType() == TokenTypes.LITERAL_DEFAULT; ```
Source:
public void testClassWithPrivateCtorAndNestedExtendingSubclass() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(FinalClassCheck.class); final String[] expected = { "10:5: " + getCheckMessage(MSG_KEY, "B"), "16:5: " + getCheckMessage(MSG_KEY, "C"), }; verify(checkConfig, getNonCompilablePath( "InputFinalClassClassWithPrivateCtorWithNestedExtendingClass.java"), expected); }

Target:
we do not expect new violations. Can you explain why it appeared after you deleted package name from the class?
Source:
private boolean hasIgnoredModifiers(DetailAST modifiers) { final boolean isStatic = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; final boolean isFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null; final boolean ignoredStatic = ignoreStatic && isStatic; final boolean ignoredFinal = ignoreFinal && isFinal; final boolean result; if (ignoreStaticFinal) { result = isStatic && isFinal || ignoredFinal || ignoredStatic; } else { result = ignoredFinal && !isStatic || ignoredStatic && !isFinal; } return result; }

Target:
please simplify boolean expressions above. Here `ignoredStatic` and `ignoredFinal` contain `isStatic` and `isFinal` in their initialization.
Source:
public void anotherMethod() { this.anonMethod(new AnonWithEmpty() { private int member; @Override public void fooEmpty() { this.member++; } }); }

Target:
`@Override` this annotations is not needed in test inputs
Source:
private static int indexOfTypeParameter(List<DetailAST> typeParams, String requiredTypeName) { final Iterator<DetailAST> typeParamsIt = typeParams.iterator(); int paramIndex = -1; int index = 0; while (typeParamsIt.hasNext()) { final DetailAST typeParam = typeParamsIt.next(); if (typeParam.findFirstToken(TokenTypes.IDENT).getText() .equals(requiredTypeName)) { paramIndex = index; break; } index++; } return paramIndex; }

Target:
Why isn't this a for each loop like the other method?
Source:
void test() { Function<String, String> trimmer = s -> s.trim(); // warn }

Target:
Inputs between the 2 should be more unique. Please add a parenthesis around the lambda parameter like https://github.com/checkstyle/checkstyle/blob/3835575706d8240b3ec054d17ed48f692b168611/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/lambdaparametername/InputLambdaParameterName.java#L10 /
Source:
public static boolean isTypeDef(DetailAST node) { return node.getType() == TokenTypes.CLASS_DEF || node.getType() == TokenTypes.ENUM_DEF || node.getType() == TokenTypes.INTERFACE_DEF; }

Target:
why public?
Source:
public int compareOrder(NodeInfo other) { int result = 0; if (other instanceof ElementNode) { result = getDepth() - ((AbstractNode) other).getDepth(); if (result == 0) { final ElementNode[] children = getCommonAncestorChildren(other); result = children[0].indexAmongSiblings - children[1].indexAmongSiblings; } } return result; }

Target:
We check instance to be ElementNode but do a cast to AbstractNode. Shouldn't both be the same class?
Source:
public void visitToken(final DetailAST ast) { if (!allowClassImports && ast.getType() == TokenTypes.IMPORT) { final DetailAST startingDot = ast.getFirstChild(); logsStarredImportViolation(startingDot); } else if (!allowStaticMemberImports) { // must navigate past the static keyword final DetailAST startingDot = ast.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } }

Target:
Please generate regression report with `allowClassImports = true` and `allowStaticMemberImports = false`
Source:
public void visitToken(DetailAST arrayInit) { final DetailAST rcurly = arrayInit.findFirstToken(TokenTypes.RCURLY); final DetailAST previousSibling = rcurly.getPreviousSibling(); if (arrayInit.getChildCount() != 1 && !TokenUtil.areOnSameLine(rcurly, previousSibling) && !TokenUtil.areOnSameLine(arrayInit, previousSibling) && previousSibling.getType() != TokenTypes.COMMA) { log(rcurly, MSG_KEY); } }

Target:
@romani @rnveach May be violation should be reported on last array item instead of rcurly?
Source:
public int compareOrder(NodeInfo nodeInfo) { int cmp = getLineNumber() - nodeInfo.getLineNumber(); if (cmp == 0) { cmp = getColumnNumber() - nodeInfo.getColumnNumber(); if (cmp == 0) { cmp = getLocalPart().compareTo(nodeInfo.getLocalPart()); } } return cmp; }

Target:
Rename it `result` to fix spelling failure
Source:
private static boolean shouldCheckWhitespaceAfter(DetailAST ast) { boolean checkWhitespace = true; if (ast.getNextSibling() != null) { final DetailAST sibling = ast.getNextSibling(); if (sibling.getType() == TokenTypes.ANNOTATIONS) { checkWhitespace = false; } else if (sibling.getType() == TokenTypes.ARRAY_DECLARATOR) { checkWhitespace = sibling.getFirstChild().getType() != TokenTypes.ANNOTATIONS; } } return checkWhitespace; }

Target:
please move this line outside of IF.
Source:
private static Set<String> getListById(Node subSection, String id) { final Node node = XmlUtil.findChildElementById(subSection, id); assertNotNull(node, "Expected list element with id " + id); return XmlUtil.getChildrenElements(node) .stream() .map(Node::getTextContent) .collect(Collectors.toSet()); }

Target:
please remove this assert, it is util method, it should just do some job.
Source:
public void testNonExistentArgument(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws Exception { systemErr.capture(); systemOut.capture(); JavadocPropertiesGenerator.main("--nonexistent-argument"); final String expected = String.format(Locale.ROOT, "Missing required options " + "[--destfile=<outputFile>, params[0]=<inputFile>]%n") + USAGE; assertEquals(expected, systemErr.getCapturedData(), "Unexpected error log"); assertEquals("", systemOut.getCapturedData(), "Unexpected output log"); }

Target:
``` systemErr.capture(); systemOut.capture(); ``` looks like these lines are duplicated many times. May be extract them to some method with `@BeforeEach ` annotation?
Source:
public void testLocaleIsSupported() { final String language = DEFAULT_LOCALE.getLanguage(); if (!Locale.ROOT.getLanguage().equals(language) && !Locale.ENGLISH.getLanguage().equals(language)) { final LocalizedMessage localizedMessage = createSampleLocalizedMessage(); assertThat("Unsupported language: " + DEFAULT_LOCALE, localizedMessage.getMessage(), not("Empty statement.")); } }

Target:
I think check for `language.isEmpty()` is better , as will be same as in other tests, so it will look like a family
Source:
private boolean isMessageMatch(AuditEvent event) { final boolean match; if (eventMessageRegexp == null) { match = true; } else { final Matcher messageMatcher = eventMessageRegexp.matcher(event.getMessage()); match = messageMatcher.find(); } return match; }

Target:
Please make it like `boolean match = true;` and test `eventMessageRegexp != null`
Source:
private static DetailAST getLastLambdaToken(DetailAST lambda) { DetailAST node = lambda.getLastChild(); while (node.getLastChild() != null) { node = node.getLastChild(); } return node; }

Target:
Would the code be cleaner with ```` DetailAST node = lambda; do { node = node.getLastChild(); } while (node.getLastChild() != null); ```` ?
Source:
public boolean isMatch(TreeWalkerAuditEvent event) { boolean match = false; if (isInScopeOfSuppression(event)) { if (isCheckMatch(event)) { match = isMessageMatch(event); } else if (isIdMatch(event)) { match = isMessageMatch(event); } } return match; }

Target:
It could be `match = isInScopeOfSuppression(event) && isMessageMatch(event) (isCheckMatch(event) || isIdMatch(event));`
Source:
private static boolean hasUnbracedStatements(DetailAST ast) { final DetailAST nextSibling = ast.getNextSibling(); return nextSibling != null && nextSibling.getType() == TokenTypes.SLIST && !"{".equals(nextSibling.getFirstChild().getText()); }

Target:
This can be ``` return nextSibling != null && nextSibling.getType() == TokenTypes.SLIST && nextSibling.getFirstChild().getType() != TokenTypes.SLIST; ```
Source:
private static boolean shouldBeAloneOnLineWithAloneOrSinglelineOption(Details details, String targetSrcLine) { return !isAloneOnLine(details, targetSrcLine) && !isEmptyBody(details.lcurly) && !isSingleLineBlock(details); }

Target:
This is no longer re-ordered so I am assume it was resolved.
Source:
public int[] getAcceptableTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.PACKAGE_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.ENUM_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.TYPECAST, TokenTypes.LITERAL_THROWS, TokenTypes.IMPLEMENTS_CLAUSE, TokenTypes.TYPE_ARGUMENT, TokenTypes.LITERAL_NEW, TokenTypes.DOT, TokenTypes.ANNOTATION_FIELD_DEF, }; }

Target:
@pbludov @romani Any reasons why these shouldn't be default?
Source:
public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) { final XpathFilter xpathFilter = getXpathFilter(); return xpathFilter.accept(treeWalkerAuditEvent); }

Target:
We should only create the inner filter once and re-use the same one. Accept is called for every file, so this will cause an unnecessary slowdown just to recreate the instance over and over. Please remove `getXpathFilter` and move all code to `finishLocalSetup` and assign it to a field.
Source:
private void visitTypeDef(DetailAST typeDef) { if (isVerifiable(typeDef)) { checkIdent(typeDef.findFirstToken(TokenTypes.IDENT)); checkTypeParameters(typeDef); final DetailAST extendsClause = typeDef.findFirstToken(TokenTypes.EXTENDS_CLAUSE); if (extendsClause != null) { checkBaseTypes(extendsClause); } final DetailAST implementsClause = typeDef.findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE); if (implementsClause != null) { checkBaseTypes(implementsClause); } } }

Target:
Issue says we are just checking `extends` and `implements`. Don't these 2 lines do more than that? I see the content of your issue went with Class name too, but the issue title doesn't agree too. @romani Should `IllegalType` really extend to defined class names too?
Source:
private static void fillChecksFromModifierPackage() { NAME_TO_FULL_MODULE_NAME.put("ModifierOrderCheck", BASE_PACKAGE + ".checks.modifier.ModifierOrderCheck"); NAME_TO_FULL_MODULE_NAME.put("RedundantModifierCheck", BASE_PACKAGE + ".checks.modifier.RedundantModifierCheck"); NAME_TO_FULL_MODULE_NAME.put("InterfaceMemberImpliedModifierCheck", BASE_PACKAGE + ".checks.modifier.InterfaceMemberImpliedModifierCheck"); }

Target:
please order the checks alphabetically.
Source:
protected static DefaultConfiguration createRootConfig(Configuration config) { final DefaultConfiguration dc = new DefaultConfiguration(ROOT_MODULE_NAME); if (config != null) { dc.addChild(config); } return dc; }

Target:
why check for null become required, you do not pass null at AbstractXpathRegressionTest
Source:
public ParseErrorMessage(int lineNumber, String messageKey, Object... messageArguments) { this.lineNumber = lineNumber; this.messageKey = messageKey; this.messageArguments = messageArguments.clone(); }

Target:
Why should this be `public`? Now anyone can instantiate this class as the class is public and the constructor is public.
Source:
private String getHeaderLine(int headerLineNo) { String header = getHeaderLines().get(headerLineNo); if (header.isEmpty()) { header = EMPTY_LINE_PATTERN; } return header; }

Target:
please name it as `line` ,as term header we use for block of lines.
Source:
private void loadHeader(final Reader headerReader) throws IOException { final LineNumberReader lnr = new LineNumberReader(headerReader); try { while (true) { final String line = lnr.readLine(); if (line == null) { break; } readerLines.add(line); } postProcessHeaderLines(); } finally { Closeables.closeQuietly(lnr); } }

Target:
please refactor code a bit more like: ``` do{ String line = lnr.readLine(); if (line != null) { readerLines.add(line); } } while (line != null) ```
Source:
public void testHeaderIsValidWithBlankLines() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("InputHeaderjava.blank-lines.header")); checkConfig.addAttribute("ignoreLines", ""); verify(checkConfig, getPath("InputHeaderBlankLines.java")); }

Target:
http://checkstyle.sourceforge.net/config_header.html#Header ignoreLines are empty by default, why mention it here ?
Source:
public static void syncDishImage(ArrayList<Dish> dishList) { if (dishList == null) { return; } for (Dish dish : dishList) { String imgUrl = getRequestUrl(null, dish.getImageServer()); String imgName = dish.getImageServer().split("/", 2)[1]; String filePath = getLocalFileStorageUrl("", imgName); RequestHelper.getFileFromServer(imgUrl, null, filePath); dish.setImageLocal(filePath); } }

Target:
keep return type as boolean and return the same value as RequestHelper.getFileFromServer
Source:
synchronized public static OrderManager getInstance() { return sInstance; }

Target:
why need synchonized?
Source:
public void onCreate(Bundle savedInstanceState) { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads() .detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectAll().penaltyLog().penaltyDeath().build()); } super.onCreate(savedInstanceState); // Initial all the data needed initData(); // Initial the UI manually. initUi(); }

Target:
I think we could only just set the StrictMode in Application.
Source:
public String getRequestUrl(String reqContext, String page) { if (reqContext == null) { reqContext = DEFAULT_URL + DEFAULT_APP; } return reqContext + "/" + page; }

Target:
why not make these tool methods as static?
Source:
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException { // now that the service should be available, build the required source HaleConnectService hcs = getServiceProvider().getService(HaleConnectService.class); // TODO login if applicable? (based on reader parameters) // XXX for now only support public projects LocatableInputSupplier<? extends InputStream> hcSource; try { hcSource = hcs.loadProject(owner, projectId); } catch (HaleConnectException e) { throw new IllegalStateException(); } super.setSource(hcSource); return super.execute(progress, reporter); }

Target:
Should we add the cause here? ```suggestion throw new IllegalStateException(e.getMessage(), e); ```
Source:
public boolean isPassthrough() { if (isThresholdConfigured()) { InstanceCollectionPartitioner partitioner = getPartitioner(this, SimpleLog.NO_LOG); return !partitioner.usesReferences(); } else if (isPartitionByFeatureTypeConfigured()) { return false; } else { return true; } }

Target:
So `isThresholdConfigured()` and `isPartitionByFeatureTypeConfigured()` cannot be true at the same time? Otherwise I would move the `isPartitionByFeatureTypeConfigured()` condition to be the first check.
Source:
public boolean isEmpty() { return size > 0; }

Target:
This seems wrong
Source:
protected DriverConfiguration create(String elementId, IConfigurationElement element) { if (element.getName().equals("driver")) { DriverConfiguration driverConfiguration = new DriverConfiguration(elementId, element); if (!driverConfiguration.isFileBased()) return driverConfiguration; } return null; }

Target:
The DriverConfiguration fullfills more purposes than just the Driver listing in the UI. Wouldn't it make more sense to just hide file based drivers in the UI?
Source:
public void setWindingOrder(EnumWindingOrderTypes windingOrderType) { setParameter(PARAM_UNIFY_WINDING_ORDER, Value.of(windingOrderType)); }

Target:
Note that you can only do that here because the enum value returns its name in `toString()`. Thus it is OK to be treated as a simple value.
Source:
public static boolean isCounterClockwise(Geometry geometry) { if (geometry == null) return false; // Get coordinates of geometry Coordinate[] coordinates = geometry.getCoordinates(); // Using algorithm get order of geometry boolean orientation = false; try { orientation = CGAlgorithms.isCCW(coordinates); } catch (IllegalArgumentException ex) { System.err.println("Illegal Argument"); // TODO:: or Throw ? } return orientation; }

Target:
It makes sense to propagate the exception instead of silently ignoring it. Otherwise you will return information that was not checked in any way. Thus a caller would never be sure if the result from the `isCounterClockwise` is correct or if there was an internal error.
Source:
private boolean isNestedSingleResourceBinaryModule() { if( module.length > 1 && all.length == 1 && all[0] instanceof IModuleFile) { return true; } return false; }

Target:
what do you think to write it return module.length > 1 && all.length == 1 && all[0] instanceof IModuleFile;
Source:
public IConnectionWrapper getConnection() throws CoreException { HashMap<String,String> map = new HashMap<String,String>(); map.put(DefaultConnectionProvider.ID, name); map.put(DefaultConnectionProvider.URL, url); map.put(DefaultConnectionProvider.USERNAME, userName); map.put(DefaultConnectionProvider.PASSWORD, password); IConnectionProvider provider = ExtensionManager.getProvider(DefaultConnectionProvider.PROVIDER_ID); return provider.createConnection(map); }

Target:
Optional: can be written in a more compact way: Map<String,String> map = new HashMap<>();
Source:
public JMXConnectionTypeFragment() { providerMap = UIExtensionManager.getConnectionUIElements(); childFragmentMap = new HashMap<String, WizardFragment>(); }

Target:
Optional more compact way should be possible childFragmentMap = new HashMap<>(); BTW, why not creating it directly on the attribute instead of the constructor?
Source:
protected String getLaunchCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String command = "java " + vmArguments + " -jar " + jar + " " + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }

Target:
`" " + IJBossRuntimeConstants.SPACE` that's 2 spaces right?
Source:
public static void register() { try { final DeploymentStructureChangeListener listener = new DeploymentStructureChangeListener(); final IWorkspace ws = ResourcesPlugin.getWorkspace(); ws.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_BUILD); } catch(Exception e) { ClasspathCorePlugin.log("Unable to add jboss-deployment-structure.xml change listener", e); } }

Target:
and no deregister?
Source:
protected char getSeparatorCharacter(IServer server) { // Discover the proper separator character for the paths being used char sep = File.separatorChar; IControllableServerBehavior beh = JBossServerBehaviorUtils.getControllableBehavior(server); if( beh != null ) { try { IDeploymentOptionsController cont = (IDeploymentOptionsController)beh.getController(IDeploymentOptionsController.SYSTEM_ID); if( cont != null ) { sep = cont.getPathSeparatorCharacter(); } } catch(CoreException ce) { // Ignore } } return sep; }

Target:
How about reducing the code by calling getController instead? See https://github.com/jbosstools/jbosstools-server/blob/master/as/plugins/org.jboss.ide.eclipse.as.wtp.core/src/org/jboss/ide/eclipse/as/core/util/JBossServerBehaviorUtils.java#L63