Example usage for org.springframework.util StringUtils collectionToCommaDelimitedString

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

Introduction

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

Prototype

public static String collectionToCommaDelimitedString(@Nullable Collection<?> coll) 

Source Link

Document

Convert a Collection into a delimited String (e.g., CSV).

Usage

From source file:org.springframework.statemachine.support.AbstractStateMachine.java

@Override
public String toString() {
    ArrayList<State<S, E>> all = new ArrayList<State<S, E>>();
    for (State<S, E> s : states) {
        all.addAll(s.getStates());//from w  ww . ja va2s. c  o  m
    }
    StringBuilder buf = new StringBuilder();
    for (State<S, E> s : all) {
        buf.append(s.getId() + " ");
    }
    buf.append(" / ");
    if (currentState != null) {
        buf.append(StringUtils.collectionToCommaDelimitedString(currentState.getIds()));
    }
    buf.append(" / uuid=");
    buf.append(uuid);
    buf.append(" / id=");
    buf.append(id);
    return buf.toString();
}

From source file:org.springframework.statemachine.test.StateMachineTestPlan.java

/**
 * Run test plan./*from   ww w .  j  a va 2 s .  c o m*/
 *
 * @throws Exception the exception
 */
public void test() throws Exception {

    Map<StateMachine<S, E>, LatchStateMachineListener<S, E>> listeners = new HashMap<StateMachine<S, E>, LatchStateMachineListener<S, E>>();
    for (StateMachine<S, E> stateMachine : stateMachines.values()) {
        LatchStateMachineListener<S, E> listener = new LatchStateMachineListener<S, E>();
        listeners.put(stateMachine, listener);
        stateMachine.addStateListener(listener);
    }
    log.info("Running test plan for machines "
            + StringUtils.collectionToCommaDelimitedString(stateMachines.values()));

    int stepCounter = 0;
    for (StateMachineTestPlanStep<S, E> step : steps) {
        log.info("Running test plan step " + stepCounter++);
        for (LatchStateMachineListener<S, E> listener : listeners.values()) {
            listener.reset(step.expectStateChanged != null ? step.expectStateChanged : 0,
                    step.expectStateEntered != null ? step.expectStateEntered : 0,
                    step.expectStateExited != null ? step.expectStateExited : 0,
                    step.expectEventNotAccepted != null ? step.expectEventNotAccepted : 0,
                    step.expectTransition != null ? step.expectTransition : 0,
                    step.expectTransitionStarted != null ? step.expectTransitionStarted : 0,
                    step.expectTransitionEnded != null ? step.expectTransitionEnded : 0,
                    step.expectStateMachineStarted != null ? step.expectStateMachineStarted : 0,
                    step.expectStateMachineStopped != null ? step.expectStateMachineStopped : 0,
                    step.expectExtendedStateChanged != null ? step.expectExtendedStateChanged : 0);
        }

        // need to call start here, ok to call from all steps
        for (StateMachine<S, E> stateMachine : stateMachines.values()) {
            stateMachine.start();
        }

        if (step.expectStateMachineStarted != null) {
            for (Entry<StateMachine<S, E>, LatchStateMachineListener<S, E>> entry : listeners.entrySet()) {
                assertThat(
                        "StateMachineStarted Await not matched for machine " + entry.getKey(), entry.getValue()
                                .getStateMachineStartedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat("StateMachineStarted count not matched for machine " + entry.getKey(),
                        entry.getValue().getStateMachineStarted().size(), is(step.expectStateMachineStarted));
            }
        }

        if (!step.sendEvent.isEmpty()) {
            ArrayList<StateMachine<S, E>> sendVia = new ArrayList<StateMachine<S, E>>();
            if (step.sendEventMachineId != null) {
                sendVia.add(stateMachines.get(step.sendEventMachineId));
            } else if (step.sendEventToAll) {
                sendVia.addAll(stateMachines.values());
            } else {
                sendVia.add(stateMachines.values().iterator().next());
            }
            assertThat("Error finding machine to send via", sendVia, not(empty()));
            if (!step.sendEventParallel) {
                for (StateMachine<S, E> machine : sendVia) {
                    for (E event : step.sendEvent) {
                        log.info("Sending test event " + event + " via machine " + machine);
                        machine.sendEvent(event);
                    }
                }
            } else {
                for (E event : step.sendEvent) {
                    sendEventParallel(sendVia, event);
                }
            }
        } else if (!step.sendMessage.isEmpty()) {
            ArrayList<StateMachine<S, E>> sendVia = new ArrayList<StateMachine<S, E>>();
            if (step.sendEventMachineId != null) {
                sendVia.add(stateMachines.get(step.sendEventMachineId));
            } else if (step.sendEventToAll) {
                sendVia.addAll(stateMachines.values());
            } else {
                sendVia.add(stateMachines.values().iterator().next());
            }
            assertThat("Error finding machine to send via", sendVia, not(empty()));
            for (StateMachine<S, E> machine : sendVia) {
                for (Message<E> event : step.sendMessage) {
                    log.info("Sending test event " + event + " via machine " + machine);
                    machine.sendEvent(event);
                }
            }
        }

        if (step.expectStateChanged != null) {
            for (Entry<StateMachine<S, E>, LatchStateMachineListener<S, E>> entry : listeners.entrySet()) {
                assertThat("StateChanged Await not matched for machine " + entry.getKey(),
                        entry.getValue().getStateChangedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat("StateChanged count not matched for machine " + entry.getKey(),
                        entry.getValue().getStateChanged().size(), is(step.expectStateChanged));
            }
        }

        if (step.expectStateEntered != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getStateEnteredLatch().await(defaultAwaitTime, TimeUnit.SECONDS), is(true));
                assertThat(listener.getStateEntered().size(), is(step.expectStateEntered));
            }
        }

        if (step.expectStateExited != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getStateExitedLatch().await(defaultAwaitTime, TimeUnit.SECONDS), is(true));
                assertThat(listener.getStateExited().size(), is(step.expectStateExited));
            }
        }

        if (step.expectEventNotAccepted != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getEventNotAcceptedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat(listener.getEventNotAccepted().size(), is(step.expectEventNotAccepted));
            }
        }

        if (step.expectTransition != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getTransitionLatch().await(defaultAwaitTime, TimeUnit.SECONDS), is(true));
                assertThat(listener.getTransition().size(), is(step.expectTransition));
            }
        }

        if (step.expectTransitionStarted != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getTransitionStartedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat(listener.getTransitionStarted().size(), is(step.expectTransitionStarted));
            }
        }

        if (step.expectTransitionEnded != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getTransitionEndedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat(listener.getTransitionEnded().size(), is(step.expectTransitionEnded));
            }
        }

        if (step.expectStateMachineStopped != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getStateMachineStoppedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat(listener.getStateMachineStopped().size(), is(step.expectStateMachineStopped));
            }
        }

        if (!step.expectStates.isEmpty()) {
            for (StateMachine<S, E> stateMachine : stateMachines.values()) {
                assertThat(stateMachine.getState(), notNullValue());
                Collection<Matcher<? super S>> itemMatchers = new ArrayList<Matcher<? super S>>();
                for (S expectState : step.expectStates) {
                    itemMatchers.add(is(expectState));
                }
                assertThat(stateMachine.getState().getIds(), containsInAnyOrder(itemMatchers));
            }
        }

        if (!step.expectStatesEntrered.isEmpty()) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                Collection<S> states = new ArrayList<S>();
                for (State<S, E> s : listener.getStateEntered()) {
                    states.add(s.getId());
                }
                assertThat(step.expectStatesEntrered, contains(states.toArray()));
            }
        }

        if (!step.expectStatesExited.isEmpty()) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                Collection<S> states = new ArrayList<S>();
                for (State<S, E> s : listener.getStateExited()) {
                    states.add(s.getId());
                }
                assertThat(step.expectStatesExited, contains(states.toArray()));
            }
        }

        if (step.expectExtendedStateChanged != null) {
            for (LatchStateMachineListener<S, E> listener : listeners.values()) {
                assertThat(listener.getExtendedStateChangedLatch().await(defaultAwaitTime, TimeUnit.SECONDS),
                        is(true));
                assertThat(listener.getExtendedStateChanged().size(), is(step.expectExtendedStateChanged));
            }
        }

        if (!step.expectVariableKeys.isEmpty()) {
            for (StateMachine<S, E> stateMachine : stateMachines.values()) {
                Map<Object, Object> variables = stateMachine.getExtendedState().getVariables();
                for (Object key : step.expectVariableKeys) {
                    assertThat("Key " + key + " doesn't exist in extended state variables",
                            variables.containsKey(key), is(true));
                }
            }
        }

        if (!step.expectVariables.isEmpty()) {
            for (StateMachine<S, E> stateMachine : stateMachines.values()) {
                Map<Object, Object> variables = stateMachine.getExtendedState().getVariables();
                for (Entry<Object, Object> entry : step.expectVariables.entrySet()) {
                    assertThat("Key " + entry.getKey() + " doesn't exist in extended state variables",
                            variables.containsKey(entry.getKey()), is(true));
                    assertThat("Variable " + entry.getKey() + " doesn't match in extended state variables",
                            variables.get(entry.getKey()), is(entry.getValue()));
                }
            }
        }
    }
}

