Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.android.exchange.EasSyncService.java

private void runPingLoop() throws IOException, StaleFolderListException, IllegalHeartbeatException {
    int pingHeartbeat = mPingHeartbeat;
    userLog("runPingLoop");
    // Do push for all sync services here
    long endTime = System.currentTimeMillis() + (30 * MINUTES);
    HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    ArrayList<String> readyMailboxes = new ArrayList<String>();
    ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    int pingWaitCount = 0;

    while ((System.currentTimeMillis() < endTime) && !mStop) {
        // Count of pushable mailboxes
        int pushCount = 0;
        // Count of mailboxes that can be pushed right now
        int canPushCount = 0;
        // Count of uninitialized boxes
        int uninitCount = 0;

        Serializer s = new Serializer();
        Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
                MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId
                        + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX,
                null, null);/*from w w w .  j a v  a  2  s  .  c om*/
        notReadyMailboxes.clear();
        readyMailboxes.clear();
        try {
            // Loop through our pushed boxes seeing what is available to push
            while (c.moveToNext()) {
                pushCount++;
                // Two requirements for push:
                // 1) SyncManager tells us the mailbox is syncable (not running, not stopped)
                // 2) The syncKey isn't "0" (i.e. it's synced at least once)
                long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
                int pingStatus = SyncManager.pingStatus(mailboxId);
                String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
                if (pingStatus == SyncManager.PING_STATUS_OK) {
                    String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
                    if ((syncKey == null) || syncKey.equals("0")) {
                        // We can't push until the initial sync is done
                        pushCount--;
                        uninitCount++;
                        continue;
                    }

                    if (canPushCount++ == 0) {
                        // Initialize the Ping command
                        s.start(Tags.PING_PING)
                                .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat))
                                .start(Tags.PING_FOLDERS);
                    }

                    String folderClass = getTargetCollectionClassFromCursor(c);
                    s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
                            .data(Tags.PING_CLASS, folderClass).end();
                    readyMailboxes.add(mailboxName);
                } else if ((pingStatus == SyncManager.PING_STATUS_RUNNING)
                        || (pingStatus == SyncManager.PING_STATUS_WAITING)) {
                    notReadyMailboxes.add(mailboxName);
                } else if (pingStatus == SyncManager.PING_STATUS_UNABLE) {
                    pushCount--;
                    userLog(mailboxName, " in error state; ignore");
                    continue;
                }
            }
        } finally {
            c.close();
        }

        if (Eas.USER_LOG) {
            if (!notReadyMailboxes.isEmpty()) {
                userLog("Ping not ready for: " + notReadyMailboxes);
            }
            if (!readyMailboxes.isEmpty()) {
                userLog("Ping ready for: " + readyMailboxes);
            }
        }

        // If we've waited 10 seconds or more, just ping with whatever boxes are ready
        // But use a shorter than normal heartbeat
        boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);

        if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
            // If all pingable boxes are ready for push, send Ping to the server
            s.end().end().done();
            pingWaitCount = 0;
            mPostReset = false;
            mPostAborted = false;

            // If we've been stopped, this is a good time to return
            if (mStop)
                return;

            long pingTime = SystemClock.elapsedRealtime();
            try {
                // Send the ping, wrapped by appropriate timeout/alarm
                if (forcePing) {
                    userLog("Forcing ping after waiting for all boxes to be ready");
                }
                HttpResponse res = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);

                int code = res.getStatusLine().getStatusCode();
                userLog("Ping response: ", code);

                // Return immediately if we've been asked to stop during the ping
                if (mStop) {
                    userLog("Stopping pingLoop");
                    return;
                }

                if (code == HttpStatus.SC_OK) {
                    // Make sure to clear out any pending sync errors
                    SyncManager.removeFromSyncErrorMap(mMailboxId);
                    HttpEntity e = res.getEntity();
                    int len = (int) e.getContentLength();
                    InputStream is = res.getEntity().getContent();
                    if (len != 0) {
                        int pingResult = parsePingResult(is, mContentResolver, pingErrorMap);
                        // If our ping completed (status = 1), and we weren't forced and we're
                        // not at the maximum, try increasing timeout by two minutes
                        if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
                            if (pingHeartbeat > mPingHighWaterMark) {
                                mPingHighWaterMark = pingHeartbeat;
                                userLog("Setting high water mark at: ", mPingHighWaterMark);
                            }
                            if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) {
                                pingHeartbeat += PING_HEARTBEAT_INCREMENT;
                                if (pingHeartbeat > mPingMaxHeartbeat) {
                                    pingHeartbeat = mPingMaxHeartbeat;
                                }
                                userLog("Increasing ping heartbeat to ", pingHeartbeat, "s");
                            }
                        }
                    } else {
                        userLog("Ping returned empty result; throwing IOException");
                        throw new IOException();
                    }
                } else if (isAuthError(code)) {
                    mExitStatus = EXIT_LOGIN_FAILURE;
                    userLog("Authorization error during Ping: ", code);
                    throw new IOException();
                }
            } catch (IOException e) {
                String message = e.getMessage();
                // If we get the exception that is indicative of a NAT timeout and if we
                // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
                boolean hasMessage = message != null;
                userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
                if (mPostReset) {
                    // Nothing to do in this case; this is SyncManager telling us to try another
                    // ping.
                } else if (mPostAborted || isLikelyNatFailure(message)) {
                    long pingLength = SystemClock.elapsedRealtime() - pingTime;
                    if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) {
                        pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
                        mPingHeartbeatDropped = true;
                        if (pingHeartbeat < mPingMinHeartbeat) {
                            pingHeartbeat = mPingMinHeartbeat;
                        }
                        userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
                    } else if (mPostAborted) {
                        // There's no point in throwing here; this can happen in two cases
                        // 1) An alarm, which indicates minutes without activity; no sense
                        //    backing off
                        // 2) SyncManager abort, due to sync of mailbox.  Again, we want to
                        //    keep on trying to ping
                        userLog("Ping aborted; retry");
                    } else if (pingLength < 2000) {
                        userLog("Abort or NAT type return < 2 seconds; throwing IOException");
                        throw e;
                    } else {
                        userLog("NAT type IOException");
                    }
                } else if (hasMessage && message.contains("roken pipe")) {
                    // The "broken pipe" error (uppercase or lowercase "b") seems to be an
                    // internal error, so let's not throw an exception (which leads to delays)
                    // but rather simply run through the loop again
                } else {
                    // Make sure we release the previously acquired wake lock otherwise we end up
                    // in possible battery drain as explained at http://code.google.com/p/android/issues/detail?id=9307
                    // comment #122
                    SyncManager.runAsleep(mMailboxId, 0);

                    throw e;
                }
            }
        } else if (forcePing) {
            // In this case, there aren't any boxes that are pingable, but there are boxes
            // waiting (for IOExceptions)
            userLog("pingLoop waiting 60s for any pingable boxes");
            sleep(60 * SECONDS, true);
        } else if (pushCount > 0) {
            // If we want to Ping, but can't just yet, wait a little bit
            // TODO Change sleep to wait and use notify from SyncManager when a sync ends
            sleep(2 * SECONDS, false);
            pingWaitCount++;
            //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
        } else if (uninitCount > 0) {
            // In this case, we're doing an initial sync of at least one mailbox.  Since this
            // is typically a one-time case, I'm ok with trying again every 10 seconds until
            // we're in one of the other possible states.
            userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
            sleep(10 * SECONDS, true);
        } else {
            // We've got nothing to do, so we'll check again in 20 minutes at which time
            // we'll update the folder list, check for policy changes and/or remote wipe, etc.
            // Let the device sleep in the meantime...
            userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
            sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
        }
    }

    // Save away the current heartbeat
    mPingHeartbeat = pingHeartbeat;
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.ReportFactory.java

