Java edu.umd.cs.findbugs.annotations.SuppressFBWarnings 代码实例

・13 分钟阅读

以下是展示如何使用edu.umd.cs.findbugs.annotations.SuppressFBWarnings的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ")
public void testShortenLongString() {
    String s1 =
            "string which is really quite long. string which is really quite long. string which is really quite long. string which is really quite long. string which is really quite long. ";
    String s2 = ShortString.shorten(s1);
    assertTrue(s2.length() <= ShortString.MAX_LENGTH);
    String s3 = ShortString.shorten(s2);
    assertSame(s2, s3);
}
 

实例 2


@Test(expected = IllegalArgumentException.class)
@SuppressFBWarnings(value = "DM_NEW_FOR_GETCLASS", justification = "Need a new class")
public void testFindClassesWithAnnotationNonAnnotation() {
    final Class<? extends Annotation> notAnAnnotation = new Annotation() {
        @Override
        public Class<? extends Annotation> annotationType() {
            return null;
        }
    }.getClass();
    final AnnotationDatabase db = ReflectionsDatabase.newInstance();
    db.findClassesWithAnnotation(notAnAnnotation);
}
 

实例 3


@SuppressFBWarnings({"DC_DOUBLECHECK", "DC_DOUBLECHECK"})
@Override
void init(@NonNull final Configuration initialConfiguration) {
    OPFLog.logMethod(initialConfiguration);
    if (this.configuration == null) {
        synchronized (initLock) {
            if (this.configuration == null) {
                this.configuration = initialConfiguration;
            }
        }
    }
    final List<PushProvider> providers = configuration.getProviders();
    for (PushProvider provider : providers) {
        provider.checkManifest(configuration.getCheckManifestHandler());
        providersByHostApps.put(provider.getHostAppPackage(), provider.getName());
    }
    retryManager = RetryManager.init(appContext, InfinityExponentialBackoffManager.getInstance());
    final EventListener eventListener = configuration.getEventListener();
    final boolean isOPFReceiverRegistered = isOPFReceiverRegistered();
    OPFLog.d("isOPFReceiverRegistered == " + isOPFReceiverRegistered
            + "; eventListenerWrapper == " + eventListener);
    if (isOPFReceiverRegistered && eventListener != null) {
        throw new IllegalStateException("You can't register OPFReceiver and set event listener");
    } else if (!isOPFReceiverRegistered && eventListener == null) {
        throw new IllegalStateException("You must register OPFReceiver or set event listener");
    }
    initSortedProviderList();
    this.eventListenerWrapper = EventListenerWrapperCreator
            .getEventListenerWrapper(eventListener);
    restoreLastProvider();
    OPFLog.i("Init done.");
}
 

实例 4


@Override
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
                justification = "Make some context visible statically (no matter which one)")
public void onCreate() {
        super.onCreate();
        Application.mApplication = this;
        SettingsActivity.setDefaultSharedPreferences(getApplicationContext());
        setLanguage();
        setExceptionHandler();
        // Initialize special classes
        try {
                mApplicationSettings =
                                (ApplicationSettings) Class.forName(getResourceString(R.string.class_application_settings))
                                                .getDeclaredMethod("getInstance", new Class<?>[0])
                                                .invoke(null);
        }
        catch (Exception e) {
                Log.e(TAG, "Error in getting PrivateConstants and ApplicationSettings", e);
        }
        // Set statistics
        int initialVersion = PreferenceUtil.getSharedPreferenceInt(R.string.key_statistics_initialversion, -1);
        if (initialVersion == -1) {
                PreferenceUtil.setSharedPreferenceInt(R.string.key_statistics_initialversion, getVersion());
        }
        long firstStartTime = PreferenceUtil.getSharedPreferenceLong(R.string.key_statistics_firststarttime, -1);
        if (firstStartTime == -1) {
                PreferenceUtil.setSharedPreferenceLong(R.string.key_statistics_firststarttime, System.currentTimeMillis());
        }
        PreferenceUtil.incrementCounter(R.string.key_statistics_countstarts);
}
 

实例 5


@SuppressFBWarnings(value = "EQ_UNUSUAL")
@Override
public boolean equals(Object o)
{
    if (o == null) {
        return false;
    }
    return o.getClass().isAssignableFrom(getClass());
}
 

实例 6


@Bean
public org.apache.mesos.elasticsearch.scheduler.Configuration getConfig() {
    return new org.apache.mesos.elasticsearch.scheduler.Configuration(ZookeeperCLIParameter.ZOOKEEPER_MESOS_URL, "zk://dummy.mesos.master:2181") {
        @SuppressFBWarnings("UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS")
        public String getFakePassword() {
            return "Sh0uld n0t be v1s1bl3";
        }
    };
}
 

