예제 #1
0
 public List<Map<String, String>> findShortcuts(Long[] actorIds, Long[] resourceIds) {
   StringBuffer hql = new StringBuffer();
   hql.append("select s.aid,s.sid,s.id,s.standalone,s.name,s.url,s.iconclass,s.order_");
   hql.append(" from bc_desktop_shortcut s");
   hql.append(" where s.aid in (?");
   List<Object> args = new ArrayList<Object>();
   args.add(new Long(0));
   if (actorIds != null) {
     for (Long id : actorIds) {
       hql.append(",?");
       args.add(id);
     }
   }
   hql.append(") and s.sid in (?");
   args.add(new Long(0));
   if (resourceIds != null) {
     for (Long id : resourceIds) {
       hql.append(",?");
       args.add(id);
     }
   }
   hql.append(") order by s.order_");
   if (logger.isDebugEnabled()) {
     logger.debug("actorIds=" + StringUtils.arrayToCommaDelimitedString(actorIds));
     logger.debug("resourceIds=" + StringUtils.arrayToCommaDelimitedString(resourceIds));
     logger.debug("hql=" + hql);
   }
   return HibernateJpaNativeQuery.executeNativeSql(
       jpaTemplate,
       hql.toString(),
       args.toArray(),
       new RowMapper<Map<String, String>>() {
         public Map<String, String> mapRow(Object[] rs, int rowNum) {
           Map<String, String> s = new HashMap<String, String>();
           int i = 0;
           s.put("aid", rs[i] != null ? rs[i].toString() : null);
           i++;
           s.put("sid", rs[i] != null ? rs[i].toString() : null);
           i++;
           s.put("id", rs[i++].toString());
           s.put("standalone", rs[i++].toString());
           s.put("name", rs[i] != null ? rs[i].toString() : null);
           i++;
           s.put("url", rs[i] != null ? rs[i].toString() : null);
           i++;
           s.put("iconClass", rs[i] != null ? rs[i].toString() : null);
           i++;
           s.put("orderNo", rs[i] != null ? rs[i].toString() : null);
           return s;
         }
       });
 }
예제 #2
0
 private void customizeCompression(Connector connector) {
   ProtocolHandler handler = connector.getProtocolHandler();
   if (handler instanceof AbstractHttp11Protocol) {
     AbstractHttp11Protocol<?> protocol = (AbstractHttp11Protocol<?>) handler;
     Compression compression = getCompression();
     protocol.setCompression("on");
     protocol.setCompressionMinSize(compression.getMinResponseSize());
     protocol.setCompressableMimeTypes(
         StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes()));
     if (getCompression().getExcludedUserAgents() != null) {
       protocol.setNoCompressionUserAgents(
           StringUtils.arrayToCommaDelimitedString(getCompression().getExcludedUserAgents()));
     }
   }
 }
 private static String getMessage(
     EmbeddedDatabaseConnection connection, Environment environment, String property) {
   StringBuilder message = new StringBuilder();
   message.append(
       "Cannot determine embedded database "
           + property
           + " for database type "
           + connection
           + ". ");
   message.append(
       "If you want an embedded database please put a supported " + "one on the classpath. ");
   message.append(
       "If you have database settings to be loaded from a "
           + "particular profile you may need to active it");
   if (environment != null) {
     String[] profiles = environment.getActiveProfiles();
     if (ObjectUtils.isEmpty(profiles)) {
       message.append(" (no profiles are currently active)");
     } else {
       message.append(
           " (the profiles \""
               + StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles())
               + "\" are currently active)");
     }
   }
   message.append(".");
   return message.toString();
 }
