Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

In this page you can find the example usage for java.util ArrayList remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:com.amalto.workbench.dialogs.AnnotationOrderedListsDialog.java

@Override
protected Control createDialogArea(Composite parent) {

    // Should not really be here but well,....

    parent.getShell().setText(this.title);

    Composite composite = (Composite) super.createDialogArea(parent);

    GridLayout layout = (GridLayout) composite.getLayout();
    layout.numColumns = 3;//from  w  w w . j  ava 2  s.c om
    layout.makeColumnsEqualWidth = false;
    // layout.verticalSpacing = 10;

    if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType) {
        textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY);

        // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE);
        roles = getAllRolesStr();
        ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()]));

    } else if (actionType == AnnotationLookupField_ActionType
            || actionType == AnnotationPrimaKeyInfo_ActionType) {
        textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY);

        // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE);
        roles = getConceptElements();
        ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()]));

    } else {
        if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) {
            textControl = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
        } else {
            textControl = new Text(composite, SWT.BORDER | SWT.SINGLE);
        }
    }

    if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) {
        textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    } else {
        if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) {
            textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 7));
        } else {
            textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
        }
    }

    ((GridData) textControl.getLayoutData()).minimumWidth = 400;

    textControl.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if ((e.stateMask == 0) && (e.character == SWT.CR)) {
                xPaths.add(AnnotationOrderedListsDialog.getControlText(textControl));
                viewer.refresh();
                fireXPathsChanges();
            }
        }
    });

    if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) {
        Button xpathButton = new Button(composite, SWT.PUSH | SWT.CENTER);
        xpathButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
        xpathButton.setText("...");//$NON-NLS-1$
        xpathButton.setToolTipText(Messages.AnnotationOrderedListsDialog_SelectXpath);
        xpathButton.addSelectionListener(new SelectionListener() {

            public void widgetDefaultSelected(SelectionEvent e) {

            }

            public void widgetSelected(SelectionEvent e) {
                XpathSelectDialog dlg = getNewXpathSelectDialog(parentPage, dataModelName);

                dlg.setLock(lock);

                dlg.setBlockOnOpen(true);

                dlg.open();

                if (dlg.getReturnCode() == Window.OK) {
                    ((Text) textControl).setText(dlg.getXpath());
                    dlg.close();
                }

            }

        });

    }

    Button addLabelButton = new Button(composite, SWT.PUSH);
    addLabelButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
    // addLabelButton.setText("Set");
    addLabelButton.setImage(ImageCache.getCreatedImage(EImage.ADD_OBJ.getPath()));
    addLabelButton.setToolTipText(Messages.AnnotationOrderedListsDialog_Add);
    addLabelButton.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
        };

        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            boolean exist = false;
            for (String string : xPaths) {
                if (string.equals(getControlText(textControl))) {
                    exist = true;
                }
            }
            if (!exist && getControlText(textControl) != null && getControlText(textControl) != "") {
                xPaths.add(getControlText(textControl));
            }
            viewer.refresh();
            fireXPathsChanges();
        };
    });

    final String COLUMN = columnName;

    viewer = new TableViewer(composite,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
    viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
    ((GridData) viewer.getControl().getLayoutData()).heightHint = 100;
    // Set up the underlying table
    Table table = viewer.getTable();
    // table.setLayoutData(new GridData(GridData.FILL_BOTH));

    new TableColumn(table, SWT.CENTER).setText(COLUMN);
    table.getColumn(0).setWidth(500);
    for (int i = 1, n = table.getColumnCount(); i < n; i++) {
        table.getColumn(i).pack();
    }

    table.setHeaderVisible(true);
    table.setLinesVisible(true);

    // Create the cell editors --> We actually discard those later: not natural for an user
    CellEditor[] editors = new CellEditor[1];
    if (actionType == AnnotationOrderedListsDialog.AnnotationWrite_ActionType
            || actionType == AnnotationOrderedListsDialog.AnnotationHidden_ActionType
            || actionType == AnnotationLookupField_ActionType
            || actionType == AnnotationPrimaKeyInfo_ActionType) {
        editors[0] = new ComboBoxCellEditor(table, roles.toArray(new String[] {}), SWT.READ_ONLY);
    } else {
        editors[0] = new TextCellEditor(table);
    }

    viewer.setCellEditors(editors);

    // set the content provider
    viewer.setContentProvider(new IStructuredContentProvider() {

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

        public Object[] getElements(Object inputElement) {
            @SuppressWarnings("unchecked")
            ArrayList<String> xPaths = (ArrayList<String>) inputElement;
            ArrayList<DescriptionLine> lines = new ArrayList<DescriptionLine>();
            for (String xPath : xPaths) {
                DescriptionLine line = new DescriptionLine(xPath);
                lines.add(line);
            }
            // we return an instance line made of a Sring and a boolean
            return lines.toArray(new DescriptionLine[lines.size()]);
        }
    });

    // set the label provider
    viewer.setLabelProvider(new ITableLabelProvider() {

        public boolean isLabelProperty(Object element, String property) {
            return false;
        }

        public void dispose() {
        }

        public void addListener(ILabelProviderListener listener) {
        }

        public void removeListener(ILabelProviderListener listener) {
        }

        public String getColumnText(Object element, int columnIndex) {
            // System.out.println("getColumnText() "+columnIndex);
            DescriptionLine line = (DescriptionLine) element;
            switch (columnIndex) {
            case 0:
                return line.getLabel();
            }
            return "";//$NON-NLS-1$
        }

        public Image getColumnImage(Object element, int columnIndex) {
            return null;
        }
    });

    // Set the column properties
    viewer.setColumnProperties(new String[] { COLUMN });

    // set the Cell Modifier
    viewer.setCellModifier(new ICellModifier() {

        public boolean canModify(Object element, String property) {
            // if (INSTANCE_ACCESS.equals(property)) return true; Deactivated
            return true;
            // return false;
        }

        public void modify(Object element, String property, Object value) {

            TableItem item = (TableItem) element;
            DescriptionLine line = (DescriptionLine) item.getData();
            String orgValue = line.getLabel();
            if (actionType != AnnotationWrite_ActionType && actionType != AnnotationHidden_ActionType
                    && actionType != AnnotationLookupField_ActionType
                    && actionType != AnnotationPrimaKeyInfo_ActionType) {
                int targetPos = xPaths.indexOf(value.toString());
                if (targetPos < 0) {
                    line.setLabel(value.toString());
                    int index = xPaths.indexOf(orgValue);
                    xPaths.remove(index);
                    xPaths.add(index, value.toString());
                    viewer.update(line, null);
                } else if (targetPos >= 0 && !value.toString().equals(orgValue)) {
                    MessageDialog.openInformation(null, Messages.Warning,
                            Messages.AnnotationOrderedListsDialog_ValueAlreadyExists);
                }
            } else {

                String[] attrs = roles.toArray(new String[] {});
                int index = Integer.parseInt(value.toString());
                if (index == -1) {
                    return;
                }
                value = attrs[index];
                int pos = xPaths.indexOf(value.toString());
                if (pos >= 0 && !(orgValue.equals(value))) {
                    MessageDialog.openInformation(null, Messages.Warning,
                            Messages.AnnotationOrderedListsDialog_);
                    return;
                } else if (pos < 0) {
                    line.setLabel(value.toString());
                    xPaths.set(index, value.toString());
                    viewer.update(line, null);
                }
            }

            fireXPathsChanges();
        }

        public Object getValue(Object element, String property) {
            DescriptionLine line = (DescriptionLine) element;
            String value = line.getLabel();

            if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType
                    || actionType == AnnotationLookupField_ActionType
                    || actionType == AnnotationPrimaKeyInfo_ActionType) {
                String[] attrs = roles.toArray(new String[] {});
                return Arrays.asList(attrs).indexOf(value);
            } else {
                return value;
            }

        }
    });

    // Listen for changes in the selection of the viewer to display additional parameters
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent event) {
            DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection())
                    .getFirstElement();
            if (line != null) {
                if (textControl instanceof CCombo) {
                    ((CCombo) textControl).setText(line.getLabel());
                }
                if (textControl instanceof Text) {
                    ((Text) textControl).setText(line.getLabel());
                }
            }
        }
    });

    // display for Delete Key events to delete an instance
    viewer.getTable().addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            // System.out.println("Table keyReleased() ");
            if ((e.stateMask == 0) && (e.character == SWT.DEL) && (viewer.getSelection() != null)) {
                DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection())
                        .getFirstElement();
                @SuppressWarnings("unchecked")
                ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput();
                xPaths.remove(line.getLabel());
                viewer.refresh();
            }
        }
    });

    viewer.setInput(xPaths);
    viewer.refresh();

    Composite rightButtonsComposite = new Composite(composite, SWT.NULL);
    rightButtonsComposite.setLayout(new GridLayout(1, true));
    rightButtonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));

    Button upButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER);
    upButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
    upButton.setImage(ImageCache.getCreatedImage(EImage.PREV_NAV.getPath()));
    upButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveUpTheItem);
    upButton.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
        };

        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection())
                    .getFirstElement();
            if (line == null) {
                return;
            }
            int i = 0;
            for (String xPath : xPaths) {
                if (xPath.equals(line.getLabel())) {
                    if (i > 0) {
                        xPaths.remove(i);
                        xPaths.add(i - 1, xPath);
                        viewer.refresh();
                        viewer.getTable().setSelection(i - 1);
                        viewer.getTable().showSelection();
                        fireXPathsChanges();
                    }
                    return;
                }
                i++;
            }
        };
    });
    Button downButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER);
    downButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
    downButton.setImage(ImageCache.getCreatedImage(EImage.NEXT_NAV.getPath()));
    downButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveDownTheItem);
    downButton.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
        };

        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection())
                    .getFirstElement();
            if (line == null) {
                return;
            }
            int i = 0;
            for (String xPath : xPaths) {
                if (xPath.equals(line.getLabel())) {
                    if (i < xPaths.size() - 1) {
                        xPaths.remove(i);
                        xPaths.add(i + 1, xPath);
                        viewer.refresh();
                        viewer.getTable().setSelection(i + 1);
                        viewer.getTable().showSelection();
                        fireXPathsChanges();
                    }
                    return;
                }
                i++;
            }
        };
    });
    Button delButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER);
    delButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
    delButton.setImage(ImageCache.getCreatedImage(EImage.DELETE_OBJ.getPath()));
    delButton.setToolTipText(Messages.AnnotationOrderedListsDialog_DelTheItem);

    delButton.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
        };

        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection())
                    .getFirstElement();
            if (line != null) {
                @SuppressWarnings("unchecked")
                ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput();
                xPaths.remove(line.getLabel());
                viewer.refresh();
                fireXPathsChanges();
            }
        };
    });

    textControl.setFocus();
    if (actionType != AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType
            && actionType != AnnotationOrderedListsDialog.AnnotationTargetSystems_ActionType
            && actionType != AnnotationOrderedListsDialog.AnnotationSchematron_ActionType
            && actionType != AnnotationOrderedListsDialog.AnnotationLookupField_ActionType
            && actionType != AnnotationOrderedListsDialog.AnnotationPrimaKeyInfo_ActionType) {
        checkBox = new Button(composite, SWT.CHECK);
        checkBox.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 2, 1));
        checkBox.addSelectionListener(new SelectionListener() {

            public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
            };

            public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
                recursive = checkBox.getSelection();
            };
        });
        checkBox.setSelection(recursive);
        checkBox.setText(Messages.AnnotationOrderedListsDialog_SetRoleRecursively);
        // Label label = new Label(composite, SWT.LEFT);
        // label.setText("set role recursively");
        // label.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true,
        // 1, 1));
    }

    if (actionType == AnnotationForeignKeyInfo_ActionType) {
        createFKInfoFormatComp(composite);
        addDoubleClickListener();
    }

    return composite;
}

