Example usage for java.lang Thread MAX_PRIORITY

List of usage examples for java.lang Thread MAX_PRIORITY

Introduction

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

Prototype

int MAX_PRIORITY

To view the source code for java.lang Thread MAX_PRIORITY.

Click Source Link

Document

The maximum priority that a thread can have.

Usage

From source file:cai.flow.collector.Collector.java

/**
 * // w  w  w.j  a v  a2 s.  com
 *
 */
void go() {

    ServiceThread rdr = new ServiceThread(this,
            "Reader at " + (localHost == null ? "any" : "" + localHost) + ":" + localPort, "REader") {
        public void exec() throws Throwable {
            ((Collector) o).reader_loop();
        }
    };
    rdr.setName(rdr.getName() + "-Reader");
    rdr.setPriority(Thread.MAX_PRIORITY);
    rdr.setDaemon(true);
    rdr.start();

    ServiceThread statistics;
    /**
     */
    if (stat_interval != 0) {
        statistics = new ServiceThread(this, "Statistics over " + Util.toInterval(stat_interval),
                "Statistics") {
            public void exec() throws Throwable {
                ((Collector) o).statistics_loop();
            }
        };
        statistics.setName(statistics.getName() + "-Statistics");
        statistics.setDaemon(true);
        statistics.start();
    }

    ServiceThread[] cols = new ServiceThread[collector_thread];

    for (int i = 0; i < collector_thread; i++) {
        String title = new String("Collector" + (i + 1));
        ServiceThread col = new ServiceThread(this, title, title) {
            public void exec() {
                ((Collector) o).collector_loop();
            }
        };

        cols[i] = col;
        col.setName(col.getName() + "-" + title);
        col.start();
    }

    try {
        for (int i = 0; i < collector_thread; i++)
            cols[i].join();
    } catch (InterruptedException e) {
        logger.fatal("Collector - InterruptedException in main thread, exit");
        logger.debug(e.getMessage());
    }
}

From source file:com.klinker.android.twitter.services.TalonPullNotificationService.java