예제 #4
0
  /**
   * Returns an html page valid for printing
   *
   * <p>
   *
   * @param obj instance to print.
   * @return html text strem
   * @throws ObjectNotFoundException If specified object could not be found.
   * @throws SendFailedException
   */
  @PreAuthorize("hasRole('ROLE_PERSON_READ') or hasRole('ROLE_PERSON_MAP_READ')")
  @RequestMapping(value = "/emailCurrent", method = RequestMethod.POST)
  public @ResponseBody String email(
      final HttpServletResponse response,
      final @PathVariable UUID personId,
      @RequestBody final PlanOutputTO planOutputDataTO)
      throws ObjectNotFoundException {

    Plan currentPlan = service.getCurrentForStudent(personId);
    PlanTO planTO = getFactory().from(currentPlan);
    planOutputDataTO.setPlan(planTO);

    SubjectAndBody messageText = service.createOutput(planOutputDataTO);
    if (messageText == null) return null;
    Person person = personService.get(UUID.fromString(planOutputDataTO.getPlan().getPersonId()));
    Set<String> watcherAddresses = new HashSet<String>(person.getWatcherEmailAddresses());
    watcherAddresses.addAll(
        org.springframework.util.StringUtils.commaDelimitedListToSet(
            planOutputDataTO.getEmailCC()));

    messageService.createMessage(
        planOutputDataTO.getEmailTo(),
        org.springframework.util.StringUtils.arrayToCommaDelimitedString(
            watcherAddresses.toArray(new String[watcherAddresses.size()])),
        messageText);

    return "Map Plan has been queued.";
  }
예제 #5
0
  private List<Map<String, String>> findActorMasters(Long[] followerIds) {
    if (followerIds == null || followerIds.length == 0) return null;

    StringBuffer hql = new StringBuffer();
    hql.append("select distinct ar.follower_id as fid,ar.master_id as id,m.type_ as type");
    hql.append(
        ",m.code as code,m.name as name,m.pcode as pcode,m.pname as pname,m.order_ as orderNo");
    hql.append(" from BC_IDENTITY_ACTOR_RELATION as ar");
    hql.append(" inner join BC_IDENTITY_ACTOR as m on m.id = ar.master_id");
    hql.append(" where ar.type_=0");
    hql.append(" and ar.follower_id");
    if (logger.isDebugEnabled()) {
      logger.debug("findActorMasters.hql=" + hql);
      logger.debug("findActorMasters.args=" + StringUtils.arrayToCommaDelimitedString(followerIds));
    }
    if (followerIds.length == 1) {
      hql.append(" = ?");
    } else {
      hql.append(" in (?");
      for (int i = 1; i < followerIds.length; i++) {
        hql.append(",?");
      }
      hql.append(")");
    }
    hql.append(" order by m.order_");
    return HibernateJpaNativeQuery.executeNativeSql(
        jpaTemplate, hql.toString(), followerIds, new Follower2MasterMapper());
  }
 @Test
 public void yamlSetsProfiles() throws Exception {
   this.initializer.setSearchNames("testsetprofiles");
   this.initializer.postProcessEnvironment(this.environment, this.application);
   assertEquals(
       "dev", StringUtils.arrayToCommaDelimitedString(this.environment.getActiveProfiles()));
   String property = this.environment.getProperty("my.property");
   assertThat(Arrays.asList(this.environment.getActiveProfiles()), contains("dev"));
   assertThat(property, equalTo("fromdevprofile"));
   ConfigurationPropertySources propertySource =
       (ConfigurationPropertySources)
           this.environment.getPropertySources().get("applicationConfigurationProperties");
   Collection<org.springframework.core.env.PropertySource<?>> sources = propertySource.getSource();
   assertEquals(2, sources.size());
   List<String> names = new ArrayList<String>();
   for (org.springframework.core.env.PropertySource<?> source : sources) {
     if (source instanceof EnumerableCompositePropertySource) {
       for (org.springframework.core.env.PropertySource<?> nested :
           ((EnumerableCompositePropertySource) source).getSource()) {
         names.add(nested.getName());
       }
     } else {
       names.add(source.getName());
     }
   }
   assertThat(
       names,
       contains(
           "applicationConfig: [classpath:/testsetprofiles.yml]#dev",
           "applicationConfig: [classpath:/testsetprofiles.yml]"));
 }