From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java

public ArrayList<ArrayList<String>> getPathOfConcept(HikariDataSource ds, String idConcept, String idThesaurus,
        ArrayList<String> path, ArrayList<ArrayList<String>> tabId) {

    ArrayList<String> fistPath = new ArrayList<>();
    ArrayList<ArrayList<String>> tabIdInvert = getInvertPathOfConcept(ds, idConcept, idThesaurus, fistPath,
            path, tabId);//w ww .j a  v  a  2  s.co m

    for (int i = 0; i < tabIdInvert.size(); i++) {
        ArrayList<String> pathTemp = new ArrayList<>();
        for (int j = tabIdInvert.get(i).size(); j > 0; j--) {
            pathTemp.add(tabIdInvert.get(i).get(j - 1));
        }
        tabIdInvert.remove(i);
        tabIdInvert.add(i, pathTemp);
    }
    return tabIdInvert;
}

From source file:ch.epfl.lsir.xin.algorithm.core.SVDPlusPlus.java

/**
 * This function learns a matrix factorization model using Stochastic Gradient Descent 
 * *///from ww w .j av  a2 s.c o  m
public void buildSGD() {
    double preError = Double.MAX_VALUE;
    for (int i = 0; i < this.iteration; i++) {
        System.out.println("Iteration: " + i);
        ArrayList<MatrixEntry2D> entries = this.ratingMatrix.getValidEntries();
        double error = 0; //overall error of this iteration
        while (entries.size() > 0) {
            //find a random entry
            int r = new Random().nextInt(entries.size());
            MatrixEntry2D entry = entries.get(r);
            double prediction = predict(entry.getRowIndex(), entry.getColumnIndex(), false);
            if (prediction > this.maxRating)
                prediction = this.maxRating;
            if (prediction < this.minRating)
                prediction = this.minRating;
            double difference = entry.getValue() - prediction;

            //update user bias
            double newUserBias = this.userBias[entry.getRowIndex()] + this.biasLearningRate
                    * (difference - this.biasUserReg * this.userBias[entry.getRowIndex()]);
            this.userBias[entry.getRowIndex()] = newUserBias;
            //update item bias
            double newItemBias = this.itemBias[entry.getColumnIndex()] + this.biasLearningRate
                    * (difference - this.biasItemReg * this.itemBias[entry.getColumnIndex()]);
            this.itemBias[entry.getColumnIndex()] = newItemBias;

            //update user/item factors
            double constant = Math.sqrt(this.ratingMatrix.getUserRatingNumber(entry.getRowIndex()));
            double[] sumY = new double[this.latentFactors];
            ArrayList<Integer> ratedItems = this.ratingMatrix.getRatedItems().get(entry.getRowIndex());
            for (int j = 0; j < this.latentFactors; j++) {
                double sY = 0;
                for (int k = 0; k < ratedItems.size(); k++) {
                    sY = sY + this.Y.get(ratedItems.get(k), j);
                }
                sumY[j] = constant > 0 ? sY / constant : sY;
            }
            for (int j = 0; j < this.latentFactors; j++) {
                //update user factors
                double newUserFactors = this.userMatrix.get(entry.getRowIndex(), j)
                        + this.learningRate * (difference * this.itemMatrix.get(entry.getColumnIndex(), j)
                                - this.userReg * this.userMatrix.get(entry.getRowIndex(), j));
                //update item factors
                double newItemFactors = this.itemMatrix.get(entry.getColumnIndex(), j) + this.learningRate
                        * (difference * (this.userMatrix.get(entry.getRowIndex(), j) + sumY[j])
                                - this.itemReg * this.itemMatrix.get(entry.getColumnIndex(), j));
                //update item factors Y
                for (int k = 0; k < ratedItems.size(); k++) {
                    double newItemYFactor = this.Y.get(ratedItems.get(k), j) + this.learningRate
                            * (difference * 1 / constant * this.itemMatrix.get(ratedItems.get(k), j)
                                    - this.userReg * this.Y.get(ratedItems.get(k), j));
                    this.Y.set(ratedItems.get(k), j, newItemYFactor);
                }
                this.userMatrix.set(entry.getRowIndex(), j, newUserFactors);
                this.itemMatrix.set(entry.getColumnIndex(), j, newItemFactors);
            }

            //one rating is only processed once in an iteration
            entries.remove(r);
        }
        //error
        entries = this.ratingMatrix.getValidEntries();
        for (int k = 0; k < entries.size(); k++) {
            MatrixEntry2D entry = entries.get(k);
            double prediction = predict(entry.getRowIndex(), entry.getColumnIndex(), false);
            if (prediction > this.maxRating)
                prediction = this.maxRating;
            if (prediction < this.minRating)
                prediction = this.minRating;
            error = error + Math.abs(entry.getValue() - prediction);
            //            for( int j = 0 ; j < this.latentFactors ; j++ )
            //            {
            //               error = error + this.regUser/2 * Math.pow(this.userMatrix.get(entry.getRowIndex(), j), 2) + 
            //                     this.regItem/2 * Math.pow(this.itemMatrix.get(entry.getColumnIndex(), j), 2);
            //            }      
        }
        this.logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Iteration " + i
                + " : Error ~ " + error);
        this.logger.flush();
        //check for convergence
        if (Math.abs(error - preError) <= this.convergence && error <= preError) {
            logger.println("The algorithm convergences.");
            this.logger.flush();
            break;
        }
        // learning rate update strategy 
        updateLearningRate(error, preError);

        preError = error;
        logger.flush();
    }
}

