Example usage for java.util.stream Collectors toMap

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

Introduction

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

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:com.streamsets.pipeline.stage.bigquery.destination.BigQueryTarget.java

/**
 * Convert the sdc Field to an object for row content
 *//*from   w w  w  .ja  v  a  2 s . c o  m*/
private Object getValueFromField(String fieldPath, Field field) {
    LOG.trace("Visiting Field Path '{}' of type '{}'", fieldPath, field.getType());
    switch (field.getType()) {
    case LIST:
        //REPEATED
        List<Field> listField = field.getValueAsList();
        //Convert the list to map with indices as key and Field as value (Map<Integer, Field>)
        Map<Integer, Field> fields = IntStream.range(0, listField.size()).boxed()
                .collect(Collectors.toMap(Function.identity(), listField::get));
        //filter map to remove fields with null value
        fields = fields.entrySet().stream().filter(e -> e.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //now use the map index to generate field path and generate object for big query write
        return fields.entrySet().stream()
                .map(e -> getValueFromField(fieldPath + "[" + e.getKey() + "]", e.getValue()))
                .collect(Collectors.toList());
    case MAP:
    case LIST_MAP:
        //RECORD
        return field.getValueAsMap().entrySet().stream().filter(me -> me.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey,
                        e -> getValueFromField(fieldPath + "/" + e.getKey(), e.getValue())));
    case DATE:
        return dateFormat.format(field.getValueAsDate());
    case TIME:
        return timeFormat.format(field.getValueAsTime());
    case DATETIME:
        return dateTimeFormat.format(field.getValueAsDatetime());
    case BYTE_ARRAY:
        return Base64.getEncoder().encodeToString(field.getValueAsByteArray());
    case DECIMAL:
    case BYTE:
    case CHAR:
    case FILE_REF:
        throw new IllegalArgumentException(
                Utils.format(Errors.BIGQUERY_12.getMessage(), fieldPath, field.getType()));
    default:
        //Boolean -> Map to Boolean in big query
        //Float, Double -> Map to Float in big query
        //String -> maps to String in big query
        //Short, Integer, Long -> Map to integer in big query
        return field.getValue();
    }
}

From source file:com.spankingrpgs.model.characters.GameCharacter.java

/**
 * Performs a deep copy of the specified character.
 *
 * @param gameCharacter  The character to be copied
 *///from w w  w  .j  a va 2 s.co m
public GameCharacter(GameCharacter gameCharacter) {
    this.name = gameCharacter.name;
    this.printedNames = gameCharacter.printedNames.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    this.battleName = gameCharacter.battleName;
    this.description = gameCharacter.description;
    this.gender = gameCharacter.gender;
    this.attackRanges = gameCharacter.attackRanges.stream().map(CombatRange::copy).collect(Collectors.toList());
    this.primaryStatistics = new LinkedHashMap<>(gameCharacter.primaryStatistics.size());
    this.primaryStatistics.putAll(gameCharacter.primaryStatistics);
    this.secondaryStatistics = new LinkedHashMap<>(gameCharacter.secondaryStatistics.size());
    this.secondaryStatistics.putAll(gameCharacter.secondaryStatistics);
    this.equipSlots = new LinkedHashMap<>(gameCharacter.equipSlots.size());
    this.equipSlots.putAll(gameCharacter.equipSlots.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> new EquipSlot(entry.getValue()))));
    this.skills = gameCharacter.skills.entrySet().stream()
            .collect(CollectionUtils.toLinkedHashMap(Map.Entry::getKey, Map.Entry::getValue));
    //Since AppearanceElements are immutable, a shallow copy is sufficient.
    this.appearance = gameCharacter.appearance.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    //Since statuses are immutable, a shallow copy is sufficient
    this.statuses = gameCharacter.statuses.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    this.spankingEvents = gameCharacter.spankingEvents.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    this.bumStatus = gameCharacter.bumStatus.stream().collect(Collectors.toList());
    this.role = gameCharacter.getRole();
}

From source file:de.steilerdev.myVerein.server.controller.admin.UserManagementController.java

/**
 * If a modification on a division needs to be stored durable, this function is invoked by POSTing the parameters to the URI /api/admin/user.
 * @param firstName The first name of the user.
 * @param lastName The last name of the user.
 * @param email The email (unique identifier) of the user.
 * @param birthday The birthday of the user (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param password The initial password of a new user (Only allowed for a new user).
 * @param gender The gender of the user.
 * @param street The street of the user's address.
 * @param streetNumber The street number of the user's address.
 * @param zip The zip code of the user's address.
 * @param city The city of the user's address.
 * @param country The country of the user.
 * @param activeMemberSince The date, when the user became an active member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param passiveMemberSince The date, when the user became a passive member of the club (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param resignationDate The date, when the user resigned (Formatted: d/MM/y according to Java 8 DateTimeFormatter).
 * @param iban The IBAN of the user's bank account.
 * @param bic The BIC of the user's bank account.
 * @param divisions A comma seperated list of divisions, the user is part of.
 * @param userFlag If it is a new user, the user flag is "true", otherwise it is holding the identifier (email) of the user, in case it changed.
 * @param parameters The complete map of all parameters, containing the custom user fields.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *//*from  ww w  . j  a  v  a2  s  .co  m*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@RequestParam String firstName, @RequestParam String lastName,
        @RequestParam String email, @RequestParam String birthday, @RequestParam String password,
        @RequestParam(required = false) String gender, @RequestParam String street,
        @RequestParam String streetNumber, @RequestParam String zip, @RequestParam String city,
        @RequestParam String country, @RequestParam String activeMemberSince,
        @RequestParam String passiveMemberSince, @RequestParam String resignationDate,
        @RequestParam String iban, @RequestParam String bic, @RequestParam String divisions,
        @RequestParam String userFlag, @RequestParam Map<String, String> parameters,
        @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Starting to save a user.");
    User userObject;

    logger.debug("[" + currentUser + "] Loading user");

    if (email.isEmpty() || userFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The email/user flag can not be empty");
        return new ResponseEntity<>("The email can not be empty", HttpStatus.BAD_REQUEST);
    } else if (userFlag.equals("true")) {
        logger.info("[" + currentUser + "] A new user is created using the email " + email);
        if (userRepository.findByEmail(email) == null) {
            userObject = new User();
            if (password.isEmpty()) {
                logger.warn(
                        "[" + currentUser + "] The password of the new user " + email + " can not be empty");
                return new ResponseEntity<>("The password can not be empty", HttpStatus.BAD_REQUEST);
            } else {
                userObject.setPassword(password);
            }
        } else {
            logger.warn("[" + currentUser + "] A user with the given email " + email + " already exists");
            return new ResponseEntity<>("A user with the given email already exists.", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.info("[" + currentUser + "] An existing user " + userFlag + " is modified");
        if ((userObject = userRepository.findByEmail(userFlag)) == null) {
            logger.warn("[{}] Unable to find existing user object", currentUser);
            return new ResponseEntity<>("Unable to retrieve the user", HttpStatus.BAD_REQUEST);
        } else if (!userObject.getEmail().equals(email) && userRepository.findByEmail(email) != null) {
            logger.warn("[{}] The new email {} is already taken", currentUser, email);
            return new ResponseEntity<>("The new email is already taken", HttpStatus.BAD_REQUEST);
        }
    }

    logger.debug("[" + currentUser + "] Checking permissions");

    if (!currentUser.isAllowedToAdministrate(userObject, divisionRepository)) {
        logger.warn("[" + currentUser + "] The user is not allowed to save the user");
        return new ResponseEntity<>("You are not allowed to perform these changes.", HttpStatus.FORBIDDEN);
    }

    logger.debug("[" + currentUser + "] Parsing parameters and updating user");

    if (firstName.isEmpty() || lastName.isEmpty()) {
        logger.warn("[" + currentUser + "] Required parameter missing");
        return new ResponseEntity<>("Required parameter missing", HttpStatus.BAD_REQUEST);
    }
    userObject.setFirstName(firstName);
    userObject.setLastName(lastName);
    userObject.setEmail(email);

    if (!birthday.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing birthday for " + userObject.getEmail());
        try {
            userObject.setBirthday(LocalDate.parse(birthday, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + birthday + ")");
            return new ResponseEntity<>("Wrong date format within birthday field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing birthday field for " + userObject.getEmail());
        userObject.setBirthday(null);
    }

    if (gender != null && !gender.isEmpty() && !gender.equals("default")) {
        logger.debug("[" + currentUser + "] Parsing gender for " + userObject.getEmail());
        try {
            userObject.setGender(User.Gender.valueOf(gender));
        } catch (IllegalArgumentException e) {
            logger.warn("[" + currentUser + "] Unable to parse gender: " + e.getMessage());
            return new ResponseEntity<>("Unable to parse gender", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing gender field for " + userObject.getEmail());
        userObject.setGender(null);
    }

    userObject.setStreet(street);
    userObject.setStreetNumber(streetNumber);
    userObject.setZipCode(zip);
    userObject.setCity(city);
    userObject.setCountry(country);

    if (!activeMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing active member field for " + userObject.getEmail());
        try {
            userObject
                    .setActiveSince(LocalDate.parse(activeMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + activeMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within active member field", HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing active member field for " + userObject.getEmail());
        userObject.setActiveSince(null);
    }

    if (!passiveMemberSince.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing passive member field for " + userObject.getEmail());
        try {
            userObject.setPassiveSince(
                    LocalDate.parse(passiveMemberSince, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + passiveMemberSince + ")");
            return new ResponseEntity<>("Wrong date format within passive member field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing passive member field for " + userObject.getEmail());
        userObject.setPassiveSince(null);
    }

    if (!resignationDate.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing resignation date field for " + userObject.getEmail());
        try {
            userObject.setResignationDate(
                    LocalDate.parse(resignationDate, DateTimeFormatter.ofPattern("d/MM/y")));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format (" + resignationDate + ")");
            return new ResponseEntity<>("Wrong date format within resignation date field",
                    HttpStatus.BAD_REQUEST);
        }
    } else {
        logger.debug("[" + currentUser + "] Clearing resignation date field for " + userObject.getEmail());
        userObject.setResignationDate(null);
    }

    userObject.setIban(iban);
    userObject.setBic(bic);

    if (!divisions.isEmpty()) {
        logger.debug("[" + currentUser + "] Parsing divisions for " + userObject.getEmail());
        String[] divArray = divisions.split(",");
        List<Division> divisionList = new ArrayList<>();
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                return new ResponseEntity<>("Division " + division + " does not exist", HttpStatus.BAD_REQUEST);
            } else {
                divisionList.add(div);
            }
        }
        userObject.replaceDivisions(divisionRepository, eventRepository, divisionList);
    } else {
        logger.debug("[" + currentUser + "] Clearing divisions for " + userObject.getEmail());
        userObject.replaceDivisions(divisionRepository, eventRepository, (List<Division>) null);
    }

    logger.debug("[" + currentUser + "] Parsing and setting custom user fields");
    userObject.setCustomUserField(parameters.keySet().parallelStream()
            .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) //Filtering all custom user fields, which are not empty
            .collect(Collectors.toMap(key -> key.substring(4), key -> parameters.get(key).trim()))); //Creating map of all fields

    logger.debug("[" + currentUser + "] Saving user " + userObject.getEmail());

    try {
        logger.debug("[{}] Saving user {}", currentUser, userObject);
        userRepository.save(userObject);
        logger.info("[" + currentUser + "] Successfully saved user " + userObject.getEmail());
        return new ResponseEntity<>("Successfully saved user", HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: "
                + e.getMessage());
        return new ResponseEntity<>("A database constraint was violated while saving the user.",
                HttpStatus.BAD_REQUEST);
    }
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** (3/3) Merges user generated edges/vertices with the ones already in the system 
 * @param tx//from  w  w w  .j a va2  s . c o m
 * @param config
 * @param security_service
 * @param logger
 * @param maybe_merger
 * @param mergeable
 */
public static void buildGraph_handleMerge(final TitanTransaction tx, final GraphSchemaBean config,
        final Tuple2<String, ISecurityService> security_service, final Optional<IBucketLogger> logger,
        final MutableStatsBean mutable_stats, final Collection<ObjectNode> mutable_new_vertex_keys,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger,
        final DataBucketBean bucket,
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> mergeable) {
    final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper = tx.io(IoCore.graphson())
            .mapper().create().createMapper();
    final Multimap<JsonNode, Edge> mutable_existing_edge_endpoint_store = LinkedHashMultimap.create(); //(lazy simple way of handling 1.3/2)
    final Map<ObjectNode, Vertex> mutable_per_merge_cached_vertices = new HashMap<>();

    mergeable.forEach(t4 -> {

        //TODO (ALEPH-15): handling properties: add new properties and:
        // remove any properties of any vertex/edge over which the user does not have read permission .. and then re-combine later

        final ObjectNode key = t4._1();
        final List<ObjectNode> vertices = t4._2();
        final List<ObjectNode> edges = t4._3();
        final List<Vertex> existing_vertices = t4._4();
        mutable_stats.vertex_matches_found += existing_vertices.size();

        // 1) First step is to sort out the _vertices_, here's the cases:

        // 1.1) If there's no matching vertices then create a new vertex and get the id (via a merge if finalize is set)
        //      (overwrite the _id then map to a Vertex)
        // 1.2) If there are >0 matching vertices (and only one incoming vertex) then we run a merge in which the user "has to do" the following:
        // 1.2.a) pick the winning vertex (or emit the current one to create a "duplicate node"?)
        // 1.2.a.1) (Allow user to delete the others if he has permission, by the usual emit "id" only - but don't automatically do it because it gets complicated what to do with the other _bs)
        // 1.2.b) copy any properties from the original objects into the winner and remove any so-desired properties

        final long prev_created = mutable_stats.vertices_created; //(nasty hack, see below)

        final Optional<Vertex> maybe_vertex_winner = invokeUserMergeCode(tx, config, security_service, logger,
                maybe_merger, titan_mapper, mutable_stats, Vertex.class, bucket.full_name(), key, vertices,
                existing_vertices, Collections.emptyMap()).stream().findFirst();

        maybe_vertex_winner.ifPresent(vertex_winner -> {
            mutable_per_merge_cached_vertices.put(key, vertex_winner);

            //(slighty nasty hack, use stats to see if a vertex was created vs updated...)
            if (mutable_stats.vertices_created > prev_created) {
                mutable_new_vertex_keys.add(key);
            }

            // 1.3) Tidy up (mutate) the edges            

            // 1.3.1) Make a store of all the existing edges (won't worry about in/out, it will sort itself out)

            Stream.of(Optionals.streamOf(vertex_winner.edges(Direction.IN), false),
                    Optionals.streamOf(vertex_winner.edges(Direction.OUT), false),
                    Optionals.streamOf(vertex_winner.edges(Direction.BOTH), false)).flatMap(__ -> __)
                    .forEach(e -> {
                        mutable_existing_edge_endpoint_store.put(key, e);
                    });

            // 1.3.2) Handle incoming edges:

            final Map<ObjectNode, List<ObjectNode>> grouped_edges = finalEdgeGrouping(key, vertex_winner,
                    edges);

            // 2) By here we have a list of vertices and we've mutated the edges to fill in the _inV and _outV
            // 2.1) Now get the potentially matching edges from each of the selected vertices:
            // 2.1.1) If there's no matching edges (and only one incoming edge) then create a new edge (via a merge if finalize is set)
            // 2.1.2) If there are >0 matching edges then run a merge against the edges, pick the current one

            // OK now for any resolved edges (ie grouped_edges), match up with the mutable store (which will be correctly populated by construction):

            grouped_edges.entrySet().stream().forEach(kv -> {

                final Function<String, Map<Object, Edge>> getEdges = in_or_out -> Optionals
                        .ofNullable(mutable_existing_edge_endpoint_store.get(kv.getKey().get(in_or_out)))
                        .stream().filter(e -> labelMatches(kv.getKey(), e))
                        .filter(e -> isAllowed(bucket.full_name(), security_service, e)) // (check authorized)
                        .collect(Collectors.toMap(e -> e.id(), e -> e));
                final Map<Object, Edge> in_existing = getEdges.apply(GraphAnnotationBean.inV);
                final Map<Object, Edge> out_existing = getEdges.apply(GraphAnnotationBean.outV);

                final List<Edge> existing_edges = BucketUtils.isTestBucket(bucket) ? Collections.emptyList()
                        : Stream.of(
                                Maps.difference(in_existing, out_existing).entriesInCommon().values().stream(),
                                in_existing.values().stream().filter(e -> e.inVertex() == e.outVertex()) // (handle the case where an edge starts/ends at the same node)
                ).flatMap(__ -> __).collect(Collectors.toList());

                mutable_stats.edge_matches_found += existing_edges.size();

                invokeUserMergeCode(tx, config, security_service, logger, maybe_merger, titan_mapper,
                        mutable_stats, Edge.class, bucket.full_name(), kv.getKey(), kv.getValue(),
                        existing_edges, mutable_per_merge_cached_vertices);
            });
        });

    });

    //TRACE
    //System.err.println(new Date() + ": VERTICES FOUND = " + mutable_existing_vertex_store);
}

From source file:com.diversityarrays.kdxplore.trials.AddScoringSetDialog.java

public AddScoringSetDialog(Window owner, KdxploreDatabase kdxdb, Trial trial,
        Map<Trait, List<TraitInstance>> instancesByTrait, SampleGroup curatedSampleGroup) {
    super(owner, Msg.TITLE_ADD_SCORING_SET(), ModalityType.APPLICATION_MODAL);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.kdxploreDatabase = kdxdb;
    this.trial = trial;
    this.curatedSampleGroupId = curatedSampleGroup == null ? 0 : curatedSampleGroup.getSampleGroupId();

    Map<Trait, List<TraitInstance>> noCalcs = instancesByTrait.entrySet().stream()
            .filter(e -> TraitDataType.CALC != e.getKey().getTraitDataType())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    Map<Trait, List<TraitInstance>> noCalcsSorted = new TreeMap<>(TRAIT_COMPARATOR);
    noCalcsSorted.putAll(noCalcs);/*from   ww  w  .  jav  a  2 s. c  om*/

    BiFunction<Trait, TraitInstance, String> parentNameProvider = new BiFunction<Trait, TraitInstance, String>() {
        @Override
        public String apply(Trait t, TraitInstance ti) {
            if (ti == null) {
                List<TraitInstance> list = noCalcsSorted.get(t);
                if (list == null || list.size() != 1) {
                    OptionalInt opt = traitInstanceChoiceTreeModel.getChildChosenCountIfNotAllChosen(t);
                    StringBuilder sb = new StringBuilder(t.getTraitName());

                    if (opt.isPresent()) {
                        // only some of the children are chosen
                        int childChosenCount = opt.getAsInt();
                        if (childChosenCount > 0) {
                            sb.append(" (").append(childChosenCount).append(" of ").append(list.size())
                                    .append(")");
                        }
                    } else {
                        // all of the children are chosen
                        if (list != null) {
                            sb.append(" (").append(list.size()).append(")");
                        }
                    }
                    return sb.toString();
                }
            }
            return t.getTraitName();
        }
    };

    Optional<List<TraitInstance>> opt = noCalcsSorted.values().stream().filter(list -> list.size() > 1)
            .findFirst();
    String heading1 = opt.isPresent() ? "Trait/Instance" : "Trait";

    traitInstanceChoiceTreeModel = new ChoiceTreeTableModel<>(heading1, "Use?", //$NON-NLS-1$
            noCalcsSorted, parentNameProvider, childNameProvider);

    //        traitInstanceChoiceTreeModel = new TTChoiceTreeTableModel(instancesByTrait);

    traitInstanceChoiceTreeModel.addChoiceChangedListener(new ChoiceChangedListener() {
        @Override
        public void choiceChanged(Object source, ChoiceNode[] changedNodes) {
            updateCreateAction("choiceChanged");
            treeTable.repaint();
        }
    });

    traitInstanceChoiceTreeModel.addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeStructureChanged(TreeModelEvent e) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent e) {
        }

        @Override
        public void treeNodesInserted(TreeModelEvent e) {
        }

        @Override
        public void treeNodesChanged(TreeModelEvent e) {
            updateCreateAction("treeNodesChanged");
        }
    });

    warningMsg.setText(PLEASE_PROVIDE_A_DESCRIPTION);
    warningMsg.setForeground(Color.RED);

    Container cp = getContentPane();

    Box sampleButtons = null;
    if (curatedSampleGroup != null && curatedSampleGroup.getAnyScoredSamples()) {
        sampleButtons = createWantSampleButtons(curatedSampleGroup);
    }

    Box top = Box.createVerticalBox();
    if (sampleButtons == null) {
        top.add(new JLabel(Msg.MSG_THERE_ARE_NO_CURATED_SAMPLES()));
    } else {
        top.add(sampleButtons);
    }
    top.add(descriptionField);

    cp.add(top, BorderLayout.NORTH);

    descriptionField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }
    });

    updateCreateAction("init");
    //        KDClientUtils.initAction(ImageId.`CHECK_ALL, useAllAction, "Click to Use All");

    treeTable = new JXTreeTable(traitInstanceChoiceTreeModel);
    treeTable.setAutoResizeMode(JXTreeTable.AUTO_RESIZE_ALL_COLUMNS);

    TableCellRenderer renderer = treeTable.getDefaultRenderer(Integer.class);
    if (renderer instanceof JLabel) {
        ((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);
    }

    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(useAllAction));
    buttons.add(new JButton(useNoneAction));

    buttons.add(Box.createHorizontalGlue());
    buttons.add(warningMsg);

    buttons.add(new JButton(cancelAction));
    buttons.add(Box.createHorizontalStrut(10));
    buttons.add(new JButton(createAction));

    cp.add(new JScrollPane(treeTable), BorderLayout.CENTER);
    cp.add(buttons, BorderLayout.SOUTH);

    pack();
}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBeanTest.java

public void testDoModifyXslExportInvalidToken() throws AccessDeniedException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(//from ww w .  j  a va2  s  . com
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    String randomName = getRandomName();
    Map<String, String[]> parameters = new HashMap<>();
    parameters.put("title", new String[] { randomName });
    parameters.put("description", new String[] { randomName });
    parameters.put("extension", new String[] { randomName });
    parameters.put("id_xsl_export", new String[] { Integer.toString(_xslExport.getIdXslExport()) });
    parameters.put(SecurityTokenService.PARAMETER_TOKEN, new String[] {
            SecurityTokenService.getInstance().getToken(request, "admin/xsl/modify_xsl_export.html") + "b" });
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();

    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    try {
        _instance.doModifyXslExport(new MultipartHttpServletRequest(request, multipartFiles, parameters));
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        XslExport stored = XslExportHome.findByPrimaryKey(_xslExport.getIdXslExport());
        assertNotNull(stored);
        assertEquals(_xslExport.getTitle(), stored.getTitle());
        assertEquals(_xslExport.getDescription(), stored.getDescription());
        assertEquals(_xslExport.getExtension(), stored.getExtension());
    }
}

From source file:com.streamsets.datacollector.creation.PipelineBeanCreator.java

/**
 * Creates additional PipelineStageBeans for additional runners. Stages will share stage definition and thus
 * class loader with the first given runner. That includes stages with private class loader as well.
 *
 * @param pipelineStageBeans First runner that should be duplicated.
 * @param interceptorCreatorContextBuilder Builder for interceptor context
 * @param constants Pipeline constants//from www. j  a v  a2s .  com
 * @param errors Any generated errors will be stored in this list
 *
 * @return PipelineStageBeans with new instances of the given stages
 */