@Override
public void onCreate() {
    super.onCreate();

    if (TalonPullNotificationService.isRunning) {
        stopSelf();//  www .j  ava2  s .co m
        return;
    }

    TalonPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    pullUnread = sharedPreferences.getInt("pull_unread", 0);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    Intent popup = new Intent(this, RedirectToPopup.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    popup.putExtra("from_notification", true);
    PendingIntent popupPending = PendingIntent.getActivity(this, 0, popup, 0);

    Intent compose = new Intent(this, WidgetCompose.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent composePending = PendingIntent.getActivity(this, 0, compose, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.talon_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
        mBuilder.addAction(R.drawable.ic_popup, getResources().getString(R.string.popup), popupPending);
        mBuilder.addAction(R.drawable.ic_send_dark, getResources().getString(R.string.tweet), composePending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;
                int rep = 0;

                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    ids = new ArrayList<Long>();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }

                    rep++;
                } while ((currCursor = idObject.getNextCursor()) != 0 && rep < 3);

                ids.add(settings.myId);

                idsLoaded = true;

                startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.klinker.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TalonPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TalonPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:net.dv8tion.jda.requests.WebSocketClient.java

protected void setupKeepAlive(long timeout) {
    keepAliveThread = new Thread(() -> {
        while (connected) {
            try {
                sendKeepAlive();//from w  ww .ja  va 2 s  . c o  m

                //Sleep for heartbeat interval
                Thread.sleep(timeout);
            } catch (InterruptedException ex) {
                //connection got cut... terminating keepAliveThread
                break;
            }
        }
    });
    keepAliveThread.setName("JDA MainWS-KeepAlive"
            + (sharding != null ? " Shard [" + sharding[0] + " / " + sharding[1] + "]" : ""));
    keepAliveThread.setPriority(Thread.MAX_PRIORITY);
    keepAliveThread.setDaemon(true);
    keepAliveThread.start();
}

From source file:edu.ucsb.cs.capstone.letmypeoplecode.smartrover.HttpServerTranslator.java

public void startUpdating() {
    if (myRover == null)
        throw new IllegalArgumentException("You need to set a rover controller first");
    if (useSockets) {
        if (UDP) {
            updateThreadUDP.setPriority(Thread.MAX_PRIORITY);
            updateThreadUDP.start();//from  w  w  w.j  a v  a  2s  .com
        } else {
            updateThreadSocket.setPriority(Thread.MAX_PRIORITY);
            updateThreadSocket.start();
        }
    } else {
        updateThread.setPriority(Thread.MAX_PRIORITY);
        updateThread.start();
    }
}

From source file:net.dv8tion.jda.audio.AudioConnection.java

private void setupSendThread() {
    if (sendThread == null && udpSocket != null && sendHandler != null) {
        sendThread = new Thread("AudioConnection SendThread Guild: " + channel.getGuild().getId()) {
            @Override//from   w w w.  ja  v a 2  s  .  c o  m
            public void run() {
                char seq = 0; //Sequence of audio packets. Used to determine the order of the packets.
                int timestamp = 0; //Used to sync up our packets within the same timeframe of other people talking.
                long lastFrameSent = System.currentTimeMillis();
                boolean sentSilenceOnConnect = false;
                while (!udpSocket.isClosed() && !this.isInterrupted()) {
                    try {
                        //WE NEED TO CONSIDER BUFFERING STUFF BECAUSE REASONS.
                        //Consider storing 40-60ms of encoded audio as a buffer.
                        if (sentSilenceOnConnect && sendHandler != null && sendHandler.canProvide()) {
                            silenceCounter = -1;
                            byte[] rawAudio = sendHandler.provide20MsAudio();
                            if (rawAudio == null || rawAudio.length == 0) {
                                if (speaking && (System.currentTimeMillis()
                                        - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT)
                                    setSpeaking(false);
                            } else {
                                if (!sendHandler.isOpus()) {
                                    rawAudio = encodeToOpus(rawAudio);
                                }
                                AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(),
                                        rawAudio);
                                if (!speaking)
                                    setSpeaking(true);
                                udpSocket.send(packet.asEncryptedUdpPacket(webSocket.getAddress(),
                                        webSocket.getSecretKey()));

                                if (seq + 1 > Character.MAX_VALUE)
                                    seq = 0;
                                else
                                    seq++;
                            }
                        } else if (silenceCounter > -1) {
                            AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(),
                                    silenceBytes);
                            udpSocket.send(packet.asEncryptedUdpPacket(webSocket.getAddress(),
                                    webSocket.getSecretKey()));

                            if (seq + 1 > Character.MAX_VALUE)
                                seq = 0;
                            else
                                seq++;

                            if (++silenceCounter > 10) {
                                silenceCounter = -1;
                                sentSilenceOnConnect = true;
                            }
                        } else if (speaking
                                && (System.currentTimeMillis() - lastFrameSent) > OPUS_FRAME_TIME_AMOUNT)
                            setSpeaking(false);
                    } catch (NoRouteToHostException e) {
                        LOG.warn("Closing AudioConnection due to inability to send audio packets.");
                        LOG.warn("Cannot send audio packet because JDA cannot navigate the route to Discord.\n"
                                + "Are you sure you have internet connection? It is likely that you've lost connection.");
                        webSocket.close(true, -1);
                    } catch (SocketException e) {
                        //Most likely the socket has been closed due to the audio connection be closed. Next iteration will kill loop.
                    } catch (Exception e) {
                        LOG.log(e);
                    } finally {
                        timestamp += OPUS_FRAME_SIZE;
                        long sleepTime = (OPUS_FRAME_TIME_AMOUNT)
                                - (System.currentTimeMillis() - lastFrameSent);
                        if (sleepTime > 0) {
                            try {
                                Thread.sleep(sleepTime);
                            } catch (InterruptedException e) {
                                //We've been asked to stop. The next iteration will kill the loop. 
                            }
                        }
                        if (System.currentTimeMillis() < lastFrameSent + 60) // If the sending didn't took longer than 60ms (3 times the time frame)
                        {
                            lastFrameSent += OPUS_FRAME_TIME_AMOUNT; // incrase lastFrameSent
                        } else {
                            lastFrameSent = System.currentTimeMillis(); // else reset lastFrameSent to current time
                        }
                    }
                }
            }
        };
        sendThread.setPriority((Thread.NORM_PRIORITY + Thread.MAX_PRIORITY) / 2);
        sendThread.setDaemon(true);
        sendThread.start();
    }
}

From source file:org.apache.hyracks.control.nc.NodeControllerService.java

@Override
public void start() throws Exception {
    LOGGER.log(Level.INFO, "Starting NodeControllerService");
    ipc.start();//from w w w.j  a v a 2 s  . co  m
    netManager.start();

    startApplication();
    init();

    datasetNetworkManager.start();
    if (messagingNetManager != null) {
        messagingNetManager.start();
    }
    IIPCHandle ccIPCHandle = ipc.getHandle(new InetSocketAddress(ncConfig.ccHost, ncConfig.ccPort),
            ncConfig.retries);
    this.ccs = new ClusterControllerRemoteProxy(ccIPCHandle);
    HeartbeatSchema.GarbageCollectorInfo[] gcInfos = new HeartbeatSchema.GarbageCollectorInfo[gcMXBeans.size()];
    for (int i = 0; i < gcInfos.length; ++i) {
        gcInfos[i] = new HeartbeatSchema.GarbageCollectorInfo(gcMXBeans.get(i).getName());
    }
    HeartbeatSchema hbSchema = new HeartbeatSchema(gcInfos);
    // Use "public" versions of network addresses and ports
    NetworkAddress datasetAddress = datasetNetworkManager.getPublicNetworkAddress();
    NetworkAddress netAddress = netManager.getPublicNetworkAddress();
    NetworkAddress meesagingPort = messagingNetManager != null ? messagingNetManager.getPublicNetworkAddress()
            : null;
    ccs.registerNode(new NodeRegistration(ipc.getSocketAddress(), id, ncConfig, netAddress, datasetAddress,
            osMXBean.getName(), osMXBean.getArch(), osMXBean.getVersion(), osMXBean.getAvailableProcessors(),
            runtimeMXBean.getVmName(), runtimeMXBean.getVmVersion(), runtimeMXBean.getVmVendor(),
            runtimeMXBean.getClassPath(), runtimeMXBean.getLibraryPath(), runtimeMXBean.getBootClassPath(),
            runtimeMXBean.getInputArguments(), runtimeMXBean.getSystemProperties(), hbSchema, meesagingPort,
            PidHelper.getPid()));

    synchronized (this) {
        while (registrationPending) {
            wait();
        }
    }
    if (registrationException != null) {
        throw registrationException;
    }
    appCtx.setDistributedState(nodeParameters.getDistributedState());

    workQueue.start();

    heartbeatTask = new HeartbeatTask(ccs);

    // Use reflection to set the priority of the timer thread.
    Field threadField = timer.getClass().getDeclaredField("thread");
    threadField.setAccessible(true);
    Thread timerThread = (Thread) threadField.get(timer); // The internal timer thread of the Timer object.
    timerThread.setPriority(Thread.MAX_PRIORITY);
    // Schedule heartbeat generator.
    timer.schedule(heartbeatTask, 0, nodeParameters.getHeartbeatPeriod());

    if (nodeParameters.getProfileDumpPeriod() > 0) {
        // Schedule profile dump generator.
        timer.schedule(new ProfileDumpTask(ccs), 0, nodeParameters.getProfileDumpPeriod());
    }

    LOGGER.log(Level.INFO, "Started NodeControllerService");
    if (ncAppEntryPoint != null) {
        ncAppEntryPoint.notifyStartupComplete();
    }
}

From source file:com.android.camera.one.v2.OneCameraZslImpl.java

/**
 * Instantiates a new camera based on Camera 2 API.
 *
 * @param device The underlying Camera 2 device.
 * @param characteristics The device's characteristics.
 * @param pictureSize the size of the final image to be taken.
 *//*from ww  w. j  ava  2  s  .  c  o m*/
OneCameraZslImpl(CameraDevice device, CameraCharacteristics characteristics, Size pictureSize) {
    Log.v(TAG, "Creating new OneCameraZslImpl");

    mDevice = device;
    mCharacteristics = characteristics;
    mLensRange = LensRangeCalculator.getDiopterToRatioCalculator(characteristics);
    mDirection = new CameraDirectionProvider(mCharacteristics);
    mFullSizeAspectRatio = calculateFullSizeAspectRatio(characteristics);

    mCameraThread = new HandlerThread("OneCamera2");
    // If this thread stalls, it will delay viewfinder frames.
    mCameraThread.setPriority(Thread.MAX_PRIORITY);
    mCameraThread.start();
    mCameraHandler = new Handler(mCameraThread.getLooper());

    mCameraListenerThread = new HandlerThread("OneCamera2-Listener");
    mCameraListenerThread.start();
    mCameraListenerHandler = new Handler(mCameraListenerThread.getLooper());

    // TODO: Encoding on multiple cores results in preview jank due to
    // excessive GC.
    int numEncodingCores = CameraUtil.getNumCpuCores();
    mImageSaverThreadPool = new ThreadPoolExecutor(numEncodingCores, numEncodingCores, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    mCaptureManager = new ImageCaptureManager(MAX_CAPTURE_IMAGES, mCameraListenerHandler,
            mImageSaverThreadPool);
    mCaptureManager.setCaptureReadyListener(new ImageCaptureManager.CaptureReadyListener() {
        @Override
        public void onReadyStateChange(boolean capturePossible) {
            mReadyStateManager.setInput(ReadyStateRequirement.CAPTURE_MANAGER_READY, capturePossible);
        }
    });

    // Listen for changes to auto focus state and dispatch to
    // mFocusStateListener.
    mCaptureManager.addMetadataChangeListener(CaptureResult.CONTROL_AF_STATE,
            new ImageCaptureManager.MetadataChangeListener() {
                @Override
                public void onImageMetadataChange(Key<?> key, Object oldValue, Object newValue,
                        CaptureResult result) {
                    FocusStateListener listener = mFocusStateListener;
                    if (listener != null) {
                        listener.onFocusStatusUpdate(AutoFocusHelper.stateFromCamera2State(
                                result.get(CaptureResult.CONTROL_AF_STATE)), result.getFrameNumber());
                    }
                }
            });

    // Allocate the image reader to store all images received from the
    // camera.
    if (pictureSize == null) {
        // TODO The default should be selected by the caller, and
        // pictureSize should never be null.
        pictureSize = getDefaultPictureSize();
    }
    mCaptureImageReader = ImageReader.newInstance(pictureSize.getWidth(), pictureSize.getHeight(),
            sCaptureImageFormat, MAX_CAPTURE_IMAGES);

    mCaptureImageReader.setOnImageAvailableListener(mCaptureManager, mCameraHandler);
    mMediaActionSound.load(MediaActionSound.SHUTTER_CLICK);
}

From source file:org.geowebcache.diskquota.DiskQuotaMonitor.java

private ScheduledExecutorService createCleanUpExecutor() {

    final int numCleaningThreads = quotaConfig.getMaxConcurrentCleanUps();
    log.info("Setting up disk quota periodic enforcement task");
    CustomizableThreadFactory tf = new CustomizableThreadFactory("GWC DiskQuota clean up thread-");
    tf.setThreadPriority(1 + (Thread.MAX_PRIORITY - Thread.MIN_PRIORITY) / 5);

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(numCleaningThreads, tf);

    return executorService;
}

From source file:org.apache.easyant.core.EasyAntMain.java

/**
 * Process command line arguments. When ant is started from Launcher, launcher-only arguments do not get passed
 * through to this routine.//from   www  .j  a v  a  2  s.  com
 *
 * @since Ant 1.6
 */
private void processArgs(CommandLine line) {
    String searchForThis;
    PrintStream logTo = null;

    if (line.hasOption("help")) {
        printUsage();
        return;
    }
    if (easyAntConfiguration.getMsgOutputLevel() >= Project.MSG_VERBOSE || line.hasOption("version")) {
        printVersion();
        if (line.hasOption("version")) {
            return;
        }
    }
    if (line.hasOption("showMemoryDetails")) {
        easyAntConfiguration.setShowMemoryDetails(true);
    }
    if (line.hasOption("diagnostics")) {
        Diagnostics.doReport(System.out, easyAntConfiguration.getMsgOutputLevel());
        return;
    }
    if (line.hasOption("quiet")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_WARN);
    }
    if (line.hasOption("verbose")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_VERBOSE);
    }
    if (line.hasOption("debug")) {
        easyAntConfiguration.setMsgOutputLevel(Project.MSG_DEBUG);
    }
    if (line.hasOption("noinput")) {
        easyAntConfiguration.setAllowInput(false);
    }
    if (line.hasOption("logfile")) {
        try {
            File logFile = new File(line.getOptionValue("logfile"));
            logTo = new PrintStream(new FileOutputStream(logFile));
            isLogFileUsed = true;
        } catch (IOException ioe) {
            String msg = "Cannot write on the specified log file. "
                    + "Make sure the path exists and you have write " + "permissions.";
            throw new BuildException(msg);
        } catch (ArrayIndexOutOfBoundsException aioobe) {
            String msg = "You must specify a log file when " + "using the -log argument";
            throw new BuildException(msg);
        }
    }
    if (line.hasOption("buildmodule")) {
        File buildModule = new File(line.getOptionValue("buildmodule").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildModule(buildModule);
    }
    if (line.hasOption("buildfile")) {
        File buildFile = new File(line.getOptionValue("buildfile").replace('/', File.separatorChar));
        easyAntConfiguration.setBuildFile(buildFile);
    }
    if (line.hasOption("buildconf")) {
        easyAntConfiguration.getActiveBuildConfigurations().add(line.getOptionValue("buildconf"));
    }

    File easyantConfFile = null;

    if (line.hasOption("configfile")) {
        easyantConfFile = new File(line.getOptionValue("configfile").replace('/', File.separatorChar));
    } else {
        // if no command line switch is specified check the default location

        File easyantHome = new File(
                System.getProperty(EasyAntMagicNames.EASYANT_HOME).replace('/', File.separatorChar));
        File defaultGlobalEasyantConfFile = new File(easyantHome,
                EasyAntConstants.DEFAULT_GLOBAL_EASYANT_CONF_FILE);

        if (defaultGlobalEasyantConfFile.exists()) {
            easyantConfFile = defaultGlobalEasyantConfFile;
        }
    }

    if (easyantConfFile != null) {
        try {
            easyAntConfiguration = EasyantConfigurationFactory.getInstance()
                    .createConfigurationFromFile(easyAntConfiguration, easyantConfFile.toURI().toURL());
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }

    if (line.hasOption("listener")) {
        easyAntConfiguration.getListeners().add(line.getOptionValue("listener"));
    }
    if (line.hasOption("D")) {
        easyAntConfiguration.getDefinedProps().putAll(line.getOptionProperties("D"));
    }
    if (line.hasOption("logger")) {
        if (easyAntConfiguration.getLoggerClassname() != null) {
            throw new BuildException("Only one logger class may be specified.");
        }
        easyAntConfiguration.setLoggerClassname(line.getOptionValue("logger"));
    }
    if (line.hasOption("inputhandler")) {
        if (easyAntConfiguration.getInputHandlerClassname() != null) {
            throw new BuildException("Only one input handler class may " + "be specified.");
        }
        easyAntConfiguration.setInputHandlerClassname(line.getOptionValue("inputhandler"));
    }
    if (line.hasOption("emacs")) {
        easyAntConfiguration.setEmacsMode(true);
    }
    if (line.hasOption("projecthelp")) {
        // set the flag to display the targets and quit
        projectHelp = true;
    }
    if (line.hasOption("find")) {
        // eat up next arg if present, default to module.ivy
        if (line.getOptionValues("find").length > 0) {
            searchForThis = line.getOptionValue("find");

        } else {
            searchForThis = EasyAntConstants.DEFAULT_BUILD_MODULE;
        }
        easyAntConfiguration.setBuildModule(new File(searchForThis));
        easyAntConfiguration.setBuildModuleLookupEnabled(true);
    }
    if (line.hasOption("propertyfile")) {
        propertyFiles.add(line.getOptionValue("propertyfile"));
    }
    if (line.hasOption("keep-going")) {
        easyAntConfiguration.setKeepGoingMode(true);
    }
    if (line.hasOption("offline")) {
        easyAntConfiguration.setOffline(true);
    }
    if (line.hasOption("nice")) {
        easyAntConfiguration.setThreadPriority(Integer.decode(line.getOptionValue("nice")));

        if (easyAntConfiguration.getThreadPriority() < Thread.MIN_PRIORITY
                || easyAntConfiguration.getThreadPriority() > Thread.MAX_PRIORITY) {
            throw new BuildException("Niceness value is out of the range 1-10");
        }
    }
    if (line.hasOption("autoproxy")) {
        easyAntConfiguration.setProxy(true);
    }
    if (!line.getArgList().isEmpty()) {
        for (Object o : line.getArgList()) {
            String target = (String) o;
            easyAntConfiguration.getTargets().add(target);
        }
    }

    // Load the property files specified by -propertyfile
    loadPropertyFiles();

    if (logTo != null) {
        easyAntConfiguration.setOut(logTo);
        easyAntConfiguration.setErr(logTo);
        System.setOut(easyAntConfiguration.getOut());
        System.setErr(easyAntConfiguration.getErr());
    }
    readyToRun = true;
}