Example usage for java.util Collections swap

List of usage examples for java.util Collections swap

Introduction

In this page you can find the example usage for java.util Collections swap.

Prototype

private static void swap(Object[] arr, int i, int j) 

Source Link

Document

Swaps the two specified elements in the specified array.

Usage

From source file:org.talend.designer.core.ui.editor.connections.Connection.java

/**
 * This function will change the merge order of the connection.
 * //from  w ww. j a v  a2  s .  c  o m
 * @param id
 */
public void setInputId(int id) {
    int newId = id - 1;
    int curId = 0;
    if (target != null) {
        if (target.getIncomingConnections().size() < newId) {
            throw new IllegalArgumentException(Messages.getString("Connection.inputInvalid")); //$NON-NLS-1$
        }
        if (target.getIncomingConnections().get(newId).equals(this)) {
            return; // id is already set
        }
        for (int i = 0; i < target.getIncomingConnections().size(); i++) {
            if (target.getIncomingConnections().get(i).equals(this)) {
                curId = i;
                break;
            }
        }
        Collections.swap(target.getIncomingConnections(), curId, newId);
    }
}

From source file:org.betaconceptframework.astroboa.model.impl.ComplexCmsPropertyImpl.java

@Override
public boolean swapChildPropertyValues(String relativePropertyPath, int from, int to) {

    if (relativePropertyPath == null || relativePropertyPath.endsWith(CmsConstants.RIGHT_BRACKET)) {
        return false;
    }//from   ww w  .  j a v  a  2  s.c  o  m

    if (from == to || from < 0 || to < 0) {
        return false;
    }

    //Check its definition
    CmsPropertyDefinition childPropertyDefinition = getChildPropertyDefinition(relativePropertyPath);

    if (childPropertyDefinition == null || !childPropertyDefinition.isMultiple()) {
        return false;
    }

    if (ValueType.Complex == childPropertyDefinition.getValueType()) {
        List<CmsProperty<?, ?>> propertyList = getChildPropertyList(relativePropertyPath);

        try {
            Collections.swap(propertyList, from, to);
            //Now fix indices
            for (CmsProperty<?, ?> childProperty : propertyList) {
                if (childProperty instanceof CmsPropertyIndexable) {
                    ((CmsPropertyIndexable) childProperty).setIndex(propertyList.indexOf(childProperty));
                }
            }

            return true;
        } catch (Exception e) {
            LoggerFactory.getLogger(getClass()).error("", e);
            return false;
        }
    } else {
        //Property is simple value
        CmsProperty<?, ?> property = getChildProperty(relativePropertyPath);

        if (property instanceof SimpleCmsProperty) {
            return ((SimpleCmsProperty) property).swapValues(from, to);
        } else {
            LoggerFactory.getLogger(getClass()).warn(
                    "Property {}'s definition is value type {} but property instance is of type {}",
                    new Object[] { relativePropertyPath, childPropertyDefinition.getValueType(),
                            property.getClass().getName() });
            return false;
        }
    }
}

From source file:hydrograph.ui.parametergrid.dialog.MultiParameterFileDialog.java