From source file:civilisation.individu.Human.java

public ArrayList<Patch> AStar(Patch cible) {
    int[][] map = new int[getWorldWidth()][getWorldHeight()];
    int minx = Math.min(cible.x, xcor());
    int maxx = Math.max(cible.x, xcor());
    int miny = Math.min(cible.y, ycor());
    int maxy = Math.max(cible.y, ycor());

    int addi = 0;
    int nb = 0;/*from  w  w w  .  j  a v a  2  s .co m*/
    int min = 10000;
    for (int l = 0; l < Configuration.terrains.size(); l++) {
        if (Configuration.terrains.get(l).getInfranchissable() == false) {
            nb++;
            addi += Configuration.terrains.get(l).getPassabilite();
            if (Configuration.terrains.get(l).getPassabilite() < min) {
                min = Configuration.terrains.get(l).getPassabilite();
            }
        }
    }
    int defaut = min /*addi/nb*/;
    for (int i = minx - Configuration.VisionRadius * 6; i < maxx + Configuration.VisionRadius * 6; i++) {
        for (int j = miny - Configuration.VisionRadius * 4; j < maxy + Configuration.VisionRadius * 4; j++) {
            if (i > 0 && i < getWorldWidth() && j > 0 && j < getWorldHeight()) {

                map[i][j] = defaut;
            }

        }
    }

    for (int i = 0; i < Configuration.VisionRadius * 2; i++) {
        for (int j = 0; j < Configuration.VisionRadius * 2; j++) {
            //   Color couleur = getPatchColorAt(i - getVisionRadius(), j - getVisionRadius());

            if (xcor() + i - Configuration.VisionRadius < getWorldWidth()
                    && ycor() + j - Configuration.VisionRadius < getWorldHeight()
                    && xcor() + i - Configuration.VisionRadius > 0
                    && ycor() + j - Configuration.VisionRadius > 0) {
                int passabilite = Configuration.couleurs_terrains.get(
                        getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius).getColor())
                        .getPassabilite();
                if (smellAt("passage", i - Configuration.VisionRadius, j - Configuration.VisionRadius) > 0) {
                    map[xcor() + i - Configuration.VisionRadius][ycor() + j
                            - Configuration.VisionRadius] = (int) (passabilite
                                    - (passabilite / 2 * 1 / smellAt("passage", i - Configuration.VisionRadius,
                                            j - Configuration.VisionRadius)));
                } else {
                    map[xcor() + i - Configuration.VisionRadius][ycor() + j
                            - Configuration.VisionRadius] = passabilite;
                }

                if (getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius)
                        .isMarkPresent("Route")) {
                    map[xcor() + i - Configuration.VisionRadius][ycor() + j - Configuration.VisionRadius] /= 2;
                }

                if (Configuration.couleurs_terrains.get(
                        getPatchAt(i - Configuration.VisionRadius, j - Configuration.VisionRadius).getColor())
                        .getInfranchissable() == true) {
                    map[xcor() + i - Configuration.VisionRadius][ycor() + j
                            - Configuration.VisionRadius] = Integer.MAX_VALUE;
                }
            }

        }
    }
    /*   for(int i = 0; i < map.length; i++)
       {
    System.out.print("[");
    for(int j = 0;j < map[i].length;j++)
    {
       if(map[i][j] != 1000)
       {
          System.out.print(map[i][j]);
       }
    }
    System.out.println("]");
       }*/
    ArrayList<Noeud> liste_noeud = new ArrayList<Noeud>();
    ArrayList<Noeud> open_list = new ArrayList<Noeud>();
    ArrayList<Noeud> close_list = new ArrayList<Noeud>();
    Noeud noeud = new Noeud(getPatch().x, getPatch().y, 0, 0);
    noeud.setDistanceRacine(0);
    close_list.add(noeud);
    liste_noeud.add(noeud);
    int cpt = 1;
    for (int i = -1; i < 2; i++) {
        for (int j = -1; j < 2; j++) {
            int x = noeud.getPosX();
            int y = noeud.getPosY();
            if ((x + i < getWorldWidth() && x + i > 0) && (y + j < getWorldHeight() && y + j > 0)
                    && (i != 0 || j != 0) && map[x + i][y + j] != Integer.MAX_VALUE) {
                Noeud noeu = new Noeud(x + i, y + j, 0, cpt);
                int distanceRacine = map[x + i][y + j];
                noeu.setDistanceRacine(distanceRacine);
                open_list.add(noeu);
                liste_noeud.add(noeu);
                cpt++;
            }
        }
    }
    /*System.out.println("Open_list 1 : ");
    for(int i = 0; i < open_list.size();i++)
    {
    System.out.println("Noeud : "+open_list.get(i).getId()+" x : "+open_list.get(i).getPosX()+" y : "+open_list.get(i).getPosY()+ " distance : "+open_list.get(i).getDistanceRacine());
    }*/
    Noeud suivant = PlusProcheNoeud(open_list, cible);
    if (suivant != null) {
        /*if(suivant.getParent() != noeud.getId())
        {
                   
           for(int i = 0; i< close_list.size();i++)
           {
          if(close_list.get(i).getId() > suivant.getParent())
          {
             close_list.remove(i);
          }
           }
                   
        }*/
        close_list.add(suivant);
    }
    //System.out.println("close_list 1 : " + close_list);
    noeud = suivant;

    while (noeud != null && (noeud.getPosX() != cible.x || noeud.getPosY() != cible.y)) {
        //System.out.println("Agent : "+getID()+" Noeud suivant : "+noeud.getId()+ " x : "+noeud.getPosX()+ " y : "+noeud.getPosY()+ " parent : "+noeud.getParent()+ " x cible : "+cible.x+" y cible : "+cible.y);
        open_list.remove(noeud);
        for (int i = -1; i < 2; i++) {
            for (int j = -1; j < 2; j++) {
                int x = noeud.getPosX();
                int y = noeud.getPosY();
                if ((x + i < getWorldWidth() && x + i > 0) && (y + j < getWorldHeight() && y + j > 0)
                        && (i != 0 || j != 0) && map[x + i][y + j] != Integer.MAX_VALUE) {
                    Noeud noeu = new Noeud(x + i, y + j, noeud.getId(), cpt);
                    if (!doublons(open_list, noeu)) {
                        int distanceRacine = map[x + i][y + j] + noeud.getDistanceRacine();
                        noeu.setDistanceRacine(distanceRacine);
                        open_list.add(noeu);
                        liste_noeud.add(noeu);
                        cpt++;
                        //   System.out.println("Nouveau noeud "+noeu.getId()+" x : "+noeu.getPosX() + " y : "+noeu.getPosY());
                    }
                }
            }
        }
        suivant = PlusProcheNoeud(open_list, cible);
        if (suivant != null) {
            /*if(suivant.getParent() != noeud.getId())
            {
                       
               for(int i = 0; i< close_list.size();i++)
               {
             if(close_list.get(i).getId() > suivant.getParent())
             {
                close_list.remove(i);
             }
               }
                       
            }*/
            close_list.add(suivant);
        }
        noeud = suivant;
    }

    ArrayList<Patch> liste = new ArrayList<Patch>();

    /*   for(int i = 0;i < close_list.size();i++)
       {
    int x = close_list.get(i).getPosX();
    int y = close_list.get(i).getPosY();
    if(map[x][y] >= Configuration.VitesseEstimeeParDefaut)
    {
       return liste;
    }
    else
    {
       liste.add(0,getPatchAt(x - position.x, y - position.y));
    }
       }*/
    Noeud nodesui = close_list.get(close_list.size() - 1);
    while (!(nodesui.getPosX() == getPatch().x && nodesui.getPosY() == getPatch().y)) {
        int x = nodesui.getPosX();
        int y = nodesui.getPosY();
        liste.add(0, getPatchAt(x - getPatch().x, y - getPatch().y));
        nodesui = liste_noeud.get(nodesui.getParent());
    }
    //         System.out.println("Debut ");
    for (int i = 0; i < liste.size(); i++) {
        int x = liste.get(i).x;
        int y = liste.get(i).y;
        if (x > xcor() + Configuration.VisionRadius || x < xcor() - Configuration.VisionRadius
                || y > ycor() + Configuration.VisionRadius || y < ycor() - Configuration.VisionRadius) {

            if (i == 0) {
                //System.out.println("test");

                setHeading(Math.random() * 360.);
                fd(1);
            }
            //   System.out.println("Fin 1 "+"cible x : "+cible.x+" cible y :"+cible.y);
            return liste;
        }
        //      System.out.println("Pos => x : "+x + " y : "+y);
    }
    //         System.out.println("Pos => x : "+xcor() + " y : "+ycor());
    //   System.out.println("Fin 2 cible x : "+cible.x+" cible y :"+cible.y);
    return liste;
}

