auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Client setupClient(HttpClient httpClient, Duration timeout) { START ReactorNettyClientHttpEngine engine = END new ReactorNettyClientHttpEngine( httpClient, new DefaultChannelGroup(new DefaultEventExecutor()), HttpResources.get(), timeout); final ClientBuilder builder = ClientBuilder.newBuilder(); ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder)builder; clientBuilder.httpEngine(engine); return builder.build(); } `final` please.

Target:
private static Client setupClient(HttpClient httpClient, Duration timeout) { final ReactorNettyClientHttpEngine engine = new ReactorNettyClientHttpEngine( httpClient, new DefaultChannelGroup(new DefaultEventExecutor()), HttpResources.get(), timeout); final ClientBuilder builder = ClientBuilder.newBuilder(); final ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder)builder; clientBuilder.httpEngine(engine); return builder.build(); }
Source:
public Set<Class<?>> getProviderClasses() { START if (providerClasses == null && parent != null) END return parent.getProviderClasses(); if(initialized) { return providerClasses; } Set<Class<?>> set = new HashSet<Class<?>>(); if (parent != null) set.addAll(parent.getProviderClasses()); set.addAll(providerClasses); return set; } I think you can remove the check

Target:
public Set<Class<?>> getProviderClasses() { if(initialized) { return providerClasses; } Set<Class<?>> set = new HashSet<Class<?>>(); if (parent != null) set.addAll(parent.getProviderClasses()); set.addAll(providerClasses); return set; }
Source:
public static String createHeader(String username, String password) { StringBuffer buf = new StringBuffer(username); buf.append(':').append(password); START return "Basic " + java.util.Base64.getEncoder().encodeToString(buf.toString().getBytes(StandardCharsets.UTF_8)); END } there is no need for using FQDN because only one Base64 is imported now

