Example usage for org.springframework.util StringUtils arrayToCommaDelimitedString

List of usage examples for org.springframework.util StringUtils arrayToCommaDelimitedString

Introduction

In this page you can find the example usage for org.springframework.util StringUtils arrayToCommaDelimitedString.

Prototype

public static String arrayToCommaDelimitedString(@Nullable Object[] arr) 

Source Link

Document

Convert a String array into a comma delimited String (i.e., CSV).

Usage

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Reads basic message information such as sender, recipients and mail subject to message headers.
 * @param msg/*from w  ww . j  a v a 2s  .c om*/
 * @return
 */
protected Map<String, Object> createMessageHeaders(MimeMailMessage msg) throws MessagingException, IOException {
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(CitrusMailMessageHeaders.MAIL_MESSAGE_ID, msg.getMimeMessage().getMessageID());
    headers.put(CitrusMailMessageHeaders.MAIL_FROM,
            StringUtils.arrayToCommaDelimitedString(msg.getMimeMessage().getFrom()));
    headers.put(CitrusMailMessageHeaders.MAIL_TO, StringUtils.arrayToCommaDelimitedString(
            (msg.getMimeMessage().getRecipients(javax.mail.Message.RecipientType.TO))));
    headers.put(CitrusMailMessageHeaders.MAIL_CC, StringUtils.arrayToCommaDelimitedString(
            (msg.getMimeMessage().getRecipients(javax.mail.Message.RecipientType.CC))));
    headers.put(CitrusMailMessageHeaders.MAIL_BCC, StringUtils.arrayToCommaDelimitedString(
            (msg.getMimeMessage().getRecipients(javax.mail.Message.RecipientType.BCC))));
    headers.put(CitrusMailMessageHeaders.MAIL_REPLY_TO,
            StringUtils.arrayToCommaDelimitedString((msg.getMimeMessage().getReplyTo())));
    headers.put(CitrusMailMessageHeaders.MAIL_DATE,
            msg.getMimeMessage().getSentDate() != null ? dateFormat.format(msg.getMimeMessage().getSentDate())
                    : null);
    headers.put(CitrusMailMessageHeaders.MAIL_SUBJECT, msg.getMimeMessage().getSubject());
    headers.put(CitrusMailMessageHeaders.MAIL_CONTENT_TYPE,
            parseContentType(msg.getMimeMessage().getContentType()));

    return headers;
}

From source file:org.testng.spring.test.AbstractSingleSpringContextTests.java

/**
 * Load an ApplicationContext from the given config locations.
 * @param locations the config locations
 * @return the corresponding ApplicationContext instance (potentially cached)
 *//*  ww w  .  ja v  a 2  s . c o  m*/
protected ConfigurableApplicationContext loadContextLocations(String[] locations) throws Exception {
    ++this.loadCount;
    if (logger.isInfoEnabled()) {
        logger.info("Loading context for: " + StringUtils.arrayToCommaDelimitedString(locations));
    }
    return new ClassPathXmlApplicationContext(locations);
}

From source file:ch.sdi.core.impl.ftp.FtpExecutor.java

/**
 * @param aArgs//from   www  .  j  a  v a2  s  .  co m
 */
public void init(String[] aArgs) throws SdiException {
    try {
        myLog.debug("analyzing given arguments: " + StringUtils.arrayToCommaDelimitedString(aArgs));
        int base = 0;
        int minParams = 3; // listings require 3 params
        for (base = 0; base < aArgs.length; base++) {
            if (aArgs[base].equals("-a")) {
                myLocalActive = true;
            } else if (aArgs[base].equals("-A")) {
                myPassword = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
                myUsername = "anonymous";
            } else if (aArgs[base].equals("-e")) {
                myUseEpsvWithIPv4 = true;
            } else if (aArgs[base].equals("-k")) {
                myKeepAliveTimeout = Long.parseLong(aArgs[++base]);
            } else if (aArgs[base].equals("-p")) {
                myProtocol = aArgs[++base];
            } else if (aArgs[base].equals("-w")) {
                myControlKeepAliveReplyTimeout = Integer.parseInt(aArgs[++base]);
            } else if (aArgs[base].equals("-T")) {
                myTrustmgr = aArgs[++base];
            } else if (aArgs[base].equals("-PrH")) {
                myProxyHost = aArgs[++base];
                String parts[] = myProxyHost.split(":");
                if (parts.length == 2) {
                    myProxyHost = parts[0];
                    myProxyPort = Integer.parseInt(parts[1]);
                }
            } else if (aArgs[base].equals("-PrU")) {
                myProxyUser = aArgs[++base];
            } else if (aArgs[base].equals("-PrP")) {
                myProxyPassword = aArgs[++base];
            } else {
                if (aArgs[base].startsWith("-")) {
                    myLog.warn("unhandled argument: " + aArgs[base]);
                    continue;
                } // if aArgs[base].startsWith( "-" )

                break;
            }
        }

        int remain = aArgs.length - base;
        if (myUsername != null) {
            minParams -= 2;
        }
        if (remain < minParams) // server, user, pass, remote, local [protocol]
        {
            throw createFtpException("Error: Too less params");
        }

        myServer = aArgs[base++];
        myPort = 0;
        String parts[] = myServer.split(":");
        if (parts.length == 2) {
            myServer = parts[0];
            myPort = Integer.parseInt(parts[1]);
        }
        if (myUsername == null) {
            myUsername = aArgs[base++];
            myPassword = aArgs[base++];
        }

        myInitialized = true;
    } catch (Throwable t) {
        myLog.error("Exception caught: ", t);
        myLog.info(USAGE);

        if (t instanceof SdiException) {
            throw (SdiException) t;
        } // if t instanceof SdiException

        throw createFtpException("inititalization problems", t);
    }

}