public static void parser(String projectName, BufferedReader htmlReportReader, UIResponseObserver observer,
        ReportType reportType) {//  w ww  .j a  va2s  .  c  o m
    String tmpLine = null;
    ArrayList<CodeMatchesPrecision> list = new ArrayList<CodeMatchesPrecision>();
    ArrayList<String> data = new ArrayList<String>();
    int insertedCnt = 0;

    if (htmlReportReader == null) {
        log.debug("Fail to generate " + projectName + " " + reportType + " Report");
        observer.setFailMessage("Fail to generate " + projectName + " " + reportType + " Report");
        return;
    }

    String msgHead = " > Creating Report : " + projectName + "\n";
    String pMessage = " >> Parsing [" + reportType.getType() + "] HTML file.";
    log.debug(pMessage);

    try {
        StringBuffer tmpValue = new StringBuffer("");
        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<table border='0' cellspacing='0' cellpadding='0' class='reportTable'")) {
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("</thead>")) {
                        break;
                    }
                }
                break;
            }
        }

        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<tr ")) {
                int index = 0;
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("<td ")) {
                        while ((tmpLine = htmlReportReader.readLine()) != null) {
                            tmpLine = tmpLine.trim();
                            if (tmpLine.startsWith("</td>")) {
                                String removedTagValue = removeHtmlTag(tmpValue);
                                data.add(removedTagValue);
                                tmpValue.setLength(0);
                                ++index;
                                break;
                            }
                            tmpValue.append(tmpLine);
                        }
                    }
                    if (tmpLine.startsWith("</tr>")) {
                        if (hasNoData(index)) {
                            break;
                        }
                        CodeMatchesPrecision codeMatchesPrecision = new CodeMatchesPrecision();
                        codeMatchesPrecision.setFile(data.get(0));
                        codeMatchesPrecision.setSize(Tools.transStringToInteger(data.get(1)));
                        codeMatchesPrecision.setFileLine(Tools.transStringToInteger(data.get(2)));
                        codeMatchesPrecision.setTotalLines(Tools.transStringToInteger(data.get(3)));
                        codeMatchesPrecision.setComponent(data.get(4));
                        codeMatchesPrecision.setVersion(data.get(5));
                        codeMatchesPrecision.setLicense(data.get(6));
                        codeMatchesPrecision.setUsage(data.get(7));
                        codeMatchesPrecision.setStatus(data.get(8));
                        codeMatchesPrecision.setPercentage(data.get(9));
                        codeMatchesPrecision.setMatchedFile(data.get(10));
                        codeMatchesPrecision.setMatchedFileLine(Tools.transStringToInteger(data.get(11)));
                        codeMatchesPrecision.setFileComment(data.get(12));
                        codeMatchesPrecision.setComponentComment(data.get(13));
                        list.add(codeMatchesPrecision);
                        data.clear();

                        insertedCnt++;
                        if (insertedCnt % 10000 == 0) {
                            log.debug("codeMatchesPrecision insertedCnt: " + insertedCnt);
                            if (observer != null) {
                                observer.pushMessageWithHeader(
                                        msgHead + pMessage + "\n >>> Inserted data count : " + insertedCnt);
                            }
                            insertCodematchTable(projectName, list);
                            list.clear();
                        }
                        break;
                    }
                }
            }
            if (tmpLine.startsWith("</table>")) {
                log.debug("codeMatchesPrecision insertedCnt: " + insertedCnt);
                insertCodematchTable(projectName, list);
                list.clear();
                break;
            }
        }
    } catch (IOException e) {
        ReportAPIWrapper.log.warn(e);
        String[] buttonOK = { "OK" };
        JOptionPane.showOptionDialog(null, "Out Of Memory Error", "Java heap space", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
    }
    ReportAPIWrapper.log.debug("codeMatchesPrecision insertedCnt finally : " + insertedCnt);
}