Target:
public static String createHeader(String username, String password) { StringBuffer buf = new StringBuffer(username); buf.append(':').append(password); return "Basic " + Base64.getEncoder().encodeToString(buf.toString().getBytes(StandardCharsets.UTF_8)); }
Source:
public boolean close(final long timeout, final TimeUnit unit) { internalClose(); try { // mimic executor.awaitTermination giving time for tasks to complete long duration = TimeUnit.MILLISECONDS.convert(timeout, unit); START Thread.sleep(duration); END } catch (InterruptedException e) { onErrorConsumers.forEach(consumer -> { consumer.accept(e); }); Thread.currentThread().interrupt(); return false; } return true; } Is it possible to run internalClose() with schduleExecutor.scheduleWithFixedDelay() without thread.sleep? Is it better ?

Target:
public boolean close(final long timeout, final TimeUnit unit) { // Ignoring timeout because we are canceling tasks on a local list. // This is not a shutdown of an executor which may be running // other unrelated tasks. internalClose(); return true; }
Source:
START public static String getTracingInfoFormat(HttpRequest request) { END return getHeaderString(request, RESTEasyTracing.HEADER_ACCEPT_FORMAT); } This would be better as package protected instead of public.

Target:
protected static String getTracingInfoFormat(HttpRequest request) { return getHeaderString(request, RESTEasyTracing.HEADER_ACCEPT_FORMAT); }
Source:
public Response register() throws Exception { START ResteasyProviderFactory factory = ResteasyProviderFactory.newInstance(); END factory.registerProviderInstance(paramConvertrProvider); factory.registerProviderInstance(exceptionMapper); return Response.ok("ok").build(); } I have some doubts about the change here. In this case, the attempt is exactly to alter the current ResteasyProviderFactory instance (yes, I agree, that's not a best practice at all). By creating a new instance and not setting it in the singleton reference within ResteasyProviderFactory, you're altering the test. I suspect this is not spotted by Travis CI because the test here is likely not running due to the exclusions for RESTEASY-1935.

Target:
public Response register() throws Exception { ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); factory.registerProviderInstance(paramConvertrProvider); factory.registerProviderInstance(exceptionMapper); return Response.ok("ok").build(); }
Source:
public boolean configure(FeatureContext context) { // this is tied to the deployment, which is what we want for the reactive context if(context.getConfiguration().getRuntimeType() == RuntimeType.CLIENT) return false; Dispatcher dispatcher = ResteasyProviderFactory.getContextData(Dispatcher.class); if(dispatcher == null) { START System.err.println("Creating new context for "+context.getConfiguration().getRuntimeType()+" deployment because it looks like we're in a special thread"); END return false; } dispatcher.getDefaultContextObjects().put(Context.class, new Context()); return true; } This should probably be i18n log

Target:
public boolean configure(FeatureContext context) { // this is tied to the deployment, which is what we want for the reactive context if(context.getConfiguration().getRuntimeType() == RuntimeType.CLIENT) return false; Dispatcher dispatcher = ResteasyProviderFactory.getContextData(Dispatcher.class); if(dispatcher == null) { // this can happen, but it means we're not able to find a deployment return false; } dispatcher.getDefaultContextObjects().put(Context.class, new Context()); return true; }
Source:
START public static void addToVisitedProcessors(String item) { END visitedProcessors.add(item); } Shouldn't this be synchronized?

Target:
public static synchronized void addToVisitedProcessors(String item) { visitedProcessors.add(item); }
Source:
public PostResourceMethodInvokers() { START this.invokers = new LinkedHashSet<>(); END } Do we really need a Set internally relying on a Map here? Can't we simply have an ArrayList ? I don't think we really care about duplicates (it's really an internal abstraction), do we? Basically, I'd rather not affecting the memory footprint, considering this object is created for each invocation.

Target:
public PostResourceMethodInvokers() { this.invokers = new ArrayList<>(); }
Source:
public void subscribe(@Context SseEventSink sink) throws IOException { synchronized (outputLock) { if (sink == null) { throw new IllegalStateException("No client connected."); START } END } eventSink = sink; //subscribe if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); } So, the line here above (eventSink = sink;) is really a bug fix, as it stores a reference to the sink in the resource, allowing the close() method to actually do something. Nice catch.

Target:
public void subscribe(@Context SseEventSink sink) throws IOException { if (sink == null) { throw new IllegalStateException("No client connected."); } eventSink = sink; //subscribe if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }
Source:
public void process(ClientInvocationBuilder invocation, Object param) { START invocation.getInvocation().setEntity(Entity.entity(param == null? null : new GenericEntity<Object>(param, genericType), mediaType, annotations)) END } Missing ";" ... ;-)

Target:
public void process(ClientInvocationBuilder invocation, Object param) { invocation.getInvocation().setEntity(Entity.entity(param == null? null : new GenericEntity<Object>(param, genericType), mediaType, annotations)); }
Source:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName()); war.addClass(AtomProviderTest.class); START war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( END new FilePermission("<<ALL FILES>>", "read"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader")), "permissions.xml"); return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class, AtomProviderDataCollectionRecord.class, ObjectFactory.class); } With https://github.com/resteasy/Resteasy/pull/1126 only permission `new RuntimePermission("accessDeclaredMembers"))` is required to make the test pass.

Target:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName()); war.addClass(AtomProviderTest.class); return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class, AtomProviderDataCollectionRecord.class, ObjectFactory.class); }
Source:
public static Archive<?> deploy_charset() { WebArchive war = TestUtil.prepareArchive(DefaultCharsetTest.class.getSimpleName() + "_true"); war.addAsWebInfResource(DefaultCharsetTest.class.getPackage(), "DefaultCharsetTestWeb_true.xml", "web.xml"); START System.out.println(war.toString(true)); END return TestUtil.finishContainerPrepare(war, null, DefaultCharsetResource.class); } Not really a major problem, but can we get rid of System.out? :-)

Target:
public static Archive<?> deploy_charset() { WebArchive war = TestUtil.prepareArchive(DefaultCharsetTest.class.getSimpleName() + "_true"); war.addAsWebInfResource(DefaultCharsetTest.class.getPackage(), "DefaultCharsetTestWeb_true.xml", "web.xml"); return TestUtil.finishContainerPrepare(war, null, DefaultCharsetResource.class); }
Source:
START public Response post(CharSetCustomer cust) throws UnsupportedEncodingException { END logger.info(cust.getName()); String name = "bill\u00E9"; boolean equal = false; String test = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (test.compareTo(cust.getName()) == 0) { equal = true; } return equal ? Response.ok().build() : Response.serverError().build(); } @CathrineTeng Please look at this.

Target:
public Response post(CharSetCustomer cust) { logger.info(cust.getName()); String name = "bill\u00E9"; boolean equal = false; String test = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (test.compareTo(cust.getName()) == 0) { equal = true; } return equal ? Response.ok().build() : Response.serverError().build(); }
Source:
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) { Object entity = responseContext.getEntity(); if (entity != null && entity instanceof String) { START String tmpEscapedMsg = StringEscapeUtils.escapeXml((String) entity); END String escapedMsg = tmpEscapedMsg.replaceAll("/", "&#x2F;"); responseContext.setEntity(escapedMsg); } } } I've a minor (performance) concern here. By looking at the StringEscapeUtils code, in case of xml escape, what ends up being done is a 5 chars replacement (double-quote, ampersand, less-than, greater-than, xml apostrophe). The entity string is scanned linearly. Then we use String#replaceAll for the slash replacement, which builds up a pattern, matches on it and replaces. How about we manually create the Pattern, provide a regexp matching all 6 chars and perform the replacement with that? Alternatively, how about we do the linear string scan in our code and replace the 6 chars in the same pass ?

Target:
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) { Object entity = responseContext.getEntity(); if (entity != null && entity instanceof String) { String escapedMsg = escapeXml((String) entity); responseContext.setEntity(escapedMsg); } } }
Source:
public OkCancelShell(String text) { START super(ShellLookup.getInstance().getShell(text)); END } you can call just super(text), the same applies for constructor with matchers, and also the empty one

Target:
public OkCancelShell(String text) { super(text); }
Source:
START public void ok() { END new OkButton(this).click(); new WaitWhile(new ShellIsAvailable(SHELL_TITLE)); new WaitWhile(new JobIsRunning(), TimePeriod.LONG, false); } can you please also add method ok(TimePeriod waitForJobs). TimePeriod.LONG may not be enough for all cases

Target:
public void ok() { ok(TimePeriod.LONG); }
Source:
public boolean test() { shell = ShellLookup.getInstance().getCurrentActiveShell(); START return shell != null ? true : false; END } there is no difference between shell != null and shell != null ? true : false. IMHO we have nothing to do here. We simply call SWT API and when it returns null active shell than we do not have a way to find out if really no shell is active

Target:
public boolean test() { shell = ShellLookup.getInstance().getCurrentActiveShell(); return shell != null; }
Source:
public LabeledText(ReferencedComposite referencedComposite, String label) { START super(referencedComposite, 0, new WithLabelMatcher(new RegexMatcher(label + "\\s*\\**"))); END } I wouldnt use regex matcher inside this in this way. Because if a label contains a special char... it would not be matched properly.

Target:
public LabeledText(ReferencedComposite referencedComposite, String label) { super(referencedComposite, 0, new WithLabelMatcher(label)); }
Source:
default long getPriority() { START return 1; END } value could be 0, as the default one. So other requirement could choose from positive range (to be executed sooner) or negative range (to be executed later) in comparison to default implementation.

Target:
default long getPriority() { return 0; }
Source:
public void addExecutedTest(Class<?> testClass) { START System.out.println("Adding class with a run: " + testClass.getName()); END addTest(testClass); executedTestClasses.add(testClass); } logger

Target:
public void addExecutedTest(Class<?> testClass) { addTest(testClass); executedTestClasses.add(testClass); }
Source:
private boolean visible(final Widget w) { START if (w.isDisposed()) END return false; return Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { return !((w instanceof Control) && !((Control) w).getVisible()); } }); } Use braces even if condition is one line

Target:
private boolean visible(final Widget w) { if (w.isDisposed()) { return false; } return Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { return !((w instanceof Control) && !((Control) w).getVisible()); } }); }
Source:
public boolean isVisible(Widget widget) { START if (widget.isDisposed()) END return false; boolean ret = true; Object o = null; try { o = ObjectUtil.invokeMethod(widget, "isVisible"); } catch (RuntimeException e) { throw new CoreLayerException( "Runtime error during checking widget visibility", e); } if (o instanceof Boolean) { ret = ((Boolean) o).booleanValue(); } return ret; } Roll back those changes in handler. We do not check whether a widget is disposed in handler methods.

Target:
public boolean isVisible(Widget widget) { boolean ret = true; Object o = null; try { o = ObjectUtil.invokeMethod(widget, "isVisible"); } catch (RuntimeException e) { throw new CoreLayerException( "Runtime error during checking widget visibility", e); } if (o == null) { return ret; } if (o instanceof Boolean) { ret = ((Boolean) o).booleanValue(); } return ret; }
Source:
public ContentAssistant openContentAssistant(String assistantLabel) { activate(); log.info("Open editor's " + assistantLabel + " content assistant"); AbstractWait.sleep(TimePeriod.SHORT); Shell[] shells1 = ShellLookup.getInstance().getShells(); START new ShellMenu("Edit", "Content Assist", assistantLabel).select(); END ContentAssistantShellIsOpened caw = new ContentAssistantShellIsOpened( shells1); new WaitUntil(caw); return new ContentAssistant(caw.getContentAssistTable()); } if I pass non-existing assistantLabel, I should get some meaningful exception like "Content assistant "+assistantLabel+ " does not exist". or another case is if assistantLabel is found but is disabled - "Content assistant "+assistantLabel+ " is disabled".

Target:
public ContentAssistant openContentAssistant(String assistantLabel) { return openContentAssistant("Edit", "Content Assist", assistantLabel); }
Source:
public void getAvailableContextAssistantTest(){ TextEditor javaTextEditor = TextEditorTest.openJavaFile(); assertFalse(javaTextEditor.getAvailableContentAssistants().isEmpty()); START AbstractWait.sleep(TimePeriod.SHORT); END } why sleep ?

