Example usage for java.util LinkedHashSet add

List of usage examples for java.util LinkedHashSet add

Introduction

In this page you can find the example usage for java.util LinkedHashSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:restaurant.dozer.custom.mapper.CustomMappingProcessor.java

private Set<?> addToSet(Object srcObj, FieldMap fieldMap, Collection<?> srcCollectionValue, Object destObj) {
    // create a list here so we can keep track of which elements we have
    // mapped, and remove all others if removeOrphans = true
    Set<Object> mappedElements = new HashSet<Object>();

    LinkedHashSet<Object> result = new LinkedHashSet<Object>();
    // don't want to create the set if it already exists.
    Object field = fieldMap.getDestValue(destObj);
    if (field != null) {
        result.addAll((Collection<?>) field);
    }//from   ww  w  . j a v a  2s .  c  om
    Object destValue;

    Class<?> destEntryType = null;
    Class<?> prevDestEntryType = null;
    for (Object srcValue : srcCollectionValue) {
        if (destEntryType == null || (fieldMap.getDestHintContainer() != null
                && fieldMap.getDestHintContainer().hasMoreThanOneHint())) {
            destEntryType = determineCollectionItemType(fieldMap, destObj, srcValue, prevDestEntryType);
        }

        CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences();
        if (srcValue != null && copyByReferences.contains(srcValue.getClass())) {
            destValue = srcValue;
        } else {
            destValue = mapOrRecurseObject(srcObj, srcValue, destEntryType, fieldMap, destObj);
        }
        prevDestEntryType = destEntryType;

        if (RelationshipType.NON_CUMULATIVE.equals(fieldMap.getRelationshipType())
                && result.contains(destValue)) {
            List<Object> resultAsList = new ArrayList<Object>(result);
            int index = resultAsList.indexOf(destValue);
            // perform an update if complex type - can't map strings
            Object obj = resultAsList.get(index);
            // make sure it is not a String
            if (!obj.getClass().isAssignableFrom(String.class)) {
                mapToDestObject(null, srcValue, obj, false, fieldMap.getMapId());
                mappedElements.add(obj);
            }
        } else {
            if (destValue != null || fieldMap.isDestMapNull()) {
                result.add(destValue);
            }
            mappedElements.add(destValue);
        }
    }

    // If remove orphans - we only want to keep the objects we've mapped
    // from the src collection
    // so we'll clear result and replace all entries with the ones in
    // mappedElements
    if (fieldMap.isRemoveOrphans()) {
        result.clear();
        result.addAll(mappedElements);
    }

    if (field == null) {
        Class<? extends Set<?>> destSetType = (Class<? extends Set<?>>) fieldMap
                .getDestFieldType(destObj.getClass());
        return CollectionUtils.createNewSet(destSetType, result);
    } else {
        // Bug #1822421 - Clear first so we don't end up with the removed
        // orphans again
        ((Set) field).clear();
        ((Set) field).addAll(result);
        return (Set<?>) field;
    }
}

From source file:org.alfresco.solr.SolrInformationServer.java

private void updateDescendantDocs(NodeMetaData parentNodeMetaData, boolean overwrite, SolrQueryRequest request,
        UpdateRequestProcessor processor, LinkedHashSet<Long> stack)
        throws AuthenticationException, IOException, JSONException {
    if (stack.contains(parentNodeMetaData.getId())) {
        log.warn("Found descendant data loop for node id " + parentNodeMetaData.getId());
        log.warn("... stack to node =" + stack);
        return;/* ww  w .ja va2 s.c om*/
    } else {
        try {
            stack.add(parentNodeMetaData.getId());
            doUpdateDescendantDocs(parentNodeMetaData, overwrite, request, processor, stack);
        } finally {
            stack.remove(parentNodeMetaData.getId());
        }
    }
}

From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java

private String generateSimEncapsuation(final Unit unit, final Iterable<Row> rows) {
    final Set<String> varNames = new LinkedHashSet<String>();
    final Procedure1<Row> _function = new Procedure1<Row>() {
        public void apply(final Row it) {
            List<Definition> _allDefs = CCodeGenerator.this.ba.allDefs(it);
            final Function1<Definition, Boolean> _function = new Function1<Definition, Boolean>() {
                public Boolean apply(final Definition it) {
                    return Boolean.valueOf((it.type != Definition.Type.UNUSED));
                }/* w w w .j ava2 s.co m*/
            };
            Iterable<Definition> _filter = IterableExtensions.<Definition>filter(_allDefs, _function);
            final Procedure1<Definition> _function_1 = new Procedure1<Definition>() {
                public void apply(final Definition it) {
                    String _name = it.getName();
                    varNames.add(_name);
                }
            };
            IterableExtensions.<Definition>forEach(_filter, _function_1);
        }
    };
    IterableExtensions.<Row>forEach(rows, _function);
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("/**");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* @file");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* @brief  Provides methods for simulating accessing to the memory registers");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* This file is a substitue for the BusAccess.c file that is used to access real memory.");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* For each type of row there are methods for setting/getting the values");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* either directly, or as a struct. A memory map overview has been");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* generated into BusMap.html.");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*/");
    _builder.newLine();
    _builder.newLine();
    _builder.append("#include <stdint.h>");
    _builder.newLine();
    _builder.append("#include <stdbool.h>");
    _builder.newLine();
    _builder.append("#include \"BusAccess.h\"");
    _builder.newLine();
    _builder.append("#include \"BusStdDefinitions.h\"");
    _builder.newLine();
    _builder.append("#include \"");
    String _headerName = this.headerName();
    _builder.append(_headerName, "");
    _builder.append(".h\"");
    _builder.newLineIfNotEmpty();
    _builder.newLine();
    _builder.append("/**");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* This method provides a null implementation of the warning functionality. You");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* can use it to provide your own error handling, or you can use the implementation");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* provided in BusPrint.h");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*/");
    _builder.newLine();
    _builder.append(
            "static void defaultWarn(warningType_t t, uint64_t value, char *def, char *row, char *msg){");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    _builder.newLine();
    _builder.append("warnFunc_p warn=defaultWarn;");
    _builder.newLine();
    _builder.newLine();
    _builder.append("/**");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* This methods allows the user to set a custom warning function. Usually this is used");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* in conjunction with the implementation provided in BusPrint.h.");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* @param warnFunction the new function to use for error reporting");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* Example Usage:");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* @code");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*    #include \"BusPrint.h\"");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*    setWarn(defaultPrintfWarn);");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("* @endcode");
    _builder.newLine();
    _builder.append(" ");
    _builder.append("*/");
    _builder.newLine();
    _builder.append("void setWarn(warnFunc_p warnFunction){");
    _builder.newLine();
    _builder.append("    ");
    _builder.append("warn=warnFunction;");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    _builder.newLine();
    _builder.append("///The index of the Clock that is toggled for each setting");
    _builder.newLine();
    _builder.append("#define ");
    _builder.append("busclk_idx", "");
    _builder.append(" ");
    int _busIndex = this.getBusIndex();
    _builder.append(_busIndex, "");
    _builder.newLineIfNotEmpty();
    _builder.newLine();
    String res = _builder.toString();
    final LinkedHashSet<String> checkedRows = new LinkedHashSet<String>();
    final LinkedHashMap<String, Integer> rowCounts = new LinkedHashMap<String, Integer>();
    for (final Row row : rows) {
        {
            final Integer idx = rowCounts.get(row.name);
            boolean _tripleEquals = (idx == null);
            if (_tripleEquals) {
                rowCounts.put(row.name, Integer.valueOf(1));
            } else {
                rowCounts.put(row.name, Integer.valueOf(((idx).intValue() + 1)));
            }
        }
    }
    for (final Row row_1 : rows) {
        boolean _contains = checkedRows.contains(row_1.name);
        boolean _not = (!_contains);
        if (_not) {
            boolean _hasWriteDefs = this.ba.hasWriteDefs(row_1);
            if (_hasWriteDefs) {
                Integer _get = rowCounts.get(row_1.name);
                CharSequence _simSetter = this.simSetter(row_1, (_get).intValue());
                String _plus = (res + _simSetter);
                res = _plus;
            }
            Integer _get_1 = rowCounts.get(row_1.name);
            CharSequence _simGetter = this.simGetter(row_1, (_get_1).intValue());
            String _plus_1 = (res + _simGetter);
            res = _plus_1;
            checkedRows.add(row_1.name);
        }
    }
    return res;
}

From source file:co.paralleluniverse.galaxy.core.Cache.java