예제 #7
0
 /**
  * Append Http headers to string builder.
  *
  * @param headers
  * @param builder
  */
 private void appendHeaders(HttpHeaders headers, StringBuilder builder) {
   for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
     builder.append(headerEntry.getKey());
     builder.append(":");
     builder.append(StringUtils.arrayToCommaDelimitedString(headerEntry.getValue().toArray()));
     builder.append(NEWLINE);
   }
 }
 /**
  * Load a Spring ApplicationContext from the given config locations.
  *
  * <p>The default implementation creates a standard {@link #createApplicationContext
  * GenericApplicationContext}, allowing for customizing the internal bean factory through {@link
  * #customizeBeanFactory}.
  *
  * @param locations the config locations (as Spring resource locations, e.g. full classpath
  *     locations or any kind of URL)
  * @return the corresponding ApplicationContext instance (potentially cached)
  * @throws Exception if context loading failed
  * @see #createApplicationContext(String[])
  */
 @Override
 protected ConfigurableApplicationContext loadContext(String... locations) throws Exception {
   if (this.logger.isInfoEnabled()) {
     this.logger.info(
         "Loading context for locations: " + StringUtils.arrayToCommaDelimitedString(locations));
   }
   return createApplicationContext(locations);
 }
예제 #9
0
 /**
  * Register fields that are required for each binding process.
  *
  * <p>If one of the specified fields is not contained in the list of incoming property values, a
  * corresponding "missing field" error will be created, with error code "required" (by the default
  * binding error processor).
  *
  * @param requiredFields array of field names
  * @see #setBindingErrorProcessor
  * @see DefaultBindingErrorProcessor#MISSING_FIELD_ERROR_CODE
  */
 public void setRequiredFields(String... requiredFields) {
   this.requiredFields = PropertyAccessorUtils.canonicalPropertyNames(requiredFields);
   if (logger.isDebugEnabled()) {
     logger.debug(
         "DataBinder requires binding of required fields ["
             + StringUtils.arrayToCommaDelimitedString(requiredFields)
             + "]");
   }
 }
 protected void handleWebSocketVersionNotSupported(
     ServerHttpRequest request, ServerHttpResponse response) {
   logger.debug(
       "WebSocket version not supported " + request.getHeaders().get("Sec-WebSocket-Version"));
   response.setStatusCode(HttpStatus.UPGRADE_REQUIRED);
   response
       .getHeaders()
       .setSecWebSocketVersion(StringUtils.arrayToCommaDelimitedString(getSupportedVerions()));
 }
  /**
   * Convert the value to the required type (if necessary from a String), using the given property
   * editor.
   *
   * @param oldValue the previous value, if available (may be {@code null})
   * @param newValue the proposed new value
   * @param requiredType the type we must convert to (or {@code null} if not known, for example in
   *     case of a collection element)
   * @param editor the PropertyEditor to use
   * @return the new value, possibly the result of type conversion
   * @throws IllegalArgumentException if type conversion failed
   */
  private Object doConvertValue(
      Object oldValue, Object newValue, Class<?> requiredType, PropertyEditor editor) {
    Object convertedValue = newValue;

    if (editor != null && !(convertedValue instanceof String)) {
      // Not a String -> use PropertyEditor's setValue.
      // With standard PropertyEditors, this will return the very same object;
      // we just want to allow special PropertyEditors to override setValue
      // for type conversion from non-String values to the required type.
      try {
        editor.setValue(convertedValue);
        Object newConvertedValue = editor.getValue();
        if (newConvertedValue != convertedValue) {
          convertedValue = newConvertedValue;
          // Reset PropertyEditor: It already did a proper conversion.
          // Don't use it again for a setAsText call.
          editor = null;
        }
      } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call",
              ex);
        }
        // Swallow and proceed.
      }
    }

    Object returnValue = convertedValue;

    if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
      // Convert String array to a comma-separated String.
      // Only applies if no PropertyEditor converted the String array before.
      // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
      if (logger.isTraceEnabled()) {
        logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]");
      }
      convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
    }

    if (convertedValue instanceof String) {
      if (editor != null) {
        // Use PropertyEditor's setAsText in case of a String value.
        if (logger.isTraceEnabled()) {
          logger.trace(
              "Converting String to [" + requiredType + "] using property editor [" + editor + "]");
        }
        String newTextValue = (String) convertedValue;
        return doConvertTextValue(oldValue, newTextValue, editor);
      } else if (String.class == requiredType) {
        returnValue = convertedValue;
      }
    }

    return returnValue;
  }