Target:
public void getAvailableContextAssistantTest() { TextEditor javaTextEditor = TextEditorTest.openJavaFile(); assertFalse(javaTextEditor.getAvailableContentAssistants().isEmpty()); }
Source:
public void cleanup() { org.jboss.reddeer.common.util.Display.syncExec(new Runnable() { @Override public void run() { for (Shell shell : org.jboss.reddeer.common.util.Display.getDisplay().getShells()) { if (shell.getText().equals(title)) { shell.dispose(); break; } } START new WaitWhile(new ShellWithTextIsAvailable(title)); END } }); } you have here waiting inside UI thread. It was done this way already but we can fix it, could you look at it?

Target:
public void cleanup() { org.jboss.reddeer.common.util.Display.syncExec(new Runnable() { @Override public void run() { for (Shell shell : org.jboss.reddeer.common.util.Display.getDisplay().getShells()) { if (shell.getText().equals(title)) { shell.dispose(); break; } } } }); new WaitWhile(new ShellWithTextIsAvailable(title)); }
Source:
public int getLineOfText(final String text) { START return TextEditorHandler.getInstance().getLineOfText((ITextEditor)getEditorPart(), text); END } call getLineOfText(text,0) instead of TextEditorHandler...

Target:
public int getLineOfText(final String text) { return getLineOfText(text, 0); }
Source:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } // do not exceed max value of Long if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { START return Math.round(seconds * FACTOR); END } } Use this expression Math.round((double)seconds \* factor) otherwise round method will return Integer.MAX_VALUE for each input greater then Integer.MAX_VALUE. It's because input parameter for round method is evaluated to float and therefore it returns integer instead of long.

Target:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } // do not exceed max value of Long if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round((double) seconds * FACTOR); } }
Source:
public ExactNumberOfProblemsExists(ProblemType type, int count) { if(type == null) { throw new NullPointerException("Problem Type cannot be null"); } if(count < 0) { throw new IllegalArgumentException("Number of problems must be greater than zero."); } this.problemType = type; this.expectedProblemsCount = count; START matchers = new AbstractProblemMatcher[]{}; END problemsView = new ProblemsView(); } Call constructors in the other way around please: ExactNumberOfProblemsExists(ProblemType type, int count) should call this (type, count, new AbstractProblemMatcher[]{}) and all logic should be there. Use this. also for matchers field

Target:
public ExactNumberOfProblemsExists(ProblemType type, int count) { this(type, count, new AbstractProblemMatcher[]{}); }
Source:
private static RedDeerProperties getByName(String name){ RedDeerProperties rdProperty; START try { END rdProperty = RedDeerProperties.getByName(name); } catch (RedDeerException e) { rdProperty = RedDeerProperties.getByName("reddeer." + name); } return rdProperty; } Do not use try catch please instead use if (!name.startsWith("reddeer.") ...

Target:
private static RedDeerProperties getByName(String name){ if (name.startsWith("reddeer.")){ return RedDeerProperties.getByName(name); } else { return RedDeerProperties.getByName("reddeer." + name); } }
Source:
START public void saveTask () { END new ShellMenu("File", "Save").select(); new ShellMenu("File", "Properties").select(); new PushButton("OK").click(); } I was not able to find any use case when File -> Save menu is enabled. So Im wondering if there's any ? Also at line 37 you are calling shell menu File -> Properties and then clicking on OK. This seems to be needless operation ..?

Target:
public void saveTask () { new ShellMenu("File", "Save").select(); }
Source:
public void setNewHighScoreMode(boolean mode) { if (mode) { this.clearTouchAreas(); this.registerTouchArea(inputText); inputText.setVisible(true); inTopText.setVisible(true); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); } else { this.clearTouchAreas(); inputText.setVisible(false); inTopText.setVisible(false); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); START } END } this.clearTouchAreas можно вынести из if и можно написать inputText.setVisible(mode) и по аналогии для других

Target:
public void setNewHighScoreMode(boolean mode) { this.clearTouchAreas(); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); if (mode) { this.registerTouchArea(inputText); inputText.setVisible(true); inTopText.setVisible(true); } else { inputText.setVisible(false); inTopText.setVisible(false); } }
Source:
private void fire() { Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); activity.getSceneSwitcher().getGameScene().createTorpedo( gun.getShootStartPoint() START , gun.getGunAngle()); END } я вообще думал, что выстрел будет делаться так gun.fire(); т.е. activity.getSceneSwitcher().getGameScene().createTorpedo( gun.getShootStartPoint(),gun.getGunAngle()); выполнять в методе класса Gun

Target:
private void fire() { getGun().fire(); }
Source:
private void stopGun() { START Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); END gun.stopRotate(); } Часто повторяется, лучше сделать метод getGun в классе SceletoneActivity или Events

Target:
private void stopGun() { getGun().stopRotate(); }
Source:
public List<String> getLines() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); List<String> lines = new ArrayList<String>(); START String line; END while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } remove the explicit initialization?

Target:
public List<String> getLines() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); List<String> lines = new ArrayList<String>(); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }
Source:
private String readRequestToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringWriter writer = new StringWriter(); START String line; END while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { break; } writer.write(line); writer.write('\n'); } return writer.toString(); } please dont remove explicit initialization

