[cleanup] - added forbidden apis mvn plugin

- fixed the use of the found forbidden APIs
- changed `FiredAlert.State` values to lower case (for consistency sake)

Original commit: elastic/x-pack-elasticsearch@9b3f8383d9
This commit is contained in:
uboness 2015-02-17 16:31:18 +01:00
parent 37d9fd062e
commit 54923420d9
12 changed files with 173 additions and 50 deletions

3
all-signatures.txt Normal file
View File

@ -0,0 +1,3 @@
@defaultMessage Convert to URI
java.net.URL#getPath()
java.net.URL#getFile()

60
core-signatures.txt Normal file
View File

@ -0,0 +1,60 @@
@defaultMessage spawns threads with vague names; use a custom thread factory and name threads so that you can tell (by its name) which executor it is associated with
java.util.concurrent.Executors#newFixedThreadPool(int)
java.util.concurrent.Executors#newSingleThreadExecutor()
java.util.concurrent.Executors#newCachedThreadPool()
java.util.concurrent.Executors#newSingleThreadScheduledExecutor()
java.util.concurrent.Executors#newScheduledThreadPool(int)
java.util.concurrent.Executors#defaultThreadFactory()
java.util.concurrent.Executors#privilegedThreadFactory()
java.lang.Character#codePointBefore(char[],int) @ Implicit start offset is error-prone when the char[] is a buffer and the first chars are random chars
java.lang.Character#codePointAt(char[],int) @ Implicit end offset is error-prone when the char[] is a buffer and the last chars are random chars
java.io.StringReader#<init>(java.lang.String) @ Use FastStringReader instead
@defaultMessage Reference management is tricky, leave it to SearcherManager
org.apache.lucene.index.IndexReader#decRef()
org.apache.lucene.index.IndexReader#incRef()
org.apache.lucene.index.IndexReader#tryIncRef()
@defaultMessage QueryWrapperFilter is cachable by default - use Queries#wrap instead
org.apache.lucene.search.QueryWrapperFilter#<init>(org.apache.lucene.search.Query)
@defaultMessage Because the filtercache doesn't take deletes into account FilteredQuery can't be used - use XFilteredQuery instead
org.apache.lucene.search.FilteredQuery#<init>(org.apache.lucene.search.Query,org.apache.lucene.search.Filter)
org.apache.lucene.search.FilteredQuery#<init>(org.apache.lucene.search.Query,org.apache.lucene.search.Filter,org.apache.lucene.search.FilteredQuery$FilterStrategy)
@defaultMessage Pass the precision step from the mappings explicitly instead
org.apache.lucene.search.NumericRangeQuery#newDoubleRange(java.lang.String,java.lang.Double,java.lang.Double,boolean,boolean)
org.apache.lucene.search.NumericRangeQuery#newFloatRange(java.lang.String,java.lang.Float,java.lang.Float,boolean,boolean)
org.apache.lucene.search.NumericRangeQuery#newIntRange(java.lang.String,java.lang.Integer,java.lang.Integer,boolean,boolean)
org.apache.lucene.search.NumericRangeQuery#newLongRange(java.lang.String,java.lang.Long,java.lang.Long,boolean,boolean)
org.apache.lucene.search.NumericRangeFilter#newDoubleRange(java.lang.String,java.lang.Double,java.lang.Double,boolean,boolean)
org.apache.lucene.search.NumericRangeFilter#newFloatRange(java.lang.String,java.lang.Float,java.lang.Float,boolean,boolean)
org.apache.lucene.search.NumericRangeFilter#newIntRange(java.lang.String,java.lang.Integer,java.lang.Integer,boolean,boolean)
org.apache.lucene.search.NumericRangeFilter#newLongRange(java.lang.String,java.lang.Long,java.lang.Long,boolean,boolean)
@defaultMessage Only use wait / notify when really needed try to use concurrency primitives, latches or callbacks instead.
java.lang.Object#wait()
java.lang.Object#wait(long)
java.lang.Object#wait(long,int)
java.lang.Object#notify()
java.lang.Object#notifyAll()
@defaultMessage Beware of the behavior of this method on MIN_VALUE
java.lang.Math#abs(int)
java.lang.Math#abs(long)
@defaultMessage Please do not try to stop the world
java.lang.System#gc()
@defaultMessage Use Channels.* methods to write to channels. Do not write directly.
java.nio.channels.WritableByteChannel#write(java.nio.ByteBuffer)
java.nio.channels.FileChannel#write(java.nio.ByteBuffer, long)
java.nio.channels.GatheringByteChannel#write(java.nio.ByteBuffer[], int, int)
java.nio.channels.GatheringByteChannel#write(java.nio.ByteBuffer[])
java.nio.channels.ReadableByteChannel#read(java.nio.ByteBuffer)
java.nio.channels.ScatteringByteChannel#read(java.nio.ByteBuffer[])
java.nio.channels.ScatteringByteChannel#read(java.nio.ByteBuffer[], int, int)
java.nio.channels.FileChannel#read(java.nio.ByteBuffer, long)

