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.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void startNotifications() throws Exception {

    if (uri == null)
        throw new NullPointerException("Please set the URI before starting notifications!");
    this.cbean = new ConsumerBean();
    cbean.setStatus(ConsumerStatus.STARTING);
    cbean.setName(getName());//w  w w.  j ava2  s  .c o m
    cbean.setConsumerId(consumerId);
    cbean.setVersion(consumerVersion);
    cbean.setStartTime(System.currentTimeMillis());
    try {
        cbean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }

    System.out.println("Running events on topic " + Constants.ALIVE_TOPIC + " to notify of '" + getName()
            + "' service being available.");

    final Thread aliveThread = new Thread(new Runnable() {
        public void run() {

            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                aliveConnection = connectionFactory.createConnection();
                aliveConnection.start();

                final Session session = aliveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageProducer producer = session.createProducer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                // Here we are sending the message out to the topic
                while (isActive()) {
                    try {
                        Thread.sleep(Constants.NOTIFICATION_FREQUENCY);

                        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(cbean));
                        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

                        if (ConsumerStatus.STARTING.equals(cbean.getStatus())) {
                            cbean.setStatus(ConsumerStatus.RUNNING);
                        }

                    } catch (InterruptedException ne) {
                        break;
                    } catch (Exception neOther) {
                        neOther.printStackTrace();
                    }
                }
            } catch (Exception ne) {
                ne.printStackTrace();
                setActive(false);
            }
        }
    });
    aliveThread.setName("Alive Notification Topic");
    aliveThread.setDaemon(true);
    aliveThread.setPriority(Thread.MIN_PRIORITY);
    aliveThread.start();
}

From source file:RhodesService.java

public static void installApplication(final String url) {
    Thread bgThread = new Thread(new Runnable() {
        public void run() {
            try {
                final RhodesService r = RhodesService.getInstance();
                final File tmpFile = r.downloadPackage(url);
                if (tmpFile != null) {
                    PerformOnUiThread.exec(new Runnable() {
                        public void run() {
                            try {
                                Logger.D(TAG, "Install package " + tmpFile.getAbsolutePath());
                                Uri uri = Uri.fromFile(tmpFile);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                                r.startActivity(intent);
                            } catch (Exception e) {
                                Log.e(TAG, "Can't install file from " + tmpFile.getAbsolutePath(), e);
                                Logger.E(TAG, "Can't install file from " + tmpFile.getAbsolutePath() + ": "
                                        + e.getMessage());
                            }/* w  ww.  j  a va 2s . c o  m*/
                        }
                    });
                }
            } catch (IOException e) {
                Log.e(TAG, "Can't download package from " + url, e);
                Logger.E(TAG, "Can't download package from " + url + ": " + e.getMessage());
            }
        }
    });
    bgThread.setPriority(Thread.MIN_PRIORITY);
    bgThread.start();
}

From source file:weka.server.WekaServer.java

/**
 * Starts the Jetty server// ww w  .  ja v  a  2s.  c  om
 * 
 * @throws Exception if a problem occurs
 */