From source file:org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient.java

@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
    return getHttpClient().headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
            .websocket(StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols()))
            .uri(url.toString()).handle((inbound, outbound) -> {
                HttpHeaders responseHeaders = toHttpHeaders(inbound);
                String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
                HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
                NettyDataBufferFactory factory = new NettyDataBufferFactory(outbound.alloc());
                WebSocketSession session = new ReactorNettyWebSocketSession(inbound, outbound, info, factory);
                if (logger.isDebugEnabled()) {
                    logger.debug("Started session '" + session.getId() + "' for " + url);
                }/*from  w  w w. j a v a 2s.  c  om*/
                return handler.handle(session);
            }).doOnRequest(n -> {
                if (logger.isDebugEnabled()) {
                    logger.debug("Connecting to " + url);
                }
            }).next();
}

From source file:org.springframework.yarn.am.container.DefaultContainerLauncher.java

@Override
public void launchContainer(Container container, List<String> commands) {
    if (log.isDebugEnabled()) {
        log.debug("Launching container: " + container + " with commands "
                + StringUtils.collectionToCommaDelimitedString(commands));
    }/*from ww w. j av a2  s . c om*/

    ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class);
    String stagingId = container.getId().getApplicationAttemptId().getApplicationId().toString();
    if (getResourceLocalizer() instanceof SmartResourceLocalizer) {
        ((SmartResourceLocalizer) getResourceLocalizer()).setStagingId(stagingId);
    } else {
        log.warn(
                "Resource localizer is not instance of SmartResourceLocalizer, thus we're unable to set staging id");
    }

    ctx.setLocalResources(getResourceLocalizer().getResources());
    ctx.setCommands(commands);

    // Yarn doesn't tell container what is its container id
    // so we do it here
    Map<String, String> env = getEnvironment();
    env.put(YarnSystemConstants.SYARN_CONTAINER_ID, ConverterUtils.toString(container.getId()));
    ctx.setEnvironment(env);
    ctx = getInterceptors().preLaunch(container, ctx);

    StartContainerRequest startContainerRequest = Records.newRecord(StartContainerRequest.class);

    if (log.isDebugEnabled()) {
        log.debug("Using ContainerLaunchContext: " + ctx);
    }

    startContainerRequest.setContainerLaunchContext(ctx);
    startContainerRequest.setContainerToken(container.getContainerToken());

    StartContainersRequest startContainersRequest = Records.newRecord(StartContainersRequest.class);
    ArrayList<StartContainerRequest> startContainerRequestList = new ArrayList<StartContainerRequest>();
    startContainerRequestList.add(startContainerRequest);
    startContainersRequest.setStartContainerRequests(startContainerRequestList);

    StartContainersResponse startContainersResponse = getCmTemplate(container)
            .startContainers(startContainersRequest);

    // failed indicates failure for the request, not failure on container
    Map<ContainerId, SerializedException> failed = startContainersResponse.getFailedRequests();
    List<ContainerId> succeed = startContainersResponse.getSuccessfullyStartedContainers();

    if (log.isDebugEnabled()) {
        log.debug("Response for starting container=[" + container + "] is startContainersResponse=["
                + startContainersResponse + "]");
    }

    // notify interested parties of new launched container
    if (getYarnEventPublisher() != null) {
        for (ContainerId cid : succeed) {
            if (container.getId().equals(cid)) {
                getYarnEventPublisher().publishContainerLaunched(this, container);
            }
        }
        for (ContainerId cid : failed.keySet()) {
            if (container.getId().equals(cid)) {
                getYarnEventPublisher().publishContainerLaunchRequestFailed(this, container);
            }
        }
    }
}

From source file:org.springframework.yarn.examples.grid.yarn.YarnManagedContainerGroups.java

@Override
public void addContainerNode(YarnContainerNode node) {
    Container container = node.getContainer();
    Assert.notNull(container, "Yarn Container must be set");
    YarnContainerGroup g = null;//w  w  w  .j av a  2s. c  o m
    boolean added = false;
    List<String> resolvesGroups = resolveGroupNamesInternal(container);

    if (!resolvesGroups.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Matched node=" + node + " to groups "
                    + StringUtils.collectionToCommaDelimitedString(resolvesGroups));
        }
        for (String name : resolvesGroups) {
            g = managedGroups.get(name);
            if (g != null && !g.isFull()) {
                g.addMember(node);
                added = true;
                if (log.isDebugEnabled()) {
                    log.debug("Added " + ConverterUtils.toString(container.getId()) + " to " + g.getId());
                }
                break;
            }
        }
    }

    if (!added) {
        if (log.isDebugEnabled()) {
            log.debug("No match for groups for node " + node + " adding to fallback group");
        }
        g = unmanagedContainerGroup;
        g.addMember(node);
    }

    containerGridListener.containerNodeAdded(node);
    containerGroupsListener.groupMemberAdded(g, node);
}

From source file:org.springframework.yarn.examples.grid.yarn.YarnManagedContainerGroups.java

/**
 * Sets the group hosts./*ww w . j  a  v a 2  s .co m*/
 *
 * @param groupHosts the group hosts
 */
public void setGroupHosts(Map<String, List<String>> groupHosts) {
    for (Entry<String, List<String>> entry : groupHosts.entrySet()) {
        if (log.isDebugEnabled()) {
            log.debug("setGroupHosts " + entry.getKey() + " "
                    + StringUtils.collectionToCommaDelimitedString(entry.getValue()));
        }
        getMayCreateGroup(entry.getKey()).setHosts(entry.getValue());
    }
}