Example usage for java.util Vector firstElement

List of usage examples for java.util Vector firstElement

Introduction

In this page you can find the example usage for java.util Vector firstElement.

Prototype

public synchronized E firstElement() 

Source Link

Document

Returns the first component (the item at index 0 ) of this vector.

Usage

From source file:edu.umn.cs.spatialHadoop.util.Parallel.java

public static <T> List<T> forEach(int start, int end, RunnableRange<T> r, int parallelism)
        throws InterruptedException {
    Vector<T> results = new Vector<T>();
    if (end <= start)
        return results;
    final Vector<Throwable> exceptions = new Vector<Throwable>();
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            exceptions.add(ex);/* w w w  . ja v  a  2 s.  com*/
        }
    };

    // Put an upper bound on parallelism to avoid empty ranges
    if (parallelism > (end - start))
        parallelism = end - start;
    if (parallelism == 1) {
        // Avoid creating threads
        results.add(r.run(start, end));
    } else {
        LOG.info("Creating " + parallelism + " threads");
        final int[] partitions = new int[parallelism + 1];
        for (int i_thread = 0; i_thread <= parallelism; i_thread++)
            partitions[i_thread] = i_thread * (end - start) / parallelism + start;
        final Vector<RunnableRangeThread<T>> threads = new Vector<RunnableRangeThread<T>>();
        for (int i_thread = 0; i_thread < parallelism; i_thread++) {
            RunnableRangeThread<T> thread = new RunnableRangeThread<T>(r, partitions[i_thread],
                    partitions[i_thread + 1]);
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
            threads.lastElement().start();
        }
        for (int i_thread = 0; i_thread < parallelism; i_thread++) {
            threads.get(i_thread).join();
            results.add(threads.get(i_thread).getResult());
        }
        if (!exceptions.isEmpty())
            throw new RuntimeException(exceptions.size() + " unhandled exceptions", exceptions.firstElement());
    }
    return results;
}

From source file:com.ibm.xsp.webdav.resource.DAVResourceDomino.java