protected void startJettyServer() throws Exception {
    // load any persisted scheduled tasks
    loadTasks();

    if (m_jettyServer != null) {
        throw new Exception("Server is already running. Stop it first.");
    }

    if (m_hostname == null) {
        throw new Exception("No hostname has been specified!!");
    }

    weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started");

    m_jettyServer = new Server();

    String wekaServerPasswordPath = WekaPackageManager.WEKA_HOME.toString() + File.separator + "server"
            + File.separator + "weka.pwd";
    File wekaServerPasswordFile = new File(wekaServerPasswordPath);
    boolean useAuth = wekaServerPasswordFile.exists();

    SecurityHandler securityHandler = null;
    if (useAuth) {
        System.out.println("[WekaServer] installing security handler");
        Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);
        constraint.setRoles(new String[] { Constraint.ANY_ROLE });
        constraint.setAuthenticate(true);

        ConstraintMapping constraintMapping = new ConstraintMapping();
        constraintMapping.setConstraint(constraint);
        constraintMapping.setPathSpec("/*");

        securityHandler = new SecurityHandler();
        securityHandler.setUserRealm(new HashUserRealm("WekaServer", wekaServerPasswordFile.toString()));
        securityHandler.setConstraintMappings(new ConstraintMapping[] { constraintMapping });

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(wekaServerPasswordFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                // not a comment character, then assume its the data
                if (!line.startsWith("#")) {
                    String[] parts = line.split(":");
                    if (parts.length > 3 || parts.length < 2) {
                        continue;
                    }
                    m_username = parts[0].trim();
                    m_password = parts[1].trim();
                    if (parts.length == 3 && parts[1].trim().startsWith("OBF")) {
                        m_password = m_password + ":" + parts[2];
                        String deObbs = Password.deobfuscate(m_password);
                        m_password = deObbs;
                    }
                    break;
                }
            }
        } catch (Exception ex) {
            System.err.println("[WekaServer} Error reading password file: " + ex.getMessage());
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

    // Servlets
    ContextHandlerCollection contexts = new ContextHandlerCollection();

    // Root context
    Context root = new Context(contexts, RootServlet.CONTEXT_PATH, Context.SESSIONS);
    RootServlet rootServlet = new RootServlet(m_taskMap, this);
    root.addServlet(new ServletHolder(rootServlet), "/*");

    // Execute task
    Context executeTask = new Context(contexts, ExecuteTaskServlet.CONTEXT_PATH, Context.SESSIONS);
    executeTask.addServlet(new ServletHolder(new ExecuteTaskServlet(m_taskMap, this)), "/*");

    // Task status
    Context taskStatus = new Context(contexts, GetTaskStatusServlet.CONTEXT_PATH, Context.SESSIONS);
    taskStatus.addServlet(new ServletHolder(new GetTaskStatusServlet(m_taskMap, this)), "/*");

    // Purge task
    Context purgeTask = new Context(contexts, PurgeTaskServlet.CONTEXT_PATH, Context.SESSIONS);
    purgeTask.addServlet(new ServletHolder(new PurgeTaskServlet(m_taskMap, this)), "/*");

    // Add slave
    Context addSlave = new Context(contexts, AddSlaveServlet.CONTEXT_PATH, Context.SESSIONS);
    addSlave.addServlet(new ServletHolder(new AddSlaveServlet(m_taskMap, this)), "/*");

    // Server load factor
    Context loadFactor = new Context(contexts, GetServerLoadServlet.CONTEXT_PATH, Context.SESSIONS);
    loadFactor.addServlet(new ServletHolder(new GetServerLoadServlet(m_taskMap, this)), "/*");

    // Set task status (from slave)
    Context setTaskStatus = new Context(contexts, SetTaskStatusServlet.CONTEXT_PATH, Context.SESSIONS);
    setTaskStatus.addServlet(new ServletHolder(new SetTaskStatusServlet(m_taskMap, this)), "/*");

    // Set last executon for task (from slave)
    Context setLastExecution = new Context(contexts, SetLastExecutionServlet.CONTEXT_PATH, Context.SESSIONS);
    setLastExecution.addServlet(new ServletHolder(new SetLastExecutionServlet(m_taskMap, this)), "/*");

    // Get task list servlet
    Context getTaskList = new Context(contexts, GetTaskListServlet.CONTEXT_PATH, Context.SESSIONS);
    getTaskList.addServlet(new ServletHolder(new GetTaskListServlet(m_taskMap, this)), "/*");

    // Get task result servlet
    Context getTaskResult = new Context(contexts, GetTaskResultServlet.CONTEXT_PATH, Context.SESSIONS);
    getTaskResult.addServlet(new ServletHolder(new GetTaskResultServlet(m_taskMap, this)), "/*");

    // Get schedule servlet
    Context getSchedule = new Context(contexts, GetScheduleServlet.CONTEXT_PATH, Context.SESSIONS);
    getSchedule.addServlet(new ServletHolder(new GetScheduleServlet(m_taskMap, this)), "/*");

    m_jettyServer.setHandlers((securityHandler != null) ? new Handler[] { securityHandler, contexts }
            : new Handler[] { contexts });

    // start execution

    SocketConnector connector = new SocketConnector();
    connector.setPort(m_port);
    connector.setHost(m_hostname);
    connector.setName("WekaServer@" + m_hostname);

    m_jettyServer.setConnectors(new Connector[] { connector });

    m_jettyServer.start();
    startExecutorPool();

    // start a purge thread that purges stale tasks
    Thread purgeThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                purgeTasks(m_staleTime);
                try {
                    Thread.sleep(m_staleTime);
                } catch (InterruptedException ie) {
                }
            }
        }
    };

    if (m_staleTime > 0) {
        System.out.println("[WekaServer] Starting purge thread.");
        purgeThread.setPriority(Thread.MIN_PRIORITY);
        purgeThread.setDaemon(m_daemon);
        purgeThread.start();
    } else {
        System.out.println("[WekaServer] Purge thread disabled.");
    }

    // start a thread for executing scheduled tasks
    Thread scheduleChecker = new Thread() {
        GregorianCalendar m_cal = new GregorianCalendar();

        @Override
        public void run() {
            while (true) {
                List<WekaTaskEntry> tasks = m_taskMap.getTaskList();
                for (WekaTaskEntry t : tasks) {
                    NamedTask task = m_taskMap.getTask(t);
                    if (task instanceof Scheduled
                            && task.getTaskStatus().getExecutionStatus() != TaskStatusInfo.PROCESSING) {
                        // Date lastExecution = m_taskMap.getExecutionTime(t);
                        Date lastExecution = t.getLastExecution();
                        Schedule schedule = ((Scheduled) task).getSchedule();
                        boolean runIt = false;
                        try {
                            runIt = schedule.execute(lastExecution);
                        } catch (Exception ex) {
                            System.err.println("[WekaServer] There is a problem with scheduled task "
                                    + t.toString() + "\n\n" + ex.getMessage());
                        }
                        if (runIt) {
                            System.out.println("[WekaServer] Starting scheduled task " + t.toString());
                            executeTask(t);
                        }
                    }
                }

                try {
                    // check every 60 seconds
                    // wait enough seconds to be on the minute
                    Date now = new Date();
                    m_cal.setTime(now);
                    int seconds = (60 - m_cal.get(Calendar.SECOND));
                    Thread.sleep(seconds * 1000);
                } catch (InterruptedException ie) {
                }
            }
        }
    };

    System.out.println("[WekaServer] Starting schedule checker.");
    scheduleChecker.setPriority(Thread.MIN_PRIORITY);
    scheduleChecker.setDaemon(m_daemon);
    scheduleChecker.start();

    // Register with a master server?
    if (m_master != null && m_master.length() > 0 && m_master.lastIndexOf(":") > 0) {
        registerWithMaster();
    }

    if (!m_daemon) {
        m_jettyServer.join();
    }
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * private constructor/*from www.j a v  a  2s.c o m*/
 *
 * @param repConfig
 */