private void addPendingMessage(CacheLine line, LineMessage message) {
    LinkedHashSet<LineMessage> msgs = pendingMessages.get(line.getId());
    if (msgs == null) {
        msgs = new LinkedHashSet<LineMessage>();
        pendingMessages.put(line.getId(), msgs);
    }//from   w w w.  j  a  v a2s . c  o m
    msgs.add(message);
    if (LOG.isDebugEnabled())
        LOG.debug("addPendingMessage {} to line {}", message, line);
}

From source file:org.sakaiproject.tool.assessment.services.GradingService.java

/**
 * extractCalculatedQuestionKeyFromItemText() is a utility function for Calculated Questions.  It 
 * takes a block of item text, and uses a pattern to looks for keys 
 * that are encoded in the text./*from   w w  w .  j ava 2  s  .  c om*/
 * @param itemText content to be searched
 * @param identifierPattern pattern to use to do the search
 * @return a list of matching key values OR empty if none are found
 */
private List<String> extractCalculatedQuestionKeyFromItemText(String itemText, Pattern identifierPattern) {
    LinkedHashSet<String> keys = new LinkedHashSet<String>();
    if (itemText != null && itemText.trim().length() > 0) {
        Matcher keyMatcher = identifierPattern.matcher(itemText);
        while (keyMatcher.find()) {
            String match = keyMatcher.group(1);
            keys.add(match);
            /*
            // first character before matching group
            int start = keyMatcher.start(1) - 2;
            // first character after matching group
            int end = keyMatcher.end(1) + 1; // first character after the matching group
            // if matching group is wrapped by {}, it's not what we are looking for (like another key or just some text)
            if (start < 0 || end >= itemText.length() || itemText.charAt(start) != '{' || itemText.charAt(end) != '}') {
                keys.add(match);
            }*/
        }
    }
    return new ArrayList<String>(keys);
}

From source file:org.sakaiproject.content.tool.ListItem.java

/**
 * Asks the Server Configuration Service to get a list of available roles with the prefix "resources.enabled.roles""
 * We should expect language strings for these to be defined in the bundles.
 * @return a set of role ids that can be used
 *///ww w  .  j  a  va  2s.  c  o  m
public Set<String> availableRoleIds() {
    String[] configStrings = ServerConfigurationService.getStrings("resources.enabled.roles");

    LinkedHashSet<String> availableIds = new LinkedHashSet<String>();

    if (configStrings != null) {
        availableIds.addAll(Arrays.asList(configStrings));
    } else {
        // By default just include the public
        availableIds.add(PUBVIEW_ROLE);
    }

    return availableIds;
}

From source file:istata.service.StataService.java

/**
 * produce a list with possible sidebar suggestions for the current context
 * /*from  ww w .j  a  va2s  . co m*/
 * @param filter
 * @param pos
 * @param from
 * @param to
 * @return
 */