From source file:op.care.nursingprocess.PnlNursingProcess.java

private JPanel createNPPanel(final NursingProcess np) {
    /***//from  w w  w. ja va  2  s. c o m
     *                          _        ____ ____  _  _     _   _ ____
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |   | \ | |  _ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_  |  \| | |_) |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | |\  |  __/
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_|   |_| \_|_|
     *
     */
    if (!contenPanelMap.containsKey(np)) {
        String title = "<html><table border=\"0\">";

        if (!np.getCommontags().isEmpty()) {
            title += "<tr>" + "    <td colspan=\"2\">"
                    + CommontagsTools.getAsHTML(np.getCommontags(), SYSConst.html_16x16_tagPurple_internal)
                    + "</td>" + "  </tr>";
        }

        title += "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">" + np.getPITAsHTML() + "</td>"
                + "<td width=\"500\" align=\"left\">" + (np.isClosed() ? "<s>" : "") + np.getContentAsHTML()
                + (np.isClosed() ? "</s>" : "") + "</td></tr>";
        title += "</table>" + "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
        cptitle.getButton().setVerticalTextPosition(SwingConstants.TOP);

        if (!np.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(Integer.toString(np.getAttachedFilesConnections().size()),
                    SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);
            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                            em.close();
                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            createCP4(myNP.getCategory());
                            buildPanel();
                        }
                    };
                    new DlgFiles(np, fileHandleClosure);
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            cptitle.getRight().add(btnFiles);
        }

        if (!np.getAttachedQProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(Integer.toString(np.getAttachedQProcessConnections().size()),
                    SYSConst.icon22redStar);
            btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
            btnProcess.setForeground(Color.YELLOW);
            btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnProcess.setFont(SYSConst.ARIAL18BOLD);
            btnProcess.setPressedIcon(SYSConst.icon22Pressed);
            btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
            btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnProcess.setContentAreaFilled(false);
            btnProcess.setBorder(null);
            btnProcess.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgProcessAssign(np, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o == null) {
                                return;
                            }
                            Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                            ArrayList<QProcess> assigned = result.getFirst();
                            ArrayList<QProcess> unassigned = result.getSecond();

                            EntityManager em = OPDE.createEM();

                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                final NursingProcess myNP = em.merge(np);
                                em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSNP2PROCESS> attached = new ArrayList<SYSNP2PROCESS>(
                                        myNP.getAttachedQProcessConnections());
                                for (SYSNP2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getNursingProcess().getAttachedQProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.getID(),
                                                PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                linkObject.getQProcess()));
                                        em.remove(linkObject);
                                    }
                                }
                                attached.clear();

                                for (QProcess qProcess : assigned) {
                                    java.util.List<QProcessElement> listElements = qProcess.getElements();
                                    if (!listElements.contains(myNP)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSNP2PROCESS myLinkObject = em
                                                .merge(new SYSNP2PROCESS(myQProcess, myNP));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedNursingProcessesConnections().add(myLinkObject);
                                        myNP.getAttachedQProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myNP.getCategory()).add(myNP);
                                Collections.sort(valuecache.get(myNP.getCategory()));

                                createCP4(myNP.getCategory());
                                buildPanel();

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                } else {
                                    reloadDisplay();
                                }
                            } catch (RollbackException ole) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                        }
                    });
                }
            });
            btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            cptitle.getRight().add(btnProcess);
        }

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
            /***
             *      _     _         ____       _       _
             *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
             *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
             *     | |_) | |_| | | |  __/| |  | | | | | |_
             *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
             *
             */
            JButton btnPrint = new JButton(SYSConst.icon22print2);
            btnPrint.setContentAreaFilled(false);
            btnPrint.setBorder(null);
            btnPrint.setPressedIcon(SYSConst.icon22print2Pressed);
            btnPrint.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnPrint.setAlignmentY(Component.TOP_ALIGNMENT);
            btnPrint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    SYSFilesTools.print(NursingProcessTools.getAsHTML(np, true, true, true, true), true);
                }
            });

            cptitle.getRight().add(btnPrint);
            //                cptitle.getTitleButton().setVerticalTextPosition(SwingConstants.TOP);
        }

        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        final JButton btnMenu = new JButton(SYSConst.icon22menu);
        btnMenu.setPressedIcon(SYSConst.icon22Pressed);
        btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
        btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnMenu.setContentAreaFilled(false);
        btnMenu.setBorder(null);
        btnMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JidePopup popup = new JidePopup();
                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnMenu);
                popup.removeExcludedComponent(btnMenu);
                JPanel pnl = getMenu(np);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });

        btnMenu.setEnabled(!np.isClosed());
        cptitle.getButton().setIcon(getIcon(np));

        cptitle.getRight().add(btnMenu);
        cptitle.getMain().setBackground(getColor(np.getCategory())[SYSConst.light2]);
        cptitle.getMain().setOpaque(true);
        contenPanelMap.put(np, cptitle.getMain());
    }

    return contenPanelMap.get(np);
}