From source file:chronos.mbeans.QuartzSchedulerAdapter.java

/**
 * {@inheritDoc}/*from w  ww .  ja  va  2 s. com*/
 *
 * @see chronos.mbeans.QuartzSchedulerAdapterMBean#shutdown()
 */
@Override
public final void shutdown() {
    final Scheduler scheduler = schedulerRef.get();
    if (scheduler != null) {
        try {
            logger.trace("Got scheduler "
                    + getUniqueIdentifier(scheduler.getSchedulerName(), scheduler.getSchedulerInstanceId())
                    + "@" + System.identityHashCode(scheduler));
            TestJob.unschedule(scheduler);
            final String[] jobGroupNames = scheduler.getJobGroupNames();
            if (schedulerInstanceName.equals(scheduler.getSchedulerName())) {
                if (jobGroupNames.length == 0) {
                    logger.debug("Quartz scheduler shutting down...");
                    try {
                        scheduler.shutdown(true);
                    } catch (final SchedulerException e) {
                        logger.error("Encountered exception shutting down Quartz: " + e.getMessage(), e);
                    }
                } else {
                    logger.debug("Job groups still running "
                            + StringUtils.arrayToCommaDelimitedString(jobGroupNames));
                }
            } else {
                logger.trace("Was using an existing scheduler instance, so won't perform actual shutdown.");
            }
        } catch (final SchedulerException e) {
            logger.error(e.getMessage(), e);
        }
        if (!schedulerRef.compareAndSet(scheduler, null)) {
            logger.warn("Tried to set schedulerRef to null but was set to a different value!");
        }
    } else {
        logger.error("schedulerRef.get() returned null!");
    }
}

From source file:admin.service.SimpleJobServiceFactoryBean.java

public void afterPropertiesSet() throws Exception {

    Assert.notNull(dataSource, "DataSource must not be null.");
    Assert.notNull(jobRepository, "JobRepository must not be null.");
    Assert.notNull(jobLocator, "JobLocator must not be null.");
    Assert.notNull(jobLauncher, "JobLauncher must not be null.");

    jdbcTemplate = new JdbcTemplate(dataSource);

    if (incrementerFactory == null) {
        incrementerFactory = new DefaultDataFieldMaxValueIncrementerFactory(dataSource);
    }//from  ww  w .j  ava 2  s .  co  m

    if (databaseType == null) {
        databaseType = DatabaseType.fromMetaData(dataSource).name();
        logger.info("No database type set, using meta data indicating: " + databaseType);
    }

    if (lobHandler == null) {
        lobHandler = new DefaultLobHandler();
    }

    if (serializer == null) {
        XStreamExecutionContextStringSerializer defaultSerializer = new XStreamExecutionContextStringSerializer();
        defaultSerializer.afterPropertiesSet();

        serializer = defaultSerializer;
    }

    Assert.isTrue(incrementerFactory.isSupportedIncrementerType(databaseType), "'" + databaseType
            + "' is an unsupported database type.  The supported database types are "
            + StringUtils.arrayToCommaDelimitedString(incrementerFactory.getSupportedIncrementerTypes()));

}

From source file:org.jasig.springframework.web.portlet.context.PortletContextLoaderTests.java