public List<ContentLine> suggest(String filter, int pos, int from, int to) {
    LinkedHashSet<ContentLine> res = new LinkedHashSet<ContentLine>();

    ArrayList<ContentLine> rescmd = new ArrayList<ContentLine>();
    {
        int i = 0;
        for (ContentLine cl : cmdRepository.findAll()) {
            if (cl.getContent().startsWith(filter)) {
                ContentLine srl = new ContentLine();
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("cmd", cl);
                model.put("from", from);
                model.put("to", to);

                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/cmd.vm",
                        "UTF-8", model);

                srl.setContent(text);
                srl.setLine(i++);
                rescmd.add(srl);
            }
        }
    }

    Collections.reverse(rescmd);

    res.addAll(rescmd.subList(0, Math.min(10, rescmd.size())));

    List<ContentLine> out = new ArrayList<ContentLine>();

    try {
        IStata stata = stataFactory.getInstance();

        /*
         * get files
         */
        Collection<ContentLine> filesNames = filteredFiles(filter, pos, from, to);
        res.addAll(filesNames);

        /*
         * get VARS, should be a mothod call probably
         */

        // current token
        StringBuilder token = new StringBuilder("");
        StringBuilder rest = new StringBuilder(filter);
        int p = (pos == -1 || pos > filter.length()) ? filter.length() : pos;
        char ch = 'x';
        while (p > 0 && (CharUtils.isAsciiAlphanumeric(ch = filter.charAt(p - 1)) || ch == '_')) {
            token.insert(0, ch);
            rest.deleteCharAt(p - 1);
            p--;
        }

        // remove rest of potential token
        while (rest.length() > 0 && p > 0 && p < rest.length()
                && (CharUtils.isAsciiAlphanumeric(rest.charAt(p)) || rest.charAt(p) == '_')) {
            rest.deleteCharAt(p);
        }

        String t = token.toString();

        List<StataVar> list = new ArrayList<StataVar>();
        List<StataVar> listfull = stata.getVars("", false);
        if (t.length() > 0) {
            for (StataVar sv : listfull) {
                if (sv.getName().startsWith(t)) {
                    list.add(sv);
                }
            }
        } else {
            list = listfull;
        }

        for (int i = 0; i < list.size(); i++) {
            ContentLine srl = new ContentLine();
            srl.setLine(i + 100);
            String vname = list.get(i).getName();
            String cl = new StringBuilder(rest).insert(p, " ").insert(p, vname).toString();
            try {
                String cc = URLEncoder.encode(cl, "UTF-8");
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("var", vname);
                model.put("repl", cc);
                model.put("focuspos", p + 1 + vname.length());
                model.put("from", from);
                model.put("to", to);

                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/var.vm",
                        "UTF-8", model);

                srl.setContent(text);
                res.add(srl);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (StataNotRunningException e) {
        ContentLine srl = new ContentLine();
        srl.setLine(1);
        srl.setContent(
                "<div class='list-group-item sidebaritem error' >" + "Stata not running, you can try to start "
                        + "an instance by clicking " + "<a target='_blank' href='/start'>here</a>" + "</div>");
        out.add(srl);
    } catch (StataBusyException e1) {
        ContentLine srl = new ContentLine();
        srl.setLine(1);
        srl.setContent("<div class='list-group-item sidebaritem error' >"
                + "Stata appears to by busy or not running, you can try to "
                + "start a new instance by clicking " + "<a target='_blank' href='/start'>here</a> "
                + "or wait for the current job to complete</div>");
        out.add(srl);
    }

    out.addAll(res);
    return out;
}

From source file:snpviewer.SnpViewer.java

public void autoFindRegions() {
    if (affObserve.isEmpty()) {
        Dialogs.showErrorDialog(null,//from w  ww.  j  a va  2  s.  com
                "Find Regions can only be run when there "
                        + "is at least one Affected sample in the project.  Use the "
                        + "'Add Affected' button/menu item to add  Affected samples.",
                "No Affected samples to analyze!", "SnpViewer");
        return;
    }
    Stage stage = new Stage();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FindRegionsInterface.fxml"));
    try {
        Pane page = (Pane) loader.load();
        FindRegionsInterfaceController findReg = (FindRegionsInterfaceController) loader.getController();
        Scene scene = new Scene(page);
        stage.setScene(scene);
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        setProgressMode(true);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        stage.showAndWait();
        if (findReg.getCancelled()) {
            setProgressMode(false);
            return;
        }

        //int w, double r, boolean con, int refWind, double refCut,
        //int minReportSize, int minReportRun, double het, double dischord)
        int window = Integer.parseInt(findReg.getWindow());
        double regionLength = Double.parseDouble(findReg.getRegionLength());
        boolean checkConcordant = findReg.getCheckConcordance();
        int refineWindow = Integer.parseInt(findReg.getRefineSize());
        double refineTolerance = Double.parseDouble(findReg.getRefineTolerance());
        int minReport = Integer.parseInt(findReg.getReportLength());
        int minReportRun = Integer.parseInt(findReg.getReportMinSnps());
        double hetTolerance = Double.parseDouble(findReg.getHetTolerance());
        double dischordTolerance = Double.parseDouble(findReg.getDischordTolerance());
        boolean autosomesOnly = findReg.getAutosomesOnly();
        LinkedHashSet<String> c = new LinkedHashSet();
        for (Object item : chromosomeSelector.getItems()) {
            if (item instanceof String) {
                String chrom = (String) item;
                if (autosomesOnly) {
                    if (chrom.matches("\\d+")) {//only add autosomes
                        c.add(chrom);
                    }
                } else {
                    c.add(chrom);
                }
            }
        }

        final RegionFinder regionFinder = new RegionFinder(c, affFiles, unFiles, window, regionLength,
                checkConcordant, refineWindow, refineTolerance, minReport, minReportRun, hetTolerance,
                dischordTolerance);

        regionFinder.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Done");
                progressTitle.textProperty().unbind();
                setProgressMode(false);
                Object result = t.getSource().getValue();
                ArrayList<RegionSummary> foundRegions = new ArrayList<>();
                if (result instanceof ArrayList) {
                    for (Object r : (ArrayList) result) {
                        if (r instanceof RegionSummary) {
                            RegionSummary reg = (RegionSummary) r;
                            foundRegions.add(reg);
                        }
                    }
                    if (foundRegions.size() > 0) {
                        FXMLLoader tableLoader = new FXMLLoader(
                                getClass().getResource("MultiRegionReporter.fxml"));
                        try {
                            Pane tablePane = (Pane) tableLoader.load();
                            MultiRegionReporterController multiReg = (MultiRegionReporterController) tableLoader
                                    .getController();
                            Scene tableScene = new Scene(tablePane);
                            Stage tableStage = new Stage();
                            tableStage.setScene(tableScene);
                            tableScene.getStylesheets().add(
                                    SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
                            multiReg.displayData(foundRegions);
                            tableStage.setTitle("Find Regions Results");
                            tableStage.getIcons()
                                    .add(new Image(this.getClass().getResourceAsStream("icon.png")));
                            tableStage.initModality(Modality.NONE);
                            tableStage.show();
                        } catch (Exception ex) {
                            Dialogs.showErrorDialog(null,
                                    "Error displaying" + " results from Find Regions Method.",
                                    "Find Regions Error!", "SnpViewer", ex);
                        }
                    } else {
                        Dialogs.showInformationDialog(null, "No regions " + "found.", "Find Regions",
                                "SnpViewer");
                    }
                    savedRegions.addAll(foundRegions);
                    RegionSummary sorter = new RegionSummary();
                    sorter.mergeRegionsByPosition(savedRegions);
                }
                saveProject();
                int c = chromosomeSelector.getSelectionModel().getSelectedIndex();
                if (c > -1) {
                    selectionOverlayPane.getChildren().clear();
                    selectionOverlayPane.getChildren().add(dragSelectRectangle);
                    drawSavedRegions((String) chromosomeBoxList[c]);
                }
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Failed!");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method failed.", "Error!", "SnpViewer",
                        t.getSource().getException());
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Cancelled");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method Cancelled.", "Cancelled", "SnpViewer");
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);

            }
        });
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                regionFinder.cancel();

            }
        });
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        progressBar.progressProperty().bind(regionFinder.progressProperty());
        progressMessage.textProperty().bind(regionFinder.messageProperty());
        progressTitle.textProperty().bind(regionFinder.titleProperty());
        regionFinder.start();

    } catch (IOException ex) {
        Dialogs.showErrorDialog(null, "Error starting Find Regions method.", "Error!", "SnpViewer", ex);
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        setProgressMode(false);
    }

}