From source file:com.redskyit.scriptDriver.RunTests.java

private void runCommand(final StreamTokenizer tokenizer, File file, String source, ExecutionContext script)
        throws Exception {
    // Automatic log dumping
    if (autolog && null != driver) {
        dumpLog();//from ww  w .j a v a  2 s .  c  o  m
    }

    String cmd = tokenizer.sval;
    System.out.printf((new Date()).getTime() + ": [%s,%d] ", source, tokenizer.lineno());
    System.out.print(tokenizer.sval);

    if (cmd.equals("version")) {
        // HELP: version
        System.out.println();
        System.out.println("ScriptDriver version " + version);
        return;
    }

    if (cmd.equals("browser")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);

            if (tokenizer.sval.equals("prefs")) {
                // HELP: browser prefs ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.print(tokenizer.sval);
                    String pref = tokenizer.sval;
                    tokenizer.nextToken();
                    System.out.print(' ');
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    switch (tokenizer.ttype) {
                    case StreamTokenizer.TT_WORD:
                    case '"':
                        System.out.println(tokenizer.sval);
                        if (tokenizer.sval.equals("false")) {
                            prefs.put(pref, false);
                        } else if (tokenizer.sval.equals("true")) {
                            prefs.put(pref, true);
                        } else {
                            prefs.put(pref, tokenizer.sval);
                        }
                        return;
                    case StreamTokenizer.TT_NUMBER:
                        System.out.println(tokenizer.nval);
                        prefs.put(pref, tokenizer.nval);
                        return;
                    }
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            if (tokenizer.sval.equals("option")) {
                // HELP: browser option ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    options.addArguments(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            // HELP: browser wait <seconds>
            if (tokenizer.sval.equals("wait")) {
                tokenizer.nextToken();
                double nval = script.getExpandedNumber(tokenizer);
                System.out.print(' ');
                System.out.println(nval);
                if (_skip)
                    return;
                driver.manage().timeouts().implicitlyWait((long) (tokenizer.nval * 1000),
                        TimeUnit.MILLISECONDS);
                return;
            }

            if (tokenizer.sval.equals("start")) {
                // HELP: browser start
                System.out.println();
                if (null == driver) {
                    // https://sites.google.com/a/chromium.org/chromedriver/capabilities
                    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                    LoggingPreferences logs = new LoggingPreferences();
                    logs.enable(LogType.BROWSER, Level.ALL);
                    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    options.setExperimentalOption("prefs", prefs);
                    options.merge(capabilities);
                    driver = new ChromeDriver(options);
                    driver.setLogLevel(Level.ALL);
                    actions = new Actions(driver); // for advanced actions
                }
                return;
            }

            if (null == driver) {
                System.out.println();
                throw new Exception("browser start must be used before attempt to interract with the browser");
            }

            if (tokenizer.sval.equals("get")) {
                // HELP: browser get "url"
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == driver)
                        driver = new ChromeDriver(options);
                    driver.get(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser get command argument should be a quoted url");
            }

            if (tokenizer.sval.equals("refresh")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().refresh();
                return;
            }

            if (tokenizer.sval.equals("back")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().back();
                return;
            }

            if (tokenizer.sval.equals("forward")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().forward();
                return;
            }

            if (tokenizer.sval.equals("close")) {
                // HELP: browser close
                System.out.println();
                if (!_skip) {
                    driver.close();
                    autolog = false;
                }
                return;
            }

            if (tokenizer.sval.equals("chrome")) {
                // HELP: browser chrome <width>,<height>
                int w = 0, h = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                this.chrome = new Dimension(w, h);
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser chrome arguments error at line " + tokenizer.lineno());
            }

            if (tokenizer.sval.equals("size")) {
                // HELP: browser size <width>,<height>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    final int w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            final int h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                new WaitFor(cmd, tokenizer, false) {
                                    @Override
                                    protected void run() throws RetryException {
                                        Dimension size = new Dimension(chrome.width + w, chrome.height + h);
                                        System.out.println("// chrome " + chrome.toString());
                                        System.out.println("// size with chrome " + size.toString());
                                        try {
                                            driver.manage().window().setSize(size);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            throw new RetryException("Could not set browser size");
                                        }
                                    }
                                };
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            if (tokenizer.sval.equals("pos")) {
                // HELP: browser pos <x>,<y>
                int x = 0, y = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    x = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(x);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            y = (int) tokenizer.nval;
                            System.out.print(y);
                            System.out.println();
                            if (!_skip)
                                driver.manage().window().setPosition(new Point(x, y));
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            throw new Exception("browser unknown command argument at line " + tokenizer.lineno());
        }
        throw new Exception("browser missing command argument at line " + tokenizer.lineno());
    }

    if (cmd.equals("alias") || cmd.equals("function")) {
        // HELP: alias <name> { body }
        // HELP: function <name> (param, ...) { body }
        String name = null, args = null;
        List<String> params = null;
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);
            name = tokenizer.sval;
            params = getParams(tokenizer);
            args = getBlock(script, tokenizer, ' ', false);
            System.out.println();
            if (_skip)
                return;
            addFunction(name, params, args); // add alias
            return;
        }
        System.out.println();
        throw new Exception("alias name expected");
    }

    if (cmd.equals("while")) {
        // HELP: while { block }
        String block = null;
        block = getBlock(script, tokenizer, ' ', false);
        if (_skip)
            return;
        boolean exitloop = false;
        while (!exitloop) {
            try {
                runString(block, file, "while");
            } catch (Exception e) {
                exitloop = true;
            }
        }
        return;
    }

    if (cmd.equals("include")) {
        // HELP: include <script>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            if (_skip)
                return;
            System.out.print(' ');
            System.out.println(tokenizer.sval);
            File include = new File(tokenizer.sval.startsWith("/") ? tokenizer.sval
                    : file.getParentFile().getCanonicalPath() + "/" + tokenizer.sval);
            runScript(include.getCanonicalPath());
            return;
        }
        throw new Exception("include argument should be a quoted filename");
    }

    if (cmd.equals("exec")) {
        // HELP: exec <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec command returned failure status " + exitStatus);
            }
            return;
        }
        System.out.println();
        throw new Exception("exec argument should be string or a word");
    }

    if (cmd.equals("exec-include")) {
        // HELP: exec-include <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s = "", line = "";
            while ((line = reader.readLine()) != null) {
                s += line + "\n";
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec-include command returned failure status " + exitStatus);
            }
            if (s.length() > 0) {
                runString(s, file, tokenizer.sval);
            }
            return;
        }
        System.out.println();
        throw new Exception(cmd + " argument should be string or a word");
    }

    if (cmd.equals("log")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("dump")) {
                // HELP: log dump
                System.out.println("");
                if (driver != null)
                    dumpLog();
                return;
            }
            if (action.equals("auto")) {
                // HELP: log auto <on|off>
                // HELP: log auto <true|false>
                tokenizer.nextToken();
                String onoff = tokenizer.sval;
                System.out.print(' ');
                System.out.println(onoff);
                autolog = onoff.equals("on") || onoff.equals("true");
                return;
            }
            System.out.println();
            throw new Exception("invalid log action");
        }
        System.out.println();
        throw new Exception("log argument should be string or a word");
    }

    if (cmd.equals("default")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("wait")) {
                // HELP: default wait <seconds>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    System.out.print(' ');
                    System.out.println(tokenizer.nval);
                    _defaultWaitFor = (int) (tokenizer.nval * 1000.0);
                }
                return;
            }
            if (action.equals("screenshot")) {
                // HELP: default screenshot <path>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    screenShotPath = tokenizer.sval;
                }
                return;
            }
            System.out.println();
            throw new Exception("invalid default property " + tokenizer.sval);
        }
        System.out.println();
        throw new Exception("default argument should be string or a word");
    }

    if (cmd.equals("push")) {
        // HELP: push wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack) {
                stack = new ArrayList<Object>();
                stacks.put(action, stack);
            }
            if (action.equals("wait")) {
                stack.add(new Long(_waitFor));
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("pop")) {
        // HELP: pop wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack || stack.isEmpty()) {
                throw new Error("pop called without corresponding push");
            }
            if (action.equals("wait")) {
                int index = stack.size() - 1;
                _waitFor = (Long) stack.get(index);
                stack.remove(index);
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("echo")) {
        // HELP: echo "string"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = script.getExpandedString(tokenizer);
            System.out.print(' ');
            System.out.println(text);
            if (!_skip)
                System.out.println(text);
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("sleep")) {
        // HELP: sleep <seconds>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
            System.out.print(' ');
            System.out.println(tokenizer.nval);
            this.sleep((long) (tokenizer.nval * 1000));
            return;
        }
        System.out.println();
        throw new Exception("sleep command argument should be a number");
    }

    if (cmd.equals("fail")) {
        // HELP: fail "<message>"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = tokenizer.sval;
            System.out.print(' ');
            System.out.println(text);
            if (!_skip) {
                System.out.println("TEST FAIL: " + text);
                throw new Exception(text);
            }
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("debugger")) {
        // HELP: debugger
        System.out.println();
        this.sleepSeconds(10);
        return;
    }

    if (cmd.equals("if")) {
        // HELP: if <commands> then <commands> [else <commands>] endif
        _if = true;
        System.out.println();
        return;
    }

    if (cmd.equals("then")) {
        _if = false;
        _skip = !_test;
        System.out.println();
        return;
    }

    if (cmd.equals("else")) {
        _if = false;
        _skip = _test;
        System.out.println();
        return;
    }

    if (cmd.equals("endif")) {
        _skip = false;
        System.out.println();
        return;
    }

    if (cmd.equals("not")) {
        // HELP: not <check-command>
        System.out.println();
        _not = true;
        return;
    }

    if (null != driver) {

        // all these command require the browser to have been started

        if (cmd.equals("field") || cmd.equals("id") || cmd.equals("test-id")) {
            // HELP: field "<test-id>"
            // HELP: id "<test-id>"
            // HELP: test-id "<test-id>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.setContextToField(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a form.field argument");
        }

        if (cmd.equals("select")) {
            // HELP: select "<query-selector>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                selectContext(tokenizer, script);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("xpath")) {
            // HELP: xpath "<xpath-expression>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.xpathContext(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("wait")) {
            // HELP: wait <seconds>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.print(' ');
                System.out.println(tokenizer.nval);

                // we will repeat then next select type command until it succeeds or we timeout
                _waitFor = (long) ((new Date()).getTime() + (tokenizer.nval * 1000));
                return;
            }

            // HELP: wait <action>
            if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
                String action = tokenizer.sval;
                System.out.println(' ');
                System.out.println(action);
                if (action.equals("clickable")) {
                    long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                    if (sleep > 0) {
                        System.out.println("WebDriverWait for " + sleep + " seconds");
                        WebDriverWait wait = new WebDriverWait(driver, sleep);
                        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(selection));
                        if (element != selection) {
                            throw new Exception("element is not clickable");
                        }
                    } else {
                        System.out.println("WebDriverWait for " + sleep + " seconds (skipped)");
                    }
                    return;
                }
            }
            throw new Exception(cmd + " command requires a seconds argument");
        }

        if (cmd.equals("set") || cmd.equals("send")) {
            // HELP: set "<value>"
            // HELP: send "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.setContextValue(cmd, script, tokenizer, cmd.equals("set"));
                return;
            }
            System.out.println();
            throw new Exception("set command requires a value argument");
        }

        if (cmd.equals("test") || cmd.equals("check")) {
            // HELP: test "<value>"
            // HELP: check "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, false);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("checksum")) {
            // HELP: checksum "<checksum>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, true);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("click") || cmd.equals("click-now")) {
            // HELP: click
            System.out.println();
            final boolean wait = !cmd.equals("click-now");
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (wait) {
                            long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                            if (sleep > 0) {
                                System.out.println("WebDriverWait for " + sleep + " seconds");
                                WebDriverWait wait = new WebDriverWait(driver, sleep);
                                WebElement element = wait
                                        .until(ExpectedConditions.elementToBeClickable(selection));
                                if (element == selection) {
                                    selection.click();
                                    return;
                                } else {
                                    throw new RetryException("click failed");
                                }
                            }
                        }
                        // click-nowait, no or negative wait period, just click
                        selection.click();
                    }
                }
            };
            return;
        }

        if (cmd.equals("scroll-into-view")) {
            // HELP: scroll-into-view
            System.out.println();
            if (null == selection)
                throw new Exception(cmd + " command requires a field selection at line " + tokenizer.lineno());
            if (!_skip) {
                try {
                    scrollContextIntoView(selection);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    info(selection, selectionCommand, false);
                    throw e;
                }
            }
            return;
        }

        if (cmd.equals("clear")) {
            // HELP: clear
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() {
                    if (!_skip)
                        selection.clear();
                }
            };
            return;
        }

        if (cmd.equals("call")) {
            // HELP: call <function> { args ... }
            String function = null, args = null;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                function = script.getExpandedString(tokenizer);
                System.out.print(' ');
                System.out.print(function);
                args = getBlock(script, tokenizer, ',', true);
                System.out.println();
                if (_skip)
                    return;
                if (null == args)
                    args = "";
                String js = "var result = window.RegressionTest.test('" + function + "',[" + args + "]);"
                        + "arguments[arguments.length-1](result);";
                System.out.println("> " + js);
                Object result = driver.executeAsyncScript(js);
                if (null != result) {
                    if (result.getClass() == RemoteWebElement.class) {
                        selection = (RemoteWebElement) result;
                        stype = SelectionType.Script;
                        selector = js;
                        System.out.println("new selection " + selection);
                    }
                }
                return;
            }
            System.out.println();
            throw new Exception("missing arguments for call statement at line " + tokenizer.lineno());
        }

        if (cmd.equals("enabled")) {
            // HELP: enabled
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isEnabled() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("enabled check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("selected")) {
            // HELP: selected
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isSelected() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("selected check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("displayed")) {
            // HELP: displayed
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isDisplayed() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("displayed check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("at")) {
            // HELP: at <x|*>,<y>
            int x = 0, y = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                x = (int) tokenizer.nval;
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    x = -1;
                    System.out.print('*');
                } else {
                    x = (int) tokenizer.nval;
                    System.out.print(x);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        y = (int) tokenizer.nval;
                        System.out.print(y);
                        System.out.println();
                        final int X = x;
                        final int Y = y;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Point loc = selection.getLocation();
                                    if (((loc.x == X || X == -1) && loc.y == Y) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("location check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("at missing co-ordiantes at line " + tokenizer.lineno());
        }

        if (cmd.equals("size")) {
            // HELP: size <w|*>,<h>
            int mw = 0, w = 0, h = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    mw = w = -1;
                    System.out.print('*');
                } else {
                    mw = w = (int) tokenizer.nval;
                    System.out.print(w);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ':') {
                    tokenizer.nextToken();
                    w = (int) tokenizer.nval;
                    System.out.print(':');
                    System.out.print(w);
                    tokenizer.nextToken();
                }
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        h = (int) tokenizer.nval;
                        System.out.print(h);
                        System.out.println();
                        final int MW = mw;
                        final int W = w;
                        final int H = h;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Dimension size = selection.getSize();
                                    if (((MW == -1 || (size.width >= MW && size.width <= W))
                                            && size.height == H) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("size check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("size missing dimensions at line " + tokenizer.lineno());
        }

        if (cmd.equals("tag")) {
            // HELP: tag <tag-name>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                System.out.println();
                new WaitFor(cmd, tokenizer, true) {
                    @Override
                    protected void run() throws RetryException {
                        if (!_skip) {
                            String tag = selection.getTagName();
                            if (tokenizer.sval.equals(tag) != _not) {
                                _not = false;
                                return;
                            }
                            throw new RetryException("tag \"" + tokenizer.sval + "\" check failed, tag is "
                                    + tag + " at line " + tokenizer.lineno());
                        }
                    }
                };
                return;
            }
            System.out.println();
            throw new Exception("tag command has missing tag name at line " + tokenizer.lineno());
        }

        if (cmd.equals("info")) {
            // HELP: info
            System.out.println();
            if (null == selection)
                throw new Exception("info command requires a selection at line " + tokenizer.lineno());
            info(selection, selectionCommand, true);
            return;
        }

        if (cmd.equals("alert")) {
            // HELP: alert accept
            System.out.println();
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                if (tokenizer.sval.equals("accept")) {
                    System.out.println();
                    if (!_skip)
                        driver.switchTo().alert().accept();
                    return;
                }
            }
            System.out.println();
            throw new Exception("alert syntax error at line " + tokenizer.lineno());
        }

        if (cmd.equals("dump")) {
            // HELP: dump
            System.out.println();
            if (!_skip)
                dump();
            return;
        }

        if (cmd.equals("mouse")) {
            // HELP: mouse { <center|0,0|origin|body|down|up|click|+/-x,+/-y> commands ... }
            parseBlock(script, tokenizer, new BlockHandler() {
                public void parseToken(StreamTokenizer tokenizer, String token) {
                    int l = token.length();
                    if (token.equals("center")) {
                        actions.moveToElement(selection);
                    } else if ((l > 1 && token.substring(1, l - 1).equals("0,0")) || token.equals("origin")) {
                        actions.moveToElement(selection, 0, 0);
                    } else if (token.equals("body")) {
                        actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
                    } else if (token.equals("down")) {
                        actions.clickAndHold();
                    } else if (token.equals("up")) {
                        actions.release();
                    } else if (token.equals("click")) {
                        actions.click();
                    } else if (l > 1) {
                        String[] a = token.substring(1, l - 1).split(",");
                        actions.moveByOffset(Integer.valueOf(a[0]), Integer.valueOf(a[1]));
                    } else {
                        // no-op
                    }
                }
            });
            System.out.println();
            actions.release();
            actions.build().perform();
            return;
        }

        if (cmd.equals("screenshot")) {
            // HELP: screenshot "<path>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                String path = tokenizer.sval;
                System.out.print(' ');
                System.out.println(path);
                if (!_skip) {
                    WebDriver augmentedDriver = new Augmenter().augment(driver);
                    File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
                    String outputPath;
                    if (screenShotPath == null || path.startsWith("/") || path.substring(1, 1).equals(":")) {
                        outputPath = path;
                    } else {
                        outputPath = screenShotPath + (screenShotPath.endsWith("/") ? "" : "/") + path;
                    }
                    System.out.println(screenshot.getAbsolutePath() + " -> " + path);
                    FileUtils.moveFile(screenshot, new File(outputPath));
                }
                return;
            }
            System.out.println();
            throw new Exception("screenshot argument should be a path");
        }
    }

    if (functions.containsKey(cmd)) {
        executeFunction(cmd, file, tokenizer, script);
        return;
    }

    if (null == driver) {
        throw new Exception("browser start must be used before attempt to interract with the browser");
    }

    System.out.println();
    throw new Exception("unrecognised command, " + cmd);
}

From source file:com.vendsy.bartsy.venue.BartsyApplication.java

ArrayList<Order> processRemovedOrders(ArrayList<Order> localOrders, ArrayList<Order> remoteOrders) {

    Log.w(TAG, "processRemovedOrders()");

    // Find the orders to remove and store them in a separate list to avoid iterator issues
    ArrayList<Order> removedOrders = new ArrayList<Order>();
    for (Order order : localOrders) {
        Order remoteOrder = findMatchingOrder(remoteOrders, order);
        if (remoteOrder == null) {

            switch (order.status) {

            // The orders are gone from the host's state, remove them from the local cache too
            case Order.ORDER_STATUS_COMPLETE:
            case Order.ORDER_STATUS_REJECTED:
            case Order.ORDER_STATUS_FAILED:
            case Order.ORDER_STATUS_INCOMPLETE:
                removedOrders.add(order);
                break;

            // Local state only, the host doesn't know about those orders any more. 
            case Order.ORDER_STATUS_CANCELLED:
            case Order.ORDER_STATUS_TIMEOUT:
                break;

            // These states should really not be appearing, but if they do change them to cancelled (server timeout) state
            case Order.ORDER_STATUS_NEW:
            case Order.ORDER_STATUS_IN_PROGRESS:
                order.setCancelledState(
                        "This order took too long and it timed out. Please process orders promptly.");
                break;
            case Order.ORDER_STATUS_READY:
                order.setCancelledState(
                        "This order was not picked up on time and the customer was charged. You may dispose of it or wait in case the customer comes to claim it.");
                break;

            // This local state should not exist without the host also being in the same state. Remove them
            case Order.ORDER_STATUS_OFFERED:
            case Order.ORDER_STATUS_OFFER_REJECTED:
            case Order.ORDER_STATUS_REMOVED:
                Log.e(TAG, "Illegal order: " + order.orderId + " with status: " + order.status
                        + ". Removing it locally");
                removedOrders.add(order);
                break;
            default:
                order.setTimeoutState();
                break;
            }// w  ww .j a v  a  2s.c o  m
        }
    }

    // Remove orders found
    for (Order order : removedOrders) {
        localOrders.remove(order);
    }

    return removedOrders;
}

From source file:com.clustercontrol.jobmanagement.composite.WaitRuleComposite.java

/**
 * ????// w  w w.jav  a 2s  . co  m
 * 
 * @param jobType 
 */
private void initialize(int jobType) {

    this.setLayout(JobDialogUtil.getParentLayout());

    // 
    Label tableTitle = new Label(this, SWT.NONE);
    tableTitle.setText(Messages.getString("object.list"));

    // 
    int addTableWidth = 0;
    if (jobType == JobConstant.TYPE_JOBNET) {
        // ?
        addTableWidth = 0;
    } else if (jobType == JobConstant.TYPE_JOB) {
        // 
        addTableWidth = 170;
    } else if (jobType == JobConstant.TYPE_FILEJOB) {
        // 
        addTableWidth = 170;
    } else if (jobType == JobConstant.TYPE_REFERJOB || jobType == JobConstant.TYPE_REFERJOBNET) {
        // ???????
        addTableWidth = 0;
    } else if (jobType == JobConstant.TYPE_APPROVALJOB) {
        // ?
        addTableWidth = 170;
    } else if (jobType == JobConstant.TYPE_MONITORJOB) {
        // 
        addTableWidth = 170;
    }

    Table table = new Table(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.SINGLE);
    WidgetTestUtil.setTestId(this, "table", table);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setLayoutData(new RowData(430 + addTableWidth, 100));

    // Composite
    Composite buttonComposite = new Composite(this, SWT.NONE);
    buttonComposite.setLayout(new RowLayout());

    // dummy
    new Label(buttonComposite, SWT.NONE)
            .setLayoutData(new RowData(200 + addTableWidth, SizeConstant.SIZE_LABEL_HEIGHT));

    // 
    this.m_createCondition = new Button(buttonComposite, SWT.NONE);
    WidgetTestUtil.setTestId(this, "m_createCondition", this.m_createCondition);
    this.m_createCondition.setText(Messages.getString("add"));
    this.m_createCondition.setLayoutData(new RowData(80, SizeConstant.SIZE_BUTTON_HEIGHT));
    this.m_createCondition.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            m_log.debug("widgetSelected");
            WaitRuleDialog dialog = new WaitRuleDialog(m_shell, m_jobTreeItem);
            if (dialog.open() == IDialogConstants.OK_ID) {

                // ????????
                boolean addWaitRule = true;

                @SuppressWarnings("unchecked")
                ArrayList<Integer> info = (ArrayList<Integer>) dialog.getInputData();
                @SuppressWarnings("unchecked")
                ArrayList<ArrayList<Integer>> list = (ArrayList<ArrayList<Integer>>) m_viewer.getInput();
                if (list == null) {
                    list = new ArrayList<ArrayList<Integer>>();

                } else {

                    //?????????????false??
                    int newWaitRuleType = (Integer) info.get(GetWaitRuleTableDefine.JUDGMENT_OBJECT);
                    if (newWaitRuleType == JudgmentObjectConstant.TYPE_TIME) {

                        for (ArrayList<Integer> waitRule : list) {
                            m_log.debug("WaitRuleComposite_initialize_info = " + info);
                            int rule = waitRule.get(GetWaitRuleTableDefine.JUDGMENT_OBJECT);
                            m_log.debug("WaitRuleComposite_initialize_rule = " + rule);
                            if (rule == JudgmentObjectConstant.TYPE_TIME) {
                                addWaitRule = false;

                                MessageDialog.openWarning(null, Messages.getString("warning"),
                                        Messages.getString("message.job.61"));
                            }
                        }
                    } else if (newWaitRuleType == JudgmentObjectConstant.TYPE_START_MINUTE) {

                        for (ArrayList<Integer> waitRule : list) {
                            m_log.debug("WaitRuleComposite_initialize_info = " + info);
                            int rule = waitRule.get(GetWaitRuleTableDefine.JUDGMENT_OBJECT);
                            m_log.debug("WaitRuleComposite_initialize_rule = " + rule);
                            if (rule == JudgmentObjectConstant.TYPE_START_MINUTE) {
                                addWaitRule = false;

                                MessageDialog.openWarning(null, Messages.getString("warning"),
                                        Messages.getString("message.job.62"));
                            }
                        }
                    }
                }

                if (addWaitRule)
                    list.add(info);
                m_viewer.setInput(list);
            }
        }
    });

    // 
    this.m_modifyCondition = new Button(buttonComposite, SWT.NONE);
    WidgetTestUtil.setTestId(this, "m_modifyCondition", this.m_modifyCondition);
    this.m_modifyCondition.setText(Messages.getString("modify"));
    this.m_modifyCondition.setLayoutData(new RowData(80, SizeConstant.SIZE_BUTTON_HEIGHT));
    this.m_modifyCondition.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            WaitRuleDialog dialog = new WaitRuleDialog(m_shell, m_jobTreeItem);
            if (m_selectItem != null) {
                dialog.setInputData(m_selectItem);
                if (dialog.open() == IDialogConstants.OK_ID) {

                    ArrayList<?> info = dialog.getInputData();
                    @SuppressWarnings("unchecked")
                    ArrayList<ArrayList<?>> list = (ArrayList<ArrayList<?>>) m_viewer.getInput();

                    list.remove(m_selectItem);
                    list.add(info);

                    m_selectItem = null;
                    m_viewer.setInput(list);
                }
            } else {

            }
        }
    });

    // 
    this.m_deleteCondition = new Button(buttonComposite, SWT.NONE);
    WidgetTestUtil.setTestId(this, "m_deleteCondition", this.m_deleteCondition);
    this.m_deleteCondition.setText(Messages.getString("delete"));
    this.m_deleteCondition.setLayoutData(new RowData(80, SizeConstant.SIZE_BUTTON_HEIGHT));
    this.m_deleteCondition.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            ArrayList<?> list = (ArrayList<?>) m_viewer.getInput();
            list.remove(m_selectItem);
            m_selectItem = null;
            m_viewer.setInput(list);
        }
    });

    // separator
    JobDialogUtil.getSeparator(this);

    // ??
    Group group = new Group(this, SWT.NONE);
    group.setText(Messages.getString("condition.between.objects"));
    group.setLayout(new RowLayout());

    // ??AND
    this.m_andCondition = new Button(group, SWT.RADIO);
    WidgetTestUtil.setTestId(this, "m_andCondition", this.m_andCondition);
    this.m_andCondition.setText(Messages.getString("and"));
    this.m_andCondition.setLayoutData(new RowData(100, SizeConstant.SIZE_BUTTON_HEIGHT));

    // ??OR
    this.m_orCondition = new Button(group, SWT.RADIO);
    WidgetTestUtil.setTestId(this, "m_orCondition", this.m_orCondition);
    this.m_orCondition.setText(Messages.getString("or"));
    this.m_orCondition.setLayoutData(new RowData(100, SizeConstant.SIZE_BUTTON_HEIGHT));

    // separator
    JobDialogUtil.getSeparator(this);

    // ???????
    this.m_endCondition = new Button(this, SWT.CHECK);
    WidgetTestUtil.setTestId(this, "m_endCondition", this.m_endCondition);
    this.m_endCondition.setText(Messages.getString("end.if.condition.unmatched"));
    this.m_endCondition.setLayoutData(new RowData(220, SizeConstant.SIZE_BUTTON_HEIGHT + 5));
    this.m_endCondition.addSelectionListener(new SelectionListener() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Button check = (Button) e.getSource();
            WidgetTestUtil.setTestId(this, null, check);
            if (check.getSelection()) {
                m_endStatus.setEnabled(true);
                m_endValue.setEditable(true);
            } else {
                m_endStatus.setEnabled(false);
                m_endValue.setEditable(false);
            }
            update();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {

        }
    });

    // ??????Composite
    Composite endConditionGroup = new Composite(this, SWT.BORDER);
    endConditionGroup.setLayout(new GridLayout(2, false));

    // ??????
    Label endStatusTitle = new Label(endConditionGroup, SWT.LEFT);
    endStatusTitle.setText(Messages.getString("end.status") + " : ");
    endStatusTitle.setLayoutData(new GridData(80, SizeConstant.SIZE_LABEL_HEIGHT));

    // ??????
    this.m_endStatus = new Combo(endConditionGroup, SWT.CENTER | SWT.READ_ONLY);
    WidgetTestUtil.setTestId(this, "m_endStatus", this.m_endStatus);
    this.m_endStatus.setLayoutData(new GridData(100, SizeConstant.SIZE_COMBO_HEIGHT));
    this.m_endStatus.add(EndStatusMessage.STRING_NORMAL);
    this.m_endStatus.add(EndStatusMessage.STRING_WARNING);
    this.m_endStatus.add(EndStatusMessage.STRING_ABNORMAL);

    // ??????
    Label endValueTitle = new Label(endConditionGroup, SWT.LEFT);
    endValueTitle.setText(Messages.getString("end.value") + " : ");
    endValueTitle.setLayoutData(new GridData(80, SizeConstant.SIZE_LABEL_HEIGHT));

    // ??????
    this.m_endValue = new Text(endConditionGroup, SWT.BORDER);
    WidgetTestUtil.setTestId(this, "m_endValue", this.m_endValue);
    this.m_endValue.setLayoutData(new GridData(100, SizeConstant.SIZE_TEXT_HEIGHT));
    this.m_endValue.addVerifyListener(
            new NumberVerifyListener(DataRangeConstant.SMALLINT_LOW, DataRangeConstant.SMALLINT_HIGH));
    this.m_endValue.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent arg0) {
            update();
        }
    });

    this.m_viewer = new CommonTableViewer(table);
    this.m_viewer.createTableColumn(GetWaitRuleTableDefine.get(), GetWaitRuleTableDefine.SORT_COLUMN_INDEX,
            GetWaitRuleTableDefine.SORT_ORDER);
    this.m_viewer.addSelectionChangedListener(new WaitRuleSelectionChangedListener(this));
}