@Test
public void testContextLoaderListenerWithUnkownContextInitializer() {
    MockServletContext sc = new MockServletContext("");
    // config file doesn't matter.  just a placeholder
    sc.addInitParameter(PortletContextLoader.CONFIG_LOCATION_PARAM,
            "/org/springframework/web/context/WEB-INF/empty-context.xml");
    sc.addInitParameter(PortletContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, StringUtils
            .arrayToCommaDelimitedString(new Object[] { UnknownContextInitializer.class.getName() }));
    PortletContextLoaderListener listener = new PortletContextLoaderListener();
    listener.contextInitialized(new ServletContextEvent(sc));

    try {//  ww w.  j a  v  a 2  s  . c  o  m
        //initialize the portlet application context, needed because PortletContextLoaderListener.contextInitialized doesn't actually create
        //the portlet app context due to lack of PortletContext reference
        MockPortletContext pc = new MockPortletContext(sc);
        PortletApplicationContextUtils2.getPortletApplicationContext(pc);

        fail("expected exception");
    } catch (IllegalArgumentException ex) {
        assertTrue(ex.getMessage().contains("not assignable"));
    }
}

From source file:se.vgregion.portal.notes.calendar.controllers.NotesCalendarViewController.java

/**
 * Displays the calendar events for the logged in user.
 *
 * @param model    the model//from  w w  w.j  av  a2 s  .c  om
 * @param request  the portletRequest
 * @param response the portletResponse
 * @return the view to display
 */
@RenderMapping
public String displayCalendarEvents(ModelMap model, RenderRequest request, RenderResponse response) {

    // It would seem that Joda Times DateTimeZone does not use Sun:s TimeZone.getDefault (user.timezone) as its
    // often claims but defaults to timezone UTC. So therefor we do this:
    DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault()));
    // ... getting the value set in the java_opt - setting it as default for JT.

    String userId = portletData.getUserId(request);
    LOGGER.debug("Userid: {}", userId);
    CalendarEventsPeriod displayPeriod = (CalendarEventsPeriod) model.get(displayPeriodKey);
    if (displayPeriod == null) {
        DateTime startDate = new DateTime().withDayOfWeek(DateTimeConstants.MONDAY).withHourOfDay(0)
                .withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        displayPeriod = new CalendarEventsPeriod(startDate, CalendarEventsPeriod.DEFAULT_PERIOD_LENGTH);
        model.put(displayPeriodKey, displayPeriod);
    }
    try {
        Map<String, Future<CalendarEvents>> futureCalendarEvents = new HashMap<String, Future<CalendarEvents>>();

        // Initialize CalendarEvents
        CalendarEvents events = new CalendarEvents();
        events.setCalendarItems(new ArrayList<CalendarItem>());

        // Retrieve asynchronously
        futureCalendarEvents.put("VGR", calendarService.getFutureCalendarEvents(userId, displayPeriod));

        // Get from Google, asynchronously
        //            String selectedCalendars = request.getPreferences().getValue(this.SELECTED_GOOGLE_CALENDARS, "");
        //            List<String> selectedCalendarsList = Arrays.asList(stringToArray(selectedCalendars));
        //            futureCalendarEvents.put("Google", googleCalendarService.getFutureCalendarEvents(userId, displayPeriod,
        //                    selectedCalendarsList));

        // Get from other sources, asynchronously.
        Map<String, String> externalSources = getExternalSources(request.getPreferences());
        for (Map.Entry<String, String> externalSource : externalSources.entrySet()) {
            futureCalendarEvents.put(externalSource.getKey(),
                    calendarService.getFutureCalendarEventsFromIcalUrl(externalSource.getValue(), displayPeriod,
                            externalSource.getKey()));
        }

        // Now that we have a list of Future objects which all are processed concurrently we start to "get()" them.
        List<String> failedRetrievals = new ArrayList<String>();
        for (Map.Entry<String, Future<CalendarEvents>> futureCalendarEvent : futureCalendarEvents.entrySet()) {
            try {
                Future<CalendarEvents> value = futureCalendarEvent.getValue();
                CalendarEvents calendarEvents = value.get(15, TimeUnit.SECONDS);
                if (calendarEvents != null) {
                    List<CalendarItem> calendarItems = calendarEvents.getCalendarItems();
                    if (calendarItems != null) {
                        events.getCalendarItems().addAll(calendarItems);
                    }
                }
            } catch (Exception ex) {
                if (userId.equals("lifra1")) {
                    LOGGER.warn("Failed to get a calendar for user " + userId + ". " + ex.getMessage());
                } else {
                    LOGGER.warn("Failed to get a calendar for user " + userId + ". " + ex.getMessage(), ex);
                }
                failedRetrievals.add(futureCalendarEvent.getKey());
            }
        }

        if (failedRetrievals.size() > 0) {
            String errorMessage = "Fljande hmtningar misslyckades: "
                    + StringUtils.arrayToCommaDelimitedString(failedRetrievals.toArray()) + ".";
            model.addAttribute("errorMessage", errorMessage);
        }

        List<List<CalendarItem>> calendarItems = events.getCalendarItemsGroupedByStartDate();
        model.put("displayPeriodText", getFormattedDateIntervalToTitle(displayPeriod, locale));
        model.put("calendarItems", calendarItems);
        model.put("randomNumber", random.nextInt());
        return VIEW;
    } catch (RuntimeException ex) {
        LOGGER.error(ex.getMessage(), ex);
        return NO_CALENDAR_VIEW;
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return NO_CALENDAR_VIEW;
    }
}

