Example usage for java.util Vector insertElementAt

List of usage examples for java.util Vector insertElementAt

Introduction

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

Prototype

public synchronized void insertElementAt(E obj, int index) 

Source Link

Document

Inserts the specified object as a component in this vector at the specified index .

Usage

From source file:FileTree3.java

public boolean expand(DefaultMutableTreeNode parent) {
    DefaultMutableTreeNode flag = (DefaultMutableTreeNode) parent.getFirstChild();
    if (flag == null) // No flag
        return false;
    Object obj = flag.getUserObject();
    if (!(obj instanceof Boolean))
        return false; // Already expanded

    parent.removeAllChildren(); // Remove Flag

    File[] files = listFiles();/*from w  w  w.  j a  v a 2s  .  c  o  m*/
    if (files == null)
        return true;

    Vector v = new Vector();

    for (int k = 0; k < files.length; k++) {
        File f = files[k];
        if (!(f.isDirectory()))
            continue;

        FileNode newNode = new FileNode(f);

        boolean isAdded = false;
        for (int i = 0; i < v.size(); i++) {
            FileNode nd = (FileNode) v.elementAt(i);
            if (newNode.compareTo(nd) < 0) {
                v.insertElementAt(newNode, i);
                isAdded = true;
                break;
            }
        }
        if (!isAdded)
            v.addElement(newNode);
    }

    for (int i = 0; i < v.size(); i++) {
        FileNode nd = (FileNode) v.elementAt(i);
        IconData idata = new IconData(FileTree3.ICON_FOLDER, FileTree3.ICON_EXPANDEDFOLDER, nd);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
        parent.add(node);

        if (nd.hasSubDirs())
            node.add(new DefaultMutableTreeNode(new Boolean(true)));
    }

    return true;
}

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

/**
 * Return all matching partitions according to a time range
 * @param inFile /*w  w w  . j  av a2  s  . c  o m*/
 * @param params
 * @return
 * @throws ParseException
 * @throws IOException
 */
private static Vector<Path> selectTemporalPartitions(Path inFile, OperationsParams params)
        throws ParseException, IOException {
    // 1- Run a temporal filter step to find all matching temporal partitions
    Vector<Path> matchingPartitions = new Vector<Path>();
    // List of time ranges to check. Initially it contains one range as
    // specified by the user. Eventually, it can be split into at most two
    // partitions if partially matched by a partition.
    Vector<TimeRange> temporalRanges = new Vector<TimeRange>();
    System.out.println(new TimeRange(params.get("time")));
    temporalRanges.add(new TimeRange(params.get("time")));
    Path[] temporalIndexes = new Path[] { new Path(inFile, "yearly"), new Path(inFile, "monthly"),
            new Path(inFile, "daily") };
    int index = 0;
    final FileSystem fs = inFile.getFileSystem(params);
    while (index < temporalIndexes.length && !temporalRanges.isEmpty()) {
        Path indexDir = temporalIndexes[index];
        LOG.info("Checking index dir " + indexDir);
        TemporalIndex temporalIndex = new TemporalIndex(fs, indexDir);
        for (int iRange = 0; iRange < temporalRanges.size(); iRange++) {
            TimeRange range = temporalRanges.get(iRange);
            TemporalPartition[] matches = temporalIndex.selectContained(range.start, range.end);
            if (matches != null) {
                LOG.info("Matched " + matches.length + " partitions in " + indexDir);
                for (TemporalPartition match : matches) {
                    matchingPartitions.add(new Path(indexDir, match.dirName));
                }
                // Update range to remove matching part
                TemporalPartition firstMatch = matches[0];
                TemporalPartition lastMatch = matches[matches.length - 1];
                if (range.start < firstMatch.start && range.end > lastMatch.end) {
                    // Need to split the range into two
                    temporalRanges.setElementAt(new TimeRange(range.start, firstMatch.start), iRange);
                    temporalRanges.insertElementAt(new TimeRange(lastMatch.end, range.end), iRange);
                } else if (range.start < firstMatch.start) {
                    // Update range in-place
                    range.end = firstMatch.start;
                } else if (range.end > lastMatch.end) {
                    // Update range in-place
                    range.start = lastMatch.end;
                } else {
                    // Current range was completely covered. Remove it
                    temporalRanges.remove(iRange);
                }
            }
        }
        index++;
    }

    numOfTemporalPartitionsInLastQuery = matchingPartitions.size();
    return matchingPartitions;
}

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

/**
 * Performs a spatio-temporal aggregate query on an indexed directory
 * @param inFile//w  w w. j  a v  a  2  s  .  com
 * @param params
 * @throws ParseException 
 * @throws IOException 
 */