예제 #12
0
 /**
  * Configure Tomcat's {@link AbstractHttp11JsseProtocol} for SSL.
  *
  * @param protocol the protocol
  * @param ssl the ssl details
  */
 protected void configureSsl(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) {
   protocol.setSSLEnabled(true);
   protocol.setSslProtocol(ssl.getProtocol());
   configureSslClientAuth(protocol, ssl);
   protocol.setKeystorePass(ssl.getKeyStorePassword());
   protocol.setKeyPass(ssl.getKeyPassword());
   protocol.setKeyAlias(ssl.getKeyAlias());
   protocol.setCiphers(StringUtils.arrayToCommaDelimitedString(ssl.getCiphers()));
   if (ssl.getEnabledProtocols() != null) {
     protocol.setProperty(
         "sslEnabledProtocols",
         StringUtils.arrayToCommaDelimitedString(ssl.getEnabledProtocols()));
   }
   if (getSslStoreProvider() != null) {
     configureSslStoreProvider(protocol, getSslStoreProvider());
   } else {
     configureSslKeyStore(protocol, ssl);
     configureSslTrustStore(protocol, ssl);
   }
 }
예제 #13
0
 public Cookie toCookie() {
   Cookie c =
       new Cookie(
           AUTH_COOKIE_NAME,
           StringUtils.arrayToCommaDelimitedString(
               new Object[] {
                 username, sessionId, new SimpleDateFormat(EXPIRY_FORMAT).format(expiry)
               }));
   c.setHttpOnly(true);
   c.setMaxAge(-1);
   return c;
 }
 private String getApplicationId(ConfigurableEnvironment environment) {
   String name = environment.resolvePlaceholders(this.name);
   String index = environment.resolvePlaceholders(INDEX_PATTERN);
   String profiles = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
   if (StringUtils.hasText(profiles)) {
     name = name + ":" + profiles;
   }
   if (!"null".equals(index)) {
     name = name + ":" + index;
   }
   return name;
 }
 @Test
 public void loadTwoPropertiesFilesWithProfiles() throws Exception {
   EnvironmentTestUtils.addEnvironment(
       this.environment,
       "spring.config.location:"
           + "classpath:enableprofile.properties,classpath:enableother.properties");
   this.initializer.postProcessEnvironment(this.environment, this.application);
   assertEquals(
       "other", StringUtils.arrayToCommaDelimitedString(this.environment.getActiveProfiles()));
   String property = this.environment.getProperty("my.property");
   assertThat(property, equalTo("fromotherpropertiesfile"));
 }
예제 #16
0
 private static void invokeCopy(Configuration config, String[] parsedArgs) {
   try {
     log.info(
         "Running DistCp with arguments ["
             + StringUtils.arrayToCommaDelimitedString(parsedArgs)
             + "]");
     DistCpOptions inputOptions = OptionsParser.parse(parsedArgs);
     org.apache.hadoop.tools.DistCp distCp =
         new org.apache.hadoop.tools.DistCp(config, inputOptions);
     distCp.execute();
   } catch (Exception e) {
     throw new HadoopException("Error running DistCp job", e);
   }
 }
 @Test
 public void loadTwoPropertiesFilesWithProfilesAndSwitchOneOffFromSpecificLocation()
     throws Exception {
   EnvironmentTestUtils.addEnvironment(
       this.environment,
       "spring.config.name:enabletwoprofiles",
       "spring.config.location:classpath:enableprofile.properties");
   this.initializer.postProcessEnvironment(this.environment, this.application);
   assertEquals(
       "myprofile", StringUtils.arrayToCommaDelimitedString(this.environment.getActiveProfiles()));
   String property = this.environment.getProperty("the.property");
   // The value from the second file wins (no profile specific configuration is
   // actually loaded)
   assertThat(property, equalTo("frompropertiesfile"));
 }