From source file:demo.tomcat.SciTomcatEmbeddedServletContainerFactory.java

/**
 * Configure Tomcat's {@link AbstractHttp11JsseProtocol} for SSL.
 * @param protocol the protocol//from ww  w.j a  v  a  2 s  . c o  m
 * @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());
    configureSslKeyStore(protocol, ssl);
    String ciphers = StringUtils.arrayToCommaDelimitedString(ssl.getCiphers());
    protocol.setCiphers(ciphers);
    configureSslTrustStore(protocol, ssl);
}

From source file:com.consol.citrus.mail.server.MailServer.java

/**
 * Reads basic message information such as sender, recipients and mail subject to message headers.
 * @param msg//  w ww  .  j  a  v  a 2 s.c om
 * @return
 */
protected Map<String, String> createMessageHeaders(MimeMailMessage msg) throws MessagingException, IOException {
    Map<String, String> headers = new HashMap<String, String>();
    headers.put(CitrusMailMessageHeaders.MAIL_MESSAGE_ID, msg.getMimeMessage().getMessageID());
    headers.put(CitrusMailMessageHeaders.MAIL_FROM,
            StringUtils.arrayToCommaDelimitedString(msg.getMimeMessage().getFrom()));
    headers.put(CitrusMailMessageHeaders.MAIL_TO, StringUtils
            .arrayToCommaDelimitedString((msg.getMimeMessage().getRecipients(Message.RecipientType.TO))));
    headers.put(CitrusMailMessageHeaders.MAIL_CC, StringUtils
            .arrayToCommaDelimitedString((msg.getMimeMessage().getRecipients(Message.RecipientType.CC))));
    headers.put(CitrusMailMessageHeaders.MAIL_BCC, StringUtils
            .arrayToCommaDelimitedString((msg.getMimeMessage().getRecipients(Message.RecipientType.BCC))));
    headers.put(CitrusMailMessageHeaders.MAIL_REPLY_TO,
            StringUtils.arrayToCommaDelimitedString((msg.getMimeMessage().getReplyTo())));
    headers.put(CitrusMailMessageHeaders.MAIL_DATE,
            msg.getMimeMessage().getSentDate() != null ? dateFormat.format(msg.getMimeMessage().getSentDate())
                    : null);
    headers.put(CitrusMailMessageHeaders.MAIL_SUBJECT, msg.getMimeMessage().getSubject());
    headers.put(CitrusMailMessageHeaders.MAIL_CONTENT_TYPE,
            parseContentType(msg.getMimeMessage().getContentType()));

    return headers;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), using the given property editor.
 * // w w  w  .ja va  2  s. c o m
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> 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;
    boolean sharedEditor = false;

    if (editor != null) {
        sharedEditor = this.propertyEditorRegistry.isSharedEditor(editor);
    }

    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 {
            Object newConvertedValue;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    editor.setValue(convertedValue);
                    newConvertedValue = editor.getValue();
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                editor.setValue(convertedValue);
                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;
            if (sharedEditor) {
                // Synchronized access to shared editor instance.
                synchronized (editor) {
                    return doConvertTextValue(oldValue, newTextValue, editor);
                }
            } else {
                // Unsynchronized access to non-shared editor instance.
                return doConvertTextValue(oldValue, newTextValue, editor);
            }
        } else if (String.class.equals(requiredType)) {
            returnValue = convertedValue;
        }
    }

    return returnValue;
}