Example usage for java.lang Thread setPriority

List of usage examples for java.lang Thread setPriority

Introduction

In this page you can find the example usage for java.lang Thread setPriority.

Prototype

public final void setPriority(int newPriority) 

Source Link

Document

Changes the priority of this thread.

Usage

From source file:org.fao.geonet.OgpAppHandler.java

private void fillCaches(final ServiceContext context) {
    final Format formatService = context.getBean(Format.class); // this will initialize the formatter

    Thread fillCaches = new Thread(new Runnable() {
        @Override/*from w  ww. ja v a2  s .  c o  m*/
        public void run() {
            final ServletContext servletContext = context.getServlet().getServletContext();
            context.setAsThreadLocal();
            ApplicationContextHolder.set(_applicationContext);
            GeonetWro4jFilter filter = (GeonetWro4jFilter) servletContext
                    .getAttribute(GeonetWro4jFilter.GEONET_WRO4J_FILTER_KEY);

            @SuppressWarnings("unchecked")
            List<String> wro4jUrls = _applicationContext.getBean("wro4jUrlsToInitialize", List.class);

            for (String wro4jUrl : wro4jUrls) {
                Log.info(Geonet.GEONETWORK, "Initializing the WRO4J group: " + wro4jUrl + " cache");
                final MockHttpServletRequest servletRequest = new MockHttpServletRequest(servletContext, "GET",
                        "/static/" + wro4jUrl);
                final MockHttpServletResponse response = new MockHttpServletResponse();
                try {
                    filter.doFilter(servletRequest, response, new MockFilterChain());
                } catch (Throwable t) {
                    Log.info(Geonet.GEONETWORK,
                            "Error while initializing the WRO4J group: " + wro4jUrl + " cache", t);
                }
            }

            final Page<Metadata> metadatas = _applicationContext.getBean(MetadataRepository.class)
                    .findAll(new PageRequest(0, 1));
            if (metadatas.getNumberOfElements() > 0) {
                Integer mdId = metadatas.getContent().get(0).getId();
                context.getUserSession().loginAs(
                        new User().setName("admin").setProfile(Profile.Administrator).setUsername("admin"));
                @SuppressWarnings("unchecked")
                List<String> formattersToInitialize = _applicationContext.getBean("formattersToInitialize",
                        List.class);

                for (String formatterName : formattersToInitialize) {
                    Log.info(Geonet.GEONETWORK, "Initializing the Formatter with id: " + formatterName);
                    final MockHttpServletRequest servletRequest = new MockHttpServletRequest(servletContext);
                    final MockHttpServletResponse response = new MockHttpServletResponse();
                    try {
                        formatService.exec("eng", FormatType.html.toString(), mdId.toString(), null,
                                formatterName, Boolean.TRUE.toString(), false, FormatterWidth._100,
                                new ServletWebRequest(servletRequest, response));
                    } catch (Throwable t) {
                        Log.info(Geonet.GEONETWORK,
                                "Error while initializing the Formatter with id: " + formatterName, t);
                    }
                }
            }
        }
    });
    fillCaches.setDaemon(true);
    fillCaches.setName("Fill Caches Thread");
    fillCaches.setPriority(Thread.MIN_PRIORITY);
    fillCaches.start();
}

From source file:org.apache.hadoop.hive.metastore.AggregateStatsCache.java

/**
 * Cleans the expired nodes or removes LRU nodes of the cache,
 * until the cache size reduces to cleanUntil% full.
 *//*www.  j a  v  a2 s.c o m*/