Target:
private String readRequestToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringWriter writer = new StringWriter(); String line = null; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { break; } writer.write(line); writer.write('\n'); } return writer.toString(); }
Source:
public String getContentAsString() { START String content; END try { final InputStream contentStream = Samples.class.getResourceAsStream(filePath); content = StreamUtils.readToString(contentStream, StreamUtils.UTF_8); } catch (Throwable e) { e.printStackTrace(); throw new RuntimeException("Could not read file " + filePath + ": " + e.getMessage()); } return content; } please dont remove explicit initialization

Target:
public String getContentAsString() { String content = null; try { final InputStream contentStream = Samples.class.getResourceAsStream(filePath); content = StreamUtils.readToString(contentStream, StreamUtils.UTF_8); } catch (Throwable e) { e.printStackTrace(); throw new RuntimeException("Could not read file " + filePath + ": " + e.getMessage()); } return content; }
Source:
public static List<String> getAllPaths(InputStream in) throws IOException { Assert.notNull(in); List<String> paths = new ArrayList<String>(); TarArchiveInputStream archiveIn = new TarArchiveInputStream(new GZIPInputStream(in)); try { START for (ArchiveEntry nextEntry; (nextEntry = archiveIn.getNextEntry()) != null;) { END paths.add(nextEntry.getName()); } return paths; } finally { StreamUtils.close(archiveIn); } } please dont remove explicit initialization

Target:
public static List<String> getAllPaths(InputStream in) throws IOException { Assert.notNull(in); List<String> paths = new ArrayList<String>(); TarArchiveInputStream archiveIn = new TarArchiveInputStream(new GZIPInputStream(in)); try { for (ArchiveEntry nextEntry = null; (nextEntry = archiveIn.getNextEntry()) != null;) { paths.add(nextEntry.getName()); } return paths; } finally { StreamUtils.close(archiveIn); } }
Source:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { START IDomain domain; END try { // pre-condition domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); // operation domain.destroy(); // verification fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { // verification } } please dont remove explicit initialization

Target:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain = null; try { // pre-condition domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); // operation domain.destroy(); // verification fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { // verification } }
Source:
private HttpServerFake startHttpServerFake(String statusLine) throws Exception { int port = new Random().nextInt(9 * 1024) + 1024; START HttpServerFake serverFake; END if (statusLine == null) { serverFake = new HttpServerFake(port); } else { serverFake = new HttpServerFake(port, null, statusLine); } serverFake.start(); return serverFake; } please dont remove explicit initialization

Target:
private HttpServerFake startHttpServerFake(String statusLine) throws Exception { int port = new Random().nextInt(9 * 1024) + 1024; HttpServerFake serverFake = null; if (statusLine == null) { serverFake = new HttpServerFake(port); } else { serverFake = new HttpServerFake(port, null, statusLine); } serverFake.start(); return serverFake; }
Source:
START public AbstractConnectionBuilder<CredentialsConnectionBuilder> credentials(String username, String password) { END return new CredentialsConnectionBuilder(username, password, this.serverUrl); } If we end up getting some config attributes from the express.conf we could overload this one and set the username ``` public AbstractConnectionBuilder<CredentialsConnectionBuilder> credentials(String password) { return new CredentialsConnectionBuilder(config.getRhLogin(), password, this.serverUrl); } ```

Target:
public CredentialsConnectionBuilder credentials(String username, String password) { return new CredentialsConnectionBuilder(username, password, serverUrl, configuration); }
Source:
public List<String> getLines(Channel channel) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(channel))); List<String> lines = new ArrayList<String>(); START String line; END // Read File Line By Line while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } I doesnt really matter, just nitpicking: local vars are non-initialized. Good practice is to initialize them to a defined value. But sure, it doesnt matter here since the code right below will do it.

Target:
public List<String> getLines(Channel channel) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(channel))); List<String> lines = new ArrayList<String>(); String line = null; // Read File Line By Line while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }
Source:
protected void updateEnvironmentVariables() throws OpenShiftException { if (!canGetEnvironmentVariables()) { return; } START if (environmentVariablesMap == null) { END environmentVariablesMap = loadEnvironmentVariables(); } else { environmentVariablesMap.clear(); environmentVariablesMap.putAll(loadEnvironmentVariables()); } } here we're still checking for env map to be null, which is not possible any more, right (since you initialize it as empty map)?

Target:
protected void updateEnvironmentVariables() throws OpenShiftException { if (!canGetEnvironmentVariables()) return; else { environmentVariablesMap.clear(); environmentVariablesMap = loadEnvironmentVariables(); } }
Source:
private boolean isInPowerSaveMode() { PowerManager powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE); START if (powerManager != null) { return powerManager.isPowerSaveMode(); } else { return false; } END } It is simpler this way, don't you think? `return (powerManager != null) && powerManager.isPowerSaveMode();`