From source file:org.sakaiproject.evaluation.logic.EvalAuthoringServiceImpl.java

public Long[] copyTemplateItems(Long[] templateItemIds, String ownerId, boolean hidden, Long toTemplateId,
        boolean includeChildren) {
    if (ownerId == null || ownerId.length() == 0) {
        throw new IllegalArgumentException("Invalid ownerId, cannot be null or empty string");
    }/*from  w  ww .j a  va 2 s.  c  om*/
    if (templateItemIds == null || templateItemIds.length == 0) {
        throw new IllegalArgumentException("Invalid templateItemIds array, cannot be null or empty");
    }

    templateItemIds = ArrayUtils.unique(templateItemIds);
    EvalTemplate toTemplate = null;
    if (toTemplateId != null) {
        toTemplate = getTemplateById(toTemplateId);
        if (toTemplate == null) {
            throw new IllegalArgumentException(
                    "Invalid toTemplateId, cannot find the template by this id: " + toTemplateId);
        }
    }

    List<EvalTemplateItem> templateItemsList = dao.findBySearch(EvalTemplateItem.class,
            new Search("id", templateItemIds));
    if (templateItemsList.size() != templateItemIds.length) {
        throw new IllegalArgumentException("Invalid templateItemIds in array: " + templateItemIds);
    }

    // now we check that copying into the originating template is correct and ensure the toTemplate is set
    if (toTemplate == null) {
        // all templateItems must be from the same template if this is the case
        for (EvalTemplateItem templateItem : templateItemsList) {
            Long templateId = templateItem.getTemplate().getId();
            if (toTemplate == null) {
                toTemplate = getTemplateById(templateId);
            } else {
                if (!toTemplate.getId().equals(templateId)) {
                    throw new IllegalArgumentException(
                            "All templateItems must be from the same template when doing a copy within a template, "
                                    + "if you want to copy templateItems from multiple templates into the same templates they are currently in you must "
                                    + "do it in batches where each set if from one template");
                }
            }
        }
    }

    // sort the list of template items
    templateItemsList = TemplateItemUtils.orderTemplateItems(templateItemsList, false);

    int itemCount = 1; // start at display order 1
    if (toTemplateId == null && toTemplate != null) {
        // copying inside one template so start at the item count + 1
        // get the count of items in the destination template so we know where to start displayOrder from
        itemCount = getItemCountForTemplate(toTemplate.getId()) + 1;
    }

    /* http://bugs.sakaiproject.org/jira/browse/EVALSYS-689
     * need to track the copied items and scales to avoid copying them more than once
     */
    LinkedHashSet<EvalTemplateItem> copiedTemplateItems = new LinkedHashSet<>(templateItemsList.size());

    // shallow copy all block parents first so we can know their new IDs, then later we will update them
    List<EvalTemplateItem> parentItems = TemplateItemUtils.getParentItems(templateItemsList);
    HashMap<Long, EvalTemplateItem> parentIdToCopy = new HashMap<>(parentItems.size());
    if (!parentItems.isEmpty()) {
        for (EvalTemplateItem original : parentItems) {
            Long originalBlockParentId = original.getId();
            List<EvalTemplateItem> childItems = TemplateItemUtils.getChildItems(templateItemsList,
                    originalBlockParentId);
            if (childItems.size() > 0) {
                // only copy this if it has children, lone parents do not get copied
                EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
                parentIdToCopy.put(originalBlockParentId, copy);
            }
        }
        HashSet<EvalTemplateItem> parentItemsToSave = new HashSet<>(parentIdToCopy.values());
        dao.saveSet(parentItemsToSave);
    }

    // check for block items
    List<EvalTemplateItem> nonChildItems = TemplateItemUtils.getNonChildItems(templateItemsList);

    // iterate though in display order and copy the template items
    int displayOrder = 0;
    for (EvalTemplateItem original : nonChildItems) {
        templateItemsList.remove(original); // take this out of the list
        if (TemplateItemUtils.isBlockParent(original)) {
            // this is a block parent so copy it and its children
            Long originalBlockParentId = original.getId();
            if (parentIdToCopy.containsKey(originalBlockParentId)) {
                EvalTemplateItem copyParent = parentIdToCopy.get(originalBlockParentId);
                copyParent.setDisplayOrder(itemCount + displayOrder); // fix up display order
                copyParent.setBlockId(null);
                copyParent.setBlockParent(true);
                //dao.save(copyParent);
                copiedTemplateItems.add(copyParent);
                Long blockParentId = copyParent.getId();

                // loop through and copy all the children and assign them to the parent
                List<EvalTemplateItem> childItems = TemplateItemUtils.getChildItems(templateItemsList,
                        originalBlockParentId);
                for (int j = 0; j < childItems.size(); j++) {
                    EvalTemplateItem child = childItems.get(j);
                    templateItemsList.remove(child); // take this out of the list
                    // copy the child item
                    EvalTemplateItem copy = copyTemplateItem(child, toTemplate, ownerId, hidden);
                    copy.setDisplayOrder(j); // fix up display order
                    copy.setBlockId(blockParentId);
                    copy.setBlockParent(false);
                    //dao.save(copy);
                    copiedTemplateItems.add(copy);
                }
            }
        } else {
            // not a block parent
            EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
            copy.setDisplayOrder(itemCount + displayOrder); // fix up display order
            //dao.save(copy);
            copiedTemplateItems.add(copy);
        }
        displayOrder++;
    }

    // now copy any remaining orphaned block children into normal items
    for (EvalTemplateItem original : templateItemsList) {
        displayOrder++;
        EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
        copy.setDisplayOrder(itemCount + displayOrder); // fix up display order
        //dao.save(copy);
        copiedTemplateItems.add(copy);
    }

    if (includeChildren) {
        // make a copy of all items and put them into the TIs to replace the originals
        HashSet<Long> itemIdSet = new HashSet<>();
        for (EvalTemplateItem eti : copiedTemplateItems) {
            if (eti.getItem() != null) {
                Long itemId = eti.getItem().getId();
                itemIdSet.add(itemId);
            }
        }
        Long[] itemIds = itemIdSet.toArray(new Long[itemIdSet.size()]);
        // do the items copy
        Set<EvalItem> copiedItems = copyItemsInternal(itemIds, ownerId, hidden, includeChildren);
        HashMap<Long, EvalItem> originalIdToCopy = new HashMap<>(copiedItems.size());
        for (EvalItem evalItem : copiedItems) {
            originalIdToCopy.put(evalItem.getCopyOf(), evalItem);
        }
        // insert the copied items into the copied template items (update the foreign keys when we save)
        for (EvalTemplateItem eti : copiedTemplateItems) {
            if (eti.getItem() != null) {
                Long itemId = eti.getItem().getId(); // original id
                EvalItem copy = originalIdToCopy.get(itemId);
                if (copy != null) {
                    eti.setItem(copy);
                }
            }
        }
    }
    // save the template items
    dao.saveSet(copiedTemplateItems);

    Long[] copiedIds = new Long[copiedTemplateItems.size()];
    int counter = 0;
    for (EvalTemplateItem copiedTemplateItem : copiedTemplateItems) {
        copiedIds[counter] = copiedTemplateItem.getId();
        counter++;
    }
    return copiedIds;
}