protected RepositoryImpl(RepositoryConfig repConfig) throws RepositoryException {

    log.info("Starting repository...");

    boolean succeeded = false;
    try {
        this.repConfig = repConfig;

        // Acquire a lock on the repository home
        repLock = new RepositoryLock(repConfig.getHomeDir());
        repLock.acquire();

        // setup file systems
        repStore = repConfig.getFileSystemConfig().createFileSystem();
        String fsRootPath = "/meta";
        try {
            if (!repStore.exists(fsRootPath) || !repStore.isFolder(fsRootPath)) {
                repStore.createFolder(fsRootPath);
            }
        } catch (FileSystemException fse) {
            String msg = "failed to create folder for repository meta data";
            log.error(msg, fse);
            throw new RepositoryException(msg, fse);
        }
        metaDataStore = new BasedFileSystem(repStore, fsRootPath);

        // init root node uuid
        rootNodeId = loadRootNodeId(metaDataStore);

        // load repository properties
        repProps = loadRepProps();
        nodesCount = Long.parseLong(repProps.getProperty(STATS_NODE_COUNT_PROPERTY, "0"));
        propsCount = Long.parseLong(repProps.getProperty(STATS_PROP_COUNT_PROPERTY, "0"));

        // create registries
        nsReg = createNamespaceRegistry(new BasedFileSystem(repStore, "/namespaces"));
        ntReg = createNodeTypeRegistry(nsReg, new BasedFileSystem(repStore, "/nodetypes"));

        if (repConfig.getDataStoreConfig() != null) {
            assert InternalValue.USE_DATA_STORE;
            dataStore = createDataStore();
        } else {
            dataStore = null;
        }

        // init workspace configs
        Iterator iter = repConfig.getWorkspaceConfigs().iterator();
        while (iter.hasNext()) {
            WorkspaceConfig config = (WorkspaceConfig) iter.next();
            WorkspaceInfo info = createWorkspaceInfo(config);
            wspInfos.put(config.getName(), info);
        }

        // initialize optional clustering
        // put here before setting up any other external event source that a cluster node
        // will be interested in
        if (repConfig.getClusterConfig() != null) {
            clusterNode = createClusterNode();
            nsReg.setEventChannel(clusterNode);
            ntReg.setEventChannel(clusterNode);
        }

        // init version manager
        vMgr = createVersionManager(repConfig.getVersioningConfig(), delegatingDispatcher);
        if (clusterNode != null) {
            vMgr.setEventChannel(clusterNode.createUpdateChannel(null));
        }

        // init virtual node type manager
        virtNTMgr = new VirtualNodeTypeStateManager(getNodeTypeRegistry(), delegatingDispatcher,
                NODETYPES_NODE_ID, SYSTEM_ROOT_NODE_ID);

        // initialize startup workspaces
        initStartupWorkspaces();

        // initialize system search manager
        getSystemSearchManager(repConfig.getDefaultWorkspaceName());

        // after the workspace is initialized we pass a system session to
        // the virtual node type manager

        // todo FIXME the *global* virtual node type manager is using a session that is bound to a single specific workspace...
        virtNTMgr.setSession(getSystemSession(repConfig.getDefaultWorkspaceName()));

        // now start cluster node as last step
        if (clusterNode != null) {
            try {
                clusterNode.start();
            } catch (ClusterException e) {
                String msg = "Unable to start clustered node, forcing shutdown...";
                log.error(msg, e);
                shutdown();
                throw new RepositoryException(msg, e);
            }
        }

        // amount of time in seconds before an idle workspace is automatically
        // shut down
        int maxIdleTime = repConfig.getWorkspaceMaxIdleTime();
        if (maxIdleTime != 0) {
            // start workspace janitor thread
            Thread wspJanitor = new Thread(new WorkspaceJanitor(maxIdleTime * 1000));
            wspJanitor.setName("WorkspaceJanitor");
            wspJanitor.setPriority(Thread.MIN_PRIORITY);
            wspJanitor.setDaemon(true);
            wspJanitor.start();
        }

        succeeded = true;
        log.info("Repository started");
    } catch (RepositoryException e) {
        log.error("failed to start Repository: " + e.getMessage(), e);
        throw e;
    } finally {
        if (!succeeded) {
            // repository startup failed, clean up...
            shutdown();
        }
    }
}