Target:
private boolean isInPowerSaveMode() { PowerManager powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE); return (powerManager != null) && powerManager.isPowerSaveMode(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = this; generateAndStoreKey(); if (initCipher()) { mCryptoObject = new BiometricPrompt.CryptoObject(mCipher); } BiometricManager biometricManager = BiometricManager.from(this); START switch (biometricManager.canAuthenticate()) { case BiometricManager.BIOMETRIC_SUCCESS: showBiometricPrompt(); END break; default: authError(); } } Use if instead of switch if there are only 2 options 👍

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = this; generateAndStoreKey(); if (initCipher()) { mCryptoObject = new BiometricPrompt.CryptoObject(mCipher); } BiometricManager biometricManager = BiometricManager.from(this); if (biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) { showBiometricPrompt(); } else { authError(); } }
Source:
START public boolean isBiometricEnabled() { END SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.Companion.getAppContext()); return (appPrefs.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false)); } It can be private

Target:
protected boolean isBiometricEnabled() { SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.Companion.getAppContext()); return (appPrefs.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false)); }
Source:
START protected boolean isShowingOnlyAvailableOffline() { END Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); } protected not needed. Android Studio warns you about that. ![Screenshot 2019-03-13 at 17 28 17](https://user-images.githubusercontent.com/15261363/54296547-6ce73680-45b5-11e9-8e8c-d75d9fb39e68.png)

Target:
boolean isShowingOnlyAvailableOffline() { Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }
Source:
private void openHelp() { final String helpWeb = (String) getText(R.string.url_help); START if (helpWeb != null && helpWeb.length() > 0) { END Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(helpWeb)); startActivity(intent); } } Do you really need this check?

Target:
private void openHelp() { final String helpWeb = (String) getText(R.string.url_help); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(helpWeb)); startActivity(intent); }
Source:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); // check if its a oauth SALS callback intent if(intent.getAction().equals(ACTION_VIEW) && START intent.getData().getHost().equals("android.owncloud.com")) { END getOAuth2AccessTokenFromCapturedRedirection(intent.getData()); } } Isn't there a different way to get "android.owncloud.com" instead of using a hardcoded string?

Target:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); if(intent.getAction().equals(ACTION_VIEW)) { getOAuth2AccessTokenFromCapturedRedirection(intent.getData()); } }
Source:
public void onClick(View v) { if (v.getId() == R.id.upload_files_btn_cancel) { setResult(RESULT_CANCELED); finish(); } START else if (v.getId() == R.id.upload_files_btn_upload) { END new CheckAvailableSpaceTask().execute(); } } Move this else if just after the } above

Target:
public void onClick(View v) { if (v.getId() == R.id.upload_files_btn_cancel) { setResult(RESULT_CANCELED); finish(); } else if (v.getId() == R.id.upload_files_btn_upload) { new CheckAvailableSpaceTask(null).execute(); } }
Source:
protected void onActivityResult(int requestCode,int resultCode,Intent capturedData){ if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){ Bundle capturedImageData = capturedData.getExtras(); Bitmap capturedImage = (Bitmap) capturedImageData.get("data"); Uri capturedImageUri = getImageUri(getApplicationContext(),capturedImage); START capturedImagePath = getRealPathFromUri(capturedImageUri); END new CheckAvailableSpaceTask().execute(); } else if(resultCode == RESULT_CANCELED){ setResult(RESULT_CANCELED); finish(); } } Instead of declaring capturedImagePath as global, you can declare and initialize it here and pass it to CheckAvailableSpaceTask(), look the answer of [https://stackoverflow.com/questions/3075009/android-how-can-i-pass-parameters-to-asynctasks-onpreexecute/3077050](url)

Target:
protected void onActivityResult(int requestCode,int resultCode,Intent capturedData){ if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){ Bundle capturedImageData = capturedData.getExtras(); Bitmap capturedImage = (Bitmap) capturedImageData.get("data"); Uri capturedImageUri = getImageUri(getApplicationContext(),capturedImage); String capturedImagePath = getRealPathFromUri(capturedImageUri); new CheckAvailableSpaceTask(capturedImagePath).execute(); } else if(resultCode == RESULT_CANCELED){ setResult(RESULT_CANCELED); finish(); } }
Source:
public long getImposedExpirationDate () { long imposedExpirationDate = -1; START if (mCapabilities.getFilesSharingPublicExpireDateEnforced().isTrue()) { END imposedExpirationDate = DateUtils.addDaysToDate( new Date(), mCapabilities.getFilesSharingPublicExpireDateDays() ).getTime(); } return imposedExpirationDate; } I would add a ```NULL``` check for ```mCapabilities``` to this condition.