From source file:com.sonicle.webtop.calendar.CalendarManager.java

@Override
public void updateEventObject(int calendarId, String href, net.fortuna.ical4j.model.Calendar iCalendar)
        throws WTException {
    final UserProfile.Data udata = WT.getUserData(getTargetProfileId());
    int eventId = getEventIdByCategoryHref(calendarId, href, true);

    ICalendarInput in = new ICalendarInput(udata.getTimeZone()).withDefaultAttendeeNotify(true)
            .withIncludeVEventSourceInOutput(true);
    ArrayList<EventInput> eis = in.fromICalendarFile(iCalendar, null);
    if (eis.isEmpty())
        throw new WTException("iCalendar object does not contain any events");

    EventInput refInput = eis.remove(0);
    if (refInput.exRefersToPublicUid != null)
        throw new WTException("First iCalendar event should not have a RECURRENCE-ID set");

    // Collect dates exceptions and prepare broken event to be inserted
    ArrayList<EventInput> eiExs = new ArrayList<>();
    LinkedHashSet<LocalDate> exDates = new LinkedHashSet<>();
    for (EventInput ei : eis) {
        if (!StringUtils.equals(ei.exRefersToPublicUid, refInput.event.getPublicUid()))
            continue;
        if (exDates.contains(ei.addsExOnMaster))
            continue;

        exDates.add(ei.addsExOnMaster);
        if (!ei.isSourceEventCancelled())
            eiExs.add(ei);/* ww  w.  j  a  v a2  s .  c o  m*/
    }

    // Adds new collected exceptions and then updates master event
    if (!exDates.isEmpty()) {
        if (refInput.event.hasExcludedDates()) {
            refInput.event.getExcludedDates().addAll(exDates);
        } else {
            refInput.event.setExcludedDates(exDates);
        }
    }
    refInput.event.setEventId(eventId);
    refInput.event.setCalendarId(calendarId);
    refInput.event.setExcludedDates(exDates);
    updateEvent(refInput.event, true);

    // Here we do not support creating broken events related to the
    // main event series (re-attach unavailable). Instance exceptions 
    // should have been created above as date exception into the main
    // event; so simply create exceptions as new events.

    if (!eiExs.isEmpty()) {
        for (EventInput eiEx : eiExs) {
            eiEx.event.setCalendarId(calendarId);
            eiEx.event.setPublicUid(null); // reset uid
            //TODO: handle raw value to persist custom properties
            try {
                addEvent(eiEx.event, null, true);
            } catch (Throwable t) {
                logger.error("Unable to insert exception on {} as new event", eiEx.addsExOnMaster, t);
            }
        }
    }
}