private void spawnCleaner() {
    // This spawns a separate thread to walk through the cache and removes expired nodes.
    // Only one cleaner thread should be running at any point.
    synchronized (this) {
        if (isCleaning) {
            return;
        }
        isCleaning = true;
    }
    Thread cleaner = new Thread("AggregateStatsCache-CleanerThread") {
        @Override
        public void run() {
            numRemovedTTL = 0;
            numRemovedLRU = 0;
            long cleanerStartTime = System.currentTimeMillis();
            LOG.info("AggregateStatsCache is " + getFullPercent() + "% full, with " + getCurrentNodes()
                    + " nodes; starting cleaner thread");
            try {
                Iterator<Map.Entry<Key, AggrColStatsList>> mapIterator = cacheStore.entrySet().iterator();
                while (mapIterator.hasNext()) {
                    Map.Entry<Key, AggrColStatsList> pair = (Map.Entry<Key, AggrColStatsList>) mapIterator
                            .next();
                    AggrColStats node;
                    AggrColStatsList candidateList = (AggrColStatsList) pair.getValue();
                    List<AggrColStats> nodes = candidateList.nodes;
                    if (nodes.size() == 0) {
                        mapIterator.remove();
                        continue;
                    }
                    boolean isLocked = false;
                    try {
                        isLocked = candidateList.writeLock.tryLock(maxWriterWaitTime, TimeUnit.MILLISECONDS);
                        if (isLocked) {
                            for (Iterator<AggrColStats> listIterator = nodes.iterator(); listIterator
                                    .hasNext();) {
                                node = listIterator.next();
                                // Remove the node if it has expired
                                if (isExpired(node)) {
                                    listIterator.remove();
                                    numRemovedTTL++;
                                    currentNodes.getAndDecrement();
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        LOG.debug(e);
                    } finally {
                        if (isLocked) {
                            candidateList.writeLock.unlock();
                        }
                    }
                    // We want to make sure this runs at a low priority in the background
                    Thread.yield();
                }
                // If the expired nodes did not result in cache being cleanUntil% in size,
                // start removing LRU nodes
                while (getCurrentNodes() / maxCacheNodes > cleanUntil) {
                    evictOneNode();
                }
            } finally {
                isCleaning = false;
                LOG.info("Stopping cleaner thread; AggregateStatsCache is now " + getFullPercent()
                        + "% full, with " + getCurrentNodes() + " nodes");
                LOG.info("Number of expired nodes removed: " + numRemovedTTL);
                LOG.info("Number of LRU nodes removed: " + numRemovedLRU);
                LOG.info("Cleaner ran for: " + (System.currentTimeMillis() - cleanerStartTime) + "ms");
            }
        }
    };
    cleaner.setPriority(Thread.MIN_PRIORITY);
    cleaner.setDaemon(true);
    cleaner.start();
}

From source file:com.intuit.tank.harness.APITestHarness.java

/**
 * Run concurrent test plans at the same time
 * //from   w ww.ja v a2 s  .  c o m
 * @param parser
 */
public void runConcurrentTestPlans() {
    if (started) {
        LOG.warn("Agent already started. Ignoring start command");
        return;
    }
    tpsMonitor = new TPSMonitor(tankConfig.getAgentConfig().getTPSPeriod());
    StringBuilder info = new StringBuilder().append(" RAMP_TIME=").append(agentRunData.getRampTime())
            .append("; agentRunData.getNumUsers()=").append(agentRunData.getNumUsers())
            .append("; NUM_START_THREADS=").append(agentRunData.getNumStartUsers()).append("; simulationTime=")
            .append(agentRunData.getSimulationTime());
    LOG.info(LogUtil.getLogMessage("starting test with " + info.toString()));
    started = true;

    if (agentRunData.getJobId() == null) {
        String jobId = AmazonUtil.getJobId();
        agentRunData.setJobId(jobId);
    }

    TestPlanRunner[] sessions = new TestPlanRunner[agentRunData.getNumUsers()];
    sessionThreads = new Thread[agentRunData.getNumUsers()];
    Thread monitorThread = null;
    doneSignal = new CountDownLatch(agentRunData.getNumUsers());
    try {
        HDWorkload hdWorkload = TestPlanSingleton.getInstance().getTestPlans().get(0);
        if (StringUtils.isBlank(tankHttpClientClass)) {
            tankHttpClientClass = hdWorkload.getTankHttpClientClass();
        }
        agentRunData.setProjectName(hdWorkload.getName());
        agentRunData.setTankhttpClientClass(tankHttpClientClass);
        List<TestPlanStarter> testPlans = new ArrayList<TestPlanStarter>();
        int total = 0;
        for (HDTestPlan plan : hdWorkload.getPlans()) {
            if (plan.getUserPercentage() > 0) {
                plan.setVariables(hdWorkload.getVariables());
                TestPlanStarter starter = new TestPlanStarter(plan, agentRunData.getNumUsers());
                total += starter.getNumThreads();
                testPlans.add(starter);
                LOG.info(LogUtil.getLogMessage("Users for Test Plan " + plan.getTestPlanName() + " at "
                        + plan.getUserPercentage() + "% = " + starter.getNumThreads()));
            }
        }
        LOG.info(LogUtil.getLogMessage("Total Users calculated for all test Plans = " + total));
        if (total != agentRunData.getNumUsers()) {
            int numToAdd = agentRunData.getNumUsers() - total;
            TestPlanStarter starter = testPlans.get(testPlans.size() - 1);
            LOG.info(LogUtil.getLogMessage(
                    "adding " + numToAdd + " threads to testPlan " + starter.getPlan().getTestPlanName()));
            starter.setNumThreads(starter.getNumThreads() + numToAdd);
        }

        // create threads
        int tp = 0;
        for (TestPlanStarter starter : testPlans) {
            for (int i = 0; i < starter.getNumThreads(); i++) {
                sessions[tp] = new TestPlanRunner(starter.getPlan(), tp);
                sessionThreads[tp] = new Thread(threadGroup, sessions[tp], "AGENT");
                sessionThreads[tp].setDaemon(true);// system won't shut down normally until all user threads stop
                starter.addThread(sessionThreads[tp]);
                sessions[tp].setUniqueName(
                        sessionThreads[tp].getThreadGroup().getName() + "-" + sessionThreads[tp].getId());
                tp++;
            }
        }
        LOG.info(LogUtil.getLogMessage("Have all testPlan runners configured"));
        // start status thread first only
        if (!isLocal && !isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) {
            LOG.info(LogUtil.getLogMessage("Starting monitor thread..."));
            CloudVmStatus status = getInitialStatus();
            monitorThread = new Thread(new APIMonitor(status));
            monitorThread.setDaemon(true);
            monitorThread.setPriority(Thread.NORM_PRIORITY - 2);
            monitorThread.start();
        }

        LOG.info(LogUtil.getLogMessage("Starting threads..."));
        // start initial users
        startTime = System.currentTimeMillis();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
        LOG.info(LogUtil.getLogMessage("Simulation start: " + df.format(new Date(getStartTime()))));
        if (agentRunData.getSimulationTime() != 0) {
            LOG.info(LogUtil.getLogMessage(
                    "Scheduled Simulation End : " + df.format(new Date(getSimulationEndTimeMillis()))));
            LOG.info(LogUtil.getLogMessage(
                    "Max Simulation End : " + df.format(new Date(getMaxSimulationEndTimeMillis()))));
        } else {
            LOG.info(LogUtil.getLogMessage("Ends at script loops completed with no Max Simulation Time."));
        }
        currentNumThreads = 0;
        if (agentRunData.getNumUsers() > 0) {
            for (TestPlanStarter starter : testPlans) {
                if (isDebug()) {
                    starter.run();
                } else {
                    Thread t = new Thread(starter);
                    t.setDaemon(true);
                    t.start();
                }
            }
            boolean ramping = true;
            while (ramping) {
                boolean done = true;
                for (TestPlanStarter starter : testPlans) {
                    done = done && starter.isDone();
                }
                ramping = !done;
                if (ramping) {
                    Thread.sleep(5000);
                }
            }
            // if we broke early, fix our countdown latch
            int numToCount = 0;
            for (TestPlanStarter starter : testPlans) {
                numToCount += starter.getThreadsStarted();
            }
            while (numToCount < agentRunData.getNumUsers()) {
                doneSignal.countDown();
                numToCount++;
            }
            // wait for them to finish
            LOG.info(LogUtil.getLogMessage("Ramp Complete..."));

            doneSignal.await();
        }
    } catch (Throwable t) {
        LOG.error("error executing..." + t, t);
    } finally {
        LOG.info(LogUtil.getLogMessage("Test Complete..."));
        if (!isDebug() && NumberUtils.isDigits(agentRunData.getJobId())) {
            if (null != monitorThread) {
                APIMonitor.setJobStatus(JobStatus.Completed);
                APIMonitor.setDoMonitor(false);
            }
            sendBatchToDB(false);
            // sleep for 60 seconds to let wily agent clear any data
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                // nothing to do
            }
        }
    }
    flowControllerTemplate.endTest();
    // System.exit(0);
}

From source file:com.max2idea.android.limbo.main.LimboActivity.java

private void onStartButton() {

    if (this.mMachine.getSelectedItemPosition() == 0 || this.currMachine == null) {
        Toast.makeText(getApplicationContext(), "Select or Create a Virtual Machine first", Toast.LENGTH_LONG)
                .show();//  w w  w.  j av a2  s .c o m
        return;
    }
    String filenotexists = validateFiles();
    if (filenotexists != null) {
        Toast.makeText(getApplicationContext(), "Could not find file: " + filenotexists, Toast.LENGTH_LONG)
                .show();
        return;
    }
    if (currMachine.snapshot_name != null && !currMachine.snapshot_name.toLowerCase().equals("none")
            && !currMachine.snapshot_name.toLowerCase().equals("") && currMachine.soundcard != null
            && !currMachine.soundcard.toLowerCase().equals("none") && mUI.getSelectedItemPosition() != 1) {
        Toast.makeText(getApplicationContext(),
                "Snapshot was saved with soundcard enabled please use SDL \"User Interface\"",
                Toast.LENGTH_LONG).show();
        return;
    }

    if (currMachine != null && currMachine.cpu != null && currMachine.cpu.endsWith("(arm)")
            && (currMachine.kernel == null || currMachine.kernel.equals(""))) {
        sendHandlerMessage(handler, Const.VM_NO_KERNEL);
        return;
    }
    // Initrd is optional
    // if (currMachine!=null && currMachine.cpu !=null &&
    // currMachine.cpu.startsWith("arm")
    // && (currMachine.initrd == null || currMachine.initrd.equals(""))) {
    // sendHandlerMessage(handler, Const.VM_NO_INITRD);
    //
    // }

    if (vmexecutor == null)
        vmexecutor = new VMExecutor(currMachine);

    // Global settings
    vmexecutor.dns_addr = mDNS.getText().toString();
    vmexecutor.append = mAppend.getText().toString();
    if (this.mMultiAIO.isChecked()) {
        vmexecutor.aiomaxthreads = Const.MAX_AIO_THREADS;
    } else {
        vmexecutor.aiomaxthreads = Const.MIN_AIO_THREADS;
    }
    vmexecutor.print();
    output = "Starting VM...";
    sendHandlerMessage(handler, Const.VM_STARTED);

    if (mUI.getSelectedItemPosition() == 1) { // SDL
        Thread tsdl = new Thread(new Runnable() {
            public void run() {
                startsdl();

            }
        });
        tsdl.start();
    } else { // VNC
        if (!vmStarted) {
            Thread tvm = new Thread(new Runnable() {
                public void run() {
                    startvm(Const.UI_VNC);
                }
            });
            if (mPrio.isChecked())
                tvm.setPriority(Thread.MAX_PRIORITY);
            tvm.start();
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(LimboActivity.class.getName()).log(Level.SEVERE, null, ex);
        }
        Thread tvnc = new Thread(new Runnable() {
            public void run() {
                startvnc();
            }
        });
        // t.setPriority(Thread.MAX_PRIORITY);
        tvnc.start();
        // MK setting DNS via command line options
        // Thread tdns = new Thread(new Runnable() {
        // public void run() {
        // setDNSaddr();
        // }
        // });
        // tdns.start();
    }

}

From source file:weka.server.WekaServer.java

/**
 * Send status info for the supplied task back to the master server
 * /*  w  ww  .j  a v a2 s  .co  m*/
 * @param entry the task entry for the task in question
 * @param taskStatus the status to send
 */
protected void sendTaskStatusInfoToMaster(final WekaTaskEntry entry, final int taskStatus) {

    Thread t = new Thread() {
        @Override
        public void run() {
            PostMethod post = null;
            InputStream is = null;
            try {
                String url = "http://" + m_master;
                url = url.replace(" ", "%20");
                url += SetTaskStatusServlet.CONTEXT_PATH;
                url += "/?name=" + entry.toString();
                url += "&status=" + taskStatus;

                post = new PostMethod(url);
                post.setDoAuthentication(true);
                post.addRequestHeader(new Header("Content-Type", "text/plain"));

                // Get HTTP client
                HttpClient client = ConnectionManager.getSingleton().createHttpClient();
                ConnectionManager.addCredentials(client, m_username, m_password);

                // Execute request
                int result = client.executeMethod(post);
                // System.out.println("[WekaServer] SendTaskStatus: Response from master server : "
                // + result);
                if (result == 401) {
                    System.err.println("[WekaServer] Unable to send task status back to master"
                            + " - authentication required.\n");
                } else {

                    // the response
                    is = post.getResponseBodyAsStream();
                    ObjectInputStream ois = new ObjectInputStream(is);
                    Object response = ois.readObject();
                    if (response.toString().startsWith(WekaServlet.RESPONSE_ERROR)) {
                        System.err.println("[WekaServer] A problem occurred while "
                                + "trying to send task status back to master server : \n" + "\t"
                                + response.toString());
                    } else {
                        // System.out.println("[WekaServer] " + response.toString());
                    }
                }
            } catch (Exception ex) {
                System.err.println("[WekaServer] A problem occurred while "
                        + "trying to send task status back to master server : \n" + ex.getMessage());
                ex.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (post != null) {
                    post.releaseConnection();
                }
            }
        }
    };

    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:weka.server.WekaServer.java

/**
 * Send the last time of execution of the supplied task to the master server
 * /*from  w  ww .ja v  a2 s. co  m*/
 * @param entry the task entry for the task in question
 */
protected void sendExecutionTimeToMaster(final WekaTaskEntry entry) {

    Thread t = new Thread() {
        @Override
        public void run() {

            PostMethod post = null;
            InputStream is = null;
            try {
                String url = "http://" + m_master;
                url = url.replace(" ", "%20");
                url += SetLastExecutionServlet.CONTEXT_PATH;
                url += "/?name=" + entry.toString();
                SimpleDateFormat sdf = new SimpleDateFormat(SetLastExecutionServlet.DATE_FORMAT);
                String formattedDate = sdf.format(entry.getLastExecution());
                url += "&lastExecution=" + formattedDate;

                post = new PostMethod(url);
                post.setDoAuthentication(true);
                post.addRequestHeader(new Header("Content-Type", "text/plain"));

                // Get HTTP client
                HttpClient client = ConnectionManager.getSingleton().createHttpClient();
                ConnectionManager.addCredentials(client, m_username, m_password);

                // Execute request
                int result = client.executeMethod(post);
                // System.out.println("[WekaServer] Response from master server : " +
                // result);
                if (result == 401) {
                    System.err.println("[WekaServer] Unable to send task last execution time back "
                            + "to master - authentication required.\n");
                } else {

                    // the response
                    is = post.getResponseBodyAsStream();
                    ObjectInputStream ois = new ObjectInputStream(is);
                    Object response = ois.readObject();
                    if (response.toString().startsWith(WekaServlet.RESPONSE_ERROR)) {
                        System.err.println("[WekaServer] A problem occurred while "
                                + "trying to send task last execution timeback to master server : \n" + "\t"
                                + response.toString());
                    } else {
                        // System.out.println("[WekaServer] " + response.toString());
                    }
                }
            } catch (Exception ex) {
                System.err.println("[WekaServer] A problem occurred while "
                        + "trying to send task last execution time back to master server : \n"
                        + ex.getMessage());
                ex.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (post != null) {
                    post.releaseConnection();
                }
            }
        }
    };

    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

private void parameterSelection(final int pos, final Object obj) {

    QueryParameter param = paramList.get(pos);
    parametersValues.put(param.getName(), obj);
    final Map<String, QueryParameter> dependents = ParameterManager.getInstance()
            .getChildDependentParameters(param);
    if (dependents.size() > 0) {

        Thread executorThread = new Thread(new Runnable() {

            public void run() {
                UIActivator activator = new UIActivator(
                        (JDialog) SwingUtilities.getWindowAncestor(RuntimeParametersPanel.this),
                        I18NSupport.getString("run.load.dependent.parameters"));
                activator.start();//from  w w  w  .j  av a  2  s  . c o m

                try {
                    for (final QueryParameter qp : dependents.values()) {
                        Map<String, QueryParameter> map = ParameterManager.getInstance()
                                .getParentDependentParameters(qp);
                        Map<String, Object> vals = new HashMap<String, Object>();
                        boolean selected = true;
                        for (QueryParameter p : map.values()) {
                            Object v = parametersValues.get(p.getName());
                            if (((obj instanceof Object[]) && (((Object[]) obj).length == 0)) || (v == null)) {
                                selected = false;
                            }
                            vals.put(p.getName(), v);
                        }

                        final List<IdName> values = new ArrayList<IdName>();
                        // all parent parameters selected
                        if (selected) {
                            Query query = new Query(qp.getSource());
                            // no count and no check for other parameters completition
                            QueryExecutor executor = new QueryExecutor(query, map, vals, con, false, false,
                                    false);
                            executor.setTimeout(Globals.getQueryTimeout());
                            executor.setMaxRows(0);
                            QueryResult qr = executor.execute();
                            //int count = qr.getRowCount();
                            int columnCount = qr.getColumnCount();

                            // two columns in manual select source!!!
                            //for (int i = 0; i < count; i++) {
                            while (qr.hasNext()) {
                                IdName in = new IdName();
                                in.setId((Serializable) qr.nextValue(0));
                                if (columnCount == 1) {
                                    in.setName((Serializable) qr.nextValue(0));
                                } else {
                                    in.setName((Serializable) qr.nextValue(1));
                                }
                                values.add(in);
                            }
                            Collections.sort(values, new IdNameComparator(qp.getOrderBy()));
                            qr.close();
                        }
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                ArrayList<Serializable> defaultValues = qp.getDefaultValues();
                                if ((qp.getDefaultSourceValues() != null)
                                        && (qp.getDefaultSourceValues().size() > 1)) {
                                    defaultValues = qp.getDefaultSourceValues();
                                }
                                initParameterValue(getComponent(qp), values, qp.getName(), defaultValues);
                            }
                        });

                    }

                } catch (Exception ex) {
                    LOG.error(ex.getMessage(), ex);
                    ex.printStackTrace();
                } finally {
                    if (activator != null) {
                        activator.stop();
                    }
                }

            }
        }, "NEXT : " + getClass().getSimpleName());
        executorThread.setPriority(EngineProperties.getRunPriority());
        executorThread.start();
    }

}

From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java

@Override
public void onStart(Intent intent, final int startId) {
    super.onStart(intent, startId);

    if (!sending.compareAndSet(false, true)) {
        Log.i(TAG, "Send already in progress, skipping intent");
    }/*from w w  w .j  a v a  2  s. c o m*/

    final TiAnalyticsService self = this;

    Thread t = new Thread(new Runnable() {

        public void run() {
            Log.i(TAG, "Analytics Service Started");
            try {

                if (connectivityManager == null) {
                    Log.w(TAG, "Connectivity manager not available.");
                    stopSelf(startId);
                    return;
                }
                TiAnalyticsModel model = new TiAnalyticsModel(self);
                if (!model.hasEvents()) {
                    Log.d(TAG, "No events to send.", Log.DEBUG_MODE);
                    stopSelf(startId);
                    return;
                }

                while (model.hasEvents()) {
                    if (canSend()) {
                        LinkedHashMap<Integer, JSONObject> events = model
                                .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK);

                        int len = events.size();
                        int[] eventIds = new int[len];
                        Iterator<Integer> keys = events.keySet().iterator();

                        JSONArray records = new JSONArray();
                        // build up data to send and records to delete on success
                        for (int i = 0; i < len; i++) {
                            int id = keys.next();
                            // ids are kept even on error JSON to prevent unrestrained growth
                            // and a queue blocked by bad records.
                            eventIds[i] = id;
                            records.put(events.get(id));

                            if (Log.isDebugModeEnabled()) {
                                JSONObject obj = events.get(id);
                                Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = "
                                        + obj.getString("ts"));
                            }
                        }
                        boolean deleteEvents = true;
                        if (records.length() > 0) {
                            if (Log.isDebugModeEnabled()) {
                                Log.d(TAG, "Sending " + records.length() + " analytics events.");
                            }
                            try {
                                String jsonData = records.toString() + "\n";
                                String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL
                                        : ANALYTICS_URL + TiApplication.getInstance().getAppGUID();

                                HttpPost httpPost = new HttpPost(postUrl);
                                StringEntity entity = new StringEntity(jsonData);
                                entity.setContentType("text/json");
                                httpPost.setEntity(entity);

                                HttpParams httpParams = new BasicHttpParams();
                                HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property
                                //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property
                                HttpClient client = new DefaultHttpClient(httpParams);

                                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                                client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

                                @SuppressWarnings("unused")
                                String response = client.execute(httpPost, responseHandler);
                            } catch (Throwable t) {
                                Log.e(TAG, "Error posting events: " + t.getMessage(), t);
                                deleteEvents = false;
                                records = null;
                                break;
                            }
                        }

                        records = null;

                        if (deleteEvents) {
                            model.deleteEvents(eventIds);
                        }

                        events.clear();
                    } else {
                        Log.w(TAG, "Network unavailable, can't send analytics");
                        //TODO reset alarm?
                        break;
                    }
                }

                Log.i(TAG, "Stopping Analytics Service");
                stopSelf(startId);
            } catch (Throwable t) {
                Log.e(TAG, "Unhandled exception in analytics thread: ", t);
                stopSelf(startId);
            } finally {
                if (!sending.compareAndSet(true, false)) {
                    Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE);
                }
            }
        }
    });
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:gate.corpora.CSVImporter.java