예제 #18
0
  public MultiValueMap<String, Object> toRequestParameters() {
    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    if (message != null) {
      parameters.add("message", message);
    }
    if (linkUrl != null) {
      parameters.add("link", linkUrl);
    }
    if (name != null) {
      parameters.add("name", name);
    }
    if (caption != null) {
      parameters.add("caption", caption);
    }
    if (description != null) {
      parameters.add("description", description);
    }
    if (picture != null) {
      parameters.add("picture", picture);
    }
    if (placeId != null) {
      parameters.add("place", placeId);
      // tags are only allowed if a place is given
      if (tags != null) {
        parameters.add("tags", StringUtils.arrayToCommaDelimitedString(tags));
      }
    }
    if (privacy != null) {
      StringBuffer privacyBuffer = new StringBuffer();
      privacyBuffer.append("{'value': '").append(privacy.toString()).append("'");
      if (privacy == Privacy.CUSTOM) {
        if (allow == null && deny == null) {
          throw new IllegalArgumentException(
              "At least one of 'deny' or 'allow' must be specified when privacy is CUSTOM.");
        }
        if (allow != null) {
          privacyBuffer.append(",'allow': '").append(join(allow)).append("'");
        }
        if (deny != null) {
          privacyBuffer.append(",'deny': '").append(join(deny)).append("'");
        }
      }
      privacyBuffer.append("}");
      parameters.add("privacy", privacyBuffer.toString());
    }

    return parameters;
  }
 public ApplicationContext loadContext(String... locations) throws Exception {
   if (logger.isDebugEnabled()) {
     logger.debug(
         "Loading ApplicationContext for locations ["
             + StringUtils.arrayToCommaDelimitedString(locations)
             + "].");
   }
   GenericWebApplicationContext context = new GenericWebApplicationContext();
   prepareContext(context);
   customizeBeanFactory(context.getDefaultListableBeanFactory());
   createBeanDefinitionReader(context).loadBeanDefinitions(locations);
   AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
   customizeContext(context);
   context.refresh();
   context.registerShutdownHook();
   return context;
 }
예제 #20
0
  /**
   * Example URL: http://localhost:8080/webstore/products/add
   *
   * <p>Called when a POST is requested
   *
   * @param newProduct
   * @return
   */
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String processAddNewProductForm(
      @ModelAttribute("newProduct") @Valid Product newProduct,
      BindingResult result,
      HttpServletRequest request) {
    if (result.hasErrors()) {
      return "addProduct";
    }

    String[] suppressedFields = result.getSuppressedFields();
    if (suppressedFields.length > 0) {
      throw new RuntimeException(
          "Attempting to bind disallowed fields: "
              + StringUtils.arrayToCommaDelimitedString(suppressedFields));
    }

    MultipartFile productImage = newProduct.getProductImage();
    MultipartFile productManual = newProduct.getProductManual();

    String rootDirectory = request.getSession().getServletContext().getRealPath("/");

    if (productImage != null && !productImage.isEmpty()) {
      try {
        productImage.transferTo(
            new File(rootDirectory + "resources\\images\\" + newProduct.getProductId() + ".jpg"));
      } catch (Exception e) {
        throw new RuntimeException("Product Image saving failed", e);
      }
    }

    if (productManual != null && !productManual.isEmpty()) {
      try {
        productManual.transferTo(
            new File(rootDirectory + "resources\\pdf\\" + newProduct.getProductId() + ".pdf"));
      } catch (Exception e) {
        throw new RuntimeException("Product Manual saving failed", e);
      }
    }

    productService.addProduct(newProduct);
    return "redirect:/products";
  }
예제 #21
0
  /**
   * {@inheritDoc}
   *
   * @see uk.co.utilisoft.parms.web.util.ResponseMessageLoaderInterface#appendResponseMessageData(
   *     javax.servlet.http.HttpServletRequest, java.lang.String[])
   */
  @Override
  public Map<String, String> appendResponseMessageData(
      HttpServletRequest aRequest, String... aResponseMessageKeys) {
    Map<String, String> responseMessageData = new HashMap<String, String>();
    for (String key : aResponseMessageKeys) {
      Object value = aRequest.getSession().getAttribute(key);
      if (value != null) {
        String[] arguments =
            value.getClass().isArray()
                    && value.getClass().getComponentType().equals(String.class)
                    && ((String[]) value).length > 0
                ? ((String[]) value)
                : new String[] {};

        responseMessageData.put(key, StringUtils.arrayToCommaDelimitedString(arguments));
        WebUtils.setSessionAttribute(aRequest, key, null); // remove attribute from session
      }
    }
    return responseMessageData;
  }