From source file:com.example.gatutorial.apps.MainActivity.java

public void onClickStartEvolve(View v) {
    // Shakespeare's plays example
    int totalPopulation = 500;
    final String target;
    final float mutationRate = 0.01f;
    final Population population;
    final ArrayList<phraseChromosome> matingPool = new ArrayList<phraseChromosome>();
    keepRunning = true;//from  w ww .j  av  a2 s  .  c o m
    numOfGenerations = 0;

    target = etInputPhrase.getText().toString();
    if (target.length() == 0)
        return;
    tvTestResults.setText("Evolving phrase- " + target + "\n");

    // Step 1: Initialize population
    population = new Population(totalPopulation, target.length());

    tEvolvePopulation = new Thread(new Runnable() {
        @Override
        public void run() {
            while (keepRunning) {
                // Step 2: Selection
                // Step 2a: Calculate fitness
                population.calcDNAFitness(target);
                float totalFitness = 0.0f;

                if (population.checkIfFit()) {
                    keepRunning = false;
                } else {
                    totalFitness = population.calcTotalFitness();

                    // Step 2b: Build mating pool - using Roulette Wheel Selection
                    // Parents are selected according to their fitness. The better the
                    // chromosomes are, the more chances to be selected they have.
                    // Chromosome with bigger fitness will be selected more times.
                    for (int i = 0; i < population.size(); i++) {
                        // Add each member n times according to its fitness score probability.
                        int n = (int) (population.getObjectDNA(i).getFitness() / totalFitness
                                * population.size());
                        for (int j = 0; j < n; j++) {
                            try {
                                matingPool.add(population.getObjectDNA(i));
                            } catch (Throwable e) {
                                Log.d(LOG_TAG, "do System.gc(): " + e.getMessage());
                                System.gc();
                                keepRunning = false;
                                break;
                            }
                        }
                    }

                    // Step 3: Reproduction
                    for (int i = 0; i < population.size(); i++) {
                        int a = (int) (matingPool.size() * Math.random());
                        int b = (int) (matingPool.size() * Math.random());
                        phraseChromosome partnerA = matingPool.get(a);
                        phraseChromosome partnerB = matingPool.get(b);

                        // Step 3a: Crossover
                        phraseChromosome child = partnerA.crossover(partnerB);

                        // Step 3b: Mutation
                        child.mutate(mutationRate);

                        population.setObjectDNA(i, child);
                    }

                    matingPool.clear();
                    // System.gc();
                    numOfGenerations++;
                }

            } // /while loop

            timeEvolveDiff = System.currentTimeMillis() - timeEvolveStart;

            try {
            } catch (Throwable e) {
                // system will throw an exception, don't care it
                // Called FromWrongThreadException: only the original thread that created a view
                // hierarchy can touch its views
            }

        } // /run()
    }); // /Thread()

    hTimer = new Handler();
    rTimelapseTask = new Runnable() {
        public void run() {
            if (keepRunning) {
                tvTestResults.append(numOfGenerations + "- " + population.getObjectDNA(0).getPhrase() + "\n");
                hTimer.postDelayed(rTimelapseTask, 3000);
            } else {
                tvTestResults.append("--- Solution found! ---\nTimelapse= " + timeEvolveDiff
                        + " mills\nNumber of generations= " + numOfGenerations + "\n");
            }
        }
    };

    hTimer.post(rTimelapseTask);

    timeEvolveStart = System.currentTimeMillis();
    tEvolvePopulation.start();

}

From source file:imageuploader.ImgWindow.java

private void generatedImages(String code, File[] files)
        throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FtpException {

    int ubicacion;
    File directory = new File(code);
    ArrayList<File> imageList = new ArrayList();
    DefaultListModel mod = (DefaultListModel) jL_Info.getModel();
    if (!directory.exists()) {
        boolean result = directory.mkdir();
        if (!result) {
            JOptionPane.showMessageDialog(rootPane, "Directory -- Error");
        } else {/*w  w  w  . ja v  a2  s . c o m*/
            File dir, img;
            boolean rst;
            FileChannel source = null;
            FileChannel dest = null;
            FtpCredentials.getInstancia().connect();
            for (int i = 0; i < files.length; i++) {

                int val = 1 + i;
                //Create the Angle directory
                dir = new File(directory, "Angle" + val);
                rst = dir.mkdir();

                //Copy Images
                //DefaultListModel mod = (DefaultListModel)jL_Info.getModel();

                for (int j = 0; j < mod.getSize(); j++) {
                    img = new File(dir, code + "~" + mod.getElementAt(j).toString() + ".jpg");
                    rst = img.createNewFile();
                    imageList.add(img);
                    source = new RandomAccessFile(files[i], "rw").getChannel();
                    dest = new RandomAccessFile(img, "rw").getChannel();

                    long position = 0;
                    long count = source.size();
                    source.transferTo(position, count, dest);

                    if (source != null) {
                        source.close();
                    }
                    if (dest != null) {
                        dest.close();
                    }

                }
                ubicacion = i + 1;
                /*Using the private library  */
                if (jCHBox_MY.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/Myron/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                if (jCHB_CA.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/canada/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                if (jCHB_AZ.isSelected()) {
                    FtpCredentials.getInstancia().getClient().setDir("/australia/angle" + ubicacion + "Flash");
                    FtpCredentials.getInstancia().copyImage(imageList);
                }
                imageList.clear();

            }

            mod.removeAllElements();
            jTF_StyleCode.setText("");
            //jL_Info.removeAll();
            //list.removeAllElements();
            JOptionPane.showMessageDialog(rootPane, "Images uploaded");
        }
    } else {
        JOptionPane.showMessageDialog(rootPane, "There is a folder with the same name in the same location");
    }

}

From source file:com.ubuntuone.android.files.service.MetaService.java

/**
 * Given parents resource path and {@link ArrayList} of {@link NodeInfo}s of
 * its children, syncs cached info of these children. Updating children in
 * one method enables us to make use of database transaction.<br />
 * <ul>//from   w  ww . jav a  2s  .c  o  m
 * <li>- inserts if child is new</li>
 * <li>- updates if child has changed [thus marks is_cached = false]</li>
 * <li>- deletes if child is missing [dead node]</li>
 * </ul>
 * 
 * @param parentResourcePath
 *            the resource path of childrens parent
 * @param children
 *            {@link NodeInfo}s of the parents children
 * @throws OperationApplicationException 
 * @throws RemoteException 
 */
public void getDirectoryNode(final String resourcePath, final ResultReceiver receiver) {
    Log.i(TAG, "getDirectoryNode()");
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH, Nodes.NODE_GENERATION,
            Nodes.NODE_DATA };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";

    final Set<Integer> childrenIds = MetaUtilities.getChildrenIds(resourcePath);

    final ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    final Bundle data = new Bundle();
    data.putString(EXTRA_RESOURCE_PATH, resourcePath);

    api.listDirectory(resourcePath, new U1NodeListener() {
        @Override
        public void onStart() {
            if (receiver != null)
                receiver.send(Status.RUNNING, data);
        }

        @Override
        public void onSuccess(U1Node node) {
            if (node.getKind() == U1NodeKind.FILE && ((U1File) node).getSize() == null) {
                // Ignore files with null size.
                return;
            }
            final String[] selectionArgs = new String[] { node.getResourcePath() };
            final Cursor c = contentResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs,
                    null);
            try {
                ContentValues values = Nodes.valuesFromRepr(node);
                if (c.moveToFirst()) {
                    final int id = c.getInt(c.getColumnIndex(Nodes._ID));
                    // Node is live.
                    childrenIds.remove(id);

                    // Update node.
                    final long generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    final long newGeneration = node.getGeneration();
                    if (generation < newGeneration) {
                        Log.v(TAG, "updating child node, new generation");
                        values.put(Nodes.NODE_IS_CACHED, false);
                        values.put(Nodes.NODE_DATA, "");

                        String data = c.getString(c.getColumnIndex(Nodes.NODE_DATA));
                        FileUtilities.removeSilently(data);

                        Uri uri = MetaUtilities.buildNodeUri(id);
                        ContentProviderOperation op = ContentProviderOperation.newUpdate(uri).withValues(values)
                                .build();
                        operations.add(op);
                        if (operations.size() > 10) {
                            try {
                                contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                                operations.clear();
                            } catch (RemoteException e) {
                                Log.e(TAG, "Remote exception", e);
                            } catch (OperationApplicationException e) {
                                MetaUtilities.setIsCached(resourcePath, false);
                                return;
                            }
                            Thread.yield();
                        }
                    } else {
                        Log.v(TAG, "child up to date");
                    }
                } else {
                    // Insert node.
                    Log.v(TAG, "inserting child");
                    ContentProviderOperation op = ContentProviderOperation.newInsert(Nodes.CONTENT_URI)
                            .withValues(values).build();
                    operations.add(op);
                    if (operations.size() > 10) {
                        try {
                            contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
                            operations.clear();
                        } catch (RemoteException e) {
                            Log.e(TAG, "Remote exception", e);
                        } catch (OperationApplicationException e) {
                            MetaUtilities.setIsCached(resourcePath, false);
                            return;
                        }
                        Thread.yield();
                    }
                }
            } finally {
                c.close();
            }
        }

        @Override
        public void onUbuntuOneFailure(U1Failure failure) {
            MetaService.this.onUbuntuOneFailure(failure, receiver);
        }

        @Override
        public void onFailure(U1Failure failure) {
            MetaService.this.onFailure(failure, receiver);
        }

        @Override
        public void onFinish() {
            if (receiver != null)
                receiver.send(Status.FINISHED, data);
        }
    });

    // Remove nodes, which ids are left in childrenIds set.
    if (!childrenIds.isEmpty()) {
        Log.v(TAG, "childrenIDs not empty: " + childrenIds.size());
        final Iterator<Integer> it = childrenIds.iterator();
        while (it.hasNext()) {
            int id = it.next();
            Uri uri = MetaUtilities.buildNodeUri(id);
            ContentProviderOperation op = ContentProviderOperation.newDelete(uri).build();
            operations.add(op);
        }
    } else {
        Log.v(TAG, "childrenIDs empty");
    }

    try {
        long then = System.currentTimeMillis();
        contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations);
        MetaUtilities.setIsCached(resourcePath, true);
        long now = System.currentTimeMillis();
        Log.d(TAG, "time to update children: " + (now - then));
        contentResolver.notifyChange(Nodes.CONTENT_URI, null);
    } catch (RemoteException e) {
        Log.e(TAG, "", e);
    } catch (OperationApplicationException e) {
        MetaUtilities.setIsCached(resourcePath, false);
        return;
    }
}