From source file:net.cellcloud.android.MainActivity.java

private void startDemo() {
    if (this.running) {
        return;//from   www.  j av a  2  s  .c  o  m
    }

    this.txtLog.append("Start demo ...\n");

    this.counts.set(0);

    final int num = 30;

    // 
    final ArrayList<Primitive> primList = new ArrayList<Primitive>(num);

    for (int i = 0; i < num; ++i) {
        Primitive primitive = new Primitive();
        primitive.commit(new SubjectStuff(Utils.randomInt()));
        primitive.commit(new PredicateStuff(Utils.randomString(1024)));
        primitive.commit(new ObjectiveStuff(Utils.randomInt() % 2 == 0 ? true : false));

        JSONObject json = new JSONObject();
        try {
            json.put("name", "Xu Jiangwei");
            json.put("timestamp", System.currentTimeMillis());

            JSONObject phone = new JSONObject();
            phone.put("name", "iPhone");
            phone.put("vendor", "Apple");
            json.put("phone", phone);

            JSONObject c1 = new JSONObject();
            c1.put("name", "ThinkPad");
            c1.put("vendor", "Lenovo");

            JSONObject c2 = new JSONObject();
            c2.put("name", "MacBook Pro");
            c2.put("vendor", "Apple");

            JSONArray computers = new JSONArray();
            computers.put(c1);
            computers.put(c2);

            json.put("computer", computers);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        primitive.commit(new AttributiveStuff(json.toString()));
        primList.add(primitive);
    }

    // 
    final ArrayList<ActionDialect> dialectList = new ArrayList<ActionDialect>(num);
    for (int i = 0; i < num; ++i) {
        ActionDialect ad = new ActionDialect();
        ad.setAction("test");

        JSONObject json = null;
        try {
            json = new JSONObject(
                    "{\"total\":26,\"authorized\":true,\"root\":[{\"id\":\"8a000217444e1a0c01444e26ebdc0001\",\"summary\":\"as\",\"servicelevelSymbol\":\"\",\"stateName\":\"?\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000005\",\"updatedOn\":\"2014-02-20 15:18:17\"},{\"id\":\"8a0002d24449830a0144498955970001\",\"summary\":\"bb\",\"servicelevelSymbol\":\"\",\"stateName\":\"?\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000004\",\"updatedOn\":\"2014-02-19 17:47:13\"},{\"id\":\"8a0002d2444977bd0144497c3caf0001\",\"summary\":\"vv\",\"servicelevelSymbol\":\"\",\"stateName\":\"?\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000003\",\"updatedOn\":\"2014-02-19 17:32:25\"},{\"id\":\"8a0002d2444971420144497263530001\",\"summary\":\"dd\",\"servicelevelSymbol\":\"\",\"stateName\":\"?\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000002\",\"updatedOn\":\"2014-02-19 17:21:51\"},{\"id\":\"8a0002d244496e050144496f21370001\",\"summary\":\"sss\",\"servicelevelSymbol\":\"\",\"stateName\":\"?\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000001\",\"updatedOn\":\"2014-02-19 17:18:10\"},{\"id\":\"8a0002bd446d12d301446d183d480001\",\"summary\":\"\",\"servicelevelSymbol\":\"\",\"stateName\":\"\",\"isMajor\":\"2\",\"isOvertime\":\"\",\"code\":\"Incident00000012\",\"updatedOn\":\"2009-02-12 00:00:00\"}],\"success\":true}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ad.appendParam("data", json.toString());

        dialectList.add(ad);
    }

    this.running = true;

    Thread t = new Thread() {
        @Override
        public void run() {
            while (running) {
                if (!primList.isEmpty()) {
                    Primitive primitive = primList.remove(0);
                    TalkService.getInstance().talk(identifier, primitive);
                }

                try {
                    Thread.sleep(Utils.randomInt(200, 300));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (!dialectList.isEmpty()) {
                    ActionDialect dialect = dialectList.remove(0);
                    TalkService.getInstance().talk(identifier, dialect);
                }

                try {
                    Thread.sleep(Utils.randomInt(200, 300));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (primList.isEmpty() && dialectList.isEmpty()) {
                    try {
                        Thread.sleep(Utils.randomInt(500, 800));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            stopDemo();
                        }
                    });

                    break;
                }
            } // #while
        }
    };
    t.start();
}

From source file:com.tesora.dve.sql.parser.TranslatorUtils.java

public Statement buildDeleteStatement(List<FromTableReference> tableRefs, List<Name> explicitRefs,
        ExpressionNode whereClause, List<SortingSpecification> orderbys, LimitSpecification limit,
        Object sloc) {//  www .ja  v  a  2s.  c  o  m
    List<TableInstance> explicitDeletes = null;
    if (explicitRefs == null || explicitRefs.isEmpty()) {
        // ignore
    } else {
        explicitDeletes = new ArrayList<TableInstance>();
        for (Name r : explicitRefs) {
            if (pc.getCapability() == Capability.PARSING_ONLY) {
                explicitDeletes.add(new TableInstance(null, r, null, false));
            } else {
                Name actual = r;
                // if it has a trailing * strip that off
                List<UnqualifiedName> parts = r.getParts();
                if (parts.size() > 1 && parts.get(parts.size() - 1).isAsterisk()) {
                    ArrayList<UnqualifiedName> nparts = new ArrayList<UnqualifiedName>(parts);
                    nparts.remove(nparts.size() - 1);
                    if (nparts.size() == 1)
                        actual = nparts.get(0);
                    else
                        actual = new QualifiedName(nparts);
                }
                explicitDeletes.add(scope.lookupTableInstance(pc, actual, true));
            }
        }
    }
    DeleteStatement ds = new DeleteStatement(explicitDeletes, tableRefs, whereClause, orderbys, limit, false,
            new AliasInformation(scope), SourceLocation.make(sloc));
    ds.getDerivedInfo().takeScope(scope);

    shouldSetTimestampVariable(ds, null, null);

    return ds;
}

From source file:Control.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w ww. ja  v a  2  s  .  co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int k = 0;
    String userid = null;
    ArrayList<String> nameImage = new ArrayList<String>();
    String album = null;
    ArrayList<String> typeImage = new ArrayList<String>();
    ArrayList<Integer> priceImage = new ArrayList<Integer>();

    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    if (absoluteTempPath == null) {
        String serverContext = this.getServletContext().getRealPath("/");
        String createPath = serverContext + "temp";
        File tempfolder = new File(createPath);
        tempfolder.mkdir();
        absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    }
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (int i = items.size() - 1; i >= 0; i--) {
                if (items.get(i).isFormField()) {
                    if (null != items.get(i).getFieldName())
                        switch (items.get(i).getFieldName()) {
                        case "userid":
                            userid = items.get(i).getString();
                            break;
                        case "nameImageUpload":
                            nameImage.add(items.get(i).getString());
                            break;
                        case "albumUpload":
                            album = items.get(i).getString();
                            break;
                        case "typeImageUpload":
                            typeImage.add(items.get(i).getString());
                            break;
                        case "priceImageUpload":
                            priceImage.add(parseInt(items.get(i).getString()));
                            break;
                        default:
                            break;
                        }
                } else if ("images".equals(items.get(i).getFieldName())) {
                    if (!"".equals(items.get(i).getName()) && !items.get(i).getName().isEmpty()) {
                        String extension = null;
                        String newLink;
                        Integer newIntIdImage = Image.listImg.size() + k;
                        String newIdImage = newIntIdImage.toString();
                        if (items.get(i).getName().endsWith("jpg")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("JPG")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("png")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else if (items.get(i).getName().endsWith("PNG")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else {
                            return;
                        }
                        boolean check = Image_DAL.addImage(newLink, userid, album, nameImage.get(0),
                                typeImage.get(0), priceImage.get(0));
                        nameImage.remove(0);
                        typeImage.remove(0);
                        priceImage.remove(0);
                        if (check) {
                            items.get(i).write(file);
                            k++;
                        }
                    }
                } else {
                }
            }
            request.setAttribute("user", userid);
            RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
            dispatcher.forward(request, response);
            return;
        }
        for (int i = items.size() - 1; i >= 0; i--)
            if (items.get(i).isFormField())
                if ("userid".equals(items.get(i).getFieldName()))
                    userid = items.get(i).getString();

        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}