private void createParameterFilesBoxButtonPanel(Composite composite_2) {
    Composite composite_3 = new Composite(composite_2, SWT.NONE);
    composite_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    GridLayout gridLayout = new GridLayout(8, false);
    if (OSValidator.isMac()) {
        gridLayout.horizontalSpacing = -10;
    }/*from   w w  w  .  ja  v a 2 s . co m*/
    composite_3.setLayout(gridLayout);
    Label lblFile = new Label(composite_3, SWT.NONE);
    lblFile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblFile.setText("File");
    lblFile.setVisible(false);
    parameterFileTextBox = new Text(composite_3, SWT.BORDER);
    parameterFileTextBox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
    parameterFileTextBox.setVisible(false);
    Button btnAddJob = new Button(composite_3, SWT.NONE);
    btnAddJob.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ParameterFile paramterFile = getNewValue(e.widget.getDisplay().getActiveShell(), "jobprameter",
                    ParamterFileTypes.JOB_LEVEL);
            if (paramterFile != null) {
                String importLocation = activeProjectLocation + File.separator
                        + MultiParameterFileDialogConstants.JOB_PARAMETER_DIRECTORY_NAME + File.separator;
                String paramterFileAbsilutePath = importLocation + paramterFile.getFileName();
                try {
                    createNewParamterFile(paramterFileAbsilutePath);
                    String[] listOfFilesToBeImported = new String[1];
                    listOfFilesToBeImported[0] = paramterFile.getFileName();
                    updateParameterGridWindow(listOfFilesToBeImported, importLocation,
                            ParamterFileTypes.JOB_LEVEL);
                    applyButton.setEnabled(true);
                } catch (IOException e1) {
                    logger.debug("Unable to add parameter file", e1);
                }
            }
        }
    });
    btnAddJob.setText(" Add Job ");

    Button btnLoadJob = new Button(composite_3, SWT.NONE);
    btnLoadJob.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ParameterFile paramterFile = getNewValue(e.widget.getDisplay().getActiveShell(), "projectprameter",
                    ParamterFileTypes.PROJECT_LEVEL);
            if (paramterFile != null) {
                String importLocation = activeProjectLocation + File.separator
                        + MultiParameterFileDialogConstants.GLOBAL_PARAMETER_DIRECTORY_NAME + File.separator;
                String paramterFileAbsilutePath = importLocation + paramterFile.getFileName();
                try {
                    createNewParamterFile(paramterFileAbsilutePath);
                    String[] listOfFilesToBeImported = new String[1];
                    listOfFilesToBeImported[0] = paramterFile.getFileName();
                    updateParameterGridWindow(listOfFilesToBeImported, importLocation,
                            ParamterFileTypes.PROJECT_LEVEL);
                    applyButton.setEnabled(true);
                } catch (IOException e1) {
                    logger.debug("Unable to add parameter file", e1);
                }
            }
        }
    });
    btnLoadJob.setText("Add Project ");

    Button btnAddJobParam = new Button(composite_3, SWT.NONE);
    btnAddJobParam.setText("Load Job");
    final Button btnAddProjectParam = new Button(composite_3, SWT.NONE);
    btnAddProjectParam.setText("Load Project");

    Button btnUp_1 = new Button(composite_3, SWT.NONE);
    btnUp_1.setToolTipText(Messages.MOVE_SCHEMA_UP_TOOLTIP);
    btnUp_1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Table table = filePathTableViewer.getTable();
            int[] indexes = table.getSelectionIndices();
            for (int index : indexes) {
                if (index > 0) {
                    Collections.swap((List<ParameterFile>) parameterFiles, index, index - 1);
                    filePathTableViewer.refresh();
                }
            }
            applyButton.setEnabled(true);
        }
    });
    btnUp_1.setImage(ImagePathConstant.MOVEUP_BUTTON.getImageFromRegistry());

    Button btnDown_1 = new Button(composite_3, SWT.NONE);
    btnDown_1.setToolTipText(Messages.MOVE_SCHEMA_DOWN_TOOLTIP);
    btnDown_1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Table table = filePathTableViewer.getTable();
            int[] indexes = table.getSelectionIndices();
            for (int i = indexes.length - 1; i > -1; i--) {
                if (indexes[i] < parameterFiles.size() - 1) {
                    Collections.swap((List<ParameterFile>) parameterFiles, indexes[i], indexes[i] + 1);
                    filePathTableViewer.refresh();
                }
            }
            applyButton.setEnabled(true);
        }
    });
    btnDown_1.setImage(ImagePathConstant.MOVEDOWN_BUTTON.getImageFromRegistry());
    btnAddProjectParam.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            addFilesToParamterGrid(btnAddProjectParam.getShell(),
                    MultiParameterFileDialogConstants.GLOBAL_PARAMETER_DIRECTORY_NAME,
                    ParamterFileTypes.PROJECT_LEVEL);
            applyButton.setEnabled(true);
        }
    });
    btnAddJobParam.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            addFilesToParamterGrid(btnAddProjectParam.getShell(),
                    MultiParameterFileDialogConstants.JOB_PARAMETER_DIRECTORY_NAME,
                    ParamterFileTypes.JOB_LEVEL);
            applyButton.setEnabled(true);
        }
    });
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java