예제 #22
0
  public List<Map<String, String>> findActorRoles(Long[] actorIds) {
    if (actorIds == null || actorIds.length == 0) return new ArrayList<Map<String, String>>();

    StringBuffer hql = new StringBuffer();
    hql.append(
        "select distinct r.id as id,r.code as code,r.name as name,r.order_ as orderNo from BC_IDENTITY_ROLE as r");
    hql.append(" inner join BC_IDENTITY_ROLE_ACTOR as ra on ra.rid=r.id");
    hql.append(" where r.status_ = 0 and ra.aid");
    if (actorIds.length == 1) {
      hql.append(" = ?");
    } else {
      hql.append(" in (?");
      for (int i = 1; i < actorIds.length; i++) {
        hql.append(",?");
      }
      hql.append(")");
    }
    hql.append(" order by r.order_");
    if (logger.isDebugEnabled()) {
      logger.debug("actorIds=" + StringUtils.arrayToCommaDelimitedString(actorIds));
      logger.debug("hql=" + hql);
    }
    return HibernateJpaNativeQuery.executeNativeSql(
        jpaTemplate,
        hql.toString(),
        actorIds,
        new RowMapper<Map<String, String>>() {
          public Map<String, String> mapRow(Object[] rs, int rowNum) {
            Map<String, String> role = new HashMap<String, String>();
            int i = 0;
            role.put("id", rs[i++].toString());
            role.put("code", rs[i++].toString());
            return role;
          }
        });
  }
  protected void doProcessConfigurationClass(
      ConfigurationClass configClass, AnnotationMetadata metadata) throws IOException {

    // recursively process any member (nested) classes first
    for (String memberClassName : metadata.getMemberClassNames()) {
      MetadataReader reader = this.metadataReaderFactory.getMetadataReader(memberClassName);
      AnnotationMetadata memberClassMetadata = reader.getAnnotationMetadata();
      if (isConfigurationCandidate(memberClassMetadata)) {
        processConfigurationClass(new ConfigurationClass(reader, null));
      }
    }

    // process any @PropertySource annotations
    Map<String, Object> propertySourceAttributes =
        metadata.getAnnotationAttributes(
            org.springframework.context.annotation.PropertySource.class.getName());
    if (propertySourceAttributes != null) {
      String name = (String) propertySourceAttributes.get("name");
      String[] locations = (String[]) propertySourceAttributes.get("value");
      ClassLoader classLoader = this.resourceLoader.getClassLoader();
      for (String location : locations) {
        location = this.environment.resolveRequiredPlaceholders(location);
        ResourcePropertySource ps =
            StringUtils.hasText(name)
                ? new ResourcePropertySource(name, location, classLoader)
                : new ResourcePropertySource(location, classLoader);
        this.propertySources.push(ps);
      }
    }

    // process any @ComponentScan annotions
    Map<String, Object> componentScanAttributes =
        metadata.getAnnotationAttributes(ComponentScan.class.getName());
    if (componentScanAttributes != null) {
      // the config class is annotated with @ComponentScan -> perform the scan immediately
      Set<BeanDefinitionHolder> scannedBeanDefinitions =
          this.componentScanParser.parse(componentScanAttributes);

      // check the set of scanned definitions for any further config classes and parse recursively
      // if necessary
      for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
        if (ConfigurationClassUtils.checkConfigurationClassCandidate(
            holder.getBeanDefinition(), metadataReaderFactory)) {
          try {
            this.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
          } catch (ConflictingBeanDefinitionException ex) {
            throw new CircularComponentScanException(
                "A conflicting bean definition was detected while processing @ComponentScan annotations. "
                    + "This usually indicates a circle between scanned packages.",
                ex);
          }
        }
      }
    }

    // process any @Import annotations
    List<Map<String, Object>> allImportAttribs =
        AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
    for (Map<String, Object> importAttribs : allImportAttribs) {
      processImport(configClass, (String[]) importAttribs.get("value"), true);
    }

    // process any @ImportResource annotations
    if (metadata.isAnnotated(ImportResource.class.getName())) {
      String[] resources =
          (String[]) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("value");
      Class<?> readerClass =
          (Class<?>) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("reader");
      if (readerClass == null) {
        throw new IllegalStateException(
            "No reader class associated with imported resources: "
                + StringUtils.arrayToCommaDelimitedString(resources));
      }
      for (String resource : resources) {
        configClass.addImportedResource(resource, readerClass);
      }
    }

    // process individual @Bean methods
    Set<MethodMetadata> beanMethods = metadata.getAnnotatedMethods(Bean.class.getName());
    for (MethodMetadata methodMetadata : beanMethods) {
      configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
    }
  }
  /**
   * Convert the value to the required type (if necessary from a String), for the specified
   * property.
   *
   * @param propertyName name of the property
   * @param oldValue previous value, if available (may be <code>null</code>)
   * @param newValue proposed change value
   * @param requiredType the type we must convert to (or <code>null</code> if not known, for example
   *     in case of a collection element)
   * @return the new value, possibly the result of type conversion
   * @throws TypeMismatchException if type conversion failed
   */
  protected Object doTypeConversionIfNecessary(
      String propertyName,
      String fullPropertyName,
      Object oldValue,
      Object newValue,
      Class requiredType)
      throws TypeMismatchException {

    Object convertedValue = newValue;
    if (convertedValue != null) {

      // Custom editor for this type?
      PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName);

      // Value not of required type?
      if (pe != null
          || (requiredType != null
              && (requiredType.isArray()
                  || !requiredType.isAssignableFrom(convertedValue.getClass())))) {

        if (requiredType != null) {
          if (pe == null) {
            // No custom editor -> check BeanWrapperImpl's default editors.
            pe = (PropertyEditor) getDefaultEditor(requiredType);
            if (pe == null) {
              // No BeanWrapper default editor -> check standard JavaBean editors.
              pe = PropertyEditorManager.findEditor(requiredType);
            }
          }
        }

        if (pe != null && !(convertedValue instanceof String)) {
          // Not a String -> use PropertyEditor's setValue.
          // With standard PropertyEditors, this will return the very same object;
          // we just want to allow special PropertyEditors to override setValue
          // for type conversion from non-String values to the required type.
          try {
            pe.setValue(convertedValue);
            Object newConvertedValue = pe.getValue();
            if (newConvertedValue != convertedValue) {
              convertedValue = newConvertedValue;
              // Reset PropertyEditor: It already did a proper conversion.
              // Don't use it again for a setAsText call.
              pe = null;
            }
          } catch (IllegalArgumentException ex) {
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
          }
        }

        if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) {
          // Convert String array to a comma-separated String.
          // Only applies if no PropertyEditor converted the String array before.
          // The CSV String will be passed into a PropertyEditor's setAsText method, if any.
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Converting String array to comma-delimited String [" + convertedValue + "]");
          }
          convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
        }

        if (pe != null && convertedValue instanceof String) {
          // Use PropertyEditor's setAsText in case of a String value.
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Converting String to [" + requiredType + "] using property editor [" + pe + "]");
          }
          try {
            pe.setValue(oldValue);
            pe.setAsText((String) convertedValue);
            convertedValue = pe.getValue();
          } catch (IllegalArgumentException ex) {
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex);
          }
        }

        if (requiredType != null) {
          // Array required -> apply appropriate conversion of elements.
          if (requiredType.isArray()) {
            Class componentType = requiredType.getComponentType();
            if (convertedValue instanceof Collection) {
              // Convert Collection elements to array elements.
              Collection coll = (Collection) convertedValue;
              Object result = Array.newInstance(componentType, coll.size());
              int i = 0;
              for (Iterator it = coll.iterator(); it.hasNext(); i++) {
                Object value =
                    doTypeConversionIfNecessary(
                        propertyName,
                        propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX,
                        null,
                        it.next(),
                        componentType);
                Array.set(result, i, value);
              }
              return result;
            } else if (convertedValue != null && convertedValue.getClass().isArray()) {
              // Convert Collection elements to array elements.
              int arrayLength = Array.getLength(convertedValue);
              Object result = Array.newInstance(componentType, arrayLength);
              for (int i = 0; i < arrayLength; i++) {
                Object value =
                    doTypeConversionIfNecessary(
                        propertyName,
                        propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX,
                        null,
                        Array.get(convertedValue, i),
                        componentType);
                Array.set(result, i, value);
              }
              return result;
            } else {
              // A plain value: convert it to an array with a single component.
              Object result = Array.newInstance(componentType, 1);
              Object value =
                  doTypeConversionIfNecessary(
                      propertyName,
                      propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX,
                      null,
                      convertedValue,
                      componentType);
              Array.set(result, 0, value);
              return result;
            }
          }

          // If the resulting value definitely doesn't match the required type,
          // try field lookup as fallback. If no matching field found,
          // throw explicit TypeMismatchException with full context information.
          if (convertedValue != null
              && !requiredType.isPrimitive()
              && !requiredType.isAssignableFrom(convertedValue.getClass())) {

            // In case of String value, try to find matching field (for JDK 1.5
            // enum or custom enum with values defined as static fields).
            if (convertedValue instanceof String) {
              try {
                Field enumField = requiredType.getField((String) convertedValue);
                return enumField.get(null);
              } catch (Exception ex) {
                logger.debug("Field [" + convertedValue + "] isn't an enum value", ex);
              }
            }

            // Definitely doesn't match: throw TypeMismatchException.
            throw new TypeMismatchException(
                createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType);
          }
        }
      }
    }

    return convertedValue;
  }
 /** Show the configuration of this MessageSource. */
 public String toString() {
   return getClass().getName()
       + " with basenames ["
       + StringUtils.arrayToCommaDelimitedString(this.basenames)
       + "]";
 }
 public void setHeartbeat(long cx, long cy) {
   setNativeHeader(
       STOMP_HEARTBEAT_HEADER, StringUtils.arrayToCommaDelimitedString(new Object[] {cx, cy}));
 }
