Use JOSM's checkstyle and fix the warnings that it produced

Signed-off-by: Taylor Smock <taylor.smock@kaart.com>
pull/1/head
Taylor Smock 2019-11-06 11:23:08 -07:00
rodzic c146267bfa
commit b227b47372
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 625F6A74A3E4311A
12 zmienionych plików z 255 dodań i 91 usunięć

Wyświetl plik

@ -5,23 +5,193 @@
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
This ruleset checks some rules that you should normally follow for the JOSM-rapid plugin.
Copied from josm tools/pmd/josm-ruleset.xml
</description>
<rule ref="category/java/bestpractices.xml"/>
<rule ref="category/java/bestpractices.xml">
<exclude name="AccessorClassGeneration"/>
<exclude name="AccessorMethodGeneration"/>
<exclude name="ArrayIsStoredDirectly"/>
<exclude name="AvoidPrintStackTrace"/>
<exclude name="AvoidReassigningParameters"/>
<exclude name="AvoidStringBufferField"/>
<exclude name="AvoidUsingHardCodedIP"/>
<exclude name="ConstantsInInterface"/>
<exclude name="ForLoopCanBeForeach"/>
<exclude name="GuardLogStatement"/>
<exclude name="JUnit4TestShouldUseAfterAnnotation"/>
<exclude name="JUnit4TestShouldUseTestAnnotation"/>
<exclude name="LooseCoupling"/>
<exclude name="MethodReturnsInternalArray"/>
<exclude name="OneDeclarationPerLine"/>
<exclude name="PositionLiteralsFirstInComparisons"/>
<exclude name="PreserveStackTrace"/>
<exclude name="ReplaceHashtableWithMap"/>
<exclude name="SwitchStmtsShouldHaveDefault"/>
<exclude name="SystemPrintln"/>
<exclude name="UnusedFormalParameter"/>
<exclude name="UseVarargs"/>
</rule>
<rule ref="category/java/bestpractices.xml/PreserveStackTrace">
<properties>
<property name="violationSuppressXPath" value="//PrimaryExpression/PrimaryPrefix/Name[@Image='BugReport.intercept']"/>
</properties>
</rule>
<rule ref="category/java/bestpractices.xml/UnusedFormalParameter">
<properties>
<property name="violationSuppressXPath" value="//Annotation[MarkerAnnotation/Name/@Image='Deprecated']/..[MethodDeclaration|ConstructorDeclaration]"/>
</properties>
</rule>
<rule ref="category/java/codestyle.xml">
<exclude name="AbstractNaming"/>
<exclude name="AtLeastOneConstructor"/>
<exclude name="AvoidFinalLocalVariable"/>
<exclude name="AvoidPrefixingMethodParameters"/>
<exclude name="BooleanGetMethodName"/>
<exclude name="CallSuperInConstructor"/>
<exclude name="ClassNamingConventions"/>
<exclude name="CommentDefaultAccessModifier"/>
<exclude name="ConfusingTernary"/>
<exclude name="ControlStatementBraces"/>
<exclude name="DefaultPackage"/>
<exclude name="EmptyMethodInAbstractClassShouldBeAbstract"/>
<exclude name="FieldDeclarationsShouldBeAtStartOfClass"/>
<exclude name="FieldNamingConventions"/>
<exclude name="ForLoopsMustUseBraces"/>
<exclude name="IfElseStmtsMustUseBraces"/>
<exclude name="IfStmtsMustUseBraces"/>
<exclude name="LinguisticNaming"/>
<exclude name="LocalVariableCouldBeFinal"/>
<exclude name="LongVariable"/>
<exclude name="MethodArgumentCouldBeFinal"/><!-- way too many -->
<exclude name="MethodArgumentCouldBeFinal"/>
<exclude name="MethodNamingConventions"/>
<exclude name="NoPackage"/>
<exclude name="OnlyOneReturn"/>
<exclude name="PrematureDeclaration"/>
<exclude name="ShortClassName"/>
<exclude name="ShortMethodName"/>
<exclude name="ShortVariable"/>
<exclude name="TooManyStaticImports"/>
<exclude name="UnnecessaryConstructor"/>
<exclude name="UselessParentheses"/>
<exclude name="UseUnderscoresInNumericLiterals"/>
<exclude name="VariableNamingConventions"/>
<exclude name="WhileLoopsMustUseBraces"/>
</rule>
<rule ref="category/java/codestyle.xml/ShortMethodName">
<properties>
<property name="violationSuppressXPath" value="//MethodDeclarator[@Image='at' or @Image='ht' or @Image='of' or @Image='ok' or @Image='tr']
| //MethodDeclarator/../../Annotation/MarkerAnnotation/Name[@Image='Deprecated']
| //MethodDeclarator/../../../..[@Image='LambertConformalConic']"/>
</properties>
</rule>
<rule ref="category/java/codestyle.xml/MethodNamingConventions">
<properties>
<property name="violationSuppressXPath" value="//MethodDeclarator/../../../..[@Image='Functions' or @Image='PseudoClasses' or @Image='Role' or @Image='TaggingPreset']"/>
</properties>
</rule>
<rule ref="category/java/codestyle.xml/FieldNamingConventions">
<properties>
<property name="enumConstantPattern" value="[A-Za-z][A-Za-z_0-9]*"/>
<property name="violationSuppressXPath" value="//FieldDeclaration[@Public='true']
| //FieldDeclaration/../Annotation/MarkerAnnotation/Name[@Image='pref']
| //FieldDeclaration/Type/ReferenceType/ClassOrInterfaceType[@Image!='Boolean' and
@Image!='Byte' and
@Image!='Character' and
@Image!='Class' and
@Image!='Double' and
@Image!='Enum' and
@Image!='Float' and
@Image!='Integer' and
@Image!='Long' and
@Image!='Number' and
@Image!='Short' and
@Image!='String' ]"/>
</properties>
</rule>
<rule ref="category/java/codestyle.xml/LongVariable">
<properties>
<property name="minimum" value="44"/>
</properties>
</rule>
<rule ref="category/java/design.xml">
<exclude name="AvoidCatchingGenericException"/>
<exclude name="AvoidDeeplyNestedIfStmts"/>
<exclude name="AvoidRethrowingException"/>
<exclude name="CollapsibleIfStatements"/>
<exclude name="CouplingBetweenObjects"/>
<exclude name="CyclomaticComplexity"/>
<exclude name="DataClass"/>
<exclude name="ExceptionAsFlowControl"/>
<exclude name="ExcessiveClassLength"/>
<exclude name="ExcessiveImports"/>
<exclude name="ExcessiveMethodLength"/>
<exclude name="ExcessiveParameterList"/>
<exclude name="ExcessivePublicCount"/>
<exclude name="GodClass"/>
<exclude name="ImmutableField"/>
<exclude name="LawOfDemeter"/>
<exclude name="LoosePackageCoupling"/>
<exclude name="NcssCount"/>
<exclude name="NPathComplexity"/>
<exclude name="SignatureDeclareThrowsException"/>
<exclude name="SimplifiedTernary"/>
<exclude name="SimplifyConditional"/>
<exclude name="SingularField"/>
<exclude name="SwitchDensity"/>
<exclude name="TooManyFields"/>
<exclude name="TooManyMethods"/>
<exclude name="UseObjectForClearerAPI"/>
<exclude name="UselessOverridingMethod"/>
<exclude name="UseUtilityClass"/>
</rule>
<rule ref="category/java/errorprone.xml"/>
<rule ref="category/java/multithreading.xml/AvoidThreadGroup"/>
<rule ref="category/java/multithreading.xml/DontCallThreadRun"/>
<rule ref="category/java/multithreading.xml/NonThreadSafeSingleton" />
<rule ref="category/java/design.xml/SignatureDeclareThrowsException">
<properties>
<property name="violationSuppressXPath" value="//MethodDeclaration/../Annotation/MarkerAnnotation/Name[@Image='Override']"/>
<property name="IgnoreJUnitCompletely" value="true"/>
</properties>
</rule>
<rule ref="category/java/errorprone.xml">
<exclude name="AssignmentInOperand"/>
<exclude name="AssignmentToNonFinalStatic"/>
<exclude name="AvoidBranchingStatementAsLastInLoop"/>
<exclude name="AvoidCatchingNPE"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="AvoidFieldNameMatchingMethodName"/>
<exclude name="AvoidFieldNameMatchingTypeName"/>
<exclude name="AvoidInstanceofChecksInCatchClause"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="BeanMembersShouldSerialize"/>
<exclude name="CloneThrowsCloneNotSupportedException"/>
<exclude name="CompareObjectsWithEquals"/>
<exclude name="ConstructorCallsOverridableMethod"/>
<exclude name="DataflowAnomalyAnalysis"/>
<exclude name="DoNotCallSystemExit"/>
<exclude name="DontImportSun"/>
<exclude name="EmptyIfStmt"/>
<exclude name="EmptyWhileStmt"/>
<exclude name="MissingBreakInSwitch"/>
<exclude name="MissingSerialVersionUID"/>
<exclude name="MissingStaticMethodInNonInstantiatableClass"/>
<exclude name="NonStaticInitializer"/>
<exclude name="NullAssignment"/>
<exclude name="ReturnEmptyArrayRatherThanNull"/>
<exclude name="SimpleDateFormatNeedsLocale"/>
<exclude name="SingleMethodSingleton"/>
<exclude name="SingletonClassReturningNewInstance"/>
<exclude name="TestClassWithoutTestCases"/>
<exclude name="UseProperClassLoader"/>
</rule>
<rule ref="category/java/performance.xml">
<exclude name="AvoidInstantiatingObjectsInLoops"/>
<exclude name="AvoidUsingShortType"/>
<exclude name="ConsecutiveLiteralAppends"/>
<exclude name="InefficientEmptyStringCheck"/>
<exclude name="SimplifyStartsWith"/>
<exclude name="TooFewBranchesForASwitchStatement"/>
<exclude name="UseArrayListInsteadOfVector"/>
<exclude name="UselessStringValueOf"/>
<exclude name="UseStringBufferForStringAppends"/>
</rule>
</ruleset>