private void moveRowUp() {
    propertyDialogButtonBar.enableApplyButton(true);
    int[] indexes = table.getSelectionIndices();
    for (int index : indexes) {

        if (index > 0) {
            Collections.swap(schemaGridRowList, index, index - 1);
            tableViewer.refresh();//from   ww w  .  ja v a2s.co  m

        }
    }
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.ELTSchemaGridWidget.java

private void moveRowDown() {
    propertyDialogButtonBar.enableApplyButton(true);
    int[] indexes = table.getSelectionIndices();
    for (int i = indexes.length - 1; i > -1; i--) {

        if (indexes[i] < schemaGridRowList.size() - 1) {
            Collections.swap(schemaGridRowList, indexes[i], indexes[i] + 1);
            tableViewer.refresh();//from  w w w  .  j  av  a 2 s  . c o  m

        }

    }

}

From source file:org.apache.hadoop.hdfs.server.namenode.FSNamesystem.java

/**
 * Schedule blocks for deletion at datanodes
 * @param nodesToProcess number of datanodes to schedule deletion work
 * @return total number of block for deletion
 *///from w w  w  . ja  v  a  2  s . c  om
int computeInvalidateWork(int nodesToProcess) {
    int numOfNodes = 0;
    ArrayList<String> keyArray;
    synchronized (this) {
        numOfNodes = recentInvalidateSets.size();
        // get an array of the keys
        keyArray = new ArrayList<String>(recentInvalidateSets.keySet());
    }
    nodesToProcess = Math.min(numOfNodes, nodesToProcess);

    // randomly pick up <i>nodesToProcess</i> nodes 
    // and put them at [0, nodesToProcess)
    int remainingNodes = numOfNodes - nodesToProcess;
    if (nodesToProcess < remainingNodes) {
        for (int i = 0; i < nodesToProcess; i++) {
            int keyIndex = r.nextInt(numOfNodes - i) + i;
            Collections.swap(keyArray, keyIndex, i); // swap to front
        }
    } else {
        for (int i = 0; i < remainingNodes; i++) {
            int keyIndex = r.nextInt(numOfNodes - i);
            Collections.swap(keyArray, keyIndex, numOfNodes - i - 1); // swap to end
        }
    }

    int blockCnt = 0;
    for (int nodeCnt = 0; nodeCnt < nodesToProcess; nodeCnt++) {
        blockCnt += invalidateWorkForOneNode(keyArray.get(nodeCnt));
    }
    return blockCnt;
}

From source file:eu.davidea.flexibleadapter.FlexibleAdapter.java

/**
 * Swaps the elements of list at indices fromPosition and toPosition and notify the change.
 * <p>Selection of swiped elements is automatically updated.</p>
 *
 * @param fromPosition previous position of the item.
 * @param toPosition   new position of the item.
 * @since 5.0.0-b7/*from w  ww .  ja v  a2 s  .  c  o  m*/
 */
public void swapItems(List<T> list, int fromPosition, int toPosition) {
    if (fromPosition < 0 || fromPosition >= getItemCount() || toPosition < 0 || toPosition >= getItemCount()) {
        return;
    }
    if (DEBUG) {
        Log.v(TAG, "swapItems from=" + fromPosition + " [selected? " + isSelected(fromPosition) + "] to="
                + toPosition + " [selected? " + isSelected(toPosition) + "]");
    }

    //Collapse expandable before swapping (otherwise items are mixed badly)
    if (fromPosition < toPosition && isExpandable(getItem(fromPosition)) && isExpanded(toPosition)) {
        //collapse(toPosition);
    }

    //Perform item swap (for all LayoutManagers)
    if (fromPosition < toPosition) {
        for (int i = fromPosition; i < toPosition; i++) {
            if (DEBUG)
                Log.v(TAG, "swapItems from=" + i + " to=" + (i + 1));
            Collections.swap(mItems, i, i + 1);
            swapSelection(i, i + 1);
        }
    } else {
        for (int i = fromPosition; i > toPosition; i--) {
            if (DEBUG)
                Log.v(TAG, "swapItems from=" + i + " to=" + (i - 1));
            Collections.swap(mItems, i, i - 1);
            swapSelection(i, i - 1);
        }
    }
    notifyItemMoved(fromPosition, toPosition);

    //Header swap linkage
    if (headersShown) {
        //Situation AFTER items have been swapped, items are inverted!
        T fromItem = getItem(toPosition);
        T toItem = getItem(fromPosition);
        int oldPosition, newPosition;
        if (toItem instanceof IHeader && fromItem instanceof IHeader) {
            if (fromPosition < toPosition) {
                //Dragging down fromHeader
                //Auto-linkage all section-items with new header
                IHeader header = (IHeader) fromItem;
                List<ISectionable> items = getSectionItems(header);
                for (ISectionable sectionable : items) {
                    linkHeaderTo((T) sectionable, header, Payload.LINK);
                }
            } else {
                //Dragging up fromHeader
                //Auto-linkage all section-items with new header
                IHeader header = (IHeader) toItem;
                List<ISectionable> items = getSectionItems(header);
                for (ISectionable sectionable : items) {
                    linkHeaderTo((T) sectionable, header, Payload.LINK);
                }
            }
        } else if (toItem instanceof IHeader) {
            //A Header is being swapped up
            //Else a Header is being swapped down
            oldPosition = fromPosition < toPosition ? toPosition + 1 : toPosition;
            newPosition = fromPosition < toPosition ? toPosition : fromPosition + 1;
            //Swap header linkage
            linkHeaderTo(getItem(oldPosition), getSectionHeader(oldPosition), Payload.LINK);
            linkHeaderTo(getItem(newPosition), (IHeader) toItem, Payload.LINK);
        } else if (fromItem instanceof IHeader) {
            //A Header is being dragged down
            //Else a Header is being dragged up
            oldPosition = fromPosition < toPosition ? fromPosition : fromPosition + 1;
            newPosition = fromPosition < toPosition ? toPosition + 1 : fromPosition;
            //Swap header linkage
            linkHeaderTo(getItem(oldPosition), getSectionHeader(oldPosition), Payload.LINK);
            linkHeaderTo(getItem(newPosition), (IHeader) fromItem, Payload.LINK);
        } else {
            //A Header receives the toItem
            //Else a Header receives the fromItem
            oldPosition = fromPosition < toPosition ? toPosition : fromPosition;
            newPosition = fromPosition < toPosition ? fromPosition : toPosition;
            //Swap header linkage
            T oldItem = getItem(oldPosition);
            IHeader header = getHeaderOf(oldItem);
            if (header != null) {
                IHeader oldHeader = getSectionHeader(oldPosition);
                if (oldHeader != null && !oldHeader.equals(header)) {
                    linkHeaderTo(oldItem, oldHeader, Payload.LINK);
                }
                linkHeaderTo(getItem(newPosition), header, Payload.LINK);
            }
        }
    }
}

From source file:org.talend.designer.core.model.process.DataProcess.java

/**
 * xtan make sure the new tUnite incomingConnections order is the same as the old one.(bug:3417).
 * /*from  ww  w  .  j ava2s  . co  m*/
 * @see Connection.setInputId(int id)
 * 
 * @param oldtUnite
 * @param newtUnite
 */
private void adjustMergeOrderForDuplicateNode(INode oldtUnite, INode newtUnite) {
    if (newtUnite == null) {
        return;
    }
    List<IConnection> incomingConnectionsOld = (List<IConnection>) oldtUnite.getIncomingConnections();
    List<IConnection> incomingConnectionsNew = (List<IConnection>) newtUnite.getIncomingConnections();

    Iterator<IConnection> iteratorOld = incomingConnectionsOld.iterator();
    int i = 0;
    while (iteratorOld.hasNext()) {
        IConnection connOld = iteratorOld.next();
        Iterator<IConnection> iteratorNew = incomingConnectionsNew.iterator();
        int j = 0;
        while (iteratorNew.hasNext()) {
            IConnection connNew = iteratorNew.next();
            if (connNew.getName().equals(connOld.getName()) && i != j) {
                if (incomingConnectionsNew.size() > i) {
                    Collections.swap(incomingConnectionsNew, i, j);
                }
                break;
            }
            j++;
        }
        i++;
    }
}