Target:
private long getImposedExpirationDate () { long imposedExpirationDate = -1; if (mCapabilities!= null && mCapabilities. getFilesSharingPublicExpireDateEnforced().isTrue()) { imposedExpirationDate = DateUtils.addDaysToDate( new Date(), mCapabilities.getFilesSharingPublicExpireDateDays() ).getTime(); } return imposedExpirationDate; }
Source:
public static boolean isNetworkActive(Context context) { boolean isNetworkActive = true; ConnectivityManager cm = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); // Check network availabality (no info object implies no connectivity) START if (activeNetwork == null || (activeNetwork!= null && END !activeNetwork.isConnectedOrConnecting())) { isNetworkActive = false; } return isNetworkActive; } I would simplify to ```return (activeNetwork != null && activeNetwork.isConnectedOrConnecting())``` . No ```isActiveNetwork``` variable declared nor assigned, easier condition.

Target:
public static boolean isNetworkActive(Context context) { ConnectivityManager cm = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.isConnectedOrConnecting()); }
Source:
public void onResume() { super.onResume(); Log_OC.v(TAG, "onResume"); START if ((Util.SDK_INT <= 23 || player == null)) { END preparePlayer(); } } Why the difference depending on API level? Just curious.

Target:
public void onResume() { super.onResume(); Log_OC.v(TAG, "onResume"); preparePlayer(); }
Source:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } START catch (NullPointerException e) { END Log_OC.e(TAG, "NullPointerException while stopping on OCFile ", e); } } In general, `NullPointerException`s shouldn't be cached - the input of the block should be tested to prevent it occurs.

Target:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); if(file != null && file.equals(mFile)) { processStopRequest(true); } }
Source:
public void onCheckedChanged(CompoundButton switchView, boolean isChecked) { if (!isResumed()) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return; } START boolean permission; END if (isChecked) { permission = true; } else { permission = false; } ((FileActivity) getActivity()).getFileOperationsHelper(). setUploadPermissionsToShare( mFile, permission ); ; // undo the toggle to grant the view will be correct if the dialog is cancelled switchView.setOnCheckedChangeListener(null); switchView.toggle(); switchView.setOnCheckedChangeListener(mOnEditPermissionInteractionListener); } The value of `permission` may be set in a single line. Moreover, there is no real need of `permission`variable, `ìsChecked``may be used directly as parameter to pass to``setUploadPermissionsToShare``

Target:
public void onCheckedChanged(CompoundButton switchView, boolean isChecked) { if (!isResumed()) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return; } ((FileActivity) getActivity()).getFileOperationsHelper(). setUploadPermissionsToShare( mFile, isChecked ); ; // undo the toggle to grant the view will be correct if the dialog is cancelled switchView.setOnCheckedChangeListener(null); switchView.toggle(); switchView.setOnCheckedChangeListener(mOnEditPermissionInteractionListener); }
Source:
public static ShareType getShareType(String authority) { START if (sShareTypes.containsKey(authority)) { END return sShareTypes.get(authority); } return null; } This method may be written in a single line; check the reference for `HashMap#get`, it returns `null` if the key doesn't exist. http://developer.android.com/intl/es/reference/java/util/HashMap.html#get(java.lang.Object)

Target:
public static ShareType getShareType(String authority) { return sShareTypes.get(authority); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: finish(); START break; END default: Log_OC.w(TAG, "Unknown menu item triggered"); return false; } return true; } You can early return here

Target:
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: Log_OC.w(TAG, "Unknown menu item triggered"); return false; } }
Source:
START public static void saveBooleanPreference(String key, boolean value, Context context) { END SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putBoolean(key, value); appPreferences.apply(); } I think this and the next two methods should be `private`

Target:
private static void saveBooleanPreference(String key, boolean value, Context context) { SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putBoolean(key, value); appPreferences.apply(); }
Source:
protected RemoteOperationResult run(OwnCloudClient client) { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); START if (result.isSuccess()){ END // Read data from the result OCCapability capability = (OCCapability) result.getData().get(0); // Save the capabilities into database getStorageManager().saveCapabilities(capability); } return result; } Didn't check the mplementation behind this, but would it make sense to null check result, result.getData() and result.getDate().get(0) is this null safe by design?

Target:
protected RemoteOperationResult run(OwnCloudClient client) { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); if (result.isSuccess()){ // Read data from the result if( result.getData()!= null && result.getData().size() > 0) { OCCapability capability = (OCCapability) result.getData().get(0); // Save the capabilities into database getStorageManager().saveCapabilities(capability); } } return result; }
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); START if (DisplayUtils.isGridView(directory, getStorageManager())){ END switchToGridView(); } else { switchToListView(); } } same code fragment as line 325ff

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); }
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); START MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); END changeGridIcon(); switchLayout(directory); } Variable not used; please, remove this line.

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); mOptionsMenu = menu; START MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); END changeGridIcon(); return true; } Variable not used; please, remove this line.