public PipelineStageBeans duplicatePipelineStageBeans(StageLibraryTask stageLib,
        PipelineStageBeans pipelineStageBeans,
        InterceptorCreatorContextBuilder interceptorCreatorContextBuilder, Map<String, Object> constants,
        List<Issue> errors) {
    List<StageBean> stageBeans = new ArrayList<>(pipelineStageBeans.size());

    for (StageBean original : pipelineStageBeans.getStages()) {

        // Create StageDefinition map for this stage
        Map<Class, ServiceDefinition> services = original.getServices().stream()
                .collect(Collectors.toMap(c -> c.getDefinition().getProvides(), ServiceBean::getDefinition));

        StageBean stageBean = createStage(stageLib, original.getDefinition(), ClassLoaderReleaser.NOOP_RELEASER,
                original.getConfiguration(), services::get, interceptorCreatorContextBuilder, constants,
                errors);

        if (stageBean != null) {
            stageBeans.add(stageBean);
        }
    }

    return new PipelineStageBeans(stageBeans);
}

From source file:org.ligoj.app.plugin.prov.azure.in.ProvAzurePriceImportResource.java

private void installComputePrices(final UpdateContext context, final String termName, final int period)
        throws IOException {
    final Node node = context.getNode();
    nextStep(node, String.format(STEP_COMPUTE, termName, "initialize"), 1);

    // Get or create the term
    List<ProvInstancePriceTerm> terms = iptRepository.findAllBy(BY_NODE, node.getId());
    final ProvInstancePriceTerm term = terms.stream().filter(p -> p.getName().equals(termName)).findAny()
            .orElseGet(() -> {//from   w  w  w.j  a  v  a  2  s  . c o m
                final ProvInstancePriceTerm newTerm = new ProvInstancePriceTerm();
                newTerm.setName(termName);
                newTerm.setNode(node);
                newTerm.setPeriod(period);
                newTerm.setCode(termName);
                iptRepository.saveAndFlush(newTerm);
                return newTerm;
            });

    // Special "LOW PRIORITY" sub term of Pay As you Go
    final ProvInstancePriceTerm termLow = terms.stream().filter(p -> p.getName().equals(TERM_LOW)).findAny()
            .orElseGet(() -> {
                final ProvInstancePriceTerm newTerm = new ProvInstancePriceTerm();
                newTerm.setName(TERM_LOW);
                newTerm.setNode(node);
                newTerm.setEphemeral(true);
                newTerm.setPeriod(0);
                newTerm.setCode(TERM_LOW);
                iptRepository.saveAndFlush(newTerm);
                return newTerm;
            });

    // Get previous prices
    context.setPrevious(ipRepository.findAllBy("term.id", term.getId()).stream()
            .collect(Collectors.toMap(ProvInstancePrice::getCode, Function.identity())));
    if (context.getPreviousLowPriority() == null) {
        context.setPreviousLowPriority(ipRepository.findAllBy("term.id", termLow.getId()).stream()
                .collect(Collectors.toMap(ProvInstancePrice::getCode, Function.identity())));
    }

    // Fetch the remote prices stream and build the prices object
    nextStep(node, String.format(STEP_COMPUTE, termName, "retrieve-catalog"), 1);
    try (CurlProcessor curl = new CurlProcessor()) {
        final String rawJson = StringUtils.defaultString(curl.get(getVmApi(termName)), "{}");
        final ComputePrices prices = objectMapper.readValue(rawJson, ComputePrices.class);
        nextStep(node, String.format(STEP_COMPUTE, termName, "update"), 1);
        prices.getOffers().entrySet().stream().forEach(e -> installInstancesTerm(context, term, termLow, e));
    }
}