From source file:op.care.prescription.PnlPrescription.java

private CollapsiblePane createCP4(final Prescription prescription) {
    /***/*  w  w  w .  ja v  a  2  s. c  o  m*/
     *                          _        ____ ____  _  _    ______                          _       _   _           __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ _ __ ___  ___  ___ _ __(_)_ __ | |_(_) ___  _ __\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) | '__/ _ \/ __|/ __| '__| | '_ \| __| |/ _ \| '_ \| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  __/| | |  __/\__ \ (__| |  | | |_) | |_| | (_) | | | | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_|   |_|  \___||___/\___|_|  |_| .__/ \__|_|\___/|_| |_| |
     *                                                     \_\                               |_|                    /_/
     */
    final String key = prescription.getID() + ".xprescription";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    final CollapsiblePane cpPres = cpMap.get(key);

    String title = "<html><table border=\"0\">" + "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">"
            + prescription.getPITAsHTML() + "</td>" + "<td width=\"380\" align=\"left\">" + "<font size=+1>"
            + PrescriptionTools.getShortDescription(prescription) + "</font>"
            + PrescriptionTools.getDoseAsHTML(prescription)
            + PrescriptionTools.getInventoryInformationAsHTML(prescription) + "</td>"
            + "<td width=\"200\" align=\"left\">" + PrescriptionTools.getOriginalPrescription(prescription)
            + PrescriptionTools.getRemark(prescription) + "</td>";

    if (!prescription.getCommontags().isEmpty()) {
        title += "<tr>" + "    <td colspan=\"3\">" + CommontagsTools.getAsHTML(prescription.getCommontags(),
                SYSConst.html_16x16_tagPurple_internal) + "</td>" + "  </tr>";
    }

    if (PrescriptionTools.isAnnotationNecessary(prescription)) {
        title += "<tr>" + "    <td colspan=\"3\">" + PrescriptionTools.getAnnontationsAsHTML(prescription)
                + "</td>" + "  </tr>";
    }

    title += "</table>" + "</html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
    cpPres.setCollapsible(false);
    cptitle.getButton().setIcon(getIcon(prescription));

    cpPres.setTitleLabelComponent(cptitle.getMain());
    cpPres.setSlidingDirection(SwingConstants.SOUTH);

    if (!prescription.getAttachedFilesConnections().isEmpty()) {
        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = new JButton(
                Integer.toString(prescription.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
        btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
        btnFiles.setForeground(Color.BLUE);
        btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnFiles.setFont(SYSConst.ARIAL18BOLD);
        btnFiles.setPressedIcon(SYSConst.icon22Pressed);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
        btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnFiles.setContentAreaFilled(false);
        btnFiles.setBorder(null);

        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                // checked for acls
                Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                        internalClassID) ? null : new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                final Prescription myPrescription = em.find(Prescription.class,
                                        prescription.getID());
                                em.close();
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                        };
                new DlgFiles(prescription, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        cptitle.getRight().add(btnFiles);
    }

    if (!prescription.getAttachedProcessConnections().isEmpty()) {
        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = new JButton(
                Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
        btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
        btnProcess.setForeground(Color.YELLOW);
        btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnProcess.setFont(SYSConst.ARIAL18BOLD);
        btnProcess.setPressedIcon(SYSConst.icon22Pressed);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
        btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnProcess.setContentAreaFilled(false);
        btnProcess.setBorder(null);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSPRE2PROCESS> attached = new ArrayList<SYSPRE2PROCESS>(
                                    prescription.getAttachedProcessConnections());
                            for (SYSPRE2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getPrescription().getAttachedProcessConnections()
                                            .remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myPrescription)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSPRE2PROCESS myLinkObject = em
                                            .merge(new SYSPRE2PROCESS(myQProcess, myPrescription));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedPrescriptionConnections().add(myLinkObject);
                                    myPrescription.getAttachedProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }

                    }
                });
            }
        });
        // checked for acls
        btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
        cptitle.getRight().add(btnProcess);
    }

    /***
     *      __  __
     *     |  \/  | ___ _ __  _   _
     *     | |\/| |/ _ \ '_ \| | | |
     *     | |  | |  __/ | | | |_| |
     *     |_|  |_|\___|_| |_|\__,_|
     *
     */
    final JButton btnMenu = new JButton(SYSConst.icon22menu);
    btnMenu.setPressedIcon(SYSConst.icon22Pressed);
    btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
    btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    btnMenu.setContentAreaFilled(false);
    btnMenu.setBorder(null);
    btnMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JidePopup popup = new JidePopup();
            popup.setMovable(false);
            popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
            popup.setOwner(btnMenu);
            popup.removeExcludedComponent(btnMenu);
            JPanel pnl = getMenu(prescription);
            popup.getContentPane().add(pnl);
            popup.setDefaultFocusComponent(pnl);

            GUITools.showPopup(popup, SwingConstants.WEST);
        }
    });
    cptitle.getRight().add(btnMenu);

    cpPres.setHorizontalAlignment(SwingConstants.LEADING);
    cpPres.setOpaque(false);

    return cpPres;
}