From source file:com.mibr.android.intelligentreminder.INeedToo.java

/** Called when the activity is first created. */
@Override//  w ww  .  j a v  a  2s.c om
public void onCreate(Bundle savedInstanceState) {
    /* this was just a test      if(mLocationManager==null) {
             mLocationManager=(android.location.LocationManager) getSystemService(Context.LOCATION_SERVICE);
          }
    */
    //      TabHost host=this.getTabHost();
    //      host.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
    //         
    //         @Override
    //         public void onTabChanged(String tabId) {
    //            if(INeedToo.this._doingCreatingTabs==false) {
    //               if(tabId.equals("tab1")) {
    //                  INeedToo.this._forceNonCompany=true;
    //               }
    //            }
    //         }
    //      });
    super.onCreate(savedInstanceState);
    mLocationClient = new LocationClient(this, this, this);
    mLocationClient.connect();
    try {
        if (getIntent().getAction() != null && getIntent().getAction().equals("doPrimitiveDeletedNeed")) {
            transmitNetwork(getIntent().getStringExtra("phoneid"));
            return;
        }
    } catch (Exception eieio) {
        return;
    }
    try {
        /*
                    putExtra("needId",needId).
          putExtra("foreignNeedId",foreignNeedId).
          putExtra("phoneid",phoneid).
          putExtra("foreignLocationId",foreignLocationId)
                
         */
        if (getIntent().getAction() != null
                && getIntent().getAction().equals("transmitNetworkDeletedThisNeedByOnBehalfOf")) {
            long needId = getIntent().getLongExtra("needId", -11);
            long foreignNeedId = getIntent().getLongExtra("foreignNeedId", -11);
            String phoneId = getIntent().getStringExtra("phoneid");
            long foreignLocationId = getIntent().getLongExtra("foreignLocationId", -11);
            if (needId != -11 && foreignNeedId != -11 && foreignLocationId != -11 && isNothingNot(phoneId))
                transmitNetworkDeletedThisNeedByOnBehalfOf(needId, foreignNeedId, phoneId, foreignLocationId);
            return;
        }
    } catch (Exception ei3) {
        return;
    }

    /*bbhbb 2011-03-26*/ /*bbhbb2013_05_01 isn't this being done below?
                         *    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler("")); */

    mHandler = new Handler();

    doBindService();
    mSingleton = this;
    ///////////mSingleton.log("onCreating_INeedToo", 1);

    if (getPackageName().toLowerCase().indexOf("trial") != -1 && !isSpecialPhone()) {
        if (!iveCheckedAuthorizationStatusForThisPhone) {
            doViewCount = true;
            iveCheckedAuthorizationStatusForThisPhone = true;
            final Timer jdTimer = new Timer("Registering");
            jdTimer.schedule(new TimerTask() {
                public void run() {
                    Thread thread = new Thread(new Runnable() {
                        public void run() {
                            Intent intent = new Intent(INeedToo.this, INeedWebService.class)
                                    .setAction("CheckStatus");
                            startService(intent);
                            jdTimer.cancel();
                        }
                    });
                    thread.setPriority(Thread.MIN_PRIORITY);
                    thread.run();
                }
            }, 3000, 1000 * 60 * 10);

        }
    } else {
        if (IS_ANDROID_VERSION) {
            if (!isSpecialPhone()
                    || INeedToo.mSingleton.getPhoneId().toLowerCase().equals("20013fc135cd6097xx")) {

                final Timer jdTimer = new Timer("Licensing");
                jdTimer.schedule(new TimerTask() {
                    public void run() {
                        Thread thread = new Thread(new Runnable() {
                            public void run() {
                                // Construct the LicenseCheckerCallback. The library calls this when done.        
                                mLicenseCheckerCallback = new MyLicenseCheckerCallback();
                                // Construct the LicenseChecker with a Policy.        
                                mChecker = new LicenseChecker(INeedToo.this,
                                        new ServerManagedPolicy(INeedToo.this,
                                                new AESObfuscator(SALT, getPackageName(),
                                                        //                           "com.mibr.android.intelligentreminder",
                                                        getDeviceId())),
                                        BASE64_PUBLIC_KEY // Your public licensing key.
                                );
                                mChecker.checkAccess(mLicenseCheckerCallback);
                            }
                        });
                        thread.setPriority(Thread.MIN_PRIORITY);
                        thread.run();
                    }
                }, 3000, 1000 * 60 * 10);
            }
        }
    }

    try {
        _logFilter = Integer
                .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                        .getString("LoggingLevel", "3"));
    } catch (Exception e) {
    }

    if (!INeedLocationService.USING_LOCATION_SERVICES) {

        int logFilter = 3;
        try {
            logFilter = Integer
                    .valueOf(getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                            .getString("LoggingLevel", "3"));
        } catch (Exception e) {
        }
        Intent jdIntent = new Intent(this, INeedTimerServices.class).putExtra("logFilter", logFilter);

        getApplicationContext().startService(jdIntent);
    }
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(""));
    if (INeedToo.mSingleton.getPhoneId().toLowerCase().equals("22a100000d9f25c5")) {
        DELAYPOSTTTS = 100;
    }

    // I don't need this because IHaveNeeds.onresume does it      getApplicationContext().startService(new Intent(this, INeedLocationService.class));
    if (!_doneSplashy) {
        _doneSplashy = true;
        if (!getVersionFile()) {
            stampVersion();
            showDialog(DIALOG_SPLASH);
        } else {
            //showDialog(DIALOG_SPLASH);
        }
    }
    if (allItems != null) {
        whereImAtInAllItems++;
        if (whereImAtInAllItems < allItems.size()) {
            showDialog(DOING_SAMPLE_NEEDS_DIALOG);
        } else {
            allItems = null;
        }
    }

    setTitle(getHeading());
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        _initialTabIndex = bundle.getInt("initialtabindex", 0);
        _didContact = bundle.getBoolean("iscontact", false);
        if (_initialTabIndex == 1) {
            _doingLocationCompany = bundle.getString("doingcompany");
        } else {
            _doingLocationCompany = null;
        }
    } else {
        _doingLocationCompany = null;
    }
    final TabHost tabHost = getTabHost();
    tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Need",

            getResources().getDrawable(R.drawable.status_bar2_blackwhite))
            .setContent(new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact)));

    tabHost.addTab(tabHost.newTabSpec("tab2")
            .setIndicator("Location",
                    (BitmapDrawable) getResources().getDrawable(android.R.drawable.ic_menu_mapmode))
            .setContent(
                    new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany)));
    Intent intent = new Intent(this, NeedMap.class).putExtra("doingcompany", _doingLocationCompany);
    tabHost.addTab(tabHost.newTabSpec("tab2a")
            .setIndicator("Map", (BitmapDrawable) getResources().getDrawable(R.drawable.ic_dialog_map))
            .setContent(intent));
    /*
    tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(
    "History",(BitmapDrawable) getResources().getDrawable(
          R.drawable.chart)).setContent(
                new Intent(this, IHaveHistory.class)));
    */
    tabHost.addTab(tabHost.newTabSpec("tab4")
            .setIndicator("System",
                    (BitmapDrawable) getResources().getDrawable(R.drawable.status_bar1_blackwhite))
            .setContent(new Intent(this, ListPlus.class)));
    /*      tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(
    "Need",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.status_bar2_blackwhite), 36f)).setContent(
                new Intent(this, IHaveNeeds.class).putExtra("iscontact", this._didContact)));
            
    tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator(
       "Location",
       scaleTo((BitmapDrawable) getResources().getDrawable(
             android.R.drawable.ic_menu_mapmode), 36f)).setContent(
                   new Intent(this, IHaveLocations.class).putExtra("doingcompany", _doingLocationCompany)));
    tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator(
    "History",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.chart), 36f)).setContent(
                new Intent(this, IHaveHistory.class)));
    tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator(
    "System",
    scaleTo((BitmapDrawable) getResources().getDrawable(
          R.drawable.status_bar1_blackwhite), 31f)).setContent(
                new Intent(this, ListPlus.class)));
    */
    tabHost.setCurrentTab(_initialTabIndex);
    boolean networkingOutbound = getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
            .getBoolean("Networking_Outbound_Enabled", false);
    if (INeedWebService.mSingleton == null) {

        if (networkingOutbound) {
            enableTransmitting();
        }
        if (getSharedPreferences(INeedToo.PREFERENCES_LOCATION, Preferences.MODE_PRIVATE)
                .getBoolean("Networking_Inbound_Enabled", false)) {
            enableReceiving();
        }
    }
}