Target:
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; }
Source:
public AuthenticatorAsyncTask(Activity activity) { mContext = activity.getApplicationContext(); mListener = new WeakReference<OnAuthenticatorTaskListener>((OnAuthenticatorTaskListener)activity); START mActivity = activity; END } This attributie is not used, and not needed; please remove it.

Target:
public AuthenticatorAsyncTask(Activity activity) { mContext = activity.getApplicationContext(); mListener = new WeakReference<OnAuthenticatorTaskListener>((OnAuthenticatorTaskListener)activity); }
Source:
public void cancel(Account account, OCFile file) { UploadFileOperation upload = null; synchronized (mPendingUploads) { upload = mPendingUploads.remove(buildRemoteName(account, file)); } if (upload != null) { START mCurrentUpload.cancel(); END } } I'd say the change in this line is a mistake solving conflicts, right?

Target:
public void cancel(Account account, OCFile file) { UploadFileOperation upload = null; synchronized (mPendingUploads) { upload = mPendingUploads.remove(buildRemoteName(account, file)); } if (upload != null) { upload.cancel(); } }
Source:
private void syncContents(OwnCloudClient client) { startDirectDownloads(); startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client); startContentSynchronizations(mFavouriteFilesToSyncContents, client); START walkSubfolders(mFoldersToWalkDown, client); // this must be the last! END } Maybe, we can use directly mFoldersToWalkDown in walkSubfolders() without having to pass it

Target:
private void syncContents(OwnCloudClient client) { startDirectDownloads(); startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client); startContentSynchronizations(mFavouriteFilesToSyncContents, client); walkSubfolders(client); // this must be the last! }
Source:
private static String getExtension(String filename) { START String extension = filename.toLowerCase().substring(filename.lastIndexOf(".") + 1); END return extension; } I'd rather `toLowerCase()` is applied after `substring()`, not before.

Target:
private static String getExtension(String filename) { String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); return extension; }
Source:
public void onResume() { super.onResume(); Log_OC.e(TAG, "onResume"); START loadAndShowTextPreview(); END } Please, don't reload the text in `onResume()`. Do it in `onCreateView()` or `onActivityCreated()`; `onPause()` and `onResume()` may be called when other windows partially hide the fragment (such as the menu showing apps to open the file outside of ownCloud) even though it stays visible.

Target:
public void onResume() { super.onResume(); Log_OC.e(TAG, "onResume"); }
Source:
public void setFooterView(View footer) { START mList.addFooterView(footer); END mList.invalidate(); } Check that when user clicks on that item (the last one with the info), it is not highlighted as the others because, maybe, it is not a very good behaviour.

Target:
public void setFooterView(View footer) { mList.addFooterView(footer, null, false); mList.invalidate(); }
Source:
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) { Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description); if (!failingUrl.equals(mLastReloadedUrlAtError)) { view.reload(); mLastReloadedUrlAtError = failingUrl; START } else { END mLastReloadedUrlAtError = null; } } call super.onReceivedError();

Target:
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) { Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description); if (!failingUrl.equals(mLastReloadedUrlAtError)) { view.reload(); mLastReloadedUrlAtError = failingUrl; } else { mLastReloadedUrlAtError = null; super.onReceivedError(view, errorCode, description, failingUrl); } }
Source:
public static void assertCompany(Company company) { assertBaseCompany(company, true); assertThat(company.headquarters).isNotNull(); assertThat(company.homepage).isNotNull(); assertThat(company.origin_country).isNotEmpty(); START assertThat(company.origin_country).isNotEmpty(); END if (company.parent_company != null) assertBaseCompany(company.parent_company, true); } Any reason this is asserted twice?

Target:
public static void assertCompany(Company company) { assertBaseCompany(company, true); assertThat(company.headquarters).isNotNull(); assertThat(company.homepage).isNotNull(); assertThat(company.origin_country).isNotEmpty(); if (company.parent_company != null) assertBaseCompany(company.parent_company, true); }
Source:
public void test_upcoming() throws IOException { Call<MovieResultsPage> call = getUnauthenticatedInstance().moviesService().upcoming( null, START "el" END ); MovieResultsPage page = call.execute().body(); assertThat(page).isNotNull(); assertThat(page.results).isNotEmpty(); } Any reason why you changed this from the default? If no, please revert.

Target:
public void test_upcoming() throws IOException { Call<MovieResultsPage> call = getUnauthenticatedInstance().moviesService().upcoming(); MovieResultsPage page = call.execute().body(); assertThat(page).isNotNull(); assertThat(page.results).isNotEmpty(); }
Source:
START public TDImportResult importBytes(String databaseName, String tableName, byte[] content) END { return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, TDImportResult.class); } Should we support offset and length arguments as well?

Target:
public TDImportResult importBytes(String databaseName, String tableName, byte[] content) { return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, 0, content.length, TDImportResult.class); }