From source file:com.opengamma.util.db.management.AbstractDbManagement.java

@Override
public void dropSchema(String catalog, String schema) {
    // Does not handle triggers or stored procedures yet
    ArrayList<String> script = new ArrayList<String>();

    Connection conn = null;/*from  w w w  .  j  av a 2 s.  c  o  m*/
    try {
        if (!getCatalogCreationStrategy().catalogExists(catalog)) {
            System.out.println("Catalog " + catalog + " does not exist");
            return; // nothing to drop
        }

        conn = connect(catalog);

        if (schema != null) {
            Statement statement = conn.createStatement();
            Collection<String> schemas = getAllSchemas(catalog, statement);
            statement.close();

            if (!schemas.contains(schema)) {
                System.out.println("Schema " + schema + " does not exist");
                return; // nothing to drop
            }
        }

        setActiveSchema(conn, schema);
        Statement statement = conn.createStatement();

        // Drop constraints SQL
        if (getHibernateDialect().dropConstraints()) {
            for (Pair<String, String> constraint : getAllForeignKeyConstraints(catalog, schema, statement)) {
                String name = constraint.getFirst();
                String table = constraint.getSecond();
                ForeignKey fk = new ForeignKey();
                fk.setName(name);
                fk.setTable(new Table(table));

                String dropConstraintSql = fk.sqlDropString(getHibernateDialect(), null, schema);
                script.add(dropConstraintSql);
            }
        }

        // Drop views SQL
        for (String name : getAllViews(catalog, schema, statement)) {
            Table table = new Table(name);
            String dropViewStr = table.sqlDropString(getHibernateDialect(), null, schema);
            dropViewStr = dropViewStr.replaceAll("drop table", "drop view");
            script.add(dropViewStr);
        }

        // Drop tables SQL
        for (String name : getAllTables(catalog, schema, statement)) {
            Table table = new Table(name);
            String dropTableStr = table.sqlDropString(getHibernateDialect(), null, schema);
            script.add(dropTableStr);
        }

        // Now execute it all
        statement.close();
        statement = conn.createStatement();
        for (String sql : script) {
            //System.out.println("Executing \"" + sql + "\"");
            statement.executeUpdate(sql);
        }

        statement.close();
        statement = conn.createStatement();

        // Drop sequences SQL
        script.clear();
        for (String name : getAllSequences(catalog, schema, statement)) {
            final SequenceStructure sequenceStructure = new SequenceStructure(getHibernateDialect(), name, 0, 1,
                    Long.class);
            String[] dropSequenceStrings = sequenceStructure.sqlDropStrings(getHibernateDialect());
            script.addAll(Arrays.asList(dropSequenceStrings));
        }

        //now execute drop sequence
        statement.close();
        statement = conn.createStatement();
        for (String sql : script) {
            //System.out.println("Executing \"" + sql + "\"");
            statement.executeUpdate(sql);
        }

        statement.close();

    } catch (SQLException e) {
        throw new OpenGammaRuntimeException("Failed to drop schema", e);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
        }
    }
}