public static AggregateQuadTree.Node aggregateQuery(Path inFile, OperationsParams params)
        throws ParseException, IOException {
    // 1- Run a temporal filter step to find all matching temporal partitions
    Vector<Path> matchingPartitions = new Vector<Path>();
    // List of time ranges to check. Initially it contains one range as
    // specified by the user. Eventually, it can be split into at most two
    // partitions if partially matched by a partition.
    Vector<TimeRange> temporalRanges = new Vector<TimeRange>();
    temporalRanges.add(new TimeRange(params.get("time")));
    Path[] temporalIndexes = new Path[] { new Path(inFile, "yearly"), new Path(inFile, "monthly"),
            new Path(inFile, "daily") };
    int index = 0;
    final FileSystem fs = inFile.getFileSystem(params);
    while (index < temporalIndexes.length && !temporalRanges.isEmpty()) {
        Path indexDir = temporalIndexes[index];
        LOG.info("Checking index dir " + indexDir);
        TemporalIndex temporalIndex = new TemporalIndex(fs, indexDir);
        for (int iRange = 0; iRange < temporalRanges.size(); iRange++) {
            TimeRange range = temporalRanges.get(iRange);
            TemporalPartition[] matches = temporalIndex.selectContained(range.start, range.end);
            if (matches != null) {
                LOG.info("Matched " + matches.length + " partitions in " + indexDir);
                for (TemporalPartition match : matches) {
                    LOG.info("Matched temporal partition: " + match.dirName);
                    matchingPartitions.add(new Path(indexDir, match.dirName));
                }
                // Update range to remove matching part
                TemporalPartition firstMatch = matches[0];
                TemporalPartition lastMatch = matches[matches.length - 1];
                if (range.start < firstMatch.start && range.end > lastMatch.end) {
                    // Need to split the range into two
                    temporalRanges.setElementAt(new TimeRange(range.start, firstMatch.start), iRange);
                    temporalRanges.insertElementAt(new TimeRange(lastMatch.end, range.end), iRange);
                } else if (range.start < firstMatch.start) {
                    // Update range in-place
                    range.end = firstMatch.start;
                } else if (range.end > lastMatch.end) {
                    // Update range in-place
                    range.start = lastMatch.end;
                } else {
                    // Current range was completely covered. Remove it
                    temporalRanges.remove(iRange);
                }
            }
        }
        index++;
    }

    numOfTemporalPartitionsInLastQuery = matchingPartitions.size();

    // 2- Find all matching files (AggregateQuadTrees) in matching partitions
    final Rectangle spatialRange = params.getShape("rect", new Rectangle()).getMBR();
    // Convert spatialRange from lat/lng space to Sinusoidal space
    double cosPhiRad = Math.cos(spatialRange.y1 * Math.PI / 180);
    double southWest = spatialRange.x1 * cosPhiRad;
    double southEast = spatialRange.x2 * cosPhiRad;
    cosPhiRad = Math.cos(spatialRange.y2 * Math.PI / 180);
    double northWest = spatialRange.x1 * cosPhiRad;
    double northEast = spatialRange.x2 * cosPhiRad;
    spatialRange.x1 = Math.min(northWest, southWest);
    spatialRange.x2 = Math.max(northEast, southEast);
    // Convert to the h v space used by MODIS
    spatialRange.x1 = (spatialRange.x1 + 180.0) / 10.0;
    spatialRange.x2 = (spatialRange.x2 + 180.0) / 10.0;
    spatialRange.y2 = (90.0 - spatialRange.y2) / 10.0;
    spatialRange.y1 = (90.0 - spatialRange.y1) / 10.0;
    // Vertically flip because the Sinusoidal space increases to the south
    double tmp = spatialRange.y2;
    spatialRange.y2 = spatialRange.y1;
    spatialRange.y1 = tmp;
    // Find the range of cells in MODIS Sinusoidal grid overlapping the range
    final int h1 = (int) Math.floor(spatialRange.x1);
    final int h2 = (int) Math.ceil(spatialRange.x2);
    final int v1 = (int) Math.floor(spatialRange.y1);
    final int v2 = (int) Math.ceil(spatialRange.y2);
    PathFilter rangeFilter = new PathFilter() {
        @Override
        public boolean accept(Path p) {
            Matcher matcher = MODISTileID.matcher(p.getName());
            if (!matcher.matches())
                return false;
            int h = Integer.parseInt(matcher.group(1));
            int v = Integer.parseInt(matcher.group(2));
            return h >= h1 && h < h2 && v >= v1 && v < v2;
        }
    };

    final Vector<Path> allMatchingFiles = new Vector<Path>();

    for (Path matchingPartition : matchingPartitions) {
        // Select all matching files
        FileStatus[] matchingFiles = fs.listStatus(matchingPartition, rangeFilter);
        for (FileStatus matchingFile : matchingFiles) {
            allMatchingFiles.add(matchingFile.getPath());
        }
    }

    // 3- Query all matching files in parallel
    Vector<Node> threadsResults = Parallel.forEach(allMatchingFiles.size(),
            new RunnableRange<AggregateQuadTree.Node>() {
                @Override
                public Node run(int i1, int i2) {
                    Node threadResult = new AggregateQuadTree.Node();
                    for (int i_file = i1; i_file < i2; i_file++) {
                        try {
                            Path matchingFile = allMatchingFiles.get(i_file);
                            Matcher matcher = MODISTileID.matcher(matchingFile.getName());
                            matcher.matches(); // It has to match
                            int h = Integer.parseInt(matcher.group(1));
                            int v = Integer.parseInt(matcher.group(2));
                            // Clip the query region and normalize in this tile
                            Rectangle translated = spatialRange.translate(-h, -v);
                            int x1 = (int) (Math.max(translated.x1, 0) * 1200);
                            int y1 = (int) (Math.max(translated.y1, 0) * 1200);
                            int x2 = (int) (Math.min(translated.x2, 1.0) * 1200);
                            int y2 = (int) (Math.min(translated.y2, 1.0) * 1200);
                            AggregateQuadTree.Node fileResult = AggregateQuadTree.aggregateQuery(fs,
                                    matchingFile, new java.awt.Rectangle(x1, y1, (x2 - x1), (y2 - y1)));
                            threadResult.accumulate(fileResult);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    return threadResult;
                }
            });
    AggregateQuadTree.Node finalResult = new AggregateQuadTree.Node();
    for (Node threadResult : threadsResults)
        finalResult.accumulate(threadResult);
    numOfTreesTouchesInLastRequest = allMatchingFiles.size();
    return finalResult;
}

From source file:edu.ku.brc.specify.datamodel.busrules.InstitutionBusRules.java

@Override
public void afterFillForm(final Object dataObj) {
    super.afterFillForm(dataObj);

    if (checkbox == null && dataObj != null) {
        Component comp = formViewObj.getControlById("curMgrRelVer");
        if (comp instanceof ValComboBox) {
            relCombobox = (ValComboBox) comp;
        }//from   w ww  . j av a  2  s. c om

        comp = formViewObj.getControlById("isRelMgrGlb");
        if (relCombobox != null && comp instanceof ValCheckBox) {
            checkbox = (ValCheckBox) comp;

            checkbox.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    relCombobox.setEnabled(checkbox.isSelected());
                    ((JLabel) formViewObj.getLabelById("curMgrRelVerLbl")).setEnabled(checkbox.isSelected());
                }
            });

            final Institution inst = (Institution) viewable.getDataObj();
            if (inst != null) {
                Vector<String> releases = new Vector<String>();
                String curRelease = AppPreferences.getGlobalPrefs().get(RELEASES, null);

                if (curRelease == null) {
                    curRelease = UIHelper.getInstall4JInstallString();
                    AppPreferences.getGlobalPrefs().put(RELEASES, curRelease);
                }
                releases.add(curRelease);

                String managedRelease = inst.getCurrentManagedRelVersion();
                if (managedRelease == null) {
                    managedRelease = curRelease;
                    inst.setCurrentManagedRelVersion(managedRelease);
                }

                boolean releaseNumMismatch = !managedRelease.equals(curRelease);
                if (releaseNumMismatch) {
                    releases.insertElementAt(managedRelease, 0);
                }

                relCombobox.getComboBox().setModel(new DefaultComboBoxModel(releases));
                relCombobox.getComboBox().setSelectedIndex(releaseNumMismatch ? 1 : 0);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        UIValidator.setIgnoreAllValidation(this, true);
                        try {
                            checkbox.setSelected(!inst.getIsReleaseManagedGlobally()); // make sure the ChangeListener gets activated
                            checkbox.setSelected(inst.getIsReleaseManagedGlobally());
                        } catch (Exception ex) {
                        } finally {
                            UIValidator.setIgnoreAllValidation(this, false);
                        }
                    }
                });
            }
        }
    }
}

