id
stringlengths 29
30
| content
stringlengths 152
2.6k
|
|---|---|
codereview_new_java_data_10945
|
void registerInstance(String serviceName, String groupName, String ip, int port,
* @param groupName group of service
* @param instances instances to deRegister
* @throws NacosException nacos exception
- * @since 2.1.1
*/
- void batchDeRegisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* deregister instance from a service.
since version error. I think should be move to 2.2.0
void registerInstance(String serviceName, String groupName, String ip, int port,
* @param groupName group of service
* @param instances instances to deRegister
* @throws NacosException nacos exception
+ * @since 2.2.0
*/
+ void batchDeregisterInstance(String serviceName, String groupName, List<Instance> instances) throws NacosException;
/**
* deregister instance from a service.
|
codereview_new_java_data_10946
|
*/
public class ConfigAdvanceInfo implements Serializable {
- static final long serialVersionUID = -3148031484920416869L;
private long createTime;
```suggestion
static final long serialVersionUID = 3148031484920416869L;
```
*/
public class ConfigAdvanceInfo implements Serializable {
+ static final long serialVersionUID = 3148031484920416869L;
private long createTime;
|
codereview_new_java_data_10947
|
public class EnvUtil {
* customEnvironment.
*/
public static void customEnvironment() {
- Boolean enableCustom = getProperty(NACOS_CUSTOM_ENVIRONMENT_ENABLED, Boolean.class);
- if (Boolean.TRUE.equals(enableCustom)) {
Set<String> propertyKeys = CustomEnvironmentPluginManager.getInstance().getPropertyKeys();
Map<String, Object> sourcePropertyMap = new HashMap<>(propertyKeys.size());
for (String key : propertyKeys) {
`if (enableCustom) ` is enough?
public class EnvUtil {
* customEnvironment.
*/
public static void customEnvironment() {
+ boolean enableCustom = getProperty(NACOS_CUSTOM_ENVIRONMENT_ENABLED, Boolean.class, false);
+ if (enableCustom) {
Set<String> propertyKeys = CustomEnvironmentPluginManager.getInstance().getPropertyKeys();
Map<String, Object> sourcePropertyMap = new HashMap<>(propertyKeys.size());
for (String key : propertyKeys) {
|
codereview_new_java_data_10948
|
public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
}
}
filterChain.doFilter(request, servletResponse);
- if (threadLocalClientAttributes.get() != null) {
- threadLocalClientAttributes.remove();
- }
} catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"clientAttributes filter error," + ExceptionUtil.getAllExceptionMsg(e));
}
}
remove thread local move to finally. otherwise will casue memory leak when many exception thrown.
public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
}
}
filterChain.doFilter(request, servletResponse);
+
} catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"clientAttributes filter error," + ExceptionUtil.getAllExceptionMsg(e));
+ } finally {
+ if (threadLocalClientAttributes.get() != null) {
+ threadLocalClientAttributes.remove();
+ }
}
}
|
codereview_new_java_data_10949
|
public RestResult<Boolean> stopBeta(@RequestParam(value = "dataId") String dataI
}
ConfigChangePublisher.notifyConfigChange(
new ConfigDataChangeEvent(true, dataId, group, tenant, System.currentTimeMillis()));
- return RestResultUtils.success("remove beta ok", true);
}
/**
I think stop is ok
public RestResult<Boolean> stopBeta(@RequestParam(value = "dataId") String dataI
}
ConfigChangePublisher.notifyConfigChange(
new ConfigDataChangeEvent(true, dataId, group, tenant, System.currentTimeMillis()));
+ return RestResultUtils.success("stop beta ok", true);
}
/**
|
codereview_new_java_data_10950
|
class JvmArgsPropertySource extends AbstractPropertySource {
- private final Properties properties = new Properties(System.getProperties());
@Override
SourceType getType() {
Why do this changes? I think the old way is ok and better.
class JvmArgsPropertySource extends AbstractPropertySource {
+ private final Properties properties;
+
+ JvmArgsPropertySource() {
+ this.properties = System.getProperties();
+ }
@Override
SourceType getType() {
|
codereview_new_java_data_10951
|
*/
public class BatchInstanceData implements Serializable {
- private static final long serialVersionUID = 1L;
private List<String> namespaces;
use auto generator serialVersionUID.
*/
public class BatchInstanceData implements Serializable {
+ private static final long serialVersionUID = 7845847904043098494L;
private List<String> namespaces;
|
codereview_new_java_data_10953
|
*/
public class Member implements Comparable<Member>, Cloneable, Serializable {
- private static final long serialVersionUID = 1L;
private String ip;
Why not generated auto by idea?
*/
public class Member implements Comparable<Member>, Cloneable, Serializable {
+ private static final long serialVersionUID = -6061130045021268736L;
private String ip;
|
codereview_new_java_data_10954
|
public EphemeralClientOperationServiceImpl(ClientManagerDelegate clientManager)
}
@Override
- public void registerInstance(Service service, Instance instance, String clientId) {
- try {
- NamingUtils.checkInstanceIsLegal(instance);
- } catch (NacosException e) {
- throw new NacosRuntimeException(e.getErrCode(), e.getErrMsg());
- }
Service singleton = ServiceManager.getInstance().getSingleton(service);
if (!singleton.isEphemeral()) {
same as above.
public EphemeralClientOperationServiceImpl(ClientManagerDelegate clientManager)
}
@Override
+ public void registerInstance(Service service, Instance instance, String clientId) throws NacosException {
+ NamingUtils.checkInstanceIsLegal(instance);
Service singleton = ServiceManager.getInstance().getSingleton(service);
if (!singleton.isEphemeral()) {
|
codereview_new_java_data_10955
|
protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequest
recommendServer.set(null);
}
- if (RpcClient.this.serverListFactory.getServerList().size() == 0) {
throw new Exception("server list is empty");
}
```suggestion
if (CollectionUtils.isEmpty(RpcClient.this.serverListFactory.getServerList())) {
```
I think it's better
protected void reconnect(final ServerInfo recommendServerInfo, boolean onRequest
recommendServer.set(null);
}
+ if (CollectionUtils.isEmpty(RpcClient.this.serverListFactory.getServerList())) {
throw new Exception("server list is empty");
}
|
codereview_new_java_data_10956
|
public void onFailed(Throwable throwable) {
if (null == throwable) {
Loggers.DISTRO.info("[DISTRO-END] {} result: false", getDistroKey().toString());
} else {
- Loggers.DISTRO.warn("[DISTRO] Sync data change failed. key: {}", getDistroKey(), throwable);
}
handleFailedTask();
}
```suggestion
Loggers.DISTRO.warn("[DISTRO] Sync data change failed. key: {}", getDistroKey().toString(), throwable);
```
I think it is better
public void onFailed(Throwable throwable) {
if (null == throwable) {
Loggers.DISTRO.info("[DISTRO-END] {} result: false", getDistroKey().toString());
} else {
+ Loggers.DISTRO.warn("[DISTRO] Sync data change failed. key: {}", getDistroKey().toString(), throwable);
}
handleFailedTask();
}
|
codereview_new_java_data_10957
|
class DefaultSettingPropertySource extends AbstractPropertySource {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSettingPropertySource.class);
- private static final String DEFAULT_SETTING_PATH = "classpath:default_setting.properties";
private final Properties defaultSetting = new Properties();
add `nacos` word to reduce the possible rate for conflict with other tools.
class DefaultSettingPropertySource extends AbstractPropertySource {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSettingPropertySource.class);
+ private static final String DEFAULT_SETTING_PATH = "classpath:nacos_default_setting.properties";
private final Properties defaultSetting = new Properties();
|
codereview_new_java_data_10958
|
public void batchRegisterService(String serviceName, String groupName, List<Inst
NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} begin.", instances, serviceName);
if (CollectionUtils.isEmpty(instances)) {
NAMING_LOGGER.warn("batchRegisterInstance instances is Empty:{}", instances);
- grpcClientProxy.batchRegisterService(serviceName, groupName, instances);
}
- getExecuteClientProxy(instances.get(0)).batchRegisterService(serviceName, groupName, instances);
NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName);
}
ArrayIndexOutOf if instances is empty.
public void batchRegisterService(String serviceName, String groupName, List<Inst
NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} begin.", instances, serviceName);
if (CollectionUtils.isEmpty(instances)) {
NAMING_LOGGER.warn("batchRegisterInstance instances is Empty:{}", instances);
}
+ grpcClientProxy.batchRegisterService(serviceName, groupName, instances);
NAMING_LOGGER.info("batchRegisterInstance instances: {} ,serviceName: {} finish.", instances, serviceName);
}
|
codereview_new_java_data_10959
|
public static void checkInstanceIsLegal(Instance instance) throws NacosException
public static void checkInstanceIsEphemeral(Instance instance) throws NacosException {
if (!instance.isEphemeral()) {
throw new NacosException(NacosException.INVALID_PARAM,
- String.format("Batch registration does not allow non-temporary instance registration , Instance:%s", instance));
}
}
`non-temporary` -> `non-ephemeral` or `persistent`
public static void checkInstanceIsLegal(Instance instance) throws NacosException
public static void checkInstanceIsEphemeral(Instance instance) throws NacosException {
if (!instance.isEphemeral()) {
throw new NacosException(NacosException.INVALID_PARAM,
+ String.format("Batch registration does not allow persistent instance registration , Instance:%s", instance));
}
}
|
codereview_new_java_data_10960
|
public String callServer(String api, Map<String, String> params, Map<String, Str
}
url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
}
-
try {
HttpRestResult<String> restResult = nacosRestTemplate
.exchangeForm(url, header, Query.newInstance().initParams(params), body, method, String.class);
Why remove indent?
public String callServer(String api, Map<String, String> params, Map<String, Str
}
url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
}
try {
HttpRestResult<String> restResult = nacosRestTemplate
.exchangeForm(url, header, Query.newInstance().initParams(params), body, method, String.class);
|
codereview_new_java_data_10961
|
public void updateInstance(Service service, Instance instance, String clientId)
request.setInstance(instance);
request.setClientId(clientId);
final WriteRequest writeRequest = WriteRequest.newBuilder()
- .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP_V2)
.setData(ByteString.copyFrom(serializer.serialize(request))).setOperation(DataOperation.CHANGE.name())
.build();
try {
Pls use `group()` instead.
public void updateInstance(Service service, Instance instance, String clientId)
request.setInstance(instance);
request.setClientId(clientId);
final WriteRequest writeRequest = WriteRequest.newBuilder()
+ .setGroup(group())
.setData(ByteString.copyFrom(serializer.serialize(request))).setOperation(DataOperation.CHANGE.name())
.build();
try {
|
codereview_new_java_data_10962
|
public void onDelete(String datumKey, RaftPeer source) throws Exception {
@Override
public void shutdown() throws NacosException {
this.stopWork = true;
- if (!initialized) {
- return;
- }
this.raftStore.shutdown();
this.peers.shutdown();
Loggers.RAFT.warn("start to close old raft protocol!!!");
No need to check initialized
public void onDelete(String datumKey, RaftPeer source) throws Exception {
@Override
public void shutdown() throws NacosException {
this.stopWork = true;
this.raftStore.shutdown();
this.peers.shutdown();
Loggers.RAFT.warn("start to close old raft protocol!!!");
|
codereview_new_java_data_10963
|
public class DistroConstants {
public static final String DATA_LOAD_TIMEOUT_MILLISECONDS = "nacos.core.protocol.distro.data.load.timeoutMs";
- public static final long DEFAULT_DATA_LOAD_TIMEOUT_MILLISECONDS = 3000L;
}
default 3s maybe not enough.
public class DistroConstants {
public static final String DATA_LOAD_TIMEOUT_MILLISECONDS = "nacos.core.protocol.distro.data.load.timeoutMs";
+ public static final long DEFAULT_DATA_LOAD_TIMEOUT_MILLISECONDS = 30000L;
}
|
codereview_new_java_data_10964
|
public void close() {
while (ORIGIN_SERVER.equals(rpc.getCurrentServer().getServerIp())) {
TimeUnit.SECONDS.sleep(1);
if (--retry < 0) {
- Assert.fail("failed to auth switch server!");
}
}
No this PR content.
public void close() {
while (ORIGIN_SERVER.equals(rpc.getCurrentServer().getServerIp())) {
TimeUnit.SECONDS.sleep(1);
if (--retry < 0) {
+ Assert.fail("failed to auth switch server");
}
}
|
codereview_new_java_data_11009
|
public AsyncExecutableHttpRequest prepareRequest(HttpRequest requestInfo) {
}
case "DELETE": {
request = AsyncRequestBuilder.delete(uri);
- setRequestEntity(requestInfo,request);
break;
}
default: {
Nitpick to match project formatting style; add a space
```suggestion
setRequestEntity(requestInfo, request);
```
public AsyncExecutableHttpRequest prepareRequest(HttpRequest requestInfo) {
}
case "DELETE": {
request = AsyncRequestBuilder.delete(uri);
+ setRequestEntity(requestInfo, request);
break;
}
default: {
|
codereview_new_java_data_11010
|
public MilestoneActivityBehavior createMilestoneActivityBehavior(PlanItem planIt
} else if (StringUtils.isNotEmpty(milestone.getName())) {
name = milestone.getName();
}
- return new MilestoneActivityBehavior(expressionManager.createExpression(name), milestone.getMilestoneVariable(),milestone.getBusinessStatusUpdate());
}
@Override
Here is another missing space:
```suggestion
return new MilestoneActivityBehavior(expressionManager.createExpression(name), milestone.getMilestoneVariable(), milestone.getBusinessStatusUpdate());
```
public MilestoneActivityBehavior createMilestoneActivityBehavior(PlanItem planIt
} else if (StringUtils.isNotEmpty(milestone.getName())) {
name = milestone.getName();
}
+ return new MilestoneActivityBehavior(expressionManager.createExpression(name), milestone.getMilestoneVariable(), milestone.getBusinessStatusUpdate());
}
@Override
|
codereview_new_java_data_11011
|
protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHe
TimerEventListener timerEventListener = (TimerEventListener) conversionHelper.getCurrentCmmnElement();
timerEventListener.setTimerStartTriggerStandardEvent(event);
} else {
- conversionHelper.getCurrentSentryOnPart().setStandardEvent(xtr.getText());
}
} catch (XMLStreamException e) {
throw new FlowableException("Error converting standard event", e);
I think that here we need to use the `event` that we got from the `xtr.getElementText()` call on line 40
protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHe
TimerEventListener timerEventListener = (TimerEventListener) conversionHelper.getCurrentCmmnElement();
timerEventListener.setTimerStartTriggerStandardEvent(event);
} else {
+ conversionHelper.getCurrentSentryOnPart().setStandardEvent(event);
}
} catch (XMLStreamException e) {
throw new FlowableException("Error converting standard event", e);
|
codereview_new_java_data_11012
|
import org.flowable.bpmn.converter.util.BpmnXMLUtil;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.BpmnModel;
-import org.flowable.bpmn.model.FlowableListener;
import org.flowable.bpmn.model.HasScriptInfo;
import org.flowable.bpmn.model.ScriptInfo;
I think the import of `FlowableListener` should be removed given the changes to this file.
import org.flowable.bpmn.converter.util.BpmnXMLUtil;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.HasScriptInfo;
import org.flowable.bpmn.model.ScriptInfo;
|
codereview_new_java_data_11013
|
import java.util.ArrayList;
import java.util.List;
-import java.util.Objects;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonIgnore;
I don't see `Objects` used in this class.
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonIgnore;
|
codereview_new_java_data_11014
|
package org.flowable.engine.impl.bpmn.http.handler;
import org.flowable.common.engine.api.FlowableIllegalStateException;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.api.variable.VariableContainer;
import org.flowable.common.engine.impl.scripting.AbstractScriptEvaluator;
import org.flowable.common.engine.impl.scripting.ScriptingEngines;
-import org.flowable.engine.impl.bpmn.http.delegate.HttpRequestHandlerInvocation;
-import org.flowable.engine.impl.bpmn.listener.ScriptExecutingListener;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.http.common.api.HttpRequest;
import org.flowable.http.common.api.HttpResponse;
Missing license header
+/* Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.flowable.engine.impl.bpmn.http.handler;
import org.flowable.common.engine.api.FlowableIllegalStateException;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.common.engine.api.variable.VariableContainer;
import org.flowable.common.engine.impl.scripting.AbstractScriptEvaluator;
import org.flowable.common.engine.impl.scripting.ScriptingEngines;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.http.common.api.HttpRequest;
import org.flowable.http.common.api.HttpResponse;
|
codereview_new_java_data_11424
|
public boolean runRandomizer() {
compositeDisposable.add(reviewHelper.getRandomMedia()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
- .subscribe(this::checkUsageOfMedia));
return true;
}
/**
* Check whether media is used or not in any Wiki Page
*/
@SuppressLint("CheckResult")
- private void checkUsageOfMedia(final Media media) {
compositeDisposable.add(reviewHelper.checkFileUsage(media.getFilename())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
How about renaming this to `checkWhetherFileIsUsedInWikis`?
public boolean runRandomizer() {
compositeDisposable.add(reviewHelper.getRandomMedia()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
+ .subscribe(this::checkWhetherFileIsUsedInWikis));
return true;
}
/**
* Check whether media is used or not in any Wiki Page
*/
@SuppressLint("CheckResult")
+ private void checkWhetherFileIsUsedInWikis(final Media media) {
compositeDisposable.add(reviewHelper.checkFileUsage(media.getFilename())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
|
codereview_new_java_data_11425
|
public boolean checkWhetherFileIsUsedInWikis() {
}
final int totalCount = fileUsages.size();
- int ignoreCount = 0;
/* Ignore usage under https://commons.wikimedia.org/wiki/User:Didym/Mobile_upload/
which has been a gallery of all of our uploads since 2014 */
- for (final FileUsage cur : fileUsages) {
- if (cur.title().contains("User:Didym/Mobile upload")) {
- ignoreCount++;
}
}
- return !(ignoreCount == totalCount);
}
public static class Revision {
How about just this?
```
for (final FileUsage fileUsage : fileUsages) {
if ( ! fileUsage.title().contains("User:Didym/Mobile upload")) {
return true;
}
}
```
public boolean checkWhetherFileIsUsedInWikis() {
}
final int totalCount = fileUsages.size();
/* Ignore usage under https://commons.wikimedia.org/wiki/User:Didym/Mobile_upload/
which has been a gallery of all of our uploads since 2014 */
+ for (final FileUsage fileUsage : fileUsages) {
+ if ( ! fileUsage.title().contains("User:Didym/Mobile upload")) {
+ return true;
}
}
+ return false;
}
public static class Revision {
|
codereview_new_java_data_11426
|
private void updateNearbyNotification(@Nullable NearbyController.NearbyPlacesInf
// Means that no close nearby place is found
nearbyNotificationCardView.setVisibility(View.GONE);
}
- if(mediaDetailPagerFragment!=null && !contributionsListFragment.isVisible()) {
nearbyNotificationCardView.setVisibility(View.GONE);
}
}
Would you mind adding a comment `// Prevent Nearby banner from appearing in Media Details, fixing bug https://github.com/commons-app/apps-android-commons/issues/4731`?
Also, would you mind following the whitespace conventions at https://www.oracle.com/java/technologies/javase/codeconventions-whitespace.html? Hint: spaces after `if` and around `!=`.
Thanks a lot! :-)
private void updateNearbyNotification(@Nullable NearbyController.NearbyPlacesInf
// Means that no close nearby place is found
nearbyNotificationCardView.setVisibility(View.GONE);
}
+
+ // Prevent Nearby banner from appearing in Media Details, fixing bug https://github.com/commons-app/apps-android-commons/issues/4731
+ if (mediaDetailPagerFragment != null && !contributionsListFragment.isVisible()) {
nearbyNotificationCardView.setVisibility(View.GONE);
}
}
|
codereview_new_java_data_11427
|
private void setUpRecentLanguagesSection(final List<Language> recentLanguages) {
* @return a string without leading and trailing whitespace
*/
public String removeLeadingAndTrailingWhitespace(String source) {
int firstNonWhitespaceIndex = 0;
while (firstNonWhitespaceIndex < source.length()) {
if (Character.isWhitespace(source.charAt(firstNonWhitespaceIndex))) {
Would you mind adding as a comment your excellent advice concerning `strip`? That will tip maintainers to perform the change wgen we switch SDK version. If possible write from which version the method is available. Thanks!
private void setUpRecentLanguagesSection(final List<Language> recentLanguages) {
* @return a string without leading and trailing whitespace
*/
public String removeLeadingAndTrailingWhitespace(String source) {
+ // This method can be replaced with the inbuilt String::strip when updated to JDK 11.
+ // Note that String::trim does not adequately remove all whitespace chars.
int firstNonWhitespaceIndex = 0;
while (firstNonWhitespaceIndex < source.length()) {
if (Character.isWhitespace(source.charAt(firstNonWhitespaceIndex))) {
|
codereview_new_java_data_11428
|
private void launchZoomActivityAfterPermissionCheck(final View view) {
final Context ctx = view.getContext();
final Intent zoomableIntent = new Intent(ctx, ZoomableActivity.class);
zoomableIntent.setData(Uri.parse(media.getImageUrl()));
- zoomableIntent.putExtra("Origin", "MediaDetail");
ctx.startActivity(
zoomableIntent
);
Could you please rename to "MediaDetails"?
private void launchZoomActivityAfterPermissionCheck(final View view) {
final Context ctx = view.getContext();
final Intent zoomableIntent = new Intent(ctx, ZoomableActivity.class);
zoomableIntent.setData(Uri.parse(media.getImageUrl()));
+ zoomableIntent.putExtra("Origin", "MediaDetails");
ctx.startActivity(
zoomableIntent
);
|
codereview_new_java_data_11429
|
void placeSelected() {
finish();
}
/**
- * Centre the camera on the last saved location
*/
private void addCenterOnGPSButton(){
fabCenterOnLocation = findViewById(R.id.centre_on_gps);
fabCenterOnLocation.setOnClickListener(view -> getCentre());
}
void getCentre() {
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),15.0));
}
please separate methods with an empty line, and add javadoc for getCenter
void placeSelected() {
finish();
}
/**
+ * Center the camera on the last saved location
*/
private void addCenterOnGPSButton(){
fabCenterOnLocation = findViewById(R.id.centre_on_gps);
fabCenterOnLocation.setOnClickListener(view -> getCentre());
}
+ /**
+ * Animate map to move to desired Latitude and Longitude
+ */
void getCentre() {
mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),15.0));
}
|
codereview_new_java_data_11430
|
import javax.inject.Inject;
import javax.inject.Named;
import org.jetbrains.annotations.NotNull;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import timber.log.Timber;
public class UploadMediaPresenter implements UserActionListener, SimilarImageInterface {
Is this really needed?
import javax.inject.Inject;
import javax.inject.Named;
import org.jetbrains.annotations.NotNull;
import timber.log.Timber;
public class UploadMediaPresenter implements UserActionListener, SimilarImageInterface {
|
codereview_new_java_data_11431
|
public String removeTrailingWhitespace(String source) {
* @return a string with Latin spaces instead of Ideographic spaces
*/
public String convertIdeographicSpaceToLatinSpace(String source) {
- Pattern JapSpacePattern = Pattern.compile("\\x{3000}");
- return JapSpacePattern.matcher(source).replaceAll(" ");
}
}
Ah sorry I missed this one, could you please rename `JapSpacePattern` to `ideographicSpacePattern`?
public String removeTrailingWhitespace(String source) {
* @return a string with Latin spaces instead of Ideographic spaces
*/
public String convertIdeographicSpaceToLatinSpace(String source) {
+ Pattern ideographicSpacePattern = Pattern.compile("\\x{3000}");
+ return ideographicSpacePattern.matcher(source).replaceAll(" ");
}
}
|
codereview_new_java_data_11432
|
public static String getWLMEndDate() {
return "30 Sep";
}
public static int getWikiLovesMonumentsYear(Calendar calendar) {
int year = calendar.get(Calendar.YEAR);
if (calendar.get(Calendar.MONTH) < Calendar.SEPTEMBER) {
Would you mind writing a unit test for this? Thanks a lot!
public static String getWLMEndDate() {
return "30 Sep";
}
+ /***
+ * Function to get the current WLM year
+ * It increments at the start of September in line with the other WLM functions
+ * (No consideration of locales for now)
+ * @param calendar
+ * @return
+ */
public static int getWikiLovesMonumentsYear(Calendar calendar) {
int year = calendar.get(Calendar.YEAR);
if (calendar.get(Calendar.MONTH) < Calendar.SEPTEMBER) {
|
codereview_new_java_data_11443
|
public class CommonsApplication extends MultiDexApplication {
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App Feedback";
- public static final String REPORT_EMAIL = "commons-app-android@googlegroups.com";
public static final String REPORT_EMAIL_SUBJECT = "Report a violation";
I added this duplicate line in case we want to have a different email for reports in future.
public class CommonsApplication extends MultiDexApplication {
public static final String FEEDBACK_EMAIL_SUBJECT = "Commons Android App Feedback";
+ public static final String REPORT_EMAIL = "commons-app-android-private@googlegroups.com";
public static final String REPORT_EMAIL_SUBJECT = "Report a violation";
|
codereview_new_java_data_11444
|
private String getTechInfo(final Media media, final String type) {
.append("\n\n")
.append("Thank you for your report! Our team will investigate as soon as possible.")
.append("\n")
- .append("Please note that images also have `Nominate for deletion` button.");
return builder.toString();
}
`have` -> `have a`
private String getTechInfo(final Media media, final String type) {
.append("\n\n")
.append("Thank you for your report! Our team will investigate as soon as possible.")
.append("\n")
+ .append("Please note that images also have a `Nominate for deletion` button.");
return builder.toString();
}
|
codereview_new_java_data_11784
|
public final class ZMSConsts {
public static final String DB_COLUMN_AS_DOMAIN_NAME = "domain_name";
public static final String DB_COLUMN_AS_ROLE_NAME = "role_name";
public static final String DB_COLUMN_AS_GROUP_NAME = "group_name";
- public static final String DB_COLUMN_AS_PRINCIPAL_NAME = "principal_name";
public static final String DB_COLUMN_SYSTEM_DISABLED = "system_disabled";
public static final String DB_COLUMN_AZURE_SUBSCRIPTION = "azure_subscription";
public static final String DB_COLUMN_BUSINESS_SERVICE = "business_service";
let's remove the extra space to align the values
public final class ZMSConsts {
public static final String DB_COLUMN_AS_DOMAIN_NAME = "domain_name";
public static final String DB_COLUMN_AS_ROLE_NAME = "role_name";
public static final String DB_COLUMN_AS_GROUP_NAME = "group_name";
+ public static final String DB_COLUMN_AS_PRINCIPAL_NAME = "principal_name";
public static final String DB_COLUMN_SYSTEM_DISABLED = "system_disabled";
public static final String DB_COLUMN_AZURE_SUBSCRIPTION = "azure_subscription";
public static final String DB_COLUMN_BUSINESS_SERVICE = "business_service";
|
codereview_new_java_data_11785
|
package com.yahoo.athenz.zms;
import com.yahoo.rdl.Timestamp;
we need to add copyright notice
+/*
+ * Copyright The Athenz Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package com.yahoo.athenz.zms;
import com.yahoo.rdl.Timestamp;
|
codereview_new_java_data_11792
|
public void setFlattened(boolean flattened) {
this.flattened = flattened;
}
public boolean isSynthetic() {
return synthetic;
}
public void setSynthetic(boolean synthetic) {
this.synthetic = synthetic;
}
Can we add some documentation here?
public void setFlattened(boolean flattened) {
this.flattened = flattened;
}
+ /**
+ * Returns flag that indicates whether this shape is a custom SDK shape. If true, this shape will be excluded from the static
+ * SdkFields, preventing it from being marshalled.
+ */
public boolean isSynthetic() {
return synthetic;
}
+ /**
+ * Sets flag that indicates whether this shape is a custom SDK shape. If true, this shape will be excluded from the static
+ * SdkFields, preventing it from being marshalled.
+ */
public void setSynthetic(boolean synthetic) {
this.synthetic = synthetic;
}
|
codereview_new_java_data_11793
|
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
- * Interface for specifying a retry policy to use when evaluating whether or not a request should be retried , and the gap
* between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy.
* <p>
* When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy
nit: space before comma
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
+ * Interface for specifying a retry policy to use when evaluating whether or not a request should be retried, and the gap
* between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy.
* <p>
* When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy
|
codereview_new_java_data_11794
|
import software.amazon.awssdk.http.SdkHttpMethod;
/**
- * Class to parse the parameters to a SdkHttpRequest , make the call to the endpoint and send the HttpExecuteResponse
* to the DefaultEc2Metadata class for further processing.
*/
@SdkInternalApi
nit: space before comma
import software.amazon.awssdk.http.SdkHttpMethod;
/**
+ * Class to parse the parameters to a SdkHttpRequest, make the call to the endpoint and send the HttpExecuteResponse
* to the DefaultEc2Metadata class for further processing.
*/
@SdkInternalApi
|
codereview_new_java_data_11795
|
interface Builder {
Builder addJson(String attributeName, String json);
/**
- * Appends an attribute of name attributeName with specified value of the give EnhancedDocument.
* @param attributeName Name of the attribute that needs to be added in the Document.
* @param enhancedDocument that needs to be added as a value to a key attribute.
* @return Builder instance to construct a {@link EnhancedDocument}
Does this method add a nested document to the builder?
interface Builder {
Builder addJson(String attributeName, String json);
/**
+ * Appends an attribute of name attributeName with specified value of the given EnhancedDocument.
* @param attributeName Name of the attribute that needs to be added in the Document.
* @param enhancedDocument that needs to be added as a value to a key attribute.
* @return Builder instance to construct a {@link EnhancedDocument}
|
codereview_new_java_data_11796
|
public String toString() {
@Override
public void close() {
- if (profileFile instanceof SdkAutoCloseable) {
- ((SdkAutoCloseable) profileFile).close();
- }
// The delegate credentials provider may be closeable (eg. if it's an STS credentials provider). In this case, we should
// clean it up when this credentials provider is closed.
IoUtils.closeIfCloseable(credentialsProvider, null);
This is a red flag to me: closing something we didn't necessarily create. What if this is being used by someone else and we just closed it/broke it?
My bigger question is: why are profile file suppliers closeable?
public String toString() {
@Override
public void close() {
// The delegate credentials provider may be closeable (eg. if it's an STS credentials provider). In this case, we should
// clean it up when this credentials provider is closed.
IoUtils.closeIfCloseable(credentialsProvider, null);
|
codereview_new_java_data_11797
|
public void invokeInterceptorsAndCreateExecutionContext_multipleExecutionContext
@Test
public void invokeInterceptorsAndCreateExecutionContext_profileFileSupplier_storesValueInExecutionAttributes() {
- HttpChecksum httpCrc32Checksum = HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build();
- ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams()
- .putExecutionAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, httpCrc32Checksum);
Supplier<ProfileFile> profileFileSupplier = () -> null;
SdkClientConfiguration clientConfig = testClientConfiguration()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFileSupplier)
Why do you need to add the checksum parameter?
public void invokeInterceptorsAndCreateExecutionContext_multipleExecutionContext
@Test
public void invokeInterceptorsAndCreateExecutionContext_profileFileSupplier_storesValueInExecutionAttributes() {
+ ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams();
Supplier<ProfileFile> profileFileSupplier = () -> null;
SdkClientConfiguration clientConfig = testClientConfiguration()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFileSupplier)
|
codereview_new_java_data_11798
|
void resolveToken_profileFileSupplier_suppliesObjectPerCall() {
ProfileTokenProvider provider =
ProfileTokenProvider.builder().profileFile(supplier).profileName("sso").build();
- try {
- Mockito.when(supplier.get()).thenReturn(file1);
- provider.resolveToken();
- } catch (IllegalArgumentException e) {
- }
-
- try {
- Mockito.when(supplier.get()).thenReturn(file2);
- provider.resolveToken();
- } catch (IllegalArgumentException e) {
- }
Mockito.verify(supplier, Mockito.times(2)).get();
}
Is there any reason we are swallowing exception here?
void resolveToken_profileFileSupplier_suppliesObjectPerCall() {
ProfileTokenProvider provider =
ProfileTokenProvider.builder().profileFile(supplier).profileName("sso").build();
+ Mockito.when(supplier.get()).thenReturn(file1, file2);
+ assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class);
Mockito.verify(supplier, Mockito.times(2)).get();
}
|
codereview_new_java_data_11799
|
public S3CrtRequestBodyStreamAdapter(SdkHttpContentPublisher bodyPublisher) {
@Override
public boolean sendRequestBody(ByteBuffer outBuffer) {
return requestBodySubscriber.blockingTransferTo(outBuffer) == ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM;
}
What thread is blocking here?
public S3CrtRequestBodyStreamAdapter(SdkHttpContentPublisher bodyPublisher) {
@Override
public boolean sendRequestBody(ByteBuffer outBuffer) {
+ // blocking here because CRT S3 requires the buffer to be completely filled
return requestBodySubscriber.blockingTransferTo(outBuffer) == ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM;
}
|
codereview_new_java_data_11800
|
public String toString() {
* Method to return the number of retries allowed.
* @return The number of retries allowed.
*/
- public int getNumRetries() {
return numRetries;
}
/**
* Method to return the BackoffStrategy used.
* @return The backoff Strategy used.
*/
- public BackoffStrategy getBackoffStrategy() {
return backoffStrategy;
}
Same here, fluent getter
public String toString() {
* Method to return the number of retries allowed.
* @return The number of retries allowed.
*/
+ public int numRetries() {
return numRetries;
}
/**
* Method to return the BackoffStrategy used.
* @return The backoff Strategy used.
*/
+ public BackoffStrategy backoffStrategy() {
return backoffStrategy;
}
|
codereview_new_java_data_11801
|
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
-public enum Pem {
- ;
private static final String BEGIN_MARKER = "-----BEGIN ";
private static final Pattern BEGIN = Pattern.compile("BEGIN", Pattern.LITERAL);
/**
* Returns the first private key that is found from the input stream of a
* PEM file.
Can we convert these empty enums to static class/private ctor instead? Empty enums are another way of achieving the same thing but I think it's mostly confusing unless you really need it. The internal annotation is also missing.
Same for Rsa.
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
+import software.amazon.awssdk.annotations.SdkInternalApi;
+
+@SdkInternalApi
+public final class Pem {
private static final String BEGIN_MARKER = "-----BEGIN ";
private static final Pattern BEGIN = Pattern.compile("BEGIN", Pattern.LITERAL);
+ private Pem() {
+ }
+
/**
* Returns the first private key that is found from the input stream of a
* PEM file.
|
codereview_new_java_data_11802
|
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
-public enum Pem {
- ;
private static final String BEGIN_MARKER = "-----BEGIN ";
private static final Pattern BEGIN = Pattern.compile("BEGIN", Pattern.LITERAL);
/**
* Returns the first private key that is found from the input stream of a
* PEM file.
Can we convert this (copy paste) class to a static utility class instead of using an empty enum? I haven't seen this pattern used in our codebase and it seems unnecessary unless you really need it.
Missing internal annotation
Same for rsa
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
+import software.amazon.awssdk.annotations.SdkInternalApi;
+
+@SdkInternalApi
+public final class Pem {
private static final String BEGIN_MARKER = "-----BEGIN ";
private static final Pattern BEGIN = Pattern.compile("BEGIN", Pattern.LITERAL);
+ private Pem() {
+ }
+
/**
* Returns the first private key that is found from the input stream of a
* PEM file.
|
codereview_new_java_data_11803
|
package software.amazon.awssdk.services.cloudfront.internal.auth;
import java.util.Arrays;
public enum PemObjectType {
PRIVATE_KEY_PKCS1("-----BEGIN RSA PRIVATE KEY-----"),
PRIVATE_KEY_PKCS8("-----BEGIN PRIVATE KEY-----"),
internal annotation missing
package software.amazon.awssdk.services.cloudfront.internal.auth;
import java.util.Arrays;
+import software.amazon.awssdk.annotations.SdkInternalApi;
+@SdkInternalApi
public enum PemObjectType {
PRIVATE_KEY_PKCS1("-----BEGIN RSA PRIVATE KEY-----"),
PRIVATE_KEY_PKCS8("-----BEGIN PRIVATE KEY-----"),
|
codereview_new_java_data_11804
|
public interface SignedUrl {
String url();
/**
- * Generates an HTTP request that can be executed by an HTTP client to access the resource
*/
- SdkHttpRequest generateHttpRequest();
}
For the documentation, please include that it's a GET request. Alternatively, we can rename the method to generateHttpGetRequest()
public interface SignedUrl {
String url();
/**
+ * Generates an HTTP GET request that can be executed by an HTTP client to access the resource
*/
+ SdkHttpRequest generateHttpGetRequest();
}
|
codereview_new_java_data_11805
|
* small parts from a single object. The Transfer Manager is built on top of the Java bindings of the AWS Common Runtime S3 client
* and leverages Amazon S3 multipart upload and byte-range fetches for parallel transfers.
*
- * <h1>Instantiate a Transfer Manager</h1>
- * <b>Create a transfer manager with SDK default settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = defaultTM}
- * <b>Create a transfer manager with custom settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = customTM}
* <h1>Common Usage Patterns</h1>
* <b>Upload a file to S3</b>
Nit: Instantiate Transfer Manager, or Create a transfer manager instance
* small parts from a single object. The Transfer Manager is built on top of the Java bindings of the AWS Common Runtime S3 client
* and leverages Amazon S3 multipart upload and byte-range fetches for parallel transfers.
*
+ * <h1>Instantiate Transfer Manager</h1>
+ * <b>Create a transfer manager instance with SDK default settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = defaultTM}
+ * <b>Create a transfer manager instance with custom settings</b>
* {@snippet class = software.amazon.awssdk.transfer.s3.samples.S3TransferManagerSamples region = customTM}
* <h1>Common Usage Patterns</h1>
* <b>Upload a file to S3</b>
|
codereview_new_java_data_11806
|
public interface Builder extends SdkHttpClient.Builder<ApacheHttpClient.Builder>
Builder dnsResolver(DnsResolver dnsResolver);
/**
- * Configuration that defines a Socket Factory. If no matches are found, the default factory is used.
*/
Builder socketFactory(ConnectionSocketFactory socketFactory);
Are there any other pieces of configuration that are not used if this socket factory is set? E.g. TRUST_ALL_CERTIFICATES? Can we document what those are?
public interface Builder extends SdkHttpClient.Builder<ApacheHttpClient.Builder>
Builder dnsResolver(DnsResolver dnsResolver);
/**
+ * Configuration that defines a custom Socket factory. If set to a null value, a default factory is used.
+ * <p>
+ * When set to a non-null value, the use of a custom factory implies the configuration options TRUST_ALL_CERTIFICATES,
+ * TLS_TRUST_MANAGERS_PROVIDER, and TLS_KEY_MANAGERS_PROVIDER are ignored.
*/
Builder socketFactory(ConnectionSocketFactory socketFactory);
|
codereview_new_java_data_11807
|
@SdkPublicApi
@SdkPreviewApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final String scheme;
private final String host;
private final int port;
private final String username;
private final String password;
private final Boolean useSystemPropertyValues;
- private static final String HTTPS = "https";
private ProxyConfiguration(BuilderImpl builder) {
this.useSystemPropertyValues = builder.useSystemPropertyValues;
Can we use https://github.com/aws/aws-sdk-java-v2/blob/master/core/sdk-core/src/main/java/software/amazon/awssdk/core/Protocol.java#L29? (Sorry, I should've mentioned it earlier)
@SdkPublicApi
@SdkPreviewApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
+ private static final String HTTPS = "https";
private final String scheme;
private final String host;
private final int port;
private final String username;
private final String password;
private final Boolean useSystemPropertyValues;
private ProxyConfiguration(BuilderImpl builder) {
this.useSystemPropertyValues = builder.useSystemPropertyValues;
|
codereview_new_java_data_11808
|
void executeTestSuite(TestDiscovery.RulesTestcase testcase) {
}
private Stream<ValidationTestCase> validTestcases() {
- TestDiscovery discovery = new TestDiscovery();
return TEST_DISCOVERY.getValidRules()
.stream()
- .map(name -> new ValidationTestCase(name, discovery.validRulesetUrl(name), discovery.testCaseUrl(name)));
}
private Stream<TestDiscovery.RulesTestcase> checkableTestCases() {
It's confusing to have two instances of TestDiscovery, is it possible to refactor?
void executeTestSuite(TestDiscovery.RulesTestcase testcase) {
}
private Stream<ValidationTestCase> validTestcases() {
return TEST_DISCOVERY.getValidRules()
.stream()
+ .map(name -> new ValidationTestCase(name, TEST_DISCOVERY.validRulesetUrl(name), TEST_DISCOVERY.testCaseUrl(name)));
}
private Stream<TestDiscovery.RulesTestcase> checkableTestCases() {
|
codereview_new_java_data_11809
|
// TODO : Implement further functionality such as ToString, fromValue and Exception Handling as needed.
public enum EndpointMode {
- IPv4,
- IPv6
}
Enum should use all caps. IPV4, IPV6
// TODO : Implement further functionality such as ToString, fromValue and Exception Handling as needed.
public enum EndpointMode {
+ IPV4,
+ IPV6
}
|
codereview_new_java_data_11814
|
protected boolean hasSerialHost(Record record) {
protected String getSubfieldOrDefault(DataField field, char subfieldCode, String defaultValue) {
Subfield subfield = field.getSubfield(subfieldCode);
String data = subfield != null ? subfield.getData() : null;
- return data == null ? defaultValue : data;
}
protected boolean isOnlineAccordingTo338(Record record) {
Good catch! By the way, what happens if the subfield exists but contains only empty string? Do we also want to return the defaultValue in this case? (I'm not sure if this is a proper case anyway)
protected boolean hasSerialHost(Record record) {
protected String getSubfieldOrDefault(DataField field, char subfieldCode, String defaultValue) {
Subfield subfield = field.getSubfield(subfieldCode);
String data = subfield != null ? subfield.getData() : null;
+ return (data == null || data == "") ? defaultValue : data;
}
protected boolean isOnlineAccordingTo338(Record record) {
|
codereview_new_java_data_11842
|
public void onConnectionClose(MySQLResponseService service) {
XAStateLog.saveXARecoveryLog(session.getSessionXaID(), service);
}
@Override
public String getStage() {
return COMMIT_STAGE;
how to handle connectionError in ResponseHandler?
public void onConnectionClose(MySQLResponseService service) {
XAStateLog.saveXARecoveryLog(session.getSessionXaID(), service);
}
+ @Override
+ public void onConnectError(MySQLResponseService service) {
+ service.setXaStatus(TxState.TX_COMMIT_FAILED_STATE);
+ XAStateLog.saveXARecoveryLog(session.getSessionXaID(), service);
+ }
+
@Override
public String getStage() {
return COMMIT_STAGE;
|
codereview_new_java_data_11843
|
public String getConfigurationAsJsonString() {
Map<String, String> propsAsStringMap = new HashMap<>();
configurationAsProperties.forEach((key, value) -> {
- String strKey = Objects.toString(key);
- if (SettingsApiServlet.haveKey(strKey)) {
- String strValue = Objects.toString(value);
- //do not add non acceptable empty key then it back to default
- if (StringUtils.isNotEmpty(strValue) || SettingsApiServlet.acceptEmptyValueForKey(strKey)) {
- //escape "\" char with "\\" otherwise json will fail
- propsAsStringMap.put(strKey, strValue.replace("\\", "\\\\"));
- }
}
}
- );
return new PropertiesToJsonConverter().convertToJson(propsAsStringMap);
}
```suggestion
configurationAsProperties.forEach((key, value) -> {
String strKey = Objects.toString(key);
if (SettingsApiServlet.haveKey(strKey)) {
String strValue = Objects.toString(value);
//do not add non acceptable empty key then it back to default
if (StringUtils.isNotEmpty(strValue) || SettingsApiServlet.acceptEmptyValueForKey(strKey)) {
//escape "\" char with "\\" otherwise json will fail
propsAsStringMap.put(strKey, strValue.replace("\\", "\\\\"));
}
}
});
```
public String getConfigurationAsJsonString() {
Map<String, String> propsAsStringMap = new HashMap<>();
configurationAsProperties.forEach((key, value) -> {
+ String strKey = Objects.toString(key);
+ if (SettingsApiServlet.haveKey(strKey)) {
+ String strValue = Objects.toString(value);
+ //do not add non acceptable empty key then it back to default
+ if (StringUtils.isNotEmpty(strValue) || SettingsApiServlet.acceptEmptyValueForKey(strKey)) {
+ //escape "\" char with "\\" otherwise json will fail
+ propsAsStringMap.put(strKey, strValue.replace("\\", "\\\\"));
}
}
+ });
return new PropertiesToJsonConverter().convertToJson(propsAsStringMap);
}
|
codereview_new_java_data_11844
|
public CoverArtArchiveResult(final boolean found, final Timestamp modified, fina
this.cover = cover;
}
- public boolean isFounded() {
return found;
}
Should be called `isFound`
public CoverArtArchiveResult(final boolean found, final Timestamp modified, fina
this.cover = cover;
}
+ public boolean isFound() {
return found;
}
|
codereview_new_java_data_11845
|
public DLNAComplianceResult checkCompliance(ImageInfo imageInfo) {
switch (this.toInt()) {
case DLNAImageProfile.GIF_LRG_INT -> checkGIF(imageInfo, complianceResult);
- case DLNAImageProfile.JPEG_LRG_INT, DLNAImageProfile.JPEG_MED_INT, DLNAImageProfile.JPEG_RES_H_V_INT, DLNAImageProfile.JPEG_SM_INT, DLNAImageProfile.JPEG_TN_INT -> checkJPEG(imageInfo, complianceResult);
- case DLNAImageProfile.PNG_LRG_INT, DLNAImageProfile.PNG_TN_INT -> checkPNG(imageInfo, complianceResult);
default -> throw new IllegalStateException("Illegal DLNA media profile");
}
Some of these lines are getting long with this style of switch statement. I find the old style easier to read, with one case per line. Does anyone else have an opinion @UniversalMediaServer/developers ?
public DLNAComplianceResult checkCompliance(ImageInfo imageInfo) {
switch (this.toInt()) {
case DLNAImageProfile.GIF_LRG_INT -> checkGIF(imageInfo, complianceResult);
+ case DLNAImageProfile.JPEG_LRG_INT,
+ DLNAImageProfile.JPEG_MED_INT,
+ DLNAImageProfile.JPEG_RES_H_V_INT,
+ DLNAImageProfile.JPEG_SM_INT,
+ DLNAImageProfile.JPEG_TN_INT -> checkJPEG(imageInfo, complianceResult);
+ case DLNAImageProfile.PNG_LRG_INT,
+ DLNAImageProfile.PNG_TN_INT -> checkPNG(imageInfo, complianceResult);
default -> throw new IllegalStateException("Illegal DLNA media profile");
}
|
codereview_new_java_data_11846
|
public String getResolutionForKeepAR(int scaleWidth, int scaleHeight) {
private void setMetadataFromFileName(File file) {
String absolutePath = file.getAbsolutePath();
if (
- file != null &&
absolutePath != null &&
- (
- Platform.isMac() &&
- // skip metadata extraction and API lookups for live photos (little MP4s) backed up from iPhones
- absolutePath.contains("Photos Library.photoslibrary")
- )
) {
return;
}
if `file` is null, then the previous line `file.getAbsolutePath()` would throw a NPE ...
public String getResolutionForKeepAR(int scaleWidth, int scaleHeight) {
private void setMetadataFromFileName(File file) {
String absolutePath = file.getAbsolutePath();
if (
absolutePath != null &&
+ Platform.isMac() &&
+ // skip metadata extraction and API lookups for live photos (little MP4s) backed up from iPhones
+ absolutePath.contains("Photos Library.photoslibrary")
) {
return;
}
|
codereview_new_java_data_11847
|
public synchronized final void checkTables(boolean force) throws SQLException {
// Files and metadata
MediaTableMetadata.checkTable(connection);
MediaTableFiles.checkTable(connection);
- MediaTableVideoMetadatas.checkTable(connection);
MediaTableSubtracks.checkTable(connection);
MediaTableChapters.checkTable(connection);
MediaTableRegexpRules.checkTable(connection);
`metadatas` should always be `metadata`, since that works for plural too
public synchronized final void checkTables(boolean force) throws SQLException {
// Files and metadata
MediaTableMetadata.checkTable(connection);
MediaTableFiles.checkTable(connection);
+ MediaTableVideoMetadata.checkTable(connection);
MediaTableSubtracks.checkTable(connection);
MediaTableChapters.checkTable(connection);
MediaTableRegexpRules.checkTable(connection);
|
codereview_new_java_data_11893
|
public class PopReviveService extends ServiceThread {
private int queueId;
private BrokerController brokerController;
private String reviveTopic;
- private volatile long currentReviveMessageTimestamp = -1;
private volatile boolean shouldRunPopRevive = false;
private final NavigableMap<PopCheckPoint/* oldCK */, Pair<Long/* timestamp */, Boolean/* result */>> inflightReviveRequestMap = Collections.synchronizedNavigableMap(new TreeMap<>());
Need to add the volatile modifier here?
public class PopReviveService extends ServiceThread {
private int queueId;
private BrokerController brokerController;
private String reviveTopic;
+ private long currentReviveMessageTimestamp = -1;
private volatile boolean shouldRunPopRevive = false;
private final NavigableMap<PopCheckPoint/* oldCK */, Pair<Long/* timestamp */, Boolean/* result */>> inflightReviveRequestMap = Collections.synchronizedNavigableMap(new TreeMap<>());
|
codereview_new_java_data_11894
|
void registerProcessor(final int requestCode, final NettyRequestProcessor proces
boolean isChannelWritable(final String addr);
- boolean isAddressCanConnect(final String addr);
void closeChannels(final List<String> addrList);
}
Suggest rename it to "isAddressReachable"
void registerProcessor(final int requestCode, final NettyRequestProcessor proces
boolean isChannelWritable(final String addr);
+ boolean isAddressReachable(final String addr);
void closeChannels(final List<String> addrList);
}
|
codereview_new_java_data_11895
|
public static TopicMessageType parseFromMessageProperty(Map<String, String> mess
return TopicMessageType.DELAY;
} else if (messageProperty.get(MessageConst.PROPERTY_SHARDING_KEY) != null) {
return TopicMessageType.FIFO;
- } else {
- return TopicMessageType.NORMAL;
}
}
public String getMetricsValue() {
`else` here is redundant seemingly.
public static TopicMessageType parseFromMessageProperty(Map<String, String> mess
return TopicMessageType.DELAY;
} else if (messageProperty.get(MessageConst.PROPERTY_SHARDING_KEY) != null) {
return TopicMessageType.FIFO;
}
+ return TopicMessageType.NORMAL;
}
public String getMetricsValue() {
|
codereview_new_java_data_11896
|
public List<MessageExt> takeMessages(final int batchSize) {
/**
* Return the result that whether current message is exist in the process queue or not.
*/
- public boolean hasMessage(MessageExt message) {
if (message == null) {
// should never reach here.
return false;
`hasMessage` --> `containsMessage`
appears easier to comprehend
public List<MessageExt> takeMessages(final int batchSize) {
/**
* Return the result that whether current message is exist in the process queue or not.
*/
+ public boolean containsMessage(MessageExt message) {
if (message == null) {
// should never reach here.
return false;
|
codereview_new_java_data_11897
|
public class ResetOffsetRequestHeader implements CommandCustomHeader {
private int queueId = -1;
- @CFNotNull
private Long offset;
@CFNotNull
The CFNotNull of offset is not necessary, and will produce WARN for old client
public class ResetOffsetRequestHeader implements CommandCustomHeader {
private int queueId = -1;
private Long offset;
@CFNotNull
|
codereview_new_java_data_11898
|
public RemotingCommand sendMessage(final ChannelHandlerContext ctx,
if (Objects.equals(deletePolicy, DeletePolicy.COMPACTION)) {
if (StringUtils.isBlank(msgInner.getKeys())) {
response.setCode(ResponseCode.MESSAGE_ILLEGAL);
- response.setRemark("the message don't have message key");
return response;
}
}
```suggestion
response.setRemark("Required message key is missing");
```
public RemotingCommand sendMessage(final ChannelHandlerContext ctx,
if (Objects.equals(deletePolicy, DeletePolicy.COMPACTION)) {
if (StringUtils.isBlank(msgInner.getKeys())) {
response.setCode(ResponseCode.MESSAGE_ILLEGAL);
+ response.setRemark("Required message key is missing");
return response;
}
}
|
codereview_new_java_data_11899
|
package org.apache.rocketmq.common.attribute;
public enum DeletePolicy {
- NORMAL,
COMPACTION
}
STANDARD may be more appropriate than NORMAL.
package org.apache.rocketmq.common.attribute;
public enum DeletePolicy {
+ DELETE,
COMPACTION
}
|
codereview_new_java_data_11900
|
public void setInBrokerContainer(boolean inBrokerContainer) {
}
private String defaultBrokerName() {
- return localHostName == null ? "DEFAULT_BROKER" : localHostName;
}
public String getCanonicalName() {
```suggestion
return StringUtils.isEmpty(localHostName) ? "DEFAULT_BROKER" : localHostName;
```
public void setInBrokerContainer(boolean inBrokerContainer) {
}
private String defaultBrokerName() {
+ return StringUtils.isEmpty(localHostName) ? "DEFAULT_BROKER" : localHostName;
}
public String getCanonicalName() {
|
codereview_new_java_data_11901
|
public class BrokerReplicaInfo {
private final String clusterName;
private final String brokerName;
- // Start from 2, because no.1 will be used when the instance is initiated
private final AtomicLong nextAssignBrokerId;
private final HashMap<String/*Address*/, Long/*brokerId*/> brokerIdTable;
- public BrokerReplicaInfo(String clusterName, String brokerName, String address) {
this.clusterName = clusterName;
this.brokerName = brokerName;
this.brokerIdTable = new HashMap<>();
- this.brokerIdTable.put(address, MixAll.FIRST_SLAVE_ID);
- this.nextAssignBrokerId = new AtomicLong(MixAll.FIRST_SLAVE_ID + 1);
}
public void removeBrokerAddress(final String address) {
It is recommended to start from 1
public class BrokerReplicaInfo {
private final String clusterName;
private final String brokerName;
+ // Start from 1
private final AtomicLong nextAssignBrokerId;
private final HashMap<String/*Address*/, Long/*brokerId*/> brokerIdTable;
+ public BrokerReplicaInfo(String clusterName, String brokerName) {
this.clusterName = clusterName;
this.brokerName = brokerName;
this.brokerIdTable = new HashMap<>();
+ this.nextAssignBrokerId = new AtomicLong(MixAll.FIRST_SLAVE_ID);
}
public void removeBrokerAddress(final String address) {
|
codereview_new_java_data_11902
|
public static BrokerController createBrokerController(String[] args) {
System.exit(-2);
}
- if (!nettyServerConfig.getBindIP().equals("0.0.0.0") &&
- !nettyServerConfig.getBindIP().equals(brokerConfig.getBrokerIP1())) {
- System.out.printf("Broker bind ip: %s should be 0.0.0.0 or equal to broker ip1: %s", nettyServerConfig.getBindIP(), brokerConfig.getBrokerIP1());
- System.exit(-2);
- }
-
String namesrvAddr = brokerConfig.getNamesrvAddr();
if (null != namesrvAddr) {
try {
The host to bind may be different with wildcard address and broker IP1. Broker IP1 is for clients to connect to brokers. For example, in the cloud environment, brokerIP1 is configured to its public IP.
The ECS itself may have multiple network interfaces wiring virtually to different networks.
public static BrokerController createBrokerController(String[] args) {
System.exit(-2);
}
String namesrvAddr = brokerConfig.getNamesrvAddr();
if (null != namesrvAddr) {
try {
|
codereview_new_java_data_11903
|
private void calcTimerDistribution() {
Slot slotEach = timerWheel.getSlot(currTime + j * precisionMs);
periodTotal += slotEach.num;
}
- LOGGER.info("{} period's total num: {}", timerDist.get(i), periodTotal);
this.timerMetrics.updateDistPair(timerDist.get(i), periodTotal);
}
long endTime = System.currentTimeMillis();
- LOGGER.info("Total cost Time: {}", endTime - startTime);
}
public void recover() {
IMO, debug should be used here.
private void calcTimerDistribution() {
Slot slotEach = timerWheel.getSlot(currTime + j * precisionMs);
periodTotal += slotEach.num;
}
+ LOGGER.debug("{} period's total num: {}", timerDist.get(i), periodTotal);
this.timerMetrics.updateDistPair(timerDist.get(i), periodTotal);
}
long endTime = System.currentTimeMillis();
+ LOGGER.debug("Total cost Time: {}", endTime - startTime);
}
public void recover() {
|
codereview_new_java_data_11904
|
private void updateTopicSubscribeInfoWhenSubscriptionChanged() {
*/
public synchronized void subscribe(String topic, String subExpression, MessageQueueListener messageQueueListener) throws MQClientException {
try {
- if (topic == null || "".equals(topic)) {
throw new IllegalArgumentException("Topic can not be null or empty.");
}
setSubscriptionType(SubscriptionType.SUBSCRIBE);
StringUtils tool judges empty and white space better
private void updateTopicSubscribeInfoWhenSubscriptionChanged() {
*/
public synchronized void subscribe(String topic, String subExpression, MessageQueueListener messageQueueListener) throws MQClientException {
try {
+ if (StringUtils.isEmpty(topic)) {
throw new IllegalArgumentException("Topic can not be null or empty.");
}
setSubscriptionType(SubscriptionType.SUBSCRIBE);
|
codereview_new_java_data_11905
|
public interface LitePullConsumer {
/**
* Offset specified by batch commit
- * @param messageQueues
* @param persist
*/
- void commitSync(Map<MessageQueue, Long> messageQueues, boolean persist);
void commit(final Set<MessageQueue> messageQueues, boolean persist);
The first para seems offsets map, not messageQueues.
public interface LitePullConsumer {
/**
* Offset specified by batch commit
+ * @param offsetMap
* @param persist
*/
+ void commitSync(Map<MessageQueue, Long> offsetMap, boolean persist);
void commit(final Set<MessageQueue> messageQueues, boolean persist);
|
codereview_new_java_data_11906
|
public void assign(Collection<MessageQueue> messageQueues) {
}
@Override
- public void setSubExpression4Assgin(final String topic, final String subExpresion) {
- defaultLitePullConsumerImpl.setSubExpression4Assgin(withNamespace(topic), subExpresion);
}
@Override
`setSubExpression4Assgin` -> `setSubExpression4Assign`
public void assign(Collection<MessageQueue> messageQueues) {
}
@Override
+ public void setSubExpression4Assign(final String topic, final String subExpresion) {
+ defaultLitePullConsumerImpl.setSubExpression4Assign(withNamespace(topic), subExpresion);
}
@Override
|
codereview_new_java_data_11907
|
private static PutMessageResult transformTimerMessage(BrokerController brokerCon
long deliverMs;
try {
if (msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC) != null) {
- deliverMs = System.currentTimeMillis() + Integer.parseInt(msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC)) * 1000;
} else if (msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_MS) != null) {
- deliverMs = System.currentTimeMillis() + Integer.parseInt(msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_MS));
} else {
deliverMs = Long.parseLong(msg.getProperty(MessageConst.PROPERTY_TIMER_DELIVER_MS));
}
when set setDelayTimeSec(24 * 3600 * 3), integer overflows
private static PutMessageResult transformTimerMessage(BrokerController brokerCon
long deliverMs;
try {
if (msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC) != null) {
+ deliverMs = System.currentTimeMillis() + Long.parseLong(msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_SEC)) * 1000;
} else if (msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_MS) != null) {
+ deliverMs = System.currentTimeMillis() + Long.parseLong(msg.getProperty(MessageConst.PROPERTY_TIMER_DELAY_MS));
} else {
deliverMs = Long.parseLong(msg.getProperty(MessageConst.PROPERTY_TIMER_DELIVER_MS));
}
|
codereview_new_java_data_11908
|
public RemotingClient getRemotingClient() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
- if (addrs != null && !UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
It would be better to combine one with the following if.
public RemotingClient getRemotingClient() {
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
+ if (!UtilAll.isBlank(addrs)) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
|
codereview_new_java_data_11909
|
public long getMinOffsetInQueue() {
}
@Override
- public void dispatch(DispatchRequest request) {
final int maxRetries = 30;
boolean canWrite = this.messageStore.getRunningFlags().isCQWriteable();
for (int i = 0; i < maxRetries && canWrite; i++) {
No good to change this, just respect the history.
public long getMinOffsetInQueue() {
}
@Override
+ public void putMessagePositionInfoWrapper(DispatchRequest request) {
final int maxRetries = 30;
boolean canWrite = this.messageStore.getRunningFlags().isCQWriteable();
for (int i = 0; i < maxRetries && canWrite; i++) {
|
codereview_new_java_data_11910
|
public boolean parseDelayLevel() {
@Override
public void truncateDirtyLogicFiles(long phyOffset) {
- this.consumeQueueStore.truncateDirtyFiles(phyOffset);
}
/**
No good to change this too.
public boolean parseDelayLevel() {
@Override
public void truncateDirtyLogicFiles(long phyOffset) {
+ this.consumeQueueStore.truncateDirty(phyOffset);
}
/**
|
codereview_new_java_data_11970
|
private boolean isHostUnknown(String recipient) {
}
if (host_unknown) {
- host_unknown = Trunking.isTrunkingEnabledFor(recipient);
}
return host_unknown;
}
I think this logic got inverted when the switch to SystemProperties happened
```suggestion
if (host_unknown) {
host_unknown = !Trunking.isTrunkingEnabledFor(recipient);
}
```
private boolean isHostUnknown(String recipient) {
}
if (host_unknown) {
+ host_unknown = !Trunking.isTrunkingEnabledFor(recipient);
}
return host_unknown;
}
|
codereview_new_java_data_11971
|
private void processConnection(@Nonnull final HttpConnection connection, @Nonnul
final HttpConnection openConnection = connectionQueue.peek();
assert openConnection != null;
if (openConnection.getRequestId() > lastSequentialRequestID) {
- break; // There's a gap.
}
// Consume this connection.
break or continue? Or perhaps a better comment as to what a gap actually means / is interpreted
private void processConnection(@Nonnull final HttpConnection connection, @Nonnul
final HttpConnection openConnection = connectionQueue.peek();
assert openConnection != null;
if (openConnection.getRequestId() > lastSequentialRequestID) {
+ break; // There's a gap. As described above, connections must be used in sequence, without jumping the queue.
}
// Consume this connection.
|
codereview_new_java_data_11974
|
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
- names = {"--downloads-dir"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
- @ConfigValue(section = NODE_SECTION, name = "downloads-dir", example = "")
- private String downloadsDir = "";
@Override
public Set<Role> getRoles() {
```suggestion
names = {"--downloads-path"},
```
public class NodeFlags implements HasRoles {
private String nodeImplementation = DEFAULT_NODE_IMPLEMENTATION;
@Parameter(
+ names = {"--downloads-path"},
description = "The default location wherein all browser triggered file downloads would be "
+ "available to be retrieved from. This is usually the directory that you configure in "
+ "your browser as the default location for storing downloaded files.")
+ @ConfigValue(section = NODE_SECTION, name = "downloads-path", example = "")
+ private String downloadsPath = "";
@Override
public Set<Role> getRoles() {
|
codereview_new_java_data_11979
|
public Fixture() {
originalDriver = mock(WebDriver.class);
when(originalSwitch.alert()).thenReturn(original);
when(originalDriver.switchTo()).thenReturn(originalSwitch);
- decoratedDriver = new WebDriverDecorator().decorate(originalDriver);
decorated = decoratedDriver.switchTo().alert();
}
}
I appreciate that the current tests are updated as per the changes. However, since this is a sizeable change and it aims in solving a particular use case, I would request you to help add tests to test the changes. A simple dummy class that extends WebDriver and testing decorating the same should do the trick.
public Fixture() {
originalDriver = mock(WebDriver.class);
when(originalSwitch.alert()).thenReturn(original);
when(originalDriver.switchTo()).thenReturn(originalSwitch);
+ decoratedDriver = new WebDriverDecorator<>().decorate(originalDriver);
decorated = decoratedDriver.switchTo().alert();
}
}
|
codereview_new_java_data_11990
|
/*
- * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
```suggestion
* (c) Copyright 2022 Palantir Technologies Inc. All rights reserved.
```
/*
+ * (c) Copyright 2022 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
|
codereview_new_java_data_11991
|
/*
- * (c) Copyright 2017 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
```suggestion
* (c) Copyright 2022 Palantir Technologies Inc. All rights reserved.
```
/*
+ * (c) Copyright 2022 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
|
codereview_new_java_data_11992
|
severity = BugPattern.SeverityLevel.WARNING,
summary = "The HashMap(int) and HashSet(int) constructors are misleading: once the HashMap/HashSet reaches 3/4"
+ " of the supplied size, it resize. Instead use Maps.newHashMapWithExpectedSize or"
- + " Sets.newHashSetWithExpextedSize which behaves as expected. See"
+ " https://github.com/palantir/gradle-baseline/blob/develop/docs/best-practices/java-coding-guidelines/readme.md#avoid-new-HashMap(int)"
+ " for more information.")
public final class AvoidNewHashMapInt extends BugChecker implements BugChecker.NewClassTreeMatcher {
nit: spelling
```suggestion
+ " Sets.newHashSetWithExpectedSize which behaves as expected. See"
```
severity = BugPattern.SeverityLevel.WARNING,
summary = "The HashMap(int) and HashSet(int) constructors are misleading: once the HashMap/HashSet reaches 3/4"
+ " of the supplied size, it resize. Instead use Maps.newHashMapWithExpectedSize or"
+ + " Sets.newHashSetWithExpectedSize which behaves as expected. See"
+ " https://github.com/palantir/gradle-baseline/blob/develop/docs/best-practices/java-coding-guidelines/readme.md#avoid-new-HashMap(int)"
+ " for more information.")
public final class AvoidNewHashMapInt extends BugChecker implements BugChecker.NewClassTreeMatcher {
|
codereview_new_java_data_11993
|
summary = "Disallow usage of .collapseKeys() in EntryStream(s).")
public final class DangerousCollapseKeysUsage extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
- private static final String ERROR_MESSAGE = "The collapseKeys API of EntryStream should be avoided. The "
+ "API is frequently used as a grouping operation but its not suitable for that use case. The contract "
+ "requires duplicate keys to be adjacent to each other in the stream, which is rarely the case in "
+ "production code paths. When this constraint is violated, it leads to a duplicate key error at runtime.\n"
"should" implies info/warning, not ` SeverityLevel.ERROR`.
summary = "Disallow usage of .collapseKeys() in EntryStream(s).")
public final class DangerousCollapseKeysUsage extends BugChecker implements BugChecker.MethodInvocationTreeMatcher {
private static final long serialVersionUID = 1L;
+ private static final String ERROR_MESSAGE = "The collapseKeys API of EntryStream must be avoided. The "
+ "API is frequently used as a grouping operation but its not suitable for that use case. The contract "
+ "requires duplicate keys to be adjacent to each other in the stream, which is rarely the case in "
+ "production code paths. When this constraint is violated, it leads to a duplicate key error at runtime.\n"
|
codereview_new_java_data_12041
|
public static PackageInfo getPackageInfo(PackageManager pm, String packageName)
return InternalUtils.getPackageInfo(pm, packageName, 0);
}
- @SuppressWarnings("deprecation")
public static PackageInfo getPackageInfo(PackageManager pm, String packageName, long flags)
throws PackageManager.NameNotFoundException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags));
} else {
- return pm.getPackageInfo(packageName, (int) flags);
}
}
}
can you move the deprecated code to a separate private function with the suppress warning and remove the suppress warning from the public one?
so in case google deprecates the new function in the future we don't miss it
public static PackageInfo getPackageInfo(PackageManager pm, String packageName)
return InternalUtils.getPackageInfo(pm, packageName, 0);
}
public static PackageInfo getPackageInfo(PackageManager pm, String packageName, long flags)
throws PackageManager.NameNotFoundException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags));
} else {
+ return getPackageInfoLegacy(pm, packageName, (int) flags);
}
}
+
+ @SuppressWarnings("deprecation")
+ private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, long flags) throws PackageManager.NameNotFoundException {
+ return pm.getPackageInfo(packageName, (int) flags);
+ }
}
|
codereview_new_java_data_12044
|
public static CapConfig loadFromAssets(Context context, String path) {
* Constructs a Capacitor Configuration from config.json file within the app file-space.
*
* @param context The context.
- * @param path A path relative to the root assets directory.
* @return A loaded config file, if successful.
*/
public static CapConfig loadFromFile(Context context, String path) {
Would be relative to app disk space root no?
public static CapConfig loadFromAssets(Context context, String path) {
* Constructs a Capacitor Configuration from config.json file within the app file-space.
*
* @param context The context.
+ * @param path A path relative to the root of the app file-space.
* @return A loaded config file, if successful.
*/
public static CapConfig loadFromFile(Context context, String path) {
|
codereview_new_java_data_12045
|
public static CapConfig loadFromAssets(Context context, String path) {
* Constructs a Capacitor Configuration from config.json file within the app file-space.
*
* @param context The context.
- * @param path A path relative to the root assets directory.
* @return A loaded config file, if successful.
*/
public static CapConfig loadFromFile(Context context, String path) {
```suggestion
* @param path A path relative to the root of the app file-space.
```
public static CapConfig loadFromAssets(Context context, String path) {
* Constructs a Capacitor Configuration from config.json file within the app file-space.
*
* @param context The context.
+ * @param path A path relative to the root of the app file-space.
* @return A loaded config file, if successful.
*/
public static CapConfig loadFromFile(Context context, String path) {
|
codereview_new_java_data_12046
|
private void loadWebView() {
}
@SuppressLint("WebViewApiAvailability")
- private boolean isMinimumWebViewInstalled() {
PackageManager pm = getContext().getPackageManager();
// Check getCurrentWebViewPackage() directly if above Android 8
I think we should make this method public, in example, in Splash screen plugin we might want to hide the splash screen if this returns false and autohide is set to false, because as the app content won't load, apps won't be able to hide the splash programmatically and users will see the splash forever instead of the error page
private void loadWebView() {
}
@SuppressLint("WebViewApiAvailability")
+ public boolean isMinimumWebViewInstalled() {
PackageManager pm = getContext().getPackageManager();
// Check getCurrentWebViewPackage() directly if above Android 8
|
codereview_new_java_data_12047
|
public Builder setServerUrl(String serverUrl) {
return this;
}
- public Builder setErrorUPath(String errorPath) {
this.errorPath = errorPath;
return this;
}
```suggestion
public Builder setErrorPath(String errorPath) {
```
I think this is a typo?
public Builder setServerUrl(String serverUrl) {
return this;
}
+ public Builder setErrorPath(String errorPath) {
this.errorPath = errorPath;
return this;
}
|
codereview_new_java_data_12099
|
private void doCleanup(String broker) throws ExecutionException, InterruptedExce
log.info("Started ownership cleanup for the inactive broker:{}", broker);
int orphanServiceUnitCleanupCnt = 0;
long totalCleanupErrorCntStart = totalCleanupErrorCnt.get();
- var availableBrokers = new HashSet(brokerRegistry.getAvailableBrokersAsync()
.get(inFlightStateWaitingTimeInMillis, MILLISECONDS));
for (var etr : tableview.entrySet()) {
var stateData = etr.getValue();
```suggestion
var availableBrokers = new HashSet<>(brokerRegistry.getAvailableBrokersAsync()
```
private void doCleanup(String broker) throws ExecutionException, InterruptedExce
log.info("Started ownership cleanup for the inactive broker:{}", broker);
int orphanServiceUnitCleanupCnt = 0;
long totalCleanupErrorCntStart = totalCleanupErrorCnt.get();
+ var availableBrokers = new HashSet<>(brokerRegistry.getAvailableBrokersAsync()
.get(inFlightStateWaitingTimeInMillis, MILLISECONDS));
for (var etr : tableview.entrySet()) {
var stateData = etr.getValue();
|
codereview_new_java_data_12100
|
/**
* Defines the possible states for service units.
*
- * Refer to Service Unit State Channel in https://github.com/apache/pulsar/issues/16691 for additional details.
*/
public enum ServiceUnitState {
```suggestion
* Refer to Service Unit State Channel in <a href="https://github.com/apache/pulsar/issues/16691"/a> for additional details.
```
/**
* Defines the possible states for service units.
*
+ * @see <a href="https://github.com/apache/pulsar/issues/16691"> Service Unit State Channel </a> for additional details.
*/
public enum ServiceUnitState {
|
codereview_new_java_data_12101
|
public interface StateChangeListener {
- /**
- * Stages of events currently supported.
- * before starting the event/successful completion/failed completion.
- */
- enum EventStage {
- BEFORE,
- SUCCESS,
- FAILURE
- }
-
/**
* Handle the service unit state change.
*
* @param serviceUnit - Service Unit(Namespace bundle).
* @param data - Service unit state data.
- * @param stage - The event stage.
- * @param t - Exception in case of FAILURE, if present/known.
*/
- void handleEvent(String serviceUnit, ServiceUnitStateData data,
- EventStage stage, Throwable t);
}
Nit: like I commented above, plz consider if this can be removed.
public interface StateChangeListener {
/**
* Handle the service unit state change.
*
* @param serviceUnit - Service Unit(Namespace bundle).
* @param data - Service unit state data.
+ * @param t - Exception, if present.
*/
+ void handleEvent(String serviceUnit, ServiceUnitStateData data, Throwable t);
}
|
codereview_new_java_data_12102
|
public void initiate() {
duplicateBuffer = payloadProcessorHandle.getProcessedPayload();
}
}
- this.dataLength = duplicateBuffer.readableBytes();
- this.ml.currentLedgerSize += (dataLength - originalDataLen);
ledger.asyncAddEntry(duplicateBuffer, this, addOpCount);
} else {
log.warn("[{}] initiate with unexpected state {}, expect OPEN state.", ml.getName(), state);
Is it better to just reset the `dataLength` if the payload processor presents?
```java
if (payloadProcessorHandle != null) {
duplicateBuffer = payloadProcessorHandle.getProcessedPayload();
dataLength = duplicateBuffer.readableBytes();
}
```
public void initiate() {
duplicateBuffer = payloadProcessorHandle.getProcessedPayload();
}
}
+ if (originalDataLen != duplicateBuffer.readableBytes()) {
+ this.dataLength = duplicateBuffer.readableBytes();
+ this.ml.currentLedgerSize += (dataLength - originalDataLen);
+ }
ledger.asyncAddEntry(duplicateBuffer, this, addOpCount);
} else {
log.warn("[{}] initiate with unexpected state {}, expect OPEN state.", ml.getName(), state);
|
codereview_new_java_data_12103
|
public void received(Consumer<T> consumer, Message<T> msg) {
readerListener.received(MultiTopicsReaderImpl.this, msg);
consumer.acknowledgeCumulativeAsync(messageId).exceptionally(ex -> {
log.error("[{}][{}] auto acknowledge message {} cumulative fail.", getTopic(),
- getMultiTopicsConsumer().getSubscription(), msg.getMessageId(), ex);
return null;
});
}
Will `msg.getMessageId()` throws NPE here? I think `msg.getMessageId()` should be changed to `messageId`
public void received(Consumer<T> consumer, Message<T> msg) {
readerListener.received(MultiTopicsReaderImpl.this, msg);
consumer.acknowledgeCumulativeAsync(messageId).exceptionally(ex -> {
log.error("[{}][{}] auto acknowledge message {} cumulative fail.", getTopic(),
+ getMultiTopicsConsumer().getSubscription(), messageId, ex);
return null;
});
}
|
codereview_new_java_data_12104
|
public static CompletionException wrapToCompletionException(Throwable throwable)
}
/**
- * Creates a new {@link CompletableFuture} instance catching
- * potential exceptions and completing the future exceptionally.
*
* @param runnable the runnable to execute
* @param executor the executor to use for executing the runnable
The return type is "void"
Maybe we can reword this like:
"Executes an operation using the supplied Executor and notify failures on the supplied CompletableFuture"
public static CompletionException wrapToCompletionException(Throwable throwable)
}
/**
+ * Executes an operation using the supplied {@link Executor}
+ * and notify failures on the supplied {@link CompletableFuture}.
*
* @param runnable the runnable to execute
* @param executor the executor to use for executing the runnable
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.