From source file:reportsas.com.formulapp.Formulario.java

public void enviarR(View v) {
    String resul = "";
    SharedPreferences pref = getSharedPreferences("ParametrosBasicos", Context.MODE_PRIVATE);
    long per = pref.getInt("userid", 0);

    respuestaEncuesta = new EncuestaRespuesta(encuesta.getIdEncuesta(), per,
            Integer.parseInt(getDatePhone("MMddHHmmss")), "" + getDatePhone("yyyy-MM-dd"));
    ArrayList<PreguntaRespuesta> respuestas = new ArrayList<PreguntaRespuesta>();
    ArrayList<ParametrosRespuesta> respuestaParametros = new ArrayList<ParametrosRespuesta>();

    boolean validator = false;
    for (int i = 0; i < layout.getChildCount(); i++) {
        LinearLayout child = (LinearLayout) layout.getChildAt(i);
        int numeRes = ObtenerRespuesta(child, encuesta.getPreguntas().get(i), respuestas);
        if (encuesta.getPreguntas().get(i).getObligatoria().equals("S")) {
            for (int j = respuestas.size() - 1; j > (respuestas.size() - 1) - numeRes; j--) {
                PreguntaRespuesta respuestaValidar = respuestas.get(j);
                if (respuestaValidar.getOpcion() == null) {
                    if (respuestaValidar.getRespuesta().trim().length() == 0) {
                        Toast toast1 = Toast.makeText(this, "La pregunta :"
                                + encuesta.getPreguntas().get(i).getTitulo() + ", Es obligatoria!",
                                Toast.LENGTH_LONG);

                        toast1.show();//w w w.j a va  2  s. co m
                        validator = true;
                    }
                } else {
                    if (respuestaValidar.getOpcion().trim().length() == 0) {
                        Toast toast1 = Toast.makeText(this,
                                "Debe escoger un valor para " + respuestaValidar.getRespuesta()
                                        + " en la pregunta :" + encuesta.getPreguntas().get(i).getTitulo(),
                                Toast.LENGTH_LONG);

                        toast1.show();
                        validator = true;
                    }

                }

            }

        }
        if (validator) {
            respuestas.clear();
            break;
        }

    }
    if (encuesta.getParametros() != null) {
        for (int w = 0; w < encuesta.getParametros().size(); w++) {
            EncuestaParametro ep = encuesta.getParametros().get(w);

            if (ep.getOpcional().indexOf('N') > -1) {

                switch (ep.getIdParametro()) {
                // Captura GPS
                case 1:
                    if (parametroGPS == null)

                    {
                        Toast toast1 = Toast.makeText(this, "Debe diligenciar la ubicacin GPS ",
                                Toast.LENGTH_LONG);

                        toast1.show();
                        validator = true;
                    }

                    break;
                // Captura Imgen
                case 2:
                    if (parametroCam == null) {
                        Toast toast1 = Toast.makeText(this, "Debe obtener la captura de una imagen.",
                                Toast.LENGTH_LONG);

                        toast1.show();
                        validator = true;

                    }

                    break;
                // Lectura de Codigo
                case 3:
                    if (parametroScan == null) {
                        Toast toast1 = Toast.makeText(this, "Debe obtener el scaner de la cedula",
                                Toast.LENGTH_LONG);

                        toast1.show();
                        validator = true;
                    }

                    break;

                default:

                    break;
                }
                if (validator) {

                    break;
                }

            }

        }
        if (!validator) {
            if (parametroGPS != null) {
                respuestaParametros.add(parametroGPS);
            }

            if (parametroCam != null) {
                respuestaParametros.add(parametroCam);
            }

            if (parametroScan != null) {
                respuestaParametros.add(parametroScan);
            }

            if (respuestas.size() > 0) {
                respuestaEncuesta.setRespuesta(respuestas);
                if (respuestaParametros.size() > 0) {
                    respuestaEncuesta.setParametros(respuestaParametros);
                }
            }

        }

    }
    if (!validator) {

        final Gson gson = new Gson();

        if (DataOpciones.verificaConexion(this)) {

            String pr = pref.getString("ruta", "54.164.174.129:8081");
            //http://10.200.5.8:8081/
            String ruta = "http://" + pr + "/" + HTTP_EVENT;
            new MyAsyncTask(Formulario.this).execute("POST", gson.toJson(respuestaEncuesta), ruta);

        } else {
            insertarEncuentas(respuestaEncuesta);
        }

    }

}