List of usage examples for org.springframework.util StringUtils arrayToCommaDelimitedString
public static String arrayToCommaDelimitedString(@Nullable Object[] arr)
From source file:org.hyperic.hq.context.IntegrationTestContextLoader.java
public ApplicationContext loadContext(final String... locations) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Loading ApplicationContext for locations [" + StringUtils.arrayToCommaDelimitedString(locations) + "]."); } //EO if logger is enabled final GenericApplicationContext context = new ProxyingGenericApplicationContext(); //verify sigar's resources existence & load native libraries configureSigar(context, logger);//from w w w .j av a 2 s .com //clean previous application context (if exists) and create a new one Bootstrap.setAppContext(context); try { //initialize the application context delegateLoader.createBeanDefinitionReader(context).loadBeanDefinitions(locations); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); context.registerShutdownHook(); return context; } catch (Throwable t) { logger.error("An Error had occured during the applicationContext creation, disposing!"); Bootstrap.dispose(); throw (Exception) t; } //EO catch block }
From source file:org.jasig.ssp.service.impl.PersonEmailServiceImpl.java
@Override @Transactional/*from w w w .ja va 2 s. c o m*/ public void sendCoachingAssignmentChangeEmail(Person model, UUID oldCoachId) throws ObjectNotFoundException, SendFailedException, ValidationException { if (oldCoachId == null || model.getCoach() == null || !model.getCoach().hasEmailAddresses()) return; Person oldCoach = personService.get(oldCoachId); String appTitle = configService.getByNameEmpty("app_title"); String serverExternalPath = configService.getByNameEmpty("serverExternalPath"); String message = oldCoach.getFullName() + " has assigned " + model.getFullName() + " to your caseload in " + appTitle + ". Please visit " + serverExternalPath + " to view the student's information in " + appTitle + "."; String subject = "A coaching assignment has changed in " + appTitle; SubjectAndBody subjectAndBody = new SubjectAndBody(subject, message); if (oldCoach.hasEmailAddresses() && model.getWatcherEmailAddresses().isEmpty()) { messageService.createMessage(model.getCoach(), StringUtils.arrayToCommaDelimitedString( oldCoach.getEmailAddresses().toArray(new String[oldCoach.getEmailAddresses().size()])), subjectAndBody); } else if (oldCoach.hasEmailAddresses() && !model.getWatcherEmailAddresses().isEmpty()) { Set<String> emails = new HashSet<String>(); emails.addAll(oldCoach.getEmailAddresses()); emails.addAll(model.getWatcherEmailAddresses()); messageService.createMessage(model.getCoach(), StringUtils.arrayToCommaDelimitedString(emails.toArray(new String[emails.size()])), subjectAndBody); } else if (!oldCoach.hasEmailAddresses() && model.getWatcherEmailAddresses().isEmpty()) { messageService.createMessage(model.getCoach(), StringUtils.arrayToCommaDelimitedString( model.getWatcherEmailAddresses().toArray(new String[model.getWatcherEmailAddresses().size()])), subjectAndBody); } else { messageService.createMessage(model.getCoach(), "", subjectAndBody); } }
From source file:org.jasig.ssp.service.impl.PersonServiceImpl.java
@Override public void sendCoachingAssignmentChangeEmail(Person model, UUID oldCoachId) throws ObjectNotFoundException, SendFailedException, ValidationException { if (oldCoachId == null || model.getCoach() == null || !model.getCoach().hasEmailAddresses()) return;/*from w w w . j a v a 2 s . c o m*/ Person oldCoach = get(oldCoachId); String appTitle = configService.getByNameEmpty("app_title"); String serverExternalPath = configService.getByNameEmpty("serverExternalPath"); String message = oldCoach.getFullName() + " has assigned " + model.getFullName() + " to your caseload in " + appTitle + ". Please visit " + serverExternalPath + " to view the student's information in " + appTitle + "."; String subject = "A coaching assignment has changed in " + appTitle; SubjectAndBody subjectAndBody = new SubjectAndBody(subject, message); if (oldCoach.hasEmailAddresses()) { messageService.createMessage(model.getCoach(), StringUtils.arrayToCommaDelimitedString( oldCoach.getEmailAddresses().toArray(new String[oldCoach.getEmailAddresses().size()])), subjectAndBody); } else { messageService.createMessage(model.getCoach(), "", subjectAndBody); } }
From source file:org.kuali.student.enrollment.class1.krms.service.impl.CORuleEditorMaintainableImpl.java
@Override public Object retrieveObjectForEditOrCopy(MaintenanceDocument document, Map<String, String> dataObjectKeys) { CORuleManagementWrapper dataObject = new CORuleManagementWrapper(); dataObject.setNamespace(KSKRMSServiceConstants.NAMESPACE_CODE); dataObject.setRefDiscriminatorType(CourseOfferingServiceConstants.REF_OBJECT_URI_COURSE_OFFERING); String coId = dataObjectKeys.get("refObjectId"); dataObject.setRefObjectId(coId);// w w w. j av a 2 s .c o m //Retrieve the Clu information CourseOfferingInfo courseOffering = null; if (coId != null) { try { courseOffering = this.getCourseOfferingService().getCourseOffering(coId, ContextUtils.createDefaultContextInfo()); dataObject.setAgendas(this.getAgendasForRef(dataObject.getRefDiscriminatorType(), coId, courseOffering.getCourseId())); } catch (Exception e) { throw new RuntimeException("Could not retrieve course offering for " + coId, e); } } //Populate Clu Identification Information if (courseOffering != null) { List<String> orgIds = courseOffering.getUnitsDeploymentOrgIds(); if (orgIds != null && !orgIds.isEmpty()) { // managing multiple orgs String orgIdString = StringUtils.arrayToCommaDelimitedString(orgIds.toArray()); if (orgIdString.length() > 0) { dataObject.setAdminOrg(orgIdString); } } //Set the description and atp used on the screen. dataObject.setCluDescription(courseOffering.getCourseOfferingCode()); dataObject.setCourseOfferingTitle(courseOffering.getCourseOfferingTitle()); //Set the subjectArea for breadcrumb link dataObject.setCluSubjectCode(courseOffering.getSubjectArea()); dataObject.setCluTermCode(courseOffering.getTermId()); try { //Get the atp code. AtpInfo atp = this.getAtpService().getAtp(courseOffering.getTermId(), ContextUtils.createDefaultContextInfo()); //Set the term code for breadcrumb link dataObject.setCluTermCode(atp.getCode()); populateContextBar(dataObject, atp.getCode()); } catch (Exception e) { throw new RuntimeException("Could not populate context bar."); } } dataObject.setCompareTree(RuleCompareTreeBuilder.initCompareTree()); return dataObject; }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property.// ww w .ja v a 2s. com * @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) this.defaultEditors.get(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); } } } } if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod() .getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualType instanceof Class && convertedValue != null) { List list = (List) convertedValue; for (int i = 0; i < list.size(); i++) { Object o = list.remove(i); o = doTypeConversionIfNecessary(o, (Class) actualType); list.add(i, o); } } } } return convertedValue; }
From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptor.java
/** * Replace the placeholders in the given message with the supplied values, * or values derived from those supplied. * @param message the message template containing the placeholders to be replaced * @param methodInvocation the {@code MethodInvocation} being logged. * Used to derive values for all placeholders except {@code $[exception]} * and {@code $[returnValue]}./*from www .j ava2 s .co m*/ * @param returnValue any value returned by the invocation. * Used to replace the {@code $[returnValue]} placeholder. May be {@code null}. * @param throwable any {@code Throwable} raised during the invocation. * The value of {@code Throwable.toString()} is replaced for the * {@code $[exception]} placeholder. May be {@code null}. * @param invocationTime the value to write in place of the * {@code $[invocationTime]} placeholder * @return the formatted output to write to the log */ protected String replacePlaceholders(String message, MethodInvocation methodInvocation, @Nullable Object returnValue, @Nullable Throwable throwable, long invocationTime) { Matcher matcher = PATTERN.matcher(message); StringBuffer output = new StringBuffer(); while (matcher.find()) { String match = matcher.group(); if (PLACEHOLDER_METHOD_NAME.equals(match)) { matcher.appendReplacement(output, Matcher.quoteReplacement(methodInvocation.getMethod().getName())); } else if (PLACEHOLDER_TARGET_CLASS_NAME.equals(match)) { String className = getClassForLogging(methodInvocation.getThis()).getName(); matcher.appendReplacement(output, Matcher.quoteReplacement(className)); } else if (PLACEHOLDER_TARGET_CLASS_SHORT_NAME.equals(match)) { String shortName = ClassUtils.getShortName(getClassForLogging(methodInvocation.getThis())); matcher.appendReplacement(output, Matcher.quoteReplacement(shortName)); } else if (PLACEHOLDER_ARGUMENTS.equals(match)) { matcher.appendReplacement(output, Matcher.quoteReplacement( StringUtils.arrayToCommaDelimitedString(methodInvocation.getArguments()))); } else if (PLACEHOLDER_ARGUMENT_TYPES.equals(match)) { appendArgumentTypes(methodInvocation, matcher, output); } else if (PLACEHOLDER_RETURN_VALUE.equals(match)) { appendReturnValue(methodInvocation, matcher, output, returnValue); } else if (throwable != null && PLACEHOLDER_EXCEPTION.equals(match)) { matcher.appendReplacement(output, Matcher.quoteReplacement(throwable.toString())); } else if (PLACEHOLDER_INVOCATION_TIME.equals(match)) { matcher.appendReplacement(output, Long.toString(invocationTime)); } else { // Should not happen since placeholders are checked earlier. throw new IllegalArgumentException("Unknown placeholder [" + match + "]"); } } matcher.appendTail(output); return output.toString(); }
From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptor.java
/** * Adds a comma-separated list of the short {@code Class} names of the * method argument types to the output. For example, if a method has signature * {@code put(java.lang.String, java.lang.Object)} then the value returned * will be {@code String, Object}./*from w w w . ja v a 2 s . co m*/ * @param methodInvocation the {@code MethodInvocation} being logged. * Arguments will be retrieved from the corresponding {@code Method}. * @param matcher the {@code Matcher} containing the state of the output * @param output the {@code StringBuffer} containing the output */ private void appendArgumentTypes(MethodInvocation methodInvocation, Matcher matcher, StringBuffer output) { Class<?>[] argumentTypes = methodInvocation.getMethod().getParameterTypes(); String[] argumentTypeShortNames = new String[argumentTypes.length]; for (int i = 0; i < argumentTypeShortNames.length; i++) { argumentTypeShortNames[i] = ClassUtils.getShortName(argumentTypes[i]); } matcher.appendReplacement(output, Matcher.quoteReplacement(StringUtils.arrayToCommaDelimitedString(argumentTypeShortNames))); }
From source file:org.springframework.batch.core.repository.support.JobRepositoryFactoryBean.java
@Override public void afterPropertiesSet() throws Exception { Assert.notNull(dataSource, "DataSource must not be null."); if (jdbcOperations == null) { jdbcOperations = new JdbcTemplate(dataSource); }//from ww w . j av a2s .co m if (incrementerFactory == null) { incrementerFactory = new DefaultDataFieldMaxValueIncrementerFactory(dataSource); } if (databaseType == null) { databaseType = DatabaseType.fromMetaData(dataSource).name(); logger.info("No database type set, using meta data indicating: " + databaseType); } if (lobHandler == null && databaseType.equalsIgnoreCase(DatabaseType.ORACLE.toString())) { lobHandler = new DefaultLobHandler(); } if (serializer == null) { Jackson2ExecutionContextStringSerializer defaultSerializer = new Jackson2ExecutionContextStringSerializer(); serializer = defaultSerializer; } Assert.isTrue(incrementerFactory.isSupportedIncrementerType(databaseType), "'" + databaseType + "' is an unsupported database type. The supported database types are " + StringUtils.arrayToCommaDelimitedString(incrementerFactory.getSupportedIncrementerTypes())); if (lobType != null) { Assert.isTrue(isValidTypes(lobType), "lobType must be a value from the java.sql.Types class"); } super.afterPropertiesSet(); }
From source file:org.springframework.batch.item.excel.AbstractExcelItemReaderTests.java
@Before public void setup() throws Exception { this.itemReader = createExcelItemReader(); this.itemReader.setLinesToSkip(1); //First line is column names this.itemReader.setResource(new ClassPathResource("org/springframework/batch/item/excel/player.xls")); this.itemReader.setRowMapper(new PassThroughRowMapper()); this.itemReader.setSkippedRowsCallback(new RowCallbackHandler() { public void handleRow(RowSet rs) { logger.info("Skipping: " + StringUtils.arrayToCommaDelimitedString(rs.getCurrentRow())); }/* w w w. j a va 2 s .c o m*/ }); configureItemReader(this.itemReader); this.itemReader.afterPropertiesSet(); executionContext = new ExecutionContext(); this.itemReader.open(executionContext); }
From source file:org.springframework.batch.item.excel.AbstractExcelItemReaderTests.java
@Test public void readExcelFile() throws Exception { assertEquals(3, this.itemReader.getNumberOfSheets()); String[] row;/*ww w. j a v a2 s.co m*/ do { row = (String[]) this.itemReader.read(); this.logger.debug("Read: " + StringUtils.arrayToCommaDelimitedString(row)); if (row != null) { assertEquals(6, row.length); } } while (row != null); int readCount = (Integer) ReflectionTestUtils.getField(this.itemReader, "currentItemCount"); assertEquals(4321, readCount); }