Wyświetl plik

@ -38,11 +38,9 @@ public class ReplacementPreferenceTable extends PreferencesTable {
final JosmTextField tValue = new JosmTextField("", 50);
p.add(tValue, GBC.eop().insets(5, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));
PrefEntry pe = null;
if (askAddSetting(gui, p)) {
pe = new PrefEntry(tkey.getText(), new StringSetting(tValue.getText()), new StringSetting(null), false);
}
return pe;
return askAddSetting(gui, p)
? new PrefEntry(tkey.getText(), new StringSetting(tValue.getText()), new StringSetting(null), false)
: null;
}
private static boolean askAddSetting(JComponent gui, JPanel p) {

Wyświetl plik

@ -5,7 +5,6 @@ import static org.openstreetmap.josm.tools.I18n.tr;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import org.openstreetmap.josm.data.Bounds;
@ -47,18 +46,9 @@ public final class DetectTaskingManagerUtils {
* {@link DetectTaskingManagerUtils#PATTERNS} or {@code null}.
*/
public static Layer getTaskingManagerLayer() {
Layer returnLayer = null;
final List<Layer> layers = MainApplication.getLayerManager().getLayers();
for (final Pattern pattern : PATTERNS) {
final Optional<Layer> layer = layers.parallelStream()
.filter(tlayer -> pattern.matcher(tlayer.getName()).matches())
.findFirst();
if (layer.isPresent()) {
returnLayer = layer.get();
break;
}
}
return returnLayer;
return MainApplication.getLayerManager().getLayers().parallelStream().filter(
tlayer -> PATTERNS.parallelStream().anyMatch(pattern -> pattern.matcher(tlayer.getName()).matches()))
.findFirst().orElse(null);
}
/**

Wyświetl plik

@ -44,7 +44,7 @@ import org.openstreetmap.josm.tools.Pair;
*/
public class GetDataRunnable extends RecursiveTask<DataSet> implements CancelListener {
private static final long serialVersionUID = 258423685658089715L;
private final transient List<BBox> bbox;
private final List<BBox> bbox;
private static HttpClient client;
private final transient DataSet dataSet;
private final transient ProgressMonitor monitor;
@ -250,4 +250,13 @@ public class GetDataRunnable extends RecursiveTask<DataSet> implements CancelLis
client.disconnect();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
}

Wyświetl plik

@ -88,8 +88,7 @@ public class MapWithAIAction extends JosmAction {
.forEach(bounds::addAll);
}
final StringBuilder message = new StringBuilder();
message.append(MapWithAIPlugin.NAME);
message.append(": ");
message.append(MapWithAIPlugin.NAME).append(": ");
final MapWithAIAvailability availability = MapWithAIAvailability.getInstance();
final Map<String, Boolean> availableTypes = new TreeMap<>();
for (final Bounds bound : bounds) {
@ -102,8 +101,7 @@ public class MapWithAIAction extends JosmAction {
if (types.isEmpty()) {
message.append(tr("No data available"));
} else {
message.append("Data available: ");
message.append(String.join(", ", types));
message.append("Data available: ").append(String.join(", ", types));
}
notification.setContent(message.toString());

Wyświetl plik

@ -33,9 +33,9 @@ import org.openstreetmap.josm.tools.GBC;
*
*/
public class MapWithAILayer extends OsmDataLayer implements ActiveLayerChangeListener {
private Integer maximumAddition = null;
private String url = null;
private Boolean switchLayers = null;
private Integer maximumAddition;
private String url;
private Boolean switchLayers;
private final Lock lock;
/**
@ -151,7 +151,7 @@ public class MapWithAILayer extends OsmDataLayer implements ActiveLayerChangeLis
}
}
private boolean checkIfToggleLayer() {
private static boolean checkIfToggleLayer() {
List<String> keys = Config.getPref().getKeySet().parallelStream()
.filter(string -> string.contains(MapWithAIPlugin.NAME) && string.contains("boolean:toggle_with_layer"))
.collect(Collectors.toList());

Wyświetl plik

@ -26,7 +26,7 @@ import org.openstreetmap.josm.tools.Shortcut;
public class MapWithAIMoveAction extends JosmAction {
/** UID for abstract action */
private static final long serialVersionUID = 319374598;
private Notification lastNotification = null;
private transient Notification lastNotification;
public MapWithAIMoveAction() {
super(tr("{0}: Add selected data", MapWithAIPlugin.NAME), null, tr("Add data from {0}", MapWithAIPlugin.NAME),
@ -41,8 +41,6 @@ public class MapWithAIMoveAction extends JosmAction {
public void actionPerformed(ActionEvent event) {
for (final MapWithAILayer mapWithAI : MainApplication.getLayerManager().getLayersOfType(MapWithAILayer.class)) {
final DataSet ds = mapWithAI.getDataSet();
final List<OsmDataLayer> osmLayers = MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class);
OsmDataLayer editLayer = null;
final int maxAddition = MapWithAIPreferenceHelper.getMaximumAddition();
final List<Node> nodes = ds.getSelectedNodes().stream().filter(node -> !node.getReferrers().isEmpty())
.collect(Collectors.toList());
@ -51,33 +49,34 @@ public class MapWithAIMoveAction extends JosmAction {
if (ds.getSelected().size() > maxAddition) {
createMaxAddedDialog(maxAddition, ds.getSelected().size());
}
final Collection<OsmPrimitive> selected = maxAddition > 0
? ds.getSelected().stream().limit(maxAddition).collect(Collectors.toList())
: ds.getSelected();
for (final OsmDataLayer osmLayer : osmLayers) {
if (!osmLayer.isLocked() && osmLayer.isVisible() && osmLayer.isUploadable()
&& osmLayer.getClass().equals(OsmDataLayer.class)) {
editLayer = osmLayer;
break;
}
}
if (editLayer != null) {
final MapWithAIAddCommand command = new MapWithAIAddCommand(mapWithAI, editLayer, selected);
UndoRedoHandler.getInstance().add(command);
if (MapWithAIPreferenceHelper.isSwitchLayers()) {
MainApplication.getLayerManager().setActiveLayer(editLayer);
}
}
final Collection<OsmPrimitive> selected = limitCollection(ds, maxAddition);
final OsmDataLayer editLayer = getOsmDataLayer();
if (editLayer != null) {
final MapWithAIAddCommand command = new MapWithAIAddCommand(mapWithAI, editLayer, selected);
UndoRedoHandler.getInstance().add(command);
if (MapWithAIPreferenceHelper.isSwitchLayers()) {
MainApplication.getLayerManager().setActiveLayer(editLayer);
}
}
}
}
private static Collection<OsmPrimitive> limitCollection(DataSet ds, int maxSize) {
return maxSize > 0 ? ds.getSelected().stream().limit(maxSize).collect(Collectors.toList()) : ds.getSelected();
}
private static OsmDataLayer getOsmDataLayer() {
return MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class).stream()
.filter(OsmDataLayer::isVisible).filter(OsmDataLayer::isUploadable)
.filter(osmLayer -> !osmLayer.isLocked() && osmLayer.getClass().equals(OsmDataLayer.class)).findFirst()
.orElse(null);
}
private void createMaxAddedDialog(int maxAddition, int triedToAdd) {
final Notification notification = new Notification();
final StringBuilder message = new StringBuilder();
message.append(MapWithAIPlugin.NAME);
message.append(": ");
message.append(tr("maximum additions per action are ")).append(maxAddition).append(", ");
message.append(tr("tried to add ")).append(triedToAdd).append(".");
message.append(MapWithAIPlugin.NAME).append(": ").append(tr("maximum additions per action are "))
.append(maxAddition).append(", ").append(tr("tried to add ")).append(triedToAdd).append('.');
notification.setContent(message.toString());
notification.setDuration(Notification.TIME_DEFAULT);
notification.setIcon(JOptionPane.INFORMATION_MESSAGE);

Wyświetl plik

@ -19,14 +19,17 @@ public class MapWithAIRemoteControl extends RequestHandler.RawURLParseRequestHan
private static final PermissionPrefWithDefault PERMISSION_PREF_WITH_DEFAULT = new PermissionPrefWithDefault(
MapWithAIPlugin.NAME.concat(".remote_control"), true, tr("MapWithAI"));
private BBox download = null;
private BBox crop = null;
private Integer maxObj = null;
private Boolean switchLayer = null;
private String url = null;
private BBox download;
private BBox crop;
private Integer maxObj;
private Boolean switchLayer;
private String url;
private static final String MAX_OBJ = "max_obj";
private static final String SWITCH_LAYER = "switch_layer";
private static final String BBOX = "bbox";
private static final String CROP_BBOX = "crop_bbox";
private static final String URL_STRING = "url";
public MapWithAIRemoteControl() {
super();
@ -36,18 +39,18 @@ public class MapWithAIRemoteControl extends RequestHandler.RawURLParseRequestHan
protected void validateRequest() throws RequestHandlerBadRequestException {
if (args != null) {
try {
if (args.containsKey("bbox")) {
download = parseBBox(args.get("bbox"));
if (args.containsKey(BBOX)) {
download = parseBBox(args.get(BBOX));
}
if (args.containsKey("crop_bbox")) {
crop = parseBBox(args.get("crop_bbox"));
if (args.containsKey(CROP_BBOX)) {
crop = parseBBox(args.get(CROP_BBOX));
}
if (args.containsKey(MAX_OBJ)) {
maxObj = Integer.parseInt(args.get(MAX_OBJ));
}
if (args.containsKey("url")) {
final String urlString = args.get("url");
// Ensure the URL is valid
if (args.containsKey(URL_STRING)) {
final String urlString = args.get(URL_STRING);
// Ensure the URL_STRING is valid
url = new URL(urlString).toString();
}
if (args.containsKey(SWITCH_LAYER)) {
@ -109,26 +112,17 @@ public class MapWithAIRemoteControl extends RequestHandler.RawURLParseRequestHan
public String getPermissionMessage() {
final String br = "<br />";
final StringBuilder sb = new StringBuilder();
sb.append(tr("Remote Control has been asked to load data from the API."));
sb.append(" (");
sb.append(url);
sb.append(")");
sb.append(br);
sb.append(tr("{0} will ", MapWithAIPlugin.NAME));
if (!switchLayer) {
sb.append(tr("Remote Control has been asked to load data from the API.")).append(" (").append(url).append(')')
.append(br).append(tr("{0} will ", MapWithAIPlugin.NAME));
if (Boolean.FALSE.equals(switchLayer)) {
sb.append(tr("not "));
}
sb.append(tr("automatically switch layers."));
sb.append(br);
sb.append(tr("automatically switch layers.")).append(br);
if (download != null) {
sb.append(tr("We will download data in "));
sb.append(download.toStringCSV(","));
sb.append(br);
sb.append(tr("We will download data in ")).append(download.toStringCSV(",")).append(br);
}
if (crop != null) {
sb.append(tr("We will crop the data to"));
sb.append(crop.toStringCSV(","));
sb.append(br);
sb.append(tr("We will crop the data to")).append(crop.toStringCSV(",")).append(br);
}
sb.append(tr("There is a maximum addition of {0} objects at one time", maxObj));
return sb.toString();
@ -147,7 +141,7 @@ public class MapWithAIRemoteControl extends RequestHandler.RawURLParseRequestHan
@Override
public String[] getOptionalParams() {
return new String[] { "bbox", "url", MAX_OBJ, SWITCH_LAYER, "crop_bbox" };
return new String[] { BBOX, URL_STRING, MAX_OBJ, SWITCH_LAYER, CROP_BBOX };
}
@Override

Wyświetl plik

@ -20,11 +20,17 @@ import org.openstreetmap.josm.io.OsmReader;
* entered, and it must point to the end of the same element, when it is exited.
*/
public class OsmReaderCustom extends OsmReader {
boolean temporaryConvertUknownToTags;
protected OsmReaderCustom(boolean convertUnknownToTags) {
// Restricts visibility
super();
// TODO when we update to r15470 this.convertUnknownToTags =
// convertUnknownToTags;
// TODO when we update to r15470 this.convertUnknownToTags
temporaryConvertUknownToTags = convertUnknownToTags;
}
// TODO remove with update to r15470
protected boolean isConvertUknownToTags() {
return temporaryConvertUknownToTags;
}
@Override

Wyświetl plik

@ -26,7 +26,7 @@ import org.openstreetmap.josm.tools.Utils;
public class CreateConnectionsCommand extends Command {
private final Collection<OsmPrimitive> primitives;
private Command command = null;
private Command command;
private static final List<Class<? extends AbstractConflationCommand>> CONFLATION_COMMANDS = new ArrayList<>();
static {
CONFLATION_COMMANDS.add(ConnectedCommand.class);

Wyświetl plik

@ -25,8 +25,8 @@ public class MapWithAIAddCommand extends Command implements Runnable {
DataSet editable;
DataSet mapWithAI;
Collection<OsmPrimitive> primitives;
Command command = null;
Lock lock = null;
Command command;
Lock lock;
/**
* Add primitives from MapWithAI to the OSM data layer

Wyświetl plik

@ -25,7 +25,7 @@ import org.openstreetmap.josm.tools.Logging;
* @author Taylor Smock
*/
public class MovePrimitiveDataSetCommand extends Command {
private SequenceCommand command = null;
private SequenceCommand command;
public MovePrimitiveDataSetCommand(DataSet to, DataSet from, Collection<OsmPrimitive> primitives) {
super(to);