Uploaded image for project: 'Camel'
  1. Camel
  2. CAMEL-4765

Avoid explicit cast while using the CamelContext.getEndpoint() or ApplicationContext.getBean() API and better rely on the overloaded counterpart of them taking a class type as the second argument (implicit cast)

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Resolved
    • Minor
    • Resolution: Fixed
    • 2.9.0
    • 2.9.0
    • None
    • None
    • Unknown

    Description

      Some simple change examples on the trunk are:

      From:

      jpaTemplate = (JpaTemplate)applicationContext.getBean("jpaTemplate");
      

      To:

      jpaTemplate = applicationContext.getBean("jpaTemplate", JpaTemplate.class);
      

      Or

      From:

      HttpEndpoint epOut = (HttpEndpoint) getContext().getEndpoint("http://localhost:" + port1 + "?bridgeEndpoint=true&throwExceptionOnFailure=false");
      

      To:

      HttpEndpoint epOut = getContext().getEndpoint("http://localhost:" + port1 + "?bridgeEndpoint=true&throwExceptionOnFailure=false", HttpEndpoint.class);
      

      Here another one with the removal of @SuppressWarnings as a side effect:

      From:

          @SuppressWarnings("unchecked")
          public <T> T lookup(Class<T> type) {
              ApplicationContext context = getApplicationContext();
              String[] names = context.getBeanNamesForType(type, true, true);
              if (names != null) {
                  int count = names.length;
                  if (count == 1) {
                      // lets instantiate the single bean
                      return (T)context.getBean(names[0]);
                  } else if (count > 1) {
                      throw new IllegalArgumentException("Too many beans in the application context of type: " + type + ". Found: " + count);
                  }
              }
              throw new IllegalArgumentException("No bean available in the application context of type: " + type);
          }
      

      To:

          public <T> T lookup(Class<T> type) {
              ApplicationContext context = getApplicationContext();
              String[] names = context.getBeanNamesForType(type, true, true);
              if (names != null) {
                  int count = names.length;
                  if (count == 1) {
                      // lets instantiate the single bean
                      return context.getBean(names[0], type);
                  } else if (count > 1) {
                      throw new IllegalArgumentException("Too many beans in the application context of type: " + type + ". Found: " + count);
                  }
              }
              throw new IllegalArgumentException("No bean available in the application context of type: " + type);
          }
      

      There're also cases where we could make a huge benefit of this so that the following code:

          public <T> T getMandatoryBean(Class<T> type, String name) {
              Object value = applicationContext.getBean(name);
              assertNotNull("No spring bean found for name <" + name + ">", value);
              if (type.isInstance(value)) {
                  return type.cast(value);
              } else {
                  fail("Spring bean <" + name + "> is not an instanceof " + type.getName() + " but is of type " + ObjectHelper.className(value));
                  return null;
              }
          }
      

      became just a one liner as:

          public <T> T getMandatoryBean(Class<T> type, String name) {
              return applicationContext.getBean(name, type);
          }
      

      I also came across the cases where the prefered API indeed was used but there were unneccessary casts around it:
      From:

      // must type cast to work with Spring 2.5.x
      SpringCamelContext context = (SpringCamelContext) applicationContext.getBeansOfType(SpringCamelContext.class).values().iterator().next();
      

      To:

      SpringCamelContext context = applicationContext.getBeansOfType(SpringCamelContext.class).values().iterator().next();
      

      Another benefit of this patch is a better test code coverage, because as one would intuitively expect DefaultCamelContext.getEndpoint(String name, Class<T> endpointType) makes use of DefaultCamelContext.getEndpoint(String uri) before casting and returning the answer. So that now through the usage of the first method API (expecting two parameters) we do call both of them while testing (one explicitly and the other one implicitly)

      There're 147 sources affected by the provided patch (one source change is just because of an already pre-existing checkstyle violation by HtmlToPdfMojo.java on the trunk).

      I did verify only the tests on camel-core but not the rest with the following test result (Windows-Vista):

      Results :

      Failed tests:
      testConcurrentAppend(org.apache.camel.component.file.FileConcurrentWriteAppendSameFileTest): mock://result Received message count. Expected: <5000> but was: <2655>

      Tests run: 3969, Failures: 1, Errors: 0, Skipped: 0

      [INFO] ------------------------------------------------------------------------
      [INFO] BUILD FAILURE
      [INFO] ------------------------------------------------------------------------
      [INFO] Total time: 25:49.095s
      [INFO] Finished at: Sun Dec 11 00:45:35 CET 2011
      [INFO] Final Memory: 20M/494M
      [INFO] ------------------------------------------------------------------------
      [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.8:test (default-test) on project camel-core: There are test failures.

      Attachments

        1. CAMEL-4765.patch
          182 kB
          Babak Vahdat

        Activity

          People

            bvahdat Babak Vahdat
            bvahdat Babak Vahdat
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: