Example usage for java.util.stream Collectors joining

List of usage examples for java.util.stream Collectors joining

Introduction

In this page you can find the example usage for java.util.stream Collectors joining.

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Usage

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Adds item./*ww  w.  j  a  va  2s.c  o m*/
 * @param owner user name
 * @param folderId folder id (optional)
 * @param title title
 * @param description description
 * @param url URL
 * @param thumbnailUrl thumbnail url
 * @param itemType item type (must be a URL type)
 * @param extent extent
 * @param typeKeywords type keywords
 * @param tags tags tags
 * @param token token
 * @return add item response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ItemResponse addItem(String owner, String folderId, String title, String description, URL url,
        URL thumbnailUrl, ItemType itemType, Double[] extent, String[] typeKeywords, String[] tags,
        String token) throws IOException, URISyntaxException {
    URIBuilder builder = new URIBuilder(addItemUri(owner, StringUtils.trimToNull(folderId)));

    HttpPost req = new HttpPost(builder.build());
    HashMap<String, String> params = new HashMap<>();
    params.put("f", "json");
    params.put("title", title);
    params.put("description", description);
    params.put("type", itemType.getTypeName());
    params.put("url", url.toExternalForm());
    if (thumbnailUrl != null) {
        params.put("thumbnailurl", thumbnailUrl.toExternalForm());
    }
    if (extent != null && extent.length == 4) {
        params.put("extent",
                Arrays.asList(extent).stream().map(Object::toString).collect(Collectors.joining(",")));
    }
    if (typeKeywords != null) {
        params.put("typeKeywords", Arrays.asList(typeKeywords).stream().collect(Collectors.joining(",")));
    }
    if (tags != null) {
        params.put("tags", Arrays.asList(tags).stream().collect(Collectors.joining(",")));
    }
    params.put("token", token);

    req.setEntity(createEntity(params));

    return execute(req, ItemResponse.class);
}

From source file:com.thinkbiganalytics.alerts.spi.defaults.KyloEntityAwareAlertCriteria.java

private BooleanBuilder orFilter(QJpaAlert alert, QJpaOpsManagerFeed feed,
        QJpaServiceLevelAgreementDescription sla) {
    BooleanBuilder globalFilter = new BooleanBuilder();
    if (StringUtils.isNotBlank(getOrFilter())) {
        Lists.newArrayList(StringUtils.split(getOrFilter(), ",")).stream().forEach(filter -> {
            filter = StringUtils.trim(filter);
            if (filter != null) {
                List<String> in = null;
                if (filter.contains("||")) {
                    //replace the OR || with commas for IN clause
                    in = Arrays.asList(StringUtils.split(filter, "||")).stream().map(f -> StringUtils.trim(f))
                            .collect(Collectors.toList());
                    filter = in.stream().collect(Collectors.joining(","));
                }//from   www .j  a va 2  s  .  c o m
                BooleanBuilder booleanBuilder = new BooleanBuilder();
                List<Predicate> preds = new ArrayList<>();
                try {
                    Alert.State state = Alert.State.valueOf(filter.toUpperCase());
                    preds.add(alert.state.eq(state));
                } catch (IllegalArgumentException e) {

                }
                if (in != null) {
                    preds.add(alert.description.in(in));
                    preds.add(alert.entityType.in(in));
                    preds.add(alert.typeString.in(in));
                    preds.add(alert.subtype.in(in));
                    //add in joins on the feed or sla name
                    addOrFilter(feed, CommonFilterTranslations.feedFilters, preds, filter);
                    addOrFilter(sla, KyloEntityAwareAlertManager.alertSlaFilters, preds, filter);
                } else {
                    preds.add(alert.description.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.entityType.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.typeString.likeIgnoreCase(filter.concat("%")));
                    preds.add(alert.subtype.like(filter.concat("%")));
                    //add in joins on the feed or sla name
                    addOrFilter(feed, CommonFilterTranslations.feedFilters, preds, filter);
                    addOrFilter(sla, KyloEntityAwareAlertManager.alertSlaFilters, preds, filter);

                }

                booleanBuilder.andAnyOf(preds.toArray(new Predicate[preds.size()]));
                globalFilter.and(booleanBuilder);
            }
        });

    }
    return globalFilter;
}

From source file:org.ng200.openolympus.Application.java

private void reportMissingLocalisationKey(final String code) {
    try {// w w  w.  ja  v a  2  s .c o m
        if (code.isEmpty() || Character.isUpperCase(code.charAt(0))) {
            return;
        }
        final File file = new File(new File(StorageSpace.STORAGE_PREFIX), "missingLocalisation.txt");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        final Set<String> s = new TreeSet<>(Arrays.asList(FileUtils.readFileToString(file).split("\n")));
        s.add(code);
        FileUtils.writeStringToFile(file, s.stream().collect(Collectors.joining("\n")));
    } catch (final IOException e) {
        Application.logger.error("Couldn't add to missing key repo: {}", e);
    }
}

From source file:org.terracotta.management.entity.tms.TmsAgentTest.java

@Test
public void test_basic_tms_entity() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    try (org.terracotta.connection.Connection connection = ConnectionFactory
            .connect(URI.create("passthrough://server-1:9510/cluster-1"), new Properties())) {
        EntityRef<TmsAgentEntity, TmsAgentConfig> ref = connection.getEntityRef(TmsAgentEntity.class,
                TmsAgentVersion.LATEST.version(), getClass().getSimpleName());
        ref.create(new TmsAgentConfig());

        TmsAgentEntity entity = ref.fetchEntity();

        Cluster cluster = entity.readTopology().get();

        // reset runtime data
        expectedCluster.serverStream().forEach(expectedServer -> {
            Server server = cluster.getStripe("stripe-1").get().getServerByName(expectedServer.getServerName())
                    .get();/*w w  w. ja va2  s.c o  m*/
            expectedServer.setUpTimeSec(server.getUpTimeSec());
            expectedServer.setStartTime(server.getStartTime());
            expectedServer.setActivateTime(server.getActivateTime());
            expectedServer.setBuildId(server.getBuildId());
        });
        long realConnectionPort = cluster.getClients().values().iterator().next().connectionStream().findFirst()
                .get().getClientEndpoint().getPort();
        String uuid = cluster.getClients().values().iterator().next().getLogicalConnectionUid();
        String expected = mapper.writeValueAsString(expectedCluster.toMap()).replace("uuid", uuid)
                .replace(":-1", ":" + realConnectionPort).replace(": -1", ": " + realConnectionPort);

        System.out.println("EXPECTED:");
        System.out.println(expected);

        String actual = mapper.writeValueAsString(cluster.toMap());
        System.out.println("ACTUAL");
        System.out.println(actual);

        assertEquals(expected, actual);

        List<Message> messages = entity.readMessages().get();
        assertEquals(3, messages.size());

        // ensure a second read without any topology modifications leads to 0 messages
        assertEquals(0, entity.readMessages().get().size());

        System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));

        assertEquals("TOPOLOGY", messages.get(messages.size() - 1).getType());
        assertEquals(cluster, messages.get(messages.size() - 1).unwrap(Cluster.class));

        assertEquals("NOTIFICATION", messages.get(0).getType());
        ContextualNotification firstNotif = messages.get(0).unwrap(ContextualNotification.class);
        assertEquals("SERVER_ENTITY_CREATED", firstNotif.getType());
        assertEquals(expectedCluster.serverEntityStream().findFirst().get().getContext(),
                firstNotif.getContext());

        assertEquals("NOTIFICATION", messages.get(1).getType());
        ContextualNotification secondNotif = messages.get(1).unwrap(ContextualNotification.class);
        assertEquals("SERVER_ENTITY_FETCHED", secondNotif.getType());
        assertEquals(expectedCluster.serverEntityStream().findFirst().get().getContext(),
                firstNotif.getContext());
        assertEquals(expectedCluster.clientStream().findFirst().get().getClientId().replace("uuid", uuid),
                secondNotif.getAttributes().get(Client.KEY));

        entity.readMessages().get();

        // not connects a client management registry

        ManagementRegistry registry = new AbstractManagementRegistry() {
            @Override
            public ContextContainer getContextContainer() {
                return new ContextContainer("cacheManagerName", "my-cm-name");
            }
        };
        registry.addManagementProvider(new MyManagementProvider());

        try (org.terracotta.connection.Connection secondConnection = ConnectionFactory
                .connect(URI.create("passthrough://server-1:9510/cluster-1"), new Properties())) {

            ManagementAgentService managementAgent = new ManagementAgentService(
                    new ManagementAgentEntityFactory(secondConnection)
                            .retrieveOrCreate(new ManagementAgentConfig()));
            managementAgent.setManagementCallExecutor(executorService);

            ClientIdentifier clientIdentifier = managementAgent.getClientIdentifier();
            //System.out.println(clientIdentifier);
            assertEquals(Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]),
                    clientIdentifier.getPid());
            assertEquals("UNKNOWN", clientIdentifier.getName());
            assertNotNull(clientIdentifier.getConnectionUid());

            managementAgent.bridge(registry);
            managementAgent.setTags("EhcachePounder", "webapp-1", "app-server-node-1");

            messages = entity.readMessages().get();
            System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));
            assertEquals(6, messages.size());
            for (int i = 0; i < 5; i++) {
                assertEquals("NOTIFICATION", messages.get(0).getType());
            }
            assertEquals("CLIENT_CONNECTED", messages.get(0).unwrap(ContextualNotification.class).getType());
            assertEquals("SERVER_ENTITY_CREATED",
                    messages.get(1).unwrap(ContextualNotification.class).getType());
            assertEquals("SERVER_ENTITY_FETCHED",
                    messages.get(2).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(3).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_TAGS_UPDATED", messages.get(4).unwrap(ContextualNotification.class).getType());
            assertEquals("TOPOLOGY", messages.get(5).getType());

            registry.register(new MyObject("myCacheManagerName", "myCacheName1"));
            registry.register(new MyObject("myCacheManagerName", "myCacheName2"));

            messages = entity.readMessages().get();
            System.out.println(messages.stream().map(Message::toString).collect(Collectors.joining("\n")));
            assertEquals(3, messages.size());
            assertEquals("NOTIFICATION", messages.get(0).getType());
            assertEquals("NOTIFICATION", messages.get(1).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(0).unwrap(ContextualNotification.class).getType());
            assertEquals("CLIENT_REGISTRY_UPDATED",
                    messages.get(1).unwrap(ContextualNotification.class).getType());
            assertEquals("TOPOLOGY", messages.get(2).getType());
        }

    }
}