public boolean filter() {
    boolean ret = true;
    // // LOGGER.info("Start filter ");
    DAVRepositoryDomino rep = (DAVRepositoryDomino) this.getRepository();
    String filter = rep.getFilter();
    if (filter.equals("")) {
        // LOGGER.info("Filter null");
        return true;
    }/*from w  ww .j a  va2 s .c om*/
    // LOGGER.info("Filter is "+filter);
    Document doc = getDocument();
    if (doc == null) {
        // LOGGER.info("Get Document is null");
        return ret;
    }
    try {
        DAVRepositoryMETA drm = WebDavManager.getManager(null).getRepositoryMeta();
        if (drm == null) {
            return true;
        }
        Base repDoc = (Base) DominoProxy.resolve(drm.getRepositoryConfigLocation());
        if (repDoc != null) {
            // LOGGER.info("Rep internal address not null; has class="+repDoc.getClass().toString());
            Database db = null;
            if (repDoc instanceof Document) {
                // LOGGER.info("rep doc is a Document");
                db = ((Document) repDoc).getParentDatabase();
            }
            if (repDoc instanceof View) {
                // LOGGER.info("repdoc is a view");
                View vw = ((View) repDoc);
                db = (Database) vw.getParent();
            }
            if (db != null) {
                // LOGGER.info("Parent database not null");
                Document docP = db.createDocument();
                // LOGGER.info("Create document parameters...");
                docP.replaceItemValue("Form", "webDavParameters");
                docP.computeWithForm(true, false);
                // LOGGER.info("Compute with form OK!");
                @SuppressWarnings("rawtypes")
                Vector items = docP.getItems();
                for (int i = 0; i < items.size(); i++) {
                    Item itm = (Item) items.get(i);
                    // LOGGER.info("Item "+itm.getName()+"="+itm.getValueString());
                    filter = filter.replaceAll("\\x5B\\x5B" + itm.getName() + "\\x5D\\x5D",
                            "\"" + itm.getValueString() + "\"");
                }
                if (!filter.equals("")) {
                    // LOGGER.info("Filter="+filter);
                    Session ses = DominoProxy.getUserSession();
                    @SuppressWarnings("rawtypes")
                    Vector eval = ses.evaluate(filter, doc);
                    if (eval == null) {
                        return true;
                    }
                    String retS = eval.firstElement().toString().toLowerCase();
                    // LOGGER.info("Evaluate result="+retS);
                    if (retS.equals("1.0")) {
                        // LOGGER.info("Filter pass OK!");
                        return true;
                    } else {
                        // LOGGER.info("Filter didn't pass");
                        return false;
                    }
                }
            }
        }

    } catch (NotesException ne) {
        LOGGER.error("Error on filter;" + ne.getMessage());
        return ret;
    }
    return ret;
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

public static boolean multiplot(Path[] input, Path output, OperationsParams params)
        throws IOException, InterruptedException, ClassNotFoundException, ParseException {
    String timeRange = params.get("time");
    final Date dateFrom, dateTo;
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    try {//  w w w  .ja v a 2s.  co  m
        String[] parts = timeRange.split("\\.\\.");
        dateFrom = dateFormat.parse(parts[0]);
        dateTo = dateFormat.parse(parts[1]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println("Use the seperator two periods '..' to seperate from and to dates");
        return false; // To avoid an error that causes dateFrom to be uninitialized
    } catch (ParseException e) {
        System.err.println("Illegal date format in " + timeRange);
        return false;
    }
    // Number of frames to combine in each image
    int combine = params.getInt("combine", 1);
    // Retrieve all matching input directories based on date range
    Vector<Path> matchingPathsV = new Vector<Path>();
    for (Path inputFile : input) {
        FileSystem inFs = inputFile.getFileSystem(params);
        FileStatus[] matchingDirs = inFs.listStatus(input, new PathFilter() {
            @Override
            public boolean accept(Path p) {
                String dirName = p.getName();
                try {
                    Date date = dateFormat.parse(dirName);
                    return date.compareTo(dateFrom) >= 0 && date.compareTo(dateTo) <= 0;
                } catch (ParseException e) {
                    LOG.warn("Cannot parse directory name: " + dirName);
                    return false;
                }
            }
        });
        for (FileStatus matchingDir : matchingDirs)
            matchingPathsV.add(new Path(matchingDir.getPath(), "*.hdf"));
    }
    if (matchingPathsV.isEmpty()) {
        LOG.warn("No matching directories to given input");
        return false;
    }

    Path[] matchingPaths = matchingPathsV.toArray(new Path[matchingPathsV.size()]);
    Arrays.sort(matchingPaths);

    // Clear all paths to ensure we set our own paths for each job
    params.clearAllPaths();

    // Create a water mask if we need to recover holes on write
    if (params.get("recover", "none").equals("write")) {
        // Recover images on write requires a water mask image to be generated first
        OperationsParams wmParams = new OperationsParams(params);
        wmParams.setBoolean("background", false);
        Path wmImage = new Path(output, new Path("water_mask"));
        HDFPlot.generateWaterMask(wmImage, wmParams);
        params.set(HDFPlot.PREPROCESSED_WATERMARK, wmImage.toString());
    }
    // Start a job for each path
    int imageWidth = -1;
    int imageHeight = -1;
    boolean overwrite = params.getBoolean("overwrite", false);
    boolean pyramid = params.getBoolean("pyramid", false);
    FileSystem outFs = output.getFileSystem(params);
    Vector<Job> jobs = new Vector<Job>();
    boolean background = params.getBoolean("background", false);
    Rectangle mbr = new Rectangle(-180, -90, 180, 90);
    for (int i = 0; i < matchingPaths.length; i += combine) {
        Path[] inputPaths = new Path[Math.min(combine, matchingPaths.length - i)];
        System.arraycopy(matchingPaths, i, inputPaths, 0, inputPaths.length);
        Path outputPath = new Path(output, inputPaths[0].getParent().getName() + (pyramid ? "" : ".png"));
        if (overwrite || !outFs.exists(outputPath)) {
            // Need to plot
            Job rj = HDFPlot.plotHeatMap(inputPaths, outputPath, params);
            if (imageHeight == -1 || imageWidth == -1) {
                if (rj != null) {
                    imageHeight = rj.getConfiguration().getInt("height", 1000);
                    imageWidth = rj.getConfiguration().getInt("width", 1000);
                    mbr = (Rectangle) OperationsParams.getShape(rj.getConfiguration(), "mbr");
                } else {
                    imageHeight = params.getInt("height", 1000);
                    imageWidth = params.getInt("width", 1000);
                    mbr = (Rectangle) OperationsParams.getShape(params, "mbr");
                }
            }
            if (background && rj != null)
                jobs.add(rj);
        }
    }
    // Wait until all jobs are done
    while (!jobs.isEmpty()) {
        Job firstJob = jobs.firstElement();
        firstJob.waitForCompletion(false);
        if (!firstJob.isSuccessful()) {
            System.err.println("Error running job " + firstJob.getJobID());
            System.err.println("Killing all remaining jobs");
            for (int j = 1; j < jobs.size(); j++)
                jobs.get(j).killJob();
            throw new RuntimeException("Error running job " + firstJob.getJobID());
        }
        jobs.remove(0);
    }

    // Draw the scale in the output path if needed
    String scalerange = params.get("scalerange");
    if (scalerange != null) {
        String[] parts = scalerange.split("\\.\\.");
        double min = Double.parseDouble(parts[0]);
        double max = Double.parseDouble(parts[1]);
        String scale = params.get("scale", "none").toLowerCase();
        if (scale.equals("vertical")) {
            MultiHDFPlot.drawVerticalScale(new Path(output, "scale.png"), min, max, 64, imageHeight, params);
        } else if (scale.equals("horizontal")) {
            MultiHDFPlot.drawHorizontalScale(new Path(output, "scale.png"), min, max, imageWidth, 64, params);
        }
    }
    // Add the KML file
    createKML(outFs, output, mbr, params);
    return true;
}

From source file:withings.apiaccess.WithingsAPI.java

public Vector<WeightValue> getValues(long startDate) throws Exception {
    String startDateString = "";
    if (startDate != WeightValue.DATE_NOT_RECORDED) {
        startDateString = "&startdate=" + Long.toString(startDate);
    }/*from   ww w .ja  va 2s . c  o m*/

    String request = "http://wbsapi.withings.net/measure?action=getmeas&userid=" + user.id + "&publickey="
            + user.publicKey + startDateString + "&devtype=1"; // Only values from the scale
    String response = performRequest(request);

    // Decode JSon object
    JSONObject json = new JSONObject(response);
    JSONArray JSONvalues = json.getJSONObject("body").getJSONArray("measuregrps");
    JSONObject JSONvalue;
    JSONArray JSONtypes;
    JSONObject JSONtype;
    float weight;
    long date;
    Vector<WeightValue> weightValues = new Vector<WeightValue>();
    int size = JSONvalues.length();
    for (int i = 0; i < size; i++) {
        JSONvalue = JSONvalues.getJSONObject(i);
        if (JSONvalue.getInt("category") != 1) { // Make sure it's a measurement (=1)
            continue;
        }
        date = JSONvalue.getLong("date");

        JSONtypes = JSONvalue.getJSONArray("measures");
        for (int j = 0; j < JSONtypes.length(); j++) {
            JSONtype = JSONtypes.getJSONObject(j);
            if (JSONtype.getInt("type") == 1) { // Weight value
                weight = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                weightValues.add(new WeightValue(date, weight));
            }
        }
    }
    if (weightValues.size() > 0) {
        lastUpdate = weightValues.firstElement().date;
        Editor editor = context.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE).edit();
        editor.putLong("lastUpdate", lastUpdate);
        editor.commit();
    }
    return weightValues;
}

From source file:cm.aptoide.pt.RemoteInSearch.java

@Override
protected void onListItemClick(ListView l, View v, final int position, long id) {

    super.onListItemClick(l, v, position, id);

    Vector<String> tmp_get = db.getApk(apk_lst.get(position).apkid);

    String tmp_path = this.getString(R.string.icons_path) + apk_lst.get(position).apkid;
    File test_icon = new File(tmp_path);

    LayoutInflater li = LayoutInflater.from(this);
    View view = li.inflate(R.layout.alertscroll, null);
    Builder alrt = new AlertDialog.Builder(this).setView(view);
    final AlertDialog p = alrt.create();
    if (test_icon.exists() && test_icon.length() > 0) {
        p.setIcon(new BitmapDrawable(tmp_path));
    } else {/*from   www. j a v a2s  .com*/
        p.setIcon(android.R.drawable.sym_def_app_icon);
    }
    p.setTitle(apk_lst.get(position).name);
    TextView t1 = (TextView) view.findViewById(R.id.n11);
    t1.setText(tmp_get.firstElement());
    TextView t2 = (TextView) view.findViewById(R.id.n22);
    t2.setText(tmp_get.get(1));
    TextView t3 = (TextView) view.findViewById(R.id.n33);
    t3.setText(tmp_get.get(2));
    TextView t4 = (TextView) view.findViewById(R.id.n44);
    t4.setText(tmp_get.get(3));
    TextView t5 = (TextView) view.findViewById(R.id.n55);
    String tmpi = db.getDescript(apk_lst.get(position).apkid);
    if (!(tmpi == null)) {
        t5.setText(tmpi);
    } else {
        t5.setText("No info availale on server. Search market by pressing the button below for more info.");
    }

    p.setButton2("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            return;
        }
    });
    if (tmp_get.get(2).equalsIgnoreCase("\tno\n")) {
        p.setButton(getString(R.string.install), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                p.dismiss();
                new Thread() {
                    public void run() {
                        String apk_pkg = downloadFile(position);
                        if (apk_pkg == null) {
                            Message msg = new Message();
                            msg.arg1 = 1;
                            download_handler.sendMessage(msg);
                            download_error_handler.sendEmptyMessage(0);
                        } else {
                            installApk(apk_pkg, position);
                        }
                    }
                }.start();
            }
        });
        p.setButton3("Search Market", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                p.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=" + apk_lst.get(position).apkid));
                startActivity(intent);
            }
        });
    } else {
        p.setButton(getString(R.string.rem), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String apk_pkg = apk_lst.get(position).apkid;
                removeApk(apk_pkg, position);
            }
        });
        if (apk_lst.get(position).status == 2) {
            p.setButton3(getString(R.string.update), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    p.dismiss();
                    new Thread() {
                        public void run() {
                            String apk_pkg = downloadFile(position);
                            if (apk_pkg == null) {
                                //Toast.makeText(RemoteInSearch.this, "Could not connect to server!", Toast.LENGTH_LONG).show();
                                Message msg = new Message();
                                msg.arg1 = 1;
                                download_handler.sendMessage(msg);
                                download_error_handler.sendEmptyMessage(0);
                            } else {
                                installApk(apk_pkg, position);
                            }
                        }
                    }.start();
                }
            });
        } else {
            p.setButton3("Search Market", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    p.dismiss();
                    Intent intent = new Intent();
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=" + apk_lst.get(position).apkid));
                    startActivity(intent);
                }
            });
        }
    }
    p.show();
}