From source file:com.klinker.android.twitter.activities.profile_viewer.ProfilePager.java

public void getUser() {
    Thread getUser = new Thread(new Runnable() {
        @Override/*  w ww .j  a v a  2s .  com*/
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                thisUser = twitter.showUser(screenName);
            } catch (Exception e) {
                thisUser = null;
            }

            if (thisUser != null) {
                try {
                    FollowersDataSource.getInstance(context).createUser(thisUser,
                            sharedPrefs.getInt("current_account", 1));

                } catch (Exception e) {
                    // the user already exists. don't know if this is more efficient than querying the db or not.
                }

                final SearchRecentSuggestions suggestions = new SearchRecentSuggestions(context,
                        MySuggestionsProvider.AUTHORITY, MySuggestionsProvider.MODE);
                suggestions.saveRecentQuery("@" + thisUser.getScreenName(), null);
            }

            new GetActionBarInfo().execute();
        }
    });

    getUser.setPriority(Thread.MAX_PRIORITY);
    getUser.start();
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * private constructor// w  w w.  j  ava2 s.c o  m
 *
 * @param repConfig
 */
protected RepositoryImpl(RepositoryConfig repConfig) throws RepositoryException {

    log.info("Starting repository...");

    boolean succeeded = false;
    try {
        this.repConfig = repConfig;

        // Acquire a lock on the repository home
        repLock = new RepositoryLock(repConfig.getHomeDir());
        repLock.acquire();

        // setup file systems
        repStore = repConfig.getFileSystem();
        String fsRootPath = "/meta";
        try {
            if (!repStore.exists(fsRootPath) || !repStore.isFolder(fsRootPath)) {
                repStore.createFolder(fsRootPath);
            }
        } catch (FileSystemException fse) {
            String msg = "failed to create folder for repository meta data";
            log.error(msg, fse);
            throw new RepositoryException(msg, fse);
        }
        metaDataStore = new BasedFileSystem(repStore, fsRootPath);

        // init root node uuid
        rootNodeId = loadRootNodeId(metaDataStore);

        // load repository properties
        repProps = loadRepProps();
        nodesCount = Long.parseLong(repProps.getProperty(STATS_NODE_COUNT_PROPERTY, "0"));
        propsCount = Long.parseLong(repProps.getProperty(STATS_PROP_COUNT_PROPERTY, "0"));

        // create registries
        nsReg = createNamespaceRegistry(new BasedFileSystem(repStore, "/namespaces"));
        ntReg = createNodeTypeRegistry(nsReg, new BasedFileSystem(repStore, "/nodetypes"));

        dataStore = repConfig.getDataStore();
        if (dataStore != null) {
            assert InternalValue.USE_DATA_STORE;
        }

        // init workspace configs
        Iterator iter = repConfig.getWorkspaceConfigs().iterator();
        while (iter.hasNext()) {
            WorkspaceConfig config = (WorkspaceConfig) iter.next();
            WorkspaceInfo info = createWorkspaceInfo(config);
            wspInfos.put(config.getName(), info);
        }

        // initialize optional clustering
        // put here before setting up any other external event source that a cluster node
        // will be interested in
        if (repConfig.getClusterConfig() != null) {
            clusterNode = createClusterNode();
            nsReg.setEventChannel(clusterNode);
            ntReg.setEventChannel(clusterNode);

            createWorkspaceEventChannel = clusterNode;
            clusterNode.setListener(this);
        }

        // init version manager
        vMgr = createVersionManager(repConfig.getVersioningConfig(), delegatingDispatcher);
        if (clusterNode != null) {
            vMgr.setEventChannel(clusterNode.createUpdateChannel(null));
        }

        // init virtual node type manager
        virtNTMgr = new VirtualNodeTypeStateManager(getNodeTypeRegistry(), delegatingDispatcher,
                NODETYPES_NODE_ID, SYSTEM_ROOT_NODE_ID);

        // initialize startup workspaces
        initStartupWorkspaces();

        // initialize system search manager
        getSystemSearchManager(repConfig.getDefaultWorkspaceName());

        // after the workspace is initialized we pass a system session to
        // the virtual node type manager

        // todo FIXME the *global* virtual node type manager is using a session that is bound to a single specific workspace...
        virtNTMgr.setSession(getSystemSession(repConfig.getDefaultWorkspaceName()));

        // now start cluster node as last step
        if (clusterNode != null) {
            try {
                clusterNode.start();
            } catch (ClusterException e) {
                String msg = "Unable to start clustered node, forcing shutdown...";
                log.error(msg, e);
                shutdown();
                throw new RepositoryException(msg, e);
            }
        }

        // amount of time in seconds before an idle workspace is automatically
        // shut down
        int maxIdleTime = repConfig.getWorkspaceMaxIdleTime();
        if (maxIdleTime != 0) {
            // start workspace janitor thread
            Thread wspJanitor = new Thread(new WorkspaceJanitor(maxIdleTime * 1000));
            wspJanitor.setName("WorkspaceJanitor");
            wspJanitor.setPriority(Thread.MIN_PRIORITY);
            wspJanitor.setDaemon(true);
            wspJanitor.start();
        }

        succeeded = true;
        log.info("Repository started");
    } catch (RepositoryException e) {
        log.error("failed to start Repository: " + e.getMessage(), e);
        throw e;
    } finally {
        if (!succeeded) {
            // repository startup failed, clean up...
            shutdown();
        }
    }
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * Protected constructor.// ww w  .  j ava  2 s.  co  m
 *
 * @param repConfig the repository configuration.
 * @throws RepositoryException if there is already another repository
 *                             instance running on the given configuration
 *                             or another error occurs.
 */
protected RepositoryImpl(RepositoryConfig repConfig) throws RepositoryException {
    // Acquire a lock on the repository home
    repLock = repConfig.getRepositoryLockMechanism();
    repLock.init(repConfig.getHomeDir());
    repLock.acquire();

    long t0 = System.currentTimeMillis();
    log.info("Starting repository...");

    boolean succeeded = false;
    try {
        this.repConfig = repConfig;

        context.setFileSystem(repConfig.getFileSystem());

        // Load root node identifier
        context.setRootNodeId(loadRootNodeId());

        // initialize repository descriptors
        initRepositoryDescriptors();

        // create registries
        context.setNamespaceRegistry(createNamespaceRegistry());
        context.setNodeTypeRegistry(createNodeTypeRegistry());
        context.setPrivilegeRegistry(
                new PrivilegeRegistry(context.getNamespaceRegistry(), context.getFileSystem()));

        // Create item state cache manager
        context.setItemStateCacheFactory(new ManagedMLRUItemStateCacheFactory(cacheMgr));

        DataStore dataStore = repConfig.getDataStore();
        if (dataStore != null) {
            context.setDataStore(dataStore);
        }

        nodeIdFactory = new NodeIdFactory(repConfig.getHomeDir());
        nodeIdFactory.open();
        context.setNodeIdFactory(nodeIdFactory);

        context.setWorkspaceManager(new WorkspaceManager(this));

        // init workspace configs
        for (WorkspaceConfig config : repConfig.getWorkspaceConfigs()) {
            WorkspaceInfo info = createWorkspaceInfo(config);
            wspInfos.put(config.getName(), info);
        }

        // initialize optional clustering before setting up any other
        // external event source that a cluster node will be interested in
        ClusterNode clusterNode = null;
        if (repConfig.getClusterConfig() != null) {
            clusterNode = createClusterNode();
            context.setClusterNode(clusterNode);
            context.getNamespaceRegistry().setEventChannel(clusterNode);
            context.getNodeTypeRegistry().setEventChannel(clusterNode);
            context.getPrivilegeRegistry().setEventChannel(clusterNode);

            createWorkspaceEventChannel = clusterNode;
            clusterNode.setListener(this);
        }

        // init version manager
        InternalVersionManagerImpl vMgr = createVersionManager(repConfig.getVersioningConfig(),
                delegatingDispatcher);
        context.setInternalVersionManager(vMgr);
        if (clusterNode != null) {
            vMgr.setEventChannel(clusterNode.createUpdateChannel(null));
        }

        // init virtual node type manager
        virtNTMgr = new VirtualNodeTypeStateManager(context.getNodeTypeRegistry(), delegatingDispatcher,
                NODETYPES_NODE_ID, SYSTEM_ROOT_NODE_ID);

        // initialize startup workspaces
        initStartupWorkspaces();

        // initialize system search manager
        getSystemSearchManager(repConfig.getDefaultWorkspaceName());

        // Initialise the security manager;
        initSecurityManager();

        // after the workspace is initialized we pass a system session to
        // the virtual node type manager

        // todo FIXME the *global* virtual node type manager is using a session that is bound to a single specific workspace...
        virtNTMgr.setSession(getSystemSession(repConfig.getDefaultWorkspaceName()));

        // now start cluster node as last step
        if (clusterNode != null) {
            setDescriptor(JACKRABBIT_CLUSTER_ID, repConfig.getClusterConfig().getId());
            try {
                clusterNode.start();
            } catch (ClusterException e) {
                String msg = "Unable to start clustered node, forcing shutdown...";
                log.error(msg, e);
                shutdown();
                throw new RepositoryException(msg, e);
            }
        }

        // amount of time in seconds before an idle workspace is automatically
        // shut down
        int maxIdleTime = repConfig.getWorkspaceMaxIdleTime();
        if (maxIdleTime != 0) {
            // start workspace janitor thread
            Thread wspJanitor = new Thread(new WorkspaceJanitor(maxIdleTime * 1000));
            wspJanitor.setName("WorkspaceJanitor");
            wspJanitor.setPriority(Thread.MIN_PRIORITY);
            wspJanitor.setDaemon(true);
            wspJanitor.start();
        }

        succeeded = true;
        log.info("Repository started (" + (System.currentTimeMillis() - t0) + "ms)");
    } catch (RepositoryException e) {
        log.error("failed to start Repository: " + e.getMessage(), e);
        throw e;
    } finally {
        if (!succeeded) {
            try {
                // repository startup failed, clean up...
                shutdown();
            } catch (Throwable t) {
                // ensure this exception does not overlay the original
                // startup exception and only log it
                log.error("In addition to startup fail, another unexpected problem "
                        + "occurred while shutting down the repository again.", t);
                // Clear the repository lock if it was left in place
                repLock.release();
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.client.TestAdmin1.java

void splitTest(byte[] splitPoint, byte[][] familyNames, int[] rowCounts, int numVersions, int blockSize)
        throws Exception {
    TableName tableName = TableName.valueOf("testForceSplit");
    StringBuilder sb = new StringBuilder();
    // Add tail to String so can see better in logs where a test is running.
    for (int i = 0; i < rowCounts.length; i++) {
        sb.append("_").append(Integer.toString(rowCounts[i]));
    }/* www  . j av  a 2 s . co m*/
    assertFalse(admin.tableExists(tableName));
    try (final Table table = TEST_UTIL.createTable(tableName, familyNames, numVersions, blockSize);
            final RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName)) {

        int rowCount = 0;
        byte[] q = new byte[0];

        // insert rows into column families. The number of rows that have values
        // in a specific column family is decided by rowCounts[familyIndex]
        for (int index = 0; index < familyNames.length; index++) {
            ArrayList<Put> puts = new ArrayList<Put>(rowCounts[index]);
            for (int i = 0; i < rowCounts[index]; i++) {
                byte[] k = Bytes.toBytes(i);
                Put put = new Put(k);
                put.addColumn(familyNames[index], q, k);
                puts.add(put);
            }
            table.put(puts);

            if (rowCount < rowCounts[index]) {
                rowCount = rowCounts[index];
            }
        }

        // get the initial layout (should just be one region)
        List<HRegionLocation> m = locator.getAllRegionLocations();
        LOG.info("Initial regions (" + m.size() + "): " + m);
        assertTrue(m.size() == 1);

        // Verify row count
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        int rows = 0;
        for (@SuppressWarnings("unused")
        Result result : scanner) {
            rows++;
        }
        scanner.close();
        assertEquals(rowCount, rows);

        // Have an outstanding scan going on to make sure we can scan over splits.
        scan = new Scan();
        scanner = table.getScanner(scan);
        // Scan first row so we are into first region before split happens.
        scanner.next();

        // Split the table
        this.admin.split(tableName, splitPoint);

        final AtomicInteger count = new AtomicInteger(0);
        Thread t = new Thread("CheckForSplit") {
            @Override
            public void run() {
                for (int i = 0; i < 45; i++) {
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        continue;
                    }
                    // check again
                    List<HRegionLocation> regions = null;
                    try {
                        regions = locator.getAllRegionLocations();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (regions == null)
                        continue;
                    count.set(regions.size());
                    if (count.get() >= 2) {
                        LOG.info("Found: " + regions);
                        break;
                    }
                    LOG.debug("Cycle waiting on split");
                }
                LOG.debug("CheckForSplit thread exited, current region count: " + count.get());
            }
        };
        t.setPriority(Thread.NORM_PRIORITY - 2);
        t.start();
        t.join();

        // Verify row count
        rows = 1; // We counted one row above.
        for (@SuppressWarnings("unused")
        Result result : scanner) {
            rows++;
            if (rows > rowCount) {
                scanner.close();
                assertTrue("Scanned more than expected (" + rowCount + ")", false);
            }
        }
        scanner.close();
        assertEquals(rowCount, rows);

        List<HRegionLocation> regions = null;
        try {
            regions = locator.getAllRegionLocations();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertEquals(2, regions.size());
        if (splitPoint != null) {
            // make sure the split point matches our explicit configuration
            assertEquals(Bytes.toString(splitPoint),
                    Bytes.toString(regions.get(0).getRegionInfo().getEndKey()));
            assertEquals(Bytes.toString(splitPoint),
                    Bytes.toString(regions.get(1).getRegionInfo().getStartKey()));
            LOG.debug("Properly split on " + Bytes.toString(splitPoint));
        } else {
            if (familyNames.length > 1) {
                int splitKey = Bytes.toInt(regions.get(0).getRegionInfo().getEndKey());
                // check if splitKey is based on the largest column family
                // in terms of it store size
                int deltaForLargestFamily = Math.abs(rowCount / 2 - splitKey);
                LOG.debug("SplitKey=" + splitKey + "&deltaForLargestFamily=" + deltaForLargestFamily + ", r="
                        + regions.get(0).getRegionInfo());
                for (int index = 0; index < familyNames.length; index++) {
                    int delta = Math.abs(rowCounts[index] / 2 - splitKey);
                    if (delta < deltaForLargestFamily) {
                        assertTrue("Delta " + delta + " for family " + index + " should be at least "
                                + "deltaForLargestFamily " + deltaForLargestFamily, false);
                    }
                }
            }
        }
        TEST_UTIL.deleteTable(tableName);
    }
}