From source file:com.github.drbookings.ui.controller.StatsViewController.java

private void updateUI(final BookingsByOrigin<BookingEntry> bookings, final Range<LocalDate> dateRange) {
    if (logger.isDebugEnabled()) {
        logger.debug("Statistics for\n" + BookingEntries.toBookings(bookings.getAllBookings()).stream()
                .map(i -> i.toString()).collect(Collectors.joining("\n")));
    }/*  w  w w. j a  v  a2 s.c o m*/
    final float allAllNigths = BookingEntries.countNights(bookings, false);
    final NavigableSet<LocalDate> allDates = bookings.getAllBookings(true).stream().map(b -> b.getDate())
            .collect(Collectors.toCollection(TreeSet::new));
    long monthCount = TemporalQueries.countOccurrences(allDates,
            SettingsManager.getInstance().getFixCostsPaymentDay());
    if (logger.isDebugEnabled()) {
        logger.debug("Month count: " + monthCount);
    }
    if (monthCount < 1) {
        monthCount = 1;
        if (logger.isDebugEnabled()) {
            logger.debug("Month count (corrected): " + monthCount);
        }
    }
    final float additionalCosts = SettingsManager.getInstance().getAdditionalCosts() * monthCount;
    final float numberOfRooms = SettingsManager.getInstance().getNumberOfRooms();
    final float totalAdditionalCosts = additionalCosts * numberOfRooms;
    if (logger.isDebugEnabled()) {
        logger.debug("Fix costs total: " + totalAdditionalCosts);
    }
    for (final Entry<BookingOrigin, Collection<BookingEntry>> e : bookings.getMap().entrySet()) {

        final Collection<? extends BookingEntry> bookingsFilteredByPaymentDate = e.getValue().stream()
                .filter(new PaymentDateFilter(dateRange)).collect(Collectors.toList());

        final Collection<? extends BookingEntry> bookingsFilteredByCleaningDate = e.getValue().stream()
                .filter(new CleaningDateFilter(dateRange)).collect(Collectors.toList());

        final int numberOfAllBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()),
                false);

        final int numberOfPayedBookings = (int) BookingEntries
                .countBookings(new BookingsByOrigin<>(e.getValue()), false);

        final int numberOfAllNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(e.getValue()),
                false);

        final int numberOfPayedNights = (int) BookingEntries
                .countNights(new BookingsByOrigin<>(bookingsFilteredByPaymentDate), false);

        final float percentage;

        if (StringUtils.isBlank(e.getKey().getName())) {
            percentage = 0;
        } else {
            percentage = numberOfAllNights / allAllNigths * 100f;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " percentage of all nights: " + percentage);
        }
        final double relativeFixCosts = totalAdditionalCosts * percentage / 100;
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " relative fix costs " + relativeFixCosts);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " number of bookings (all/payed): " + numberOfAllBookings + "/"
                    + numberOfPayedBookings);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + ": Number of nights (all/payed): " + numberOfAllNights + "/"
                    + numberOfPayedNights);
        }

        if (logger.isDebugEnabled()) {
            Set<Guest> set = e.getValue().stream().map(b -> b.getElement().getGuest())
                    .collect(Collectors.toCollection(LinkedHashSet::new));
            List<Guest> list = e.getValue().stream().filter(b -> !b.isCheckOut())
                    .map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            StringBuilder sb = new StringBuilder(e.getKey() + " guest and nights (all):");
            int cnt = 1;
            int cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);

                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));

            logger.debug(sb.toString());

            set = bookingsFilteredByPaymentDate.stream().map(b -> b.getElement().getGuest())
                    .collect(Collectors.toCollection(LinkedHashSet::new));
            list = bookingsFilteredByPaymentDate.stream().filter(b -> !b.isCheckOut())
                    .map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            sb = new StringBuilder(e.getKey() + " guest and nights (payed):");
            cnt = 1;
            cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);

                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));

            logger.debug(sb.toString());

        }

        final StatisticsTableBean b = StatisticsTableBean.build(e.getKey().getName(),
                bookingsFilteredByPaymentDate);
        StatisticsTableBean.applyCleaningStuff(b, bookingsFilteredByCleaningDate);
        b.setFixCosts((float) relativeFixCosts);
        b.setNightsPercent(percentage);
        b.setNumberOfPayedNights(numberOfPayedNights);
        b.setNumberOfAllNights(numberOfAllNights);
        b.setNumberOfPayedBookings(numberOfPayedBookings);
        b.setNumberOfAllBookings(numberOfAllBookings);
        data.add(b);
    }
    // add a total row

    final float relativeFixCosts = totalAdditionalCosts;
    final StatisticsTableBean b = StatisticsTableBean.buildSum(data);
    b.setFixCosts(relativeFixCosts);
    b.setNightsPercent(100);
    data.add(b);
}