From source file:org.openflexo.foundation.ie.IEWOComponent.java

public boolean isASingleHTMLTable() {
    Vector<IEWidget> v = getRootSequence().getInnerWidgets();
    return v.size() == 1 && v.firstElement() instanceof IEHTMLTableWidget;
}

From source file:org.kepler.ssh.LocalDelete.java

/**
 * Recursively traverse the directories looking for matches on each level to
 * the relevant part of the mask. Matched files will be deleted. Matched
 * directories will be deleted only if 'recursive' is true.
 *//*from   w ww  .j  ava 2  s.c  o  m*/
private boolean delete(File node, Vector masks, boolean recursive) {

    if (isDebugging)
        log.debug(">>> " + node.getPath() + " with masks length = " + masks.size() + ": " + masks.toString());

    // the query is for a single file/dir --> it will be deleted now
    if (masks.isEmpty()) {
        return deleteNode(node, recursive, "Delete ");
    }

    // handle the case where path is not a directory but something else
    if (!node.isDirectory()) {
        if (node.isFile()) {
            // single file
            // this file cannot match the rest of the query mask
            return true; // this is not an error, just skip
        } else {
            // wildcardless mask referred to a non-existing file/dir
            log.error("Path " + node.getPath() + " is not a directory!");
            return false;
        }
    }

    // path refers to an existing dir.
    // Let's list its content with the appropriate mask
    String localMask = null;
    Vector restMask = (Vector) masks.clone();
    if (!masks.isEmpty()) {
        localMask = (String) masks.firstElement(); // first element as local
        // mask
        restMask.remove(0); // the rest
    }

    boolean result = true; // will become false if at least one file removal
    // fails

    // handle special masks . and .. separately
    if (localMask.equals(".") || localMask.equals("..")) {

        // we just need to call this method again with the next mask
        File newNode = new File(node, localMask);
        if (isDebugging)
            log.debug("Special case of " + localMask + " --> Call delete() with " + newNode.getPath());
        result = delete(newNode, restMask, recursive);

    } else {
        // meaningful mask... so list the directory and recursively traverse
        // directories
        MyLocalFilter localFilter = new MyLocalFilter(localMask);

        // Get files matching the localMask in the dir 'node'
        File[] files = node.listFiles(localFilter);

        if (isDebugging)
            log.debug("Found " + files.length + " matching files in " + node);

        for (int i = 0; i < files.length; i++) {
            // recursive call with the rest of the masks
            boolean succ = delete(files[i], restMask, recursive);
            if (!succ && isDebugging)
                log.debug("Failed removal of " + files[i].getPath());
            result = result && succ;
        }
    }

    if (isDebugging)
        log.debug("<<< " + node.getPath());
    return result;
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

public String getHeader(String name) {
    if (name == null || "".equals(name)) {
        throw new IllegalArgumentException("name cannot be null");
    }/*w w w. ja va 2 s .c o m*/
    String header = null;
    if (headers.containsKey(name)) {
        Vector<String> v = headers.get(name);
        if (v != null) {
            header = v.firstElement();
        }
    }
    return header;
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

private void placeStructures(Vector<AnnotationObject> annotations, boolean init) {

    // get starting point
    double y = thePlot.getRangeAxis().getRange().getUpperBound();
    double cur_x = thePlot.getDomainAxis().getRange().getLowerBound();

    double all_width = 0.;
    for (AnnotationObject a : annotations) {
        if (a.hasAnnotations())
            all_width += screenToDataX(rectangles_complete.get(a).width);
    }/*from www. j a  v a 2  s  . c  om*/

    double min_pp_x = annotations.firstElement().getPeakPoint().getX();
    double max_pp_x = annotations.lastElement().getPeakPoint().getX();
    double center_pp_x = (max_pp_x + min_pp_x) / 2;

    cur_x = Math.max(cur_x, center_pp_x - all_width / 2);

    // place annotations
    for (AnnotationObject a : annotations) {
        Point2D pp = a.getPeakPoint();
        if (a.hasAnnotations()) {
            double cur_width = screenToDataX(rectangles_complete.get(a).width);
            double x = cur_x + cur_width / 2.;
            theDocument.getAnchor(a).setLocation(x, y);
            theDocument.getControlPoints().put(a,
                    theDocument.computeControlPoint(new Point2D.Double(x, y), pp));

            cur_x += cur_width;
        } else {
            theDocument.getAnchor(a).setLocation(pp.getX(), pp.getY());
            theDocument.getControlPoints().put(a, theDocument.computeControlPoint(pp, pp));
        }
    }

    // refine control points
    for (int i = 0; i < annotations.size(); i++) {
        AnnotationObject ai = annotations.get(i);
        Point2D aai = theDocument.getAnchor(ai);
        Point2D cpi = theDocument.getControlPoint(ai);

        if (aai.getX() < cpi.getX()) {
            for (int l = i + 1; l < annotations.size(); l++) {
                AnnotationObject al = annotations.get(l);
                Point2D aal = theDocument.getAnchor(al);
                Point2D cpl = theDocument.getControlPoint(al);

                if (aal.getX() > cpi.getX())
                    break;
                if (cpl.getY() < cpi.getY()) {
                    cpl.setLocation(cpl.getX(), cpi.getY());
                    ai = al;
                    aai = aal;
                    cpi = cpl;
                } else
                    break;
            }
        } else {
            for (int l = i - 1; l >= 0; l--) {
                AnnotationObject al = annotations.get(l);
                Point2D aal = theDocument.getAnchor(al);
                Point2D cpl = theDocument.getControlPoint(al);

                if (aal.getX() < cpi.getX())
                    break;
                if (cpl.getY() < cpi.getY()) {
                    cpl.setLocation(cpl.getX(), cpi.getY());
                    ai = al;
                    aai = aal;
                    cpi = cpl;
                } else
                    break;
            }
        }
    }

    // fire events
    if (init)
        theDocument.fireDocumentInit();
    else
        theDocument.fireDocumentChanged();
}

From source file:com.owncloud.android.ui.fragment.contactsbackup.ContactsBackupFragment.java

public void openDate(@Nullable Date savedDate) {
    final ContactsPreferenceActivity contactsPreferenceActivity = (ContactsPreferenceActivity) getActivity();

    String backupFolderString = getResources().getString(R.string.contacts_backup_folder)
            + OCFile.PATH_SEPARATOR;//from  www.  jav a  2  s  .  c o m
    OCFile backupFolder = contactsPreferenceActivity.getStorageManager().getFileByPath(backupFolderString);

    Vector<OCFile> backupFiles = contactsPreferenceActivity.getStorageManager().getFolderContent(backupFolder,
            false);

    Collections.sort(backupFiles, new Comparator<OCFile>() {
        @Override
        public int compare(OCFile o1, OCFile o2) {
            if (o1.getModificationTimestamp() == o2.getModificationTimestamp()) {
                return 0;
            }

            if (o1.getModificationTimestamp() > o2.getModificationTimestamp()) {
                return 1;
            } else {
                return -1;
            }
        }
    });

    Calendar cal = Calendar.getInstance();
    int year;
    int month;
    int day;

    if (savedDate == null) {
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH) + 1;
        day = cal.get(Calendar.DAY_OF_MONTH);
    } else {
        year = savedDate.getYear();
        month = savedDate.getMonth();
        day = savedDate.getDay();
    }

    if (backupFiles.size() > 0 && backupFiles.lastElement() != null) {
        datePickerDialog = new DatePickerDialog(contactsPreferenceActivity, this, year, month, day);
        datePickerDialog.getDatePicker().setMaxDate(backupFiles.lastElement().getModificationTimestamp());
        datePickerDialog.getDatePicker().setMinDate(backupFiles.firstElement().getModificationTimestamp());

        datePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                selectedDate = null;
            }
        });

        datePickerDialog.show();
    } else {
        Toast.makeText(contactsPreferenceActivity, R.string.contacts_preferences_something_strange_happened,
                Toast.LENGTH_SHORT).show();
    }
}