83
pom.xml
View File

@ -392,7 +392,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<!-- we skip surefire to work with randomized testing above --> <!-- we skip surefire to work with randomized testing above -->
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
@ -402,7 +401,6 @@
<skipTests>true</skipTests> <skipTests>true</skipTests>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId> <artifactId>buildnumber-maven-plugin</artifactId>
@ -420,7 +418,88 @@
<doUpdate>false</doUpdate> <doUpdate>false</doUpdate>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>de.thetaphi</groupId>
<artifactId>forbiddenapis</artifactId>
<version>1.6.1</version>
<executions>
<execution>
<id>check-forbidden-apis</id>
<configuration>
<targetVersion>1.7</targetVersion>
<!-- disallow undocumented classes like sun.misc.Unsafe: -->
<internalRuntimeForbidden>true</internalRuntimeForbidden>
<!-- if the used Java version is too new, don't fail, just do nothing: -->
<failOnUnsupportedJava>false</failOnUnsupportedJava>
<excludes>
<exclude>jsr166e/**</exclude>
<exclude>
org/elasticsearch/common/lucene/search/Queries$QueryWrapperFilterFactory.class
</exclude>
<!-- end excludes for valid system-out -->
<!-- start excludes for Unsafe -->
<exclude>org/elasticsearch/common/util/UnsafeUtils.class</exclude>
<!-- end excludes for Unsafe -->
<!-- start excludes for Math.abs -->
<exclude>org/elasticsearch/common/util/MathUtils.class</exclude>
<exclude>org/elasticsearch/common/math/UnboxedMathUtils.class</exclude>
<exclude>org/elasticsearch/cluster/routing/operation/plain/PlainOperationRouting.class
</exclude>
<!-- end excludes for Math.abs -->
<!-- start exclude for FilteredQuery -->
<exclude>org/elasticsearch/common/lucene/search/XFilteredQuery.class</exclude>
<!-- end exclude for FilteredQuery -->
<!-- start exclude for Channels utility class -->
<exclude>org/elasticsearch/common/io/Channels.class</exclude>
<!-- end exclude for Channels -->
</excludes>
<bundledSignatures>
<!-- This will automatically choose the right signatures based on 'targetVersion': -->
<bundledSignature>jdk-unsafe</bundledSignature>
<bundledSignature>jdk-deprecated</bundledSignature>
<bundledSignature>jdk-system-out</bundledSignature>
</bundledSignatures>
<signaturesFiles>
<signaturesFile>core-signatures.txt</signaturesFile>
<signaturesFile>all-signatures.txt</signaturesFile>
</signaturesFiles>
<!--<signatures>${forbidden.signatures}</signatures>-->
</configuration>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>check-forbidden-test-apis</id>
<configuration>
<targetVersion>1.7</targetVersion>
<!-- disallow undocumented classes like sun.misc.Unsafe: -->
<internalRuntimeForbidden>true</internalRuntimeForbidden>
<!-- if the used Java version is too new, don't fail, just do nothing: -->
<failOnUnsupportedJava>false</failOnUnsupportedJava>
<excludes>
<exclude>org/quartz/**</exclude>
</excludes>
<bundledSignatures>
<!-- This will automatically choose the right signatures based on 'targetVersion': -->
<bundledSignature>jdk-unsafe</bundledSignature>
<bundledSignature>jdk-deprecated</bundledSignature>
</bundledSignatures>
<signaturesFiles>
<signaturesFile>test-signatures.txt</signaturesFile>
<signaturesFile>all-signatures.txt</signaturesFile>
</signaturesFiles>
<!--<signatures>${forbidden.test.signatures}</signatures>-->
</configuration>
<phase>test-compile</phase>
<goals>
<goal>testCheck</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>

View File

@ -337,7 +337,7 @@ public class Email implements ToXContent {
if (name == null) { if (name == null) {
return defaultPriority; return defaultPriority;
} }
switch (name.toLowerCase()) { switch (name.toLowerCase(Locale.ROOT)) {
case "highest": return HIGHEST; case "highest": return HIGHEST;
case "high": return HIGH; case "high": return HIGH;
case "normal": return NORMAL; case "normal": return NORMAL;

View File

@ -111,7 +111,7 @@ public enum Profile implements ToXContent {
@Override @Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.value(name().toLowerCase()); return builder.value(name().toLowerCase(Locale.ROOT));
} }
static MimeMessage createCommon(Email email, Session session) throws MessagingException { static MimeMessage createCommon(Email email, Session session) throws MessagingException {

View File

@ -10,6 +10,7 @@ import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.alerts.Alert; import org.elasticsearch.alerts.Alert;
import org.elasticsearch.alerts.AlertExecution; import org.elasticsearch.alerts.AlertExecution;
import org.elasticsearch.alerts.AlertsException; import org.elasticsearch.alerts.AlertsException;
import org.elasticsearch.alerts.AlertsSettingsException;
import org.elasticsearch.alerts.actions.ActionRegistry; import org.elasticsearch.alerts.actions.ActionRegistry;
import org.elasticsearch.alerts.condition.Condition; import org.elasticsearch.alerts.condition.Condition;
import org.elasticsearch.alerts.condition.ConditionRegistry; import org.elasticsearch.alerts.condition.ConditionRegistry;
@ -26,6 +27,7 @@ import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -127,7 +129,7 @@ public class FiredAlert implements ToXContent {
historyEntry.field(Parser.FIRE_TIME_FIELD.getPreferredName(), fireTime.toDateTimeISO()); historyEntry.field(Parser.FIRE_TIME_FIELD.getPreferredName(), fireTime.toDateTimeISO());
historyEntry.field(Parser.SCHEDULED_FIRE_TIME_FIELD.getPreferredName(), scheduledTime.toDateTimeISO()); historyEntry.field(Parser.SCHEDULED_FIRE_TIME_FIELD.getPreferredName(), scheduledTime.toDateTimeISO());
historyEntry.startObject(Alert.Parser.CONDITION_FIELD.getPreferredName()).field(condition.type(), condition, params).endObject(); historyEntry.startObject(Alert.Parser.CONDITION_FIELD.getPreferredName()).field(condition.type(), condition, params).endObject();
historyEntry.field(Parser.STATE_FIELD.getPreferredName(), state.toString()); historyEntry.field(Parser.STATE_FIELD.getPreferredName(), state.id());
if (message != null) { if (message != null) {
historyEntry.field(Parser.MESSAGE_FIELD.getPreferredName(), message); historyEntry.field(Parser.MESSAGE_FIELD.getPreferredName(), message);
@ -174,45 +176,22 @@ public class FiredAlert implements ToXContent {
EXECUTED, EXECUTED,
FAILED; FAILED;
public String id() {
return name().toLowerCase(Locale.ROOT);
}
public static State resolve(String id) {
try {
return valueOf(id.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException iae) {
throw new AlertsSettingsException("unknown fired alert state [" + id + "]");
}
}
@Override @Override
public String toString() { public String toString() {
switch (this) { return id();
case AWAITS_EXECUTION:
return "AWAITS_EXECUTION";
case CHECKING:
return "CHECKING";
case EXECUTION_NOT_NEEDED:
return "EXECUTION_NOT_NEEDED";
case EXECUTED:
return "EXECUTED";
case FAILED:
return "FAILED";
case THROTTLED:
return "THROTTLED";
default:
return "EXECUTION_NOT_NEEDED";
}
} }
public static State fromString(String value) {
switch(value.toUpperCase()) {
case "AWAITS_EXECUTION":
return AWAITS_EXECUTION;
case "CHECKING":
return CHECKING;
case "EXECUTION_NOT_NEEDED":
return EXECUTION_NOT_NEEDED;
case "EXECUTED":
return EXECUTED;
case "FAILED":
return FAILED;
case "THROTTLED":
return THROTTLED;
default:
throw new ElasticsearchIllegalArgumentException("unknown fired alert state [" + value + "]");
}
}
} }
public static class Parser extends AbstractComponent { public static class Parser extends AbstractComponent {
@ -274,7 +253,7 @@ public class FiredAlert implements ToXContent {
} else if (MESSAGE_FIELD.match(currentFieldName)) { } else if (MESSAGE_FIELD.match(currentFieldName)) {
alert.message = parser.textOrNull(); alert.message = parser.textOrNull();
} else if (STATE_FIELD.match(currentFieldName)) { } else if (STATE_FIELD.match(currentFieldName)) {
alert.state = State.fromString(parser.text()); alert.state = State.resolve(parser.text());
} else { } else {
throw new AlertsException("unable to parse fired alert. unexpected field [" + currentFieldName + "]"); throw new AlertsException("unable to parse fired alert. unexpected field [" + currentFieldName + "]");
} }

View File

@ -111,7 +111,7 @@ public class HistoryStore extends AbstractComponent {
} }
SearchResponse response = client.prepareSearch(ALERT_HISTORY_INDEX_PREFIX + "*") SearchResponse response = client.prepareSearch(ALERT_HISTORY_INDEX_PREFIX + "*")
.setQuery(QueryBuilders.termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), firedAlertState.toString())) .setQuery(QueryBuilders.termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), firedAlertState.id()))
.setSearchType(SearchType.SCAN) .setSearchType(SearchType.SCAN)
.setScroll(scrollTimeout) .setScroll(scrollTimeout)
.setSize(scrollSize) .setSize(scrollSize)

View File

@ -270,7 +270,7 @@ public abstract class AbstractAlertingTests extends ElasticsearchIntegrationTest
SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setIndicesOptions(IndicesOptions.lenientExpandOpen()) .setIndicesOptions(IndicesOptions.lenientExpandOpen())
.setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.toString()))) .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.id())))
.get(); .get();
assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(minimumExpectedAlertActionsWithActionPerformed)); assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(minimumExpectedAlertActionsWithActionPerformed));
if (assertConditionMet) { if (assertConditionMet) {
@ -283,7 +283,7 @@ public abstract class AbstractAlertingTests extends ElasticsearchIntegrationTest
protected long findNumberOfPerformedActions(String alertName) { protected long findNumberOfPerformedActions(String alertName) {
SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setIndicesOptions(IndicesOptions.lenientExpandOpen()) .setIndicesOptions(IndicesOptions.lenientExpandOpen())
.setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.toString()))) .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTED.id())))
.get(); .get();
return searchResponse.getHits().getTotalHits(); return searchResponse.getHits().getTotalHits();
} }
@ -304,7 +304,7 @@ public abstract class AbstractAlertingTests extends ElasticsearchIntegrationTest
SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") SearchResponse searchResponse = client().prepareSearch(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setIndicesOptions(IndicesOptions.lenientExpandOpen()) .setIndicesOptions(IndicesOptions.lenientExpandOpen())
.setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTION_NOT_NEEDED.toString()))) .setQuery(boolQuery().must(matchQuery("alert_name", alertName)).must(matchQuery("state", FiredAlert.State.EXECUTION_NOT_NEEDED.id())))
.get(); .get();
assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(expectedAlertActionsWithNoActionNeeded)); assertThat(searchResponse.getHits().getTotalHits(), greaterThanOrEqualTo(expectedAlertActionsWithNoActionNeeded));
} }

View File

@ -127,7 +127,7 @@ public class AlertThrottleTests extends AbstractAlertingTests {
CountResponse countOfThrottledActions = client() CountResponse countOfThrottledActions = client()
.prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") .prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setQuery(QueryBuilders.matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.toString())) .setQuery(QueryBuilders.matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.id()))
.get(); .get();
assertThat(countOfThrottledActions.getCount(), greaterThan(0L)); assertThat(countOfThrottledActions.getCount(), greaterThan(0L));
} }
@ -204,7 +204,7 @@ public class AlertThrottleTests extends AbstractAlertingTests {
CountResponse countOfThrottledActions = client() CountResponse countOfThrottledActions = client()
.prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") .prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setQuery(QueryBuilders.matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.toString())) .setQuery(QueryBuilders.matchQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.THROTTLED.id()))
.get(); .get();
assertThat(countOfThrottledActions.getCount(), greaterThan(0L)); assertThat(countOfThrottledActions.getCount(), greaterThan(0L));
} }

View File

@ -26,6 +26,8 @@ import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test; import org.junit.Test;
import java.util.Locale;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.FilterBuilders.rangeFilter; import static org.elasticsearch.index.query.FilterBuilders.rangeFilter;
import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*;
@ -257,7 +259,7 @@ public class BasicAlertingTest extends AbstractAlertingTests {
alertClient().prepareDeleteAlert(alertName).get(); alertClient().prepareDeleteAlert(alertName).get();
alertClient().preparePutAlert(alertName) alertClient().preparePutAlert(alertName)
.setAlertSource(createAlertSource(String.format("0/%s * * * * ? *", (scheduleTimeInMs / 1000)), request, "return hits.total >= 3")) .setAlertSource(createAlertSource(String.format(Locale.ROOT, "0/%s * * * * ? *", (scheduleTimeInMs / 1000)), request, "return hits.total >= 3"))
.get(); .get();
long time1 = System.currentTimeMillis(); long time1 = System.currentTimeMillis();

View File

@ -177,7 +177,7 @@ public class BootStrapTest extends AbstractAlertingTests {
public void run() { public void run() {
CountResponse countResponse = client().prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*") CountResponse countResponse = client().prepareCount(HistoryStore.ALERT_HISTORY_INDEX_PREFIX + "*")
.setTypes(HistoryStore.ALERT_HISTORY_TYPE) .setTypes(HistoryStore.ALERT_HISTORY_TYPE)
.setQuery(QueryBuilders.termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.EXECUTED.toString())).get(); .setQuery(QueryBuilders.termQuery(FiredAlert.Parser.STATE_FIELD.getPreferredName(), FiredAlert.State.EXECUTED.id())).get();
assertEquals(totalHistoryEntries, countResponse.getCount()); assertEquals(totalHistoryEntries, countResponse.getCount());
} }

0
test-signatures.txt Normal file
View File