From source file:edu.mit.lib.mama.Mama.java

private static List<String> findItems(Handle hdl, String qfield, String value, String[] rfields) {
    String queryBase = "select lmv.* from metadatavalue lmv, metadatavalue rmv where "
            + "lmv.item_id = rmv.item_id and rmv.metadata_field_id = ? and rmv.text_value = ? ";
    Query<Map<String, Object>> query;
    if (null == rfields) { // just return default field
        query = hdl.createQuery(queryBase + "and lmv.metadata_field_id = ?").bind(2,
                findFieldId(hdl, URI_FIELD));
    } else { // filter out fields we can't resolve
        String inList = Arrays.asList(rfields).stream().map(f -> String.valueOf(findFieldId(hdl, f)))
                .filter(id -> id != "-1").collect(Collectors.joining(","));
        query = hdl.createQuery(queryBase + "and lmv.metadata_field_id in (" + inList + ")");
    }//from  w ww .  j  a  v  a 2 s .  c o  m
    List<Mdv> rs = query.bind(0, findFieldId(hdl, qfield)).bind(1, value).map(new MdvMapper()).list();
    // group the list by Item, then construct a JSON object with each item's properties
    return rs.stream().collect(Collectors.groupingBy(Mdv::getItemId)).values().stream().map(p -> jsonObject(p))
            .collect(Collectors.toList());
}

From source file:com.intuit.wasabi.tests.service.priority.BasicPriorityTest.java

@Test(groups = { "priorityListChange" }, dependsOnGroups = { "setup",
        "priorityChange" }, dataProvider = "differentApp", dataProviderClass = PriorityDataProvider.class)
public void t_differentApplication(String experiment) {
    response = apiServerConnector.doPost("experiments", experiment);
    LOGGER.debug(response.jsonPath().prettify());
    Experiment result = ExperimentFactory.createFromJSONString(response.jsonPath().prettify());
    String exclusion = "{\"experimentIDs\": [\"" + result.id + "\","
            + validExperimentsLists.stream().map(s -> "\"" + s.id + "\"").collect(Collectors.joining(","))
            + "]}";
    response = apiServerConnector/* ww  w.j a va  2 s  . c  o  m*/
            .doPut("applications/" + validExperimentsLists.get(0).applicationName + "/priorities", exclusion);
    assertReturnCode(response, HttpStatus.SC_NO_CONTENT);
    response = apiServerConnector
            .doGet("applications/" + validExperimentsLists.get(0).applicationName + "/priorities");
    LOGGER.debug("output: " + response.asString());
    assertReturnCode(response, HttpStatus.SC_OK);
    Type listType = new TypeToken<Map<String, ArrayList<Map<String, Object>>>>() {
    }.getType();
    Map<String, List<Map<String, Object>>> resultMap = new Gson().fromJson(response.asString(), listType);
    List<Map<String, Object>> prioritizedExperiments = resultMap.get("prioritizedExperiments");
    Assert.assertEquals(prioritizedExperiments.size(), validExperimentsLists.size());
    response = apiServerConnector.doDelete("experiments/" + result.id);
    assertReturnCode(response, HttpStatus.SC_NO_CONTENT);
}

From source file:com.hubrick.raml.codegen.springweb.RestControllerClassGenerator.java

private static JExpression flushBuffer(List<String> stringBuffer) {
    final String str = stringBuffer.stream().collect(Collectors.joining(""));
    stringBuffer.clear();//from ww  w  .j  ava2s.  c  o m
    return JExpr.lit(str);
}