From source file:com.streamsets.pipeline.lib.el.StringEL.java

@ElFunction(prefix = "str", name = "splitKV", description = "Splits key value pairs into a map")
public static Map<String, Field> splitKV(@ElParam("string") String string,
        @ElParam("pairSeparator") String separator, @ElParam("kvSeparator") String kvSeparator) {
    if (Strings.isNullOrEmpty(string)) {
        return Collections.emptyMap();
    }/* w  w  w  .j a v a  2 s  . c  om*/

    Splitter.MapSplitter splitter = Splitter.on(separator).trimResults().omitEmptyStrings()
            .withKeyValueSeparator(Splitter.on(kvSeparator).limit(2));

    return splitter.split(string).entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> Field.create(e.getValue())));
}

From source file:com.bjond.utilities.MiscUtils.java

/**
  * Returns the Map of non null properties 
  */*from  w ww . ja v  a 2  s . c o  m*/
 * @param o A bean with get and set methods for its properties.
 * @return Map of property name to its value
 * @throws Exception on introspection errors.
 */
public static Map<String, Object> getNonNullProperties(final Object o) throws Exception {
    return getProperties(o).stream().filter(Unchecked.predicate(k -> getPropertyValue(o, k) != null))
            .collect(Collectors.toMap(Function.identity(), Unchecked.function(k -> getPropertyValue(o, k))));
}