From source file:edu.ku.brc.helpers.ZipFileHelper.java

/**
 * @param zipFile/*from   w  w w  . ja va2 s . c o m*/
 * @return
 * @throws ZipException
 * @throws IOException
 */
public List<File> unzipToFiles(final File zipFile) throws ZipException, IOException {
    Vector<File> files = new Vector<File>();

    final int bufSize = 65535;

    File dir = UIRegistry.getAppDataSubDir(Long.toString(System.currentTimeMillis()) + "_zip", true);
    dirsToRemoveList.add(dir);

    File outFile = null;
    FileOutputStream fos = null;
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            if (zin.available() > 0) {
                outFile = new File(dir.getCanonicalPath() + File.separator + entry.getName());
                fos = new FileOutputStream(outFile);

                byte[] bytes = new byte[bufSize]; // 64k
                int bytesRead = zin.read(bytes, 0, bufSize);
                while (bytesRead > 0) {
                    fos.write(bytes, 0, bytesRead);
                    bytesRead = zin.read(bytes, 0, bufSize);
                }

                files.insertElementAt(outFile.getCanonicalFile(), 0);
            }
            entry = zin.getNextEntry();
        }

    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return files;
}

From source file:com.ssn.event.controller.SSNShareController.java

@Override
public void mouseClicked(MouseEvent e) {
    Object mouseEventObj = e.getSource();
    if (mouseEventObj != null && mouseEventObj instanceof JLabel) {
        JLabel label = (JLabel) mouseEventObj;
        getShareForm().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // Tracking this sharing event in Google Analytics
        GoogleAnalyticsUtil.track(SSNConstants.SSN_APP_EVENT_SHARING);
        Thread thread = null;/*from w w w.ja  v  a 2 s .  co  m*/
        switch (label.getName()) {
        case "FacebookSharing":
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {

                    Set<String> sharedFileList = getFiles();
                    AccessGrant facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                    if (facebookAccessGrant == null) {
                        try {
                            LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                            loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                            loginWithFacebook.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                                if (facebookAccessGrant == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (InterruptedException ex) {
                            logger.error(ex);
                        }
                    }

                    FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(
                            SSNConstants.SSN_FACEBOOK_API_KEY, SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                    Connection<Facebook> connection = connectionFactory.createConnection(facebookAccessGrant);
                    Facebook facebook = connection.getApi();
                    MediaOperations mediaOperations = facebook.mediaOperations();

                    if (!isAlreadyLoggedIn) {
                        // SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                        FacebookProfile userProfile = facebook.userOperations().getUserProfile();
                        String userName = "";
                        if (userProfile != null) {
                            userName = userProfile.getName() != null ? userProfile.getName()
                                    : userProfile.getFirstName();
                        }
                        confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                "Confirmation", "",
                                "You are already logged in with " + userName + ", Click OK to continue.");
                        int result = confirmeDialog.getResult();
                        if (result == JOptionPane.YES_OPTION) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                    messageDialogBox.initDialogBoxUI(
                                            SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                            "Successfully uploaded.");
                                    messageDialogBox.setFocusable(true);

                                }
                            });
                        } else if (result == JOptionPane.NO_OPTION) {

                            AccessGrant facebookAccessGrant1 = null;
                            if (facebookAccessGrant1 == null) {
                                try {
                                    LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                                    loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                                    loginWithFacebook.login();

                                    boolean processFurther = false;
                                    while (!processFurther) {
                                        facebookAccessGrant1 = getHomeModel().getHomeForm()
                                                .getFacebookAccessGrant();
                                        if (facebookAccessGrant1 == null) {
                                            Thread.sleep(10000);
                                        } else {
                                            processFurther = true;
                                            //isAlreadyLoggedIn = true;
                                        }
                                    }
                                    connectionFactory = new FacebookConnectionFactory(
                                            SSNConstants.SSN_FACEBOOK_API_KEY,
                                            SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                                    connection = connectionFactory.createConnection(facebookAccessGrant);
                                    facebook = connection.getApi();
                                    mediaOperations = facebook.mediaOperations();
                                } catch (InterruptedException ex) {
                                    logger.error(ex);
                                }
                            }
                        }
                    }

                    String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;
                    final List<String> videoSupportedList = Arrays.asList(videoSupported);

                    for (String file : sharedFileList) {
                        String fileExtension = file.substring(file.lastIndexOf(".") + 1, file.length());
                        Resource resource = new FileSystemResource(file);

                        if (!videoSupportedList.contains(fileExtension.toUpperCase())) {
                            String output = mediaOperations.postPhoto(resource);
                        } else {
                            String output = mediaOperations.postVideo(resource);
                        }

                    }

                    getShareForm().dispose();
                }
            };
            thread.start();
            break;
        case "TwitterSharing":
            LoginWithTwitter.deniedPermission = false;
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {
                    Set<String> sharedFileList = getFiles();
                    OAuthToken twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                    if (twitterOAuthToken == null) {
                        try {
                            LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                            loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                            loginWithTwitter.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                if (LoginWithTwitter.deniedPermission)
                                    break;

                                twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                                if (twitterOAuthToken == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (IOException | InterruptedException ex) {
                            logger.error(ex);
                        }
                    }
                    if (!LoginWithTwitter.deniedPermission) {
                        Twitter twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                SSNConstants.SSN_TWITTER_SECRET_KEY, twitterOAuthToken.getValue(),
                                twitterOAuthToken.getSecret());
                        TimelineOperations timelineOperations = twitter.timelineOperations();
                        if (!isAlreadyLoggedIn) {
                            SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                            TwitterProfile userProfile = twitter.userOperations().getUserProfile();

                            String userName = "";
                            if (userProfile != null) {
                                userName = twitter.userOperations().getScreenName() != null
                                        ? twitter.userOperations().getScreenName()
                                        : userProfile.getName();
                            }
                            confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                    "Confirmation", "",
                                    "You are already logged in with " + userName + ", Click OK to continue.");
                            int result = confirmeDialog.getResult();
                            if (result == JOptionPane.YES_OPTION) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                        messageDialogBox.initDialogBoxUI(
                                                SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                                "Successfully uploaded.");
                                        messageDialogBox.setFocusable(true);

                                    }
                                });
                            } else if (result == JOptionPane.NO_OPTION) {

                                twitterOAuthToken = null;
                                if (twitterOAuthToken == null) {
                                    try {
                                        LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                                        loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                                        loginWithTwitter.login();

                                        boolean processFurther = false;
                                        while (!processFurther) {
                                            twitterOAuthToken = getHomeModel().getHomeForm()
                                                    .getTwitterOAuthToken();
                                            if (twitterOAuthToken == null) {
                                                Thread.sleep(10000);
                                            } else {
                                                processFurther = true;

                                            }
                                        }
                                        twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                                SSNConstants.SSN_TWITTER_SECRET_KEY,
                                                twitterOAuthToken.getValue(), twitterOAuthToken.getSecret());
                                        timelineOperations = twitter.timelineOperations();
                                    } catch (IOException | InterruptedException ex) {
                                        logger.error(ex);
                                    }
                                }
                            }
                        }

                        for (String file : sharedFileList) {
                            Resource image = new FileSystemResource(file);

                            TweetData tweetData = new TweetData("At " + new Date());
                            tweetData.withMedia(image);
                            timelineOperations.updateStatus(tweetData);
                        }
                    } else {
                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        messageDialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Alert",
                                "", "User denied for OurHive App permission on twitter.");
                        messageDialogBox.setFocusable(true);
                    }
                    getShareForm().dispose();
                }

            };
            thread.start();
            break;
        case "InstagramSharing":
            break;
        case "MailSharing":
            try {
                String OS = System.getProperty("os.name").toLowerCase();

                Set<String> sharedFileList = getFiles();
                Set<String> voiceNoteList = new HashSet<String>();
                for (String sharedFile : sharedFileList) {
                    String voiceNote = SSNDao.getVoiceCommandPath(new File(sharedFile).getAbsolutePath());
                    if (voiceNote != null && !voiceNote.isEmpty()) {
                        voiceNoteList.add(voiceNote);
                    }
                }
                sharedFileList.addAll(voiceNoteList);

                String fileFullPath = "";
                String caption = "";
                if (sharedFileList.size() == 1) {
                    fileFullPath = sharedFileList.toArray(new String[0])[0];

                    caption = SSMMediaGalleryPanel.readMetaDataForTitle(new File(fileFullPath));

                } else if (sharedFileList.size() > 1) {
                    fileFullPath = SSNHelper.createZipFileFromMultipleFiles(sharedFileList);
                }

                if (OS.contains("win")) {

                    // String subject = "SSN Subject";
                    String subject = caption.equals("") ? SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT : caption;
                    String body = "";
                    String m = "&subject=%s&body=%s";

                    String outLookExeDir = "C:\\Program Files\\Microsoft Office\\Office14\\Outlook.exe";
                    String mailCompose = "/c";
                    String note = "ipm.note";
                    String mailBodyContent = "/m";

                    m = String.format(m, subject, body);
                    String slashA = "/a";

                    String mailClientConfigParams[] = null;
                    Process startMailProcess = null;

                    mailClientConfigParams = new String[] { outLookExeDir, mailCompose, note, mailBodyContent,
                            m, slashA, fileFullPath };
                    startMailProcess = Runtime.getRuntime().exec(mailClientConfigParams);
                    OutputStream out = startMailProcess.getOutputStream();
                    File zipFile = new File(fileFullPath);
                    zipFile.deleteOnExit();
                } else if (OS.indexOf("mac") >= 0) {
                    //Process p = Runtime.getRuntime().exec(new String[]{String.format("open -a mail ", fileFullPath)});
                    Desktop desktop = Desktop.getDesktop();
                    String mailTo = caption.equals("") ? "?SUBJECT=" + SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT
                            : caption;
                    URI uriMailTo = null;
                    uriMailTo = new URI("mailto", mailTo, null);
                    desktop.mail(uriMailTo);
                }

                this.getShareForm().dispose();
            } catch (Exception ex) {
                logger.error(ex);
            }
            break;
        case "moveCopy":
            getShareForm().dispose();
            File album = new File(SSNHelper.getSsnHiveDirPath());
            File[] albumPaths = album.listFiles();
            Vector albumNames = new Vector();
            for (int i = 0; i < albumPaths.length; i++) {
                if (!(albumPaths[i].getName().equals("OurHive")) && SSNHelper.lastAlbum != null
                        && !(albumPaths[i].getName().equals(SSNHelper.lastAlbum)))
                    albumNames.add(albumPaths[i].getName());
            }
            if (SSNHelper.lastAlbum != null && !SSNHelper.lastAlbum.equals("OurHive"))
                albumNames.insertElementAt("OurHive", 0);

            SSNInputDialogBox inputBox = new SSNInputDialogBox(true, albumNames);
            inputBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Copy Media",
                    "Please Select Album Name");
            String destAlbumName = inputBox.getTextValue();
            if (StringUtils.isNotBlank(destAlbumName)) {
                homeModel.moveAlbum(destAlbumName, getFiles());
            }

        }
        getShareForm().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupIndexer.java