@Override
protected List<Action> buildActions(final NameBearerHandle handle) {
    List<Action> actions = new ArrayList<Action>();

    if (!(handle.getTarget() instanceof Corpus))
        return actions;

    actions.add(new AbstractAction("Populate from CSV File") {
        @Override//from  w ww  .j ava 2 s.co m
        public void actionPerformed(ActionEvent e) {

            // display the populater dialog and return if it is cancelled
            if (JOptionPane.showConfirmDialog(null, dialog, "Populate From CSV File",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION)
                return;

            // we want to run the population in a separate thread so we don't lock
            // up the GUI
            Thread thread = new Thread(Thread.currentThread().getThreadGroup(), "CSV Corpus Populater") {

                public void run() {
                    try {

                        // unescape the strings that define the format of the file and
                        // get the actual chars
                        char separator = StringEscapeUtils.unescapeJava(txtSeparator.getText()).charAt(0);
                        char quote = StringEscapeUtils.unescapeJava(txtQuoteChar.getText()).charAt(0);

                        // see if we can convert the URL to a File instance
                        File file = null;
                        try {
                            file = Files.fileFromURL(new URL(txtURL.getText()));
                        } catch (IllegalArgumentException iae) {
                            // this will happen if someone enters an actual URL, but we
                            // handle that later so we can just ignore the exception for
                            // now and keep going
                        }

                        if (file != null && file.isDirectory()) {
                            // if we have a File instance and that points at a directory
                            // then....

                            // get all the CSV files in the directory structure
                            File[] files = Files.listFilesRecursively(file, CSV_FILE_FILTER);

                            for (File f : files) {
                                // for each file...

                                // skip directories as we don't want to handle those
                                if (f.isDirectory())
                                    continue;

                                if (cboDocuments.isSelected()) {
                                    // if we are creating lots of documents from a single
                                    // file
                                    // then call the populate method passing through all the
                                    // options from the GUI
                                    populate((Corpus) handle.getTarget(), f.toURI().toURL(),
                                            txtEncoding.getText(), (Integer) textColModel.getValue(),
                                            cboFeatures.isSelected(), separator, quote);
                                } else {
                                    // if we are creating a single document from a single
                                    // file
                                    // then call the createDoc method passing through all
                                    // the
                                    // options from the GUI
                                    createDoc((Corpus) handle.getTarget(), f.toURI().toURL(),
                                            txtEncoding.getText(), (Integer) textColModel.getValue(),
                                            cboFeatures.isSelected(), separator, quote);
                                }
                            }
                        } else {
                            // we have a single URL to process so...

                            if (cboDocuments.isSelected()) {
                                // if we are creating lots of documents from a single file
                                // then call the populate method passing through all the
                                // options from the GUI
                                populate((Corpus) handle.getTarget(), new URL(txtURL.getText()),
                                        txtEncoding.getText(), (Integer) textColModel.getValue(),
                                        cboFeatures.isSelected(), separator, quote);
                            } else {
                                // if we are creating a single document from a single file
                                // then call the createDoc method passing through all the
                                // options from the GUI
                                createDoc((Corpus) handle.getTarget(), new URL(txtURL.getText()),
                                        txtEncoding.getText(), (Integer) textColModel.getValue(),
                                        cboFeatures.isSelected(), separator, quote);
                            }
                        }
                    } catch (Exception e) {
                        // TODO give a sensible error message
                        e.printStackTrace();
                    }
                }
            };

            // let's leave the GUI nice and responsive
            thread.setPriority(Thread.MIN_PRIORITY);

            // lets get to it and do some actual work!
            thread.start();

        }
    });

    return actions;
}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void startFileioTask(FileListAdapter fla, final int op_cd, final ArrayList<FileIoLinkParm> alp,
        String item_name, final NotifyEvent p_ntfy, final String lmp) {
    setAllFilelistItemUnChecked(fla);//w w w .  ja va 2  s. c om

    @SuppressWarnings("unused")
    String dst = "";
    String dt = null;
    @SuppressWarnings("unused")
    String nitem = item_name;
    mGp.fileIoWifiLockRequired = false;
    switch (op_cd) {
    case FILEIO_PARM_REMOTE_CREATE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_CREATE:
        dt = "Create";
        dst = item_name + " was created.";
        nitem = "";
        break;
    case FILEIO_PARM_REMOTE_RENAME:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_RENAME:
        dt = "Rename";
        dst = item_name + " was renamed.";
        nitem = "";
        break;
    case FILEIO_PARM_REMOTE_DELETE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_DELETE:
        dt = "Delete";
        dst = "Following dirs/files were deleted.";
        break;
    case FILEIO_PARM_COPY_REMOTE_TO_LOCAL:
    case FILEIO_PARM_COPY_REMOTE_TO_REMOTE:
    case FILEIO_PARM_COPY_LOCAL_TO_REMOTE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_COPY_LOCAL_TO_LOCAL:
        dt = "Copy";
        dst = "Following dirs/files were copied.";
        break;
    case FILEIO_PARM_MOVE_REMOTE_TO_REMOTE:
    case FILEIO_PARM_MOVE_LOCAL_TO_REMOTE:
    case FILEIO_PARM_MOVE_REMOTE_TO_LOCAL:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_MOVE_LOCAL_TO_LOCAL:
        dt = "Move";
        dst = "Following dirs/files were moved.";
        break;
    case FILEIO_PARM_DOWLOAD_REMOTE_FILE:
        mGp.fileIoWifiLockRequired = true;
        dt = "Download";
        dst = "";
    default:
        break;
    }

    mTcFileIoTask = new ThreadCtrl();
    mTcFileIoTask.setEnabled();

    if (currentTabName.equals(SMBEXPLORER_TAB_LOCAL)) {
        mGp.progressMsgView = mLocalProgressMsg;
        mGp.progressCancelBtn = mLocalProgressCancel;
        showLocalProgressView();
    } else if (currentTabName.equals(SMBEXPLORER_TAB_REMOTE)) {
        mGp.progressMsgView = mRemoteProgressMsg;
        mGp.progressCancelBtn = mRemoteProgressCancel;
        showRemoteProgressView();
    }
    mGp.progressMsgView.setText(dt);

    mGp.progressCancelBtn.setEnabled(true);
    mGp.progressCancelBtn.setText("Cancel");
    mProgressOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            mTcFileIoTask.setDisabled();
            mGp.progressCancelBtn.setEnabled(false);
            mGp.progressCancelBtn.setText("Cancelling");
        }
    };
    mGp.progressCancelBtn.setOnClickListener(mProgressOnClickListener);

    NotifyEvent ne = new NotifyEvent(mContext);
    ne.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            hideLocalProgressView();
            if (!mTcFileIoTask.isThreadResultSuccess()) {
                if (p_ntfy != null)
                    p_ntfy.notifyToListener(false, null);
                if (mTcFileIoTask.isThreadResultCancelled()) {
                    //                  commonDlg.showCommonDialog(false,"W","File I/O task was cancelled.","",null);
                    showDialogMsg("W", "File I/O task was cancelled.", "");
                    sendLogMsg("W", "File I/O task was cancelled.");
                    //                  refreshFilelistView();
                } else {
                    //                  commonDlg.showCommonDialog(false,"E","File I/O task was failed."+"\n"+
                    //                              mTcFileIoTask.getThreadMessage(),"",null);
                    showDialogMsg("E", "File I/O task was failed." + "\n" + mTcFileIoTask.getThreadMessage(),
                            "");
                    sendLogMsg("E", "File I/O task was failed.");
                    //                  refreshFilelistView();
                }
            } else {
                if (p_ntfy != null)
                    p_ntfy.notifyToListener(true, null);
                else
                    refreshFilelistView();
            }
            alp.clear();
            if (isTaskDataExisted())
                saveTaskData();
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            hideLocalProgressView();
        }
    });

    Thread th = new Thread(new FileIo(mGp, op_cd, alp, mTcFileIoTask, ne, this, lmp));
    mTcFileIoTask.initThreadCtrl();
    th.setPriority(Thread.MIN_PRIORITY);
    th.start();
}