实例 7


@SuppressFBWarnings(value = "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS",
        justification = "False positive")
@Test
public void testAddHeader() throws AuthFailureError {
        assumeThat(request.getHeaders(), not(hasKey(CUSTOM_HEADER)));
        request.addHeader(CUSTOM_HEADER, CUSTOM_HEADER_VALUE);
        assertThat("Failed to add headers", request.getHeaders(), hasKey(CUSTOM_HEADER));
}
 

实例 8


@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {
    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);
    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);
                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });
    return b.connect("127.0.0.1", port).sync().channel();
}
 

实例 9


@Override
@SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
public SparseVector apply(UserHistory<? extends Event> history) {
    if (history == null) {
        throw new NullPointerException("history is null");
    }
    return ImmutableSparseVector.create(Ratings.userRatingVector(history.filter(Rating.class)));
}
 

实例 10


@Test
@SuppressFBWarnings(value = "GC_UNRELATED_TYPES", justification = "it's not a bug, it's a test.")
public void testRemove() {
  final GeneralDomainBitSet<Integer> clone = this.oneTo4.clone();
  clone.remove(1);
  clone.remove(4);
  assertEquals(this.twoThree, clone);
  try {
    clone.remove("Elephant");
  } catch (final IllegalArgumentException e) {
    fail("remove(Object) should do nothing if the object is not of the domain.");
  }
  assertEquals(this.twoThree, clone);
}
 

实例 11


@SuppressFBWarnings("UC_USELESS_OBJECT")
public void setUp() {
    File serverFile = new File("test.file");
    File localFile = new File("local.file");
    evidence = new Evidence(1, "Test file", serverFile, localFile);
    Evidence e = new Evidence(2, "Test file", serverFile);
    assertNull(e.getLocalFile());
}
 

实例 12


/**
 * Tries to get the field's value.
 *
 * @return The field's value.
 * @throws ReflectionException If the operation fails.
 */
@SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "Only called in test code, not production.")
public Object get() {
    field.setAccessible(true);
    try {
        return field.get(object);
    }
    catch (IllegalAccessException e) {
        throw new ReflectionException(e);
    }
}
 

实例 13


@SuppressFBWarnings("DM_EXIT")
public void sendStatusUpdate(ExecutorDriver driver, Protos.TaskInfo taskInfo, Protos.TaskState taskState, String message, Logger logger) {
  logger.info("Sending status update "{}" ({})", message, taskState.name());
  message = message.substring(0, Math.min(configuration.getMaxTaskMessageLength(), message.length()));
  try {
    final Protos.TaskStatus.Builder builder = Protos.TaskStatus.newBuilder()
        .setTaskId(taskInfo.getTaskId())
        .setState(taskState)
        .setMessage(message);
    driver.sendStatusUpdate(builder.build());
  } catch (Throwable t) {
    try {
      logger.error("Exception while sending status updates, exiting", t);
    } finally {
      System.exit(4);
    }
  }
}
 

实例 14


@Override
@SuppressFBWarnings(value="UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "JUnit runner calls testRunStarted before this method")
public void testRunFinished(Result result) throws Exception {
  xml.printf("<?xml version="1.1" encoding="UTF-8"?>%n");
  xml.printf("<testsuite name="%s" time="%f" tests="%d" errors="%d" skipped="%d" failures="%d">%n", testName,
      result.getRunTime() / 1000.0, results.size(), errorCount, skippedCount, failureCount);
  for (TestStatus test : results) {
    String ignoreAttr = "";
    if (test.status == ignored) {
      ignoreAttr = " ignored="true"";
    }
    xml.printf(" <testcase name="%s" classname="%s" time="%f"%s>", test.name, test.classname,
        test.runTime / 1000.0, ignoreAttr);
    printIfPresent("system-out", test.stdout);
    printIfPresent("system-err", test.stderr);
    printIfPresent(test.status.traceElement, test.trace);
    xml.printf("</testcase>%n");
  }
  xml.print("</testsuite>");
  xml.close();
}
 

实例 15


/**
 * Constructor.
 *
 * @param topologyService the Topology Service to use.
 * @param webSocketPort the WebSocket port to use.
 */
@SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
                    justification = "The writing to WebSocketManager.topologyService happens only once on startup")
WebSocketManager(ITopologyService topologyService,
                 int webSocketPort) {
    WebSocketManager.topologyService = topologyService;
    this.webSocketPort = webSocketPort;
}
 
讨论
淘淘あ西西 profile image