예제 #27
0
  public Set<Resource> findResources(Long[] roleIds) {
    if (roleIds == null || roleIds.length == 0) return new HashSet<Resource>();

    StringBuffer hql = new StringBuffer();
    hql.append(
        "select distinct s.belong,s.id,s.type_,s.name,s.url,s.iconclass,s.order_,s.pname,s.option_");
    hql.append(" from bc_identity_resource s");
    hql.append(" inner join bc_identity_role_resource rs on rs.sid=s.id");
    hql.append(" where rs.rid");
    if (roleIds.length == 1) {
      hql.append(" = ?");
    } else {
      hql.append(" in (?");
      for (int i = 1; i < roleIds.length; i++) {
        hql.append(",?");
      }
      hql.append(")");
    }
    hql.append(" order by s.order_");
    if (logger.isDebugEnabled()) {
      logger.debug("roleIds=" + StringUtils.arrayToCommaDelimitedString(roleIds));
      logger.debug("hql=" + hql);
    }
    List<Long> sIds =
        HibernateJpaNativeQuery.executeNativeSql(
            jpaTemplate,
            hql.toString(),
            roleIds,
            new RowMapper<Long>() {
              public Long mapRow(Object[] rs, int rowNum) {
                // Map<String, String> s = new HashMap<String,
                // String>();
                // int i = 0;
                // s.put("pid", rs[i] != null ? rs[i].toString() :
                // null);
                // i++;
                // s.put("id", rs[i++].toString());
                // s.put("type", rs[i++].toString());
                // s.put("name", rs[i] != null ? rs[i].toString() :
                // null);
                // i++;
                // s.put("url", rs[i] != null ? rs[i].toString() :
                // null);
                // i++;
                // s.put("iconClass", rs[i] != null ? rs[i].toString()
                // : null);
                // i++;
                // s.put("orderNo", rs[i] != null ? rs[i].toString()
                // : null);
                // i++;
                // s.put("pname", rs[i] != null ? rs[i].toString() :
                // null);
                // i++;
                // s.put("option", rs[i] != null ? rs[i].toString() :
                // null);
                return new Long(rs[1].toString());
              }
            });

    Set<Resource> ss = new HashSet<Resource>();
    Map<Long, Resource> allResources = this.resourceService.findAll();
    for (Long sid : sIds) {
      if (allResources.containsKey(sid)) ss.add(allResources.get(sid));
    }

    return ss;
  }