/**
 * @param fii//  ww w. ja v  a2  s  .  co  m
 * @return
 */
private int chooseAgentsToMergeNew(final FindItemInfo fii) {
    if (true) {

        MultipleRecordCleanupDlg mrcDlg = null;
        try {
            MultipleRecordComparer mrc = new MultipleRecordComparer(fii, Agent.getClassTableId(),
                    Address.getClassTableId(), AgentVariant.getClassTableId(), AgentSpecialty.getClassTableId(),
                    AgentGeography.getClassTableId());
            mrc.setSingleRowIncluded(false, false, false, false);
            //mrc.addDisplayColumn("Agent's Name");
            mrc.addDisplayColumn("LastName");
            mrc.addDisplayColumn("FirstName");
            mrc.addDisplayColumn("MiddleInitial");

            mrc.loadData();

            mrcDlg = new MultipleRecordCleanupDlg(mrc, "Agent Cleanup");
            mrcDlg.createUI();
            if (!mrcDlg.isSingle()) {
                mrcDlg.pack();
                mrcDlg.setSize(800, 500);
                UIHelper.centerWindow(mrcDlg);
                mrcDlg.toFront();
                if (prgDlg != null)
                    prgDlg.toBack();
                mrcDlg.setVisible(true);
                if (prgDlg != null)
                    prgDlg.toFront();
                //isContinuing = !mrcDlg.isCancelled();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return mrcDlg.getBtnPressed();
    }
    Vector<ModelItem> items = new Vector<AgentCleanupIndexer.ModelItem>();

    ModelItem primary = createModelItem(fii.getId(), true);
    items.add(primary);
    System.out.println("\nfii: " + fii.getId());

    for (Integer localityId : fii.getDuplicateIds()) {
        items.add(createModelItem(localityId, false));
        System.out.println("  " + localityId);
    }
    Collections.sort(items);
    items.remove(primary);
    items.insertElementAt(primary, 0);

    JTable table = new JTable(new FindItemTableModel(items));
    UIHelper.makeTableHeadersCentered(table, false);
    //UIHelper.setVisibleRowCount(table,  10);
    UIHelper.calcColumnWidths(table, 10, 300);

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g"));
    JScrollPane sp = UIHelper.createScrollPane(table, true);

    pb.add(sp, cc.xy(1, 1));
    pb.setDefaultDialogBorder();

    dlg = new CustomDialog((Frame) getTopWindow(), getResourceString("CLNUP_LOC_CHOOSE_TITLE"), true,
            CustomDialog.OKCANCELAPPLY, pb.getPanel());
    dlg.setOkLabel(getResourceString("CLNUP_MERGE"));
    dlg.setApplyLabel(getResourceString("SKIP"));
    dlg.setCancelLabel(getResourceString("QUIT"));
    dlg.setCloseOnApplyClk(true);
    dlg.createUI();
    dlg.pack();
    UIHelper.centerAndShow(dlg, 800, dlg.getSize().height);

    return dlg.getBtnPressed();
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.LocalityCleanupIndexer.java

/**
 * @param fii//from w  w w  . j  av  a  2  s. co  m
 * @return
 */
private int chooseLocalitiesToMerge(final FindItemInfo fii) {
    if (true) {

        MultipleRecordCleanupDlg mrcDlg = null;
        try {
            MultipleRecordComparer mrc = new MultipleRecordComparer(fii, Locality.getClassTableId(),
                    LocalityDetail.getClassTableId(), GeoCoordDetail.getClassTableId());
            mrc.setSingleRowIncluded(true, true);
            //mrc.addDisplayColumn("FullName", "Full Name", "CONCAT(LocalityName, '-') AS FullName");
            mrc.addDisplayColumn("LocalityName");

            mrc.loadData();

            mrcDlg = new MultipleRecordCleanupDlg(mrc, "Locality Cleanup");
            mrcDlg.createUI();
            if (!mrcDlg.isSingle()) {
                mrcDlg.pack();
                mrcDlg.setSize(800, 500);
                UIHelper.centerWindow(mrcDlg);
                mrcDlg.toFront();
                if (prgDlg != null)
                    prgDlg.toBack();
                mrcDlg.setVisible(true);
                if (prgDlg != null)
                    prgDlg.toFront();
                //isContinuing = !mrcDlg.isCancelled();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return mrcDlg.getBtnPressed();
    }
    Vector<ModelItem> items = new Vector<LocalityCleanupIndexer.ModelItem>();

    ModelItem primary = createModelItem(fii.getId(), true);
    items.add(primary);
    System.out.println("\nfii: " + fii.getId());

    for (Integer localityId : fii.getDuplicateIds()) {
        items.add(createModelItem(localityId, false));
        System.out.println("  " + localityId);
    }
    Collections.sort(items);
    items.remove(primary);
    items.insertElementAt(primary, 0);

    JTable table = new JTable(new FindItemTableModel(items));
    UIHelper.makeTableHeadersCentered(table, false);
    //UIHelper.setVisibleRowCount(table,  10);
    UIHelper.calcColumnWidths(table, 10, 300);

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g"));
    JScrollPane sp = UIHelper.createScrollPane(table, true);

    pb.add(sp, cc.xy(1, 1));
    pb.setDefaultDialogBorder();

    dlg = new CustomDialog((Frame) getTopWindow(), getResourceString("CLNUP_LOC_CHOOSE_TITLE"), true,
            CustomDialog.OKCANCELAPPLY, pb.getPanel());
    dlg.setOkLabel(getResourceString("CLNUP_MERGE"));
    dlg.setApplyLabel(getResourceString("SKIP"));
    dlg.setCancelLabel(getResourceString("QUIT"));
    dlg.setCloseOnApplyClk(true);
    dlg.createUI();
    dlg.pack();
    UIHelper.centerAndShow(dlg, 800, dlg.getSize().height);

    return dlg.getBtnPressed();
}

From source file:com.almarsoft.GroundhogReader.lib.NNTPExtended.java

public long[] getGroupArticles(String group, long fromArticle, int limit) throws IOException {

    Vector<Long> list;
    long firstToGet, firstArticle, lastArticle;
    NewsgroupInfo groupInfo = new NewsgroupInfo();

    if (!selectNewsgroup(group, groupInfo))
        return null;

    firstArticle = groupInfo.getFirstArticle();
    lastArticle = groupInfo.getLastArticle();

    if (firstArticle == 0 && lastArticle == 0)
        return new long[0];

    // First sync with this group; see the comment below 
    if (fromArticle == -1)
        firstToGet = firstArticle;//from  w w w.jav  a  2s  .c o  m

    else {
        if (fromArticle > lastArticle) { // No new articles
            return new long[0];
        } else {
            firstToGet = fromArticle;
        }
    }

    // Now select the first article and start looping until limit or last article reached
    ArticlePointer art = new ArticlePointer();

    list = new Vector<Long>(limit);

    // FIRST CONNECTION TO THE GROUP
    // If this is the first connection we only want the last "limit" articles from the group, 
    // so we ask for the last message and go backwards until we have "limit" articles or 
    // the first one.
    if (fromArticle == -1) {
        if (!selectArticle(lastArticle, art))
            return new long[0];

        for (int i = 0; i < limit; i++) {
            list.insertElementAt((long) art.articleNumber, 0);

            if (art.articleNumber == firstToGet)
                break;

            if (!selectPreviousArticle(art))
                break;
        }
    }

    // NON-FIRST CONNECTION TO THE GROUP
    // For normal non-first connection we start with the last article we got on the previous session and advance from that
    // until limit or last article reached
    else {
        if (!selectArticle(firstToGet, art))
            return new long[0];

        for (int i = 0; i <= limit; i++) {
            list.add((long) art.articleNumber);

            if (art.articleNumber == lastArticle)
                break;

            if (!selectNextArticle(art))
                break;
        }
    }
    int listSize = list.size();
    long[] articleNumbers = new long[listSize];

    for (int i = 0; i < listSize; i++) {
        articleNumbers[i] = list.get(i);
    }

    return articleNumbers;
}

From source file:edu.ku.brc.specify.utilapps.RegisterApp.java

/**
 * @return/* w  ww.  j av a 2s . co m*/
 */
private JPanel getStatsPane(final String chartPrefixTitle, final Collection<RegProcEntry> entries,
        final String tableName) {
    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "f:p:g"));

    final Hashtable<String, String> keyDescPairsHash = rp.getAllDescPairsHash();
    final Hashtable<String, String> desc2KeyPairsHash = new Hashtable<String, String>();
    for (String key : keyDescPairsHash.keySet()) {
        desc2KeyPairsHash.put(keyDescPairsHash.get(key), key);
    }

    Vector<String> keywords = new Vector<String>();
    for (String keyword : getKeyWordsList(entries)) {
        if (keyword.endsWith("_name") || keyword.endsWith("_type") || keyword.endsWith("ISA_Number")
                || keyword.endsWith("reg_isa")) {
            //keywords.add(keyword);

        } else {
            String desc = keyDescPairsHash.get(keyword);
            //System.out.println("["+keyword+"]->["+desc+"]");
            if (desc != null) {
                keywords.add(desc);
            } else {
                System.out.println("Desc for keyword[" + keyword + "] is null.");
            }

        }
    }
    Vector<Object[]> rvList = BasicSQLUtils
            .query("SELECT DISTINCT(Name) FROM registeritem WHERE SUBSTRING(Name, 1, 4) = 'num_'");
    for (Object[] array : rvList) {
        keywords.add((String) array[0]);
    }
    Collections.sort(keywords);

    final JList list = new JList(keywords);
    pb.add(UIHelper.createScrollPane(list), cc.xy(1, 1));

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                String statName = (String) list.getSelectedValue();
                if (desc2KeyPairsHash.get(statName) != null) {
                    statName = desc2KeyPairsHash.get(statName);
                }

                DateType dateType = convertDateType(statName);
                if (dateType == DateType.None) {
                    Vector<Pair<String, Integer>> values;
                    if (statName.startsWith("num_")) {
                        values = getCollNumValuesFromList(statName);
                        Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>();
                        for (Pair<String, Integer> p : values) {
                            if (hash.get(p.first) == null) {
                                hash.put(p.first, true);
                            } else {
                                int i = 0;
                                String name = p.first;
                                while (hash.get(p.first) != null) {
                                    p.first = name + " _" + i;
                                    i++;
                                }
                                hash.put(p.first, true);
                            }
                            //p.first += "(" + p.second.toString() + ")";
                        }

                    } else {
                        values = getCollValuesFromList(statName);
                    }

                    Collections.sort(values, countComparator);
                    Vector<Pair<String, Integer>> top10Values = new Vector<Pair<String, Integer>>();
                    for (int i = 1; i < Math.min(11, values.size()); i++) {
                        top10Values.insertElementAt(values.get(values.size() - i), 0);
                    }
                    createBarChart(chartPrefixTitle + " " + statName, statName, top10Values);

                } else {
                    String desc = getByDateDesc(dateType);
                    Vector<Pair<String, Integer>> values = tableName.equals("track")
                            ? getDateValuesFromListByTable(dateType, tableName)
                            : getDateValuesFromList(dateType);
                    Collections.sort(values, titleComparator);
                    createBarChart(chartPrefixTitle + " " + desc, desc, values);
                }
            }
        }
    });

    return pb.getPanel();
}