Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

In this page you can find the example usage for java.util TreeSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:org.callimachusproject.management.CalliServer.java

@Override
public synchronized void setWebappOrigins(String[] origins) throws Exception {
    Map<String, String> previously = conf.getOriginRepositoryIDs();
    final Map<String, String> newOrigins = new LinkedHashMap<String, String>();
    for (String origin : origins) {
        if (!previously.containsKey(origin)) {
            verifyOrigin(origin);/*from   w  w  w . j a v  a2s.c o  m*/
            newOrigins.put(origin, getRepositoryId(origin));
        }
    }
    final Map<String, String> oldOrigins = new LinkedHashMap<String, String>();
    oldOrigins.putAll(previously);
    oldOrigins.keySet().removeAll(Arrays.asList(origins));
    final Map<String, String> subsequently = new LinkedHashMap<String, String>(previously);
    subsequently.keySet().removeAll(oldOrigins.keySet());
    conf.setOriginRepositoryIDs(subsequently);
    submit(new Callable<Void>() {
        public Void call() throws Exception {
            for (Map.Entry<String, String> e : oldOrigins.entrySet()) {
                String id = e.getValue();
                if (!subsequently.values().contains(id) && manager.hasRepositoryConfig(id)) {
                    String prefix = id + "/";
                    TreeSet<String> subset = new TreeSet<String>();
                    for (String other : manager.getRepositoryIDs()) {
                        if (other.startsWith(prefix)) {
                            subset.add(other);
                        }
                    }
                    while (!subset.isEmpty()) {
                        manager.removeRepository(subset.pollLast());
                    }
                    manager.removeRepository(id);
                }
            }
            for (Map.Entry<String, String> e : newOrigins.entrySet()) {
                String origin = e.getKey();
                String id = e.getValue();
                CalliRepository repository = getSetupRepository(id, origin);
                try {
                    SetupTool tool = new SetupTool(id, repository, conf);
                    tool.setupWebappOrigin(origin);
                } finally {
                    refreshRepository(id);
                }
                serveRealm(origin, id);
            }
            return null;
        }
    });
}

From source file:edu.ucla.stat.SOCR.analyses.gui.AnovaOneWay.java

protected void doGraph() {

    // graph Component is available here
    // data: variables double xData, yData, residuals, predicted are available here after doAnalysis() is run.
    ////System.out.println("\nAnovaOneWay doGraph call removeAll");

    graphPanel.removeAll();/*  www  . j  a v  a  2s  . co  m*/
    JPanel innerPanel = new JPanel();
    JScrollPane graphPane = new JScrollPane(innerPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    graphPanel.add(graphPane);
    innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
    graphPanel.setLayout(new BoxLayout(graphPanel, BoxLayout.Y_AXIS));

    // 1. Box plot of data: yData vs. xData (where xData is categorical)

    //int seriesCount = 3; // seriesCount
    //int categoryCount= 1;
    //double[][][] yValue = new double[seriesCount][categoryCount][];
    //String[] seriesName = {"1", "2", "3"};
    /*
    String[][] xNameData = new String[seriesCount][categoryCount]; // xNameData: category names.
    xNameData[0] = new String[] {""};
    xNameData[1] = xNameData[0];
    xNameData[2] = xNameData[0];
    */
    // data is for testing only.
    // the data below gives hallow triagle and circles.
    // static test data only
    /*      yValue[0][0] = new double[] {14.67,13.72,13.84,13.90,14.56,13.88,14.30,14.11,13.84,13.90,14.56,13.88, 15, 16, 17};
            
          yValue[1][0] = new double[] {13.94,14.40,14.14,14.59,13.59,14.24,14.05,11,12,13, 15, 20, 8};
            
          yValue[2][0] = new double[] {14.24,14.05,14.65,13,10,19,20,10,11,12,23, 20, 23, 24};
    */

    /* the parameters to be passed are:
    1.boxPlotTitle, xAxisLabel, YAxisLabel.
    2. serieCount, categoryCount
    3. seriesname (e.g. sex, race, etc)
    4. category's name (e.g. height, weight, etc)--xData
    5. yValue(double),
    */
    /*
    JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot of " + dependentHeader + " vs " + independentHeader, independentHeader, dependentHeader, dependentHeader + " Value  " , xData, yData,  "Regression Line", intercept, slope, "");
    ChartPanel chartPanel = new ChartPanel(scatterChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth,plotHeight));
    innerPanel.add(chartPanel);
    */

    double xDataDouble[] = new double[xData.length];
    String groupLegend = "";
    boolean useStringLegend = false;
    TreeSet<String> treeSet = new TreeSet<String>();
    try {
        for (int i = 0; i < xData.length; i++) {
            xDataDouble[i] = (new Double(xData[i])).doubleValue();
        }
    } catch (Exception e) {
        useStringLegend = true;
        for (int i = 0; i < xData.length; i++) {
            treeSet.add((String) xData[i]);
        }
    }
    int groupSize = treeSet.size();

    ////System.out.println("TreeSet.size() = " + groupSize);

    Iterator<String> iterator = treeSet.iterator();
    int groupIndex = 1;
    String groupName = null;
    while (iterator.hasNext()) {
        groupName = (String) iterator.next();
        //xDataDouble[groupIndex-1] = groupIndex;
        groupLegend += ("\t" + groupName + "=" + groupIndex + "  ");
        for (int i = 0; i < xData.length; i++) {
            if (xData[i].equalsIgnoreCase(groupName)) { // xData[i] is a String.
                xDataDouble[i] = (double) groupIndex;
            }
        }
        groupIndex++;

    }

    if (useStringLegend) {
        groupLegend = "Group Names: " + groupLegend;
        groupLegend = groupLegend.substring(0, groupLegend.length() - 2);
        //System.out.println("groupLegend = " + groupLegend);
        // 1. scatter plot of data: yData vs. xData
    }

    //JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot", independentHeader, "Residuals", "Residual Value", xData, residuals, "At Residual = 0", 0, 0, "");

    JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot", independentHeader, "Residuals",
            "Residual Value", xDataDouble, residuals, "   " + groupLegend, 0, 0, "");
    //JFreeChart scatterChart = chartFactory.getLineChart("Scatter Plot", independentHeader, dependentHeader, xDataDouble, yData);//getChart(title, xlabel, ylabel, xdata,ydata)

    ChartPanel chartPanel = new ChartPanel(scatterChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight));
    innerPanel.add(chartPanel);

    /*
    if (useStringLegend) {
       JPanel labelPanel = new JPanel();
       labelPanel.setBackground(Color.WHITE);
       JLabel legendLabel1 = new JLabel(groupLegend);
       legendLabel1.setBackground(Color.WHITE);
       labelPanel.add(legendLabel1, BorderLayout.NORTH);
       innerPanel.add(labelPanel);
    }
    */
    // this is only a test for having more than one charts in a boxlayout

    // 1.5. box plot of data
    //mapToArray(boxPlotNameValueMap);
    /*
    JFreeChart boxChart = chartFactory.getBoxAndWhiskerChart(boxPlotTitle, xAxisLabel, yAxisLabel, seriesCount, categoryCount,  seriesName, xNameData, yValue);
    chartPanel = new ChartPanel(boxChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth,plotHeight));
    graphPanel.add(chartPanel);
    */

    // 2. residual on fit plot: residuals vs. xData
    //JFreeChart rxChart = chartFactory.getLineChart("Residual on Covariate Plot", independentHeader, "Residuals", xDataDouble, residuals);

    JFreeChart rxChart = chartFactory.getQQChart("Residual on Covariate Plot", independentHeader, "Residuals",
            "Residuals", xDataDouble, residuals, "   " + groupLegend, 0, 0, "");

    chartPanel = new ChartPanel(rxChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight));
    innerPanel.add(chartPanel);

    // 3. residual on fit plot: residuals vs. predicted

    //JFreeChart rfChart = chartFactory.getLineChart("Residual on Fit Plot", "Predicted", "Residuals", predicted, residuals);

    JFreeChart rfChart = chartFactory.getQQChart("Residual on Fit Plot", "Predicted " + dependentHeader,
            "Residuals", "Residuals", predicted, residuals, "At Residual = 0", 0, 0, "");
    chartPanel = new ChartPanel(rfChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight));
    innerPanel.add(chartPanel);

    // 4. Normal QQ plot: need residuals and standardized normal scores
    //JFreeChart qqChart = chartFactory.getLineChart("Residual Normal QQ Plot", "Theoretical Quantiles", "Standardized Residuals", sortedStandardizedNormalQuantiles, sortedStandardizedResiduals);
    int len = sortedNormalQuantiles.length;
    double slope = (sortedStandardizedResiduals[len - 1] - sortedStandardizedResiduals[0])
            / (sortedNormalQuantiles[len - 1] - sortedNormalQuantiles[0]);
    double y0 = sortedStandardizedResiduals[len - 1] - slope * sortedNormalQuantiles[len - 1];

    //   max_x = Math.max (normalQuantiles[row_count-1],stdResiduals[row_count-1]);

    JFreeChart qqChart = chartFactory.getQQChart("Residual Normal QQ Plot", "Theoretical Quantiles",
            "Standardized Residuals", "Standardized Residual Value  ", sortedStandardizedNormalQuantiles,
            sortedStandardizedResiduals, "At Standardized Residual = 0", y0, slope, "noshape");
    //JFreeChart qqChart = chartFactory.getLineChart("Residual Normal QQ Plot", "Theoretical Quantiles", "Standardized Residuals", sortedStandardizedNormalQuantiles, sortedStandardizedResiduals, "noline");

    chartPanel = new ChartPanel(qqChart, false);
    chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight));
    innerPanel.add(chartPanel);

    graphPanel.validate();

}

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private void runInForkedRunner(Repository repository, String test, File repositoryReportsFolder)
        throws MojoExecutionException {
    File outputFile = new File(repositoryReportsFolder, test);
    SystemUnderTest systemUnderTest = new SystemUnderTest();
    systemUnderTest.setName(repository.getSystemUnderTest());
    systemUnderTest.setProject(Project.newInstance(repository.getProjectName()));

    Specification specification = Specification.newInstance(test);
    com.greenpepper.server.domain.Repository repositoryRunner = com.greenpepper.server.domain.Repository
            .newInstance(repository.getName());
    RepositoryType repositoryType = RepositoryType.newInstance("FILE");
    repositoryType.setRepositoryClass(repository.getType());
    EnvironmentType java = EnvironmentType.newInstance("JAVA");
    repositoryType.registerClassForEnvironment(repository.getType(), java);
    repositoryRunner.setBaseTestUrl(repository.getRoot());

    repositoryRunner.setType(repositoryType);
    specification.setRepository(repositoryRunner);
    systemUnderTest.setFixtureFactory(systemUnderDevelopment);
    systemUnderTest.setFixtureFactoryArgs(systemUnderDevelopmentArgs);

    specification.setDialectClass(repository.getDialect());

    String runnerName = repository.getRunnerName();
    if (runnerName == null) {
        if (runnerMap.size() == 1) {
            runnerName = runnerMap.keySet().iterator().next();
        } else {//from ww  w.ja  v a  2  s .co m
            runnerName = DEFAULT_RUNNER_NAME;
        }
    }

    Runner defaultRunner = runnerMap.get(runnerName);
    ExecutorService executorService = executorMap.get(runnerName);

    if (defaultRunner != null && executorService != null) {
        if (defaultRunner.getForkCount() == 1) {
            defaultRunner.setRedirectOutputToFile(redirectOutputToFile);
        }

        // We will try to get the external-link after the test (for version of Greepepper < 4.1 )
        defaultRunner.setRepositoryIndex(this.repositoryIndexes.get(repository.getName()));
        TestResultsIndex testResultsIndex = testResultsIndexes.get(repository.getName());
        RunnerTask runnerTask = new RunnerTask(specification, systemUnderTest, outputFile.getAbsolutePath(),
                defaultRunner, getLog(), testResultsIndex);
        if (defaultRunner.isIncludeProjectClasspath()) {
            TreeSet<String> classpath = new TreeSet<String>();
            for (URL url : createClasspath()) {
                classpath.add(FileUtils.toFile(url).getAbsolutePath());
            }
            systemUnderTest.setSutClasspaths(classpath);
        }

        Future<?> future = executorService.submit(runnerTask);
        RunnerResult runnerResult = new RunnerResult(runnerTask, future);
        runnerResults.add(runnerResult);
    } else {
        getLog().warn(format(
                "No runner found for executing %s in repository %s. Runner '%s' was specified (or falled back to)",
                specification.getName(), repository.getName(), runnerName));
    }
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull String toSignatureString(@Nonnull HttpRequestBase method, @Nonnull String contentType,
        @Nonnull String range, @Nonnull String date, @Nonnull URI resource, @Nonnull List<Header> emcHeaders) {
    StringBuilder emcHeaderString = new StringBuilder();

    TreeSet<String> sorted = new TreeSet<String>();

    for (Header header : emcHeaders) {
        sorted.add(header.getName().toLowerCase());
    }/*from   w ww.j  ava  2  s . c o m*/
    boolean first = true;
    for (String headerName : sorted) {
        for (Header header : emcHeaders) {
            if (header.getName().toLowerCase().equals(headerName)) {
                if (!first) {
                    emcHeaderString.append("\n");
                } else {
                    first = false;
                }
                String val = header.getValue();

                if (val == null) {
                    val = "";
                }
                emcHeaderString.append(headerName);
                emcHeaderString.append(":");
                StringBuilder tmp = new StringBuilder();
                for (char c : val.toCharArray()) {
                    if (Character.isWhitespace(c)) {
                        tmp.append(" ");
                    } else {
                        tmp.append(c);
                    }
                }
                val = tmp.toString();
                while (val.contains("  ")) {
                    val = val.replaceAll("  ", " ");
                }
                emcHeaderString.append(val);
            }
        }
    }
    String path = resource.getRawPath().toLowerCase();

    if (resource.getRawQuery() != null) {
        path = path + "?" + resource.getRawQuery().toLowerCase();
    }

    return (method.getMethod() + "\n" + contentType + "\n" + range + "\n" + date + "\n" + path + "\n"
            + emcHeaderString.toString());
}

From source file:bes.injector.InjectorBurnTest.java

private void testPromptnessOfExecution(long intervalNanos, float loadIncrement)
        throws InterruptedException, ExecutionException, TimeoutException {
    final int executorCount = 4;
    int threadCount = 8;
    int maxQueued = 1024;
    final WeibullDistribution workTime = new WeibullDistribution(3, 200000);
    final long minWorkTime = TimeUnit.MICROSECONDS.toNanos(1);
    final long maxWorkTime = TimeUnit.MILLISECONDS.toNanos(1);

    final int[] threadCounts = new int[executorCount];
    final WeibullDistribution[] workCount = new WeibullDistribution[executorCount];
    final ExecutorService[] executors = new ExecutorService[executorCount];
    final Injector injector = new Injector("");
    for (int i = 0; i < executors.length; i++) {
        executors[i] = injector.newExecutor(threadCount, maxQueued);
        threadCounts[i] = threadCount;/*from ww  w  .j av a 2 s  .  c o m*/
        workCount[i] = new WeibullDistribution(2, maxQueued);
        threadCount *= 2;
        maxQueued *= 2;
    }

    long runs = 0;
    long events = 0;
    final TreeSet<Batch> pending = new TreeSet<Batch>();
    final BitSet executorsWithWork = new BitSet(executorCount);
    long until = 0;
    // basic idea is to go through different levels of load on the executor service; initially is all small batches
    // (mostly within max queue size) of very short operations, moving to progressively larger batches
    // (beyond max queued size), and longer operations
    for (float multiplier = 0f; multiplier < 2.01f;) {
        if (System.nanoTime() > until) {
            System.out.println(String.format("Completed %.0fK batches with %.1fM events", runs * 0.001f,
                    events * 0.000001f));
            events = 0;
            until = System.nanoTime() + intervalNanos;
            multiplier += loadIncrement;
            System.out.println(String.format("Running for %ds with load multiplier %.1f",
                    TimeUnit.NANOSECONDS.toSeconds(intervalNanos), multiplier));
        }

        // wait a random amount of time so we submit new tasks in various stages of
        long timeout;
        if (pending.isEmpty())
            timeout = 0;
        else if (Math.random() > 0.98)
            timeout = Long.MAX_VALUE;
        else if (pending.size() == executorCount)
            timeout = pending.first().timeout;
        else
            timeout = (long) (Math.random() * pending.last().timeout);

        while (!pending.isEmpty() && timeout > System.nanoTime()) {
            Batch first = pending.first();
            boolean complete = false;
            try {
                for (Result result : first.results.descendingSet())
                    result.future.get(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
                complete = true;
            } catch (TimeoutException e) {
            }
            if (!complete && System.nanoTime() > first.timeout) {
                for (Result result : first.results)
                    if (!result.future.isDone())
                        throw new AssertionError();
                complete = true;
            }
            if (complete) {
                pending.pollFirst();
                executorsWithWork.clear(first.executorIndex);
            }
        }

        // if we've emptied the executors, give all our threads an opportunity to spin down
        if (timeout == Long.MAX_VALUE) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
        }

        // submit a random batch to the first free executor service
        int executorIndex = executorsWithWork.nextClearBit(0);
        if (executorIndex >= executorCount)
            continue;
        executorsWithWork.set(executorIndex);
        ExecutorService executor = executors[executorIndex];
        TreeSet<Result> results = new TreeSet<Result>();
        int count = (int) (workCount[executorIndex].sample() * multiplier);
        long targetTotalElapsed = 0;
        long start = System.nanoTime();
        long baseTime;
        if (Math.random() > 0.5)
            baseTime = 2 * (long) (workTime.sample() * multiplier);
        else
            baseTime = 0;
        for (int j = 0; j < count; j++) {
            long time;
            if (baseTime == 0)
                time = (long) (workTime.sample() * multiplier);
            else
                time = (long) (baseTime * Math.random());
            if (time < minWorkTime)
                time = minWorkTime;
            if (time > maxWorkTime)
                time = maxWorkTime;
            targetTotalElapsed += time;
            Future<?> future = executor.submit(new WaitTask(time));
            results.add(new Result(future, System.nanoTime() + time));
        }
        long end = start + (long) Math.ceil(targetTotalElapsed / (double) threadCounts[executorIndex])
                + TimeUnit.MILLISECONDS.toNanos(100L);
        long now = System.nanoTime();
        if (runs++ > executorCount && now > end)
            throw new AssertionError();
        events += results.size();
        pending.add(new Batch(results, end, executorIndex));
        //            System.out.println(String.format("Submitted batch to executor %d with %d items and %d permitted millis", executorIndex, count, TimeUnit.NANOSECONDS.toMillis(end - start)));
    }
}

From source file:geogebra.kernel.EquationSolver.java

/**
 * Calculates all roots of a polynomial given by eqn using Laguerres method.
 * Polishes roots found. The roots are stored in eqn again.
 * @param eqn: coefficients of polynomial    
 *//*from w  w  w .  j  a  v  a 2s.c  om*/
private int laguerreAllComplex(double[] real, double[] complex) {

    Complex[] complexRoots = null;
    try {
        if (laguerreSolver == null) {
            laguerreSolver = new LaguerreSolver();
        }
        complexRoots = laguerreSolver.solveAll(real, LAGUERRE_START);
    } catch (Exception e) {
        Application.debug("Problem solving with LaguerreSolver" + e.getLocalizedMessage());
        return 0;
    }

    // sort by real part & remove duplicates

    TreeSet<Complex> sortedSet = new TreeSet<Complex>(getComparatorReal());

    for (int i = 0; i < complexRoots.length; i++) {
        sortedSet.add(complexRoots[i]);
    }

    int roots = 0;
    Complex temp;
    Iterator<Complex> iterator = sortedSet.iterator();
    while (iterator.hasNext()) {
        temp = iterator.next();
        real[roots] = temp.getReal();
        complex[roots] = temp.getImaginary();
        roots++;
    }

    return roots;
}

From source file:org.ihtsdo.otf.snomed.service.ConceptLookUpServiceImpl.java

@Override
@Cacheable(value = { "conceptIds" })
public Set<String> getConceptIds(int offset, int limit) throws ConceptServiceException {
    LOGGER.debug("getting concept ids with offset {} and limit {} ", offset, limit);

    TreeSet<String> conceptIds = new TreeSet<String>();

    TitanGraph g = null;//  w  w w  .ja v a  2 s  .c  o m
    try {

        g = factory.getReadOnlyGraph();

        Iterable<Result<Vertex>> vs = g.indexQuery("concept", "v.sctid:*").offset(offset).limit(limit)
                .vertices();

        for (Result<Vertex> v : vs) {

            String sctid = v.getElement().getProperty(Properties.sctid.toString());

            if (!StringUtils.isEmpty(sctid)) {

                LOGGER.trace("Adding sctid {} to concept id list ", sctid);

                conceptIds.add(sctid);

            }

        }

        RefsetGraphFactory.commit(g);

    } catch (Exception e) {

        LOGGER.error("Error duing concept ids fetch ", e);
        RefsetGraphFactory.rollback(g);

        throw new ConceptServiceException(e);

    } finally {

        RefsetGraphFactory.shutdown(g);

    }
    LOGGER.debug("returning total {} concept ids ", conceptIds.size());

    return Collections.unmodifiableSortedSet(conceptIds);
}

From source file:edu.lternet.pasta.client.DataPackageManagerClient.java

/**
 * Determine the test identifier used for testing data package operations.
 * Eliminate identifiers that were previously deleted or are currently in use.
 * /*w w  w  .j  a v  a2  s . co m*/
 * @param dpmClient
 *          the DataPackageManagerClient object
 * @param scope
 *          the scope value, e.g. "knb-lter-lno"
 * @param initialIdentifier  the starting identifier value; keep incrementing until
 *          we find an identifier that hasn't been used
 * @return an integer value appropriate for use as a test identifier
 */
static Integer determineTestIdentifier(DataPackageManagerClient dpmClient, String scope,
        String initialIdentifier) throws Exception {
    Integer identifier = null;

    /*
     * Determine the test identifier. Eliminate identifiers that were previously
     * deleted or are currently in use.
     */
    TreeSet<String> deletedSet = new TreeSet<String>();
    String deletedDataPackages = dpmClient.listDeletedDataPackages();
    String[] deletedArray = deletedDataPackages.split("\n");
    for (int i = 0; i < deletedArray.length; i++) {
        if (deletedArray[i] != null && !deletedArray[i].equals("") && deletedArray[i].startsWith(scope)) {
            deletedSet.add(deletedArray[i]);
        }
    }

    TreeSet<String> identifierSet = new TreeSet<String>();
    String dataPackageIdentifiers = dpmClient.listDataPackageIdentifiers(scope);
    String[] identifierArray = dataPackageIdentifiers.split("\n");
    for (int i = 0; i < identifierArray.length; i++) {
        if (identifierArray[i] != null && !identifierArray[i].equals("")) {
            identifierSet.add(identifierArray[i]);
        }
    }

    int identifierValue = new Integer(initialIdentifier).intValue();
    while (identifier == null) {
        String identifierString = "" + identifierValue;
        String scopeDotIdentifier = scope + "." + identifierValue;
        if (!deletedSet.contains(scopeDotIdentifier) && !identifierSet.contains(identifierString)) {
            identifier = new Integer(identifierValue);
        } else {
            identifierValue++;
        }
    }

    return identifier;
}

From source file:com.cyanogenmod.eleven.ui.activities.SearchActivity.java

/**
 * {@inheritDoc}/*w  w  w  .j  a  va  2s.c  o m*/
 */
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPopupMenuHelper = new PopupMenuHelper(this, getSupportFragmentManager()) {
        private SearchResult mSelectedItem;

        @Override
        public PopupMenuType onPreparePopupMenu(int position) {
            mSelectedItem = mAdapter.getTItem(position);

            return PopupMenuType.SearchResult;
        }

        @Override
        protected long[] getIdList() {
            switch (mSelectedItem.mType) {
            case Artist:
                return MusicUtils.getSongListForArtist(SearchActivity.this, mSelectedItem.mId);
            case Album:
                return MusicUtils.getSongListForAlbum(SearchActivity.this, mSelectedItem.mId);
            case Song:
                return new long[] { mSelectedItem.mId };
            case Playlist:
                return MusicUtils.getSongListForPlaylist(SearchActivity.this, mSelectedItem.mId);
            default:
                return null;
            }
        }

        @Override
        protected long getSourceId() {
            return mSelectedItem.mId;
        }

        @Override
        protected Config.IdType getSourceType() {
            return mSelectedItem.mType.getSourceType();
        }

        @Override
        protected void updateMenuIds(PopupMenuType type, TreeSet<Integer> set) {
            super.updateMenuIds(type, set);

            if (mSelectedItem.mType == ResultType.Album) {
                set.add(FragmentMenuItems.MORE_BY_ARTIST);
            }
        }

        @Override
        protected String getArtistName() {
            return mSelectedItem.mArtist;
        }
    };

    // Fade it in
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

    // Control the media volume
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // Bind Apollo's service
    mToken = MusicUtils.bindToService(this, this);

    // Set the layout
    setContentView(R.layout.activity_search);

    // get the input method manager
    mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    // Initialize the adapter
    SummarySearchAdapter adapter = new SummarySearchAdapter(this);
    mAdapter = new SectionAdapter<SearchResult, SummarySearchAdapter>(this, adapter);
    // Set the prefix
    mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
    mAdapter.setupHeaderParameters(R.layout.list_search_header, false);
    mAdapter.setupFooterParameters(R.layout.list_search_footer, true);
    mAdapter.setPopupMenuClickedListener(new IPopupMenuCallback.IListener() {
        @Override
        public void onPopupMenuClicked(View v, int position) {
            mPopupMenuHelper.showPopupMenu(v, position);
        }
    });

    mLoadingEmptyContainer = (LoadingEmptyContainer) findViewById(R.id.loading_empty_container);
    // setup the no results container
    NoResultsContainer noResults = mLoadingEmptyContainer.getNoResultsContainer();
    noResults.setMainText(R.string.empty_search);
    noResults.setSecondaryText(R.string.empty_search_check);

    initListView();

    // setup handler and runnable
    mHandler = new Handler();
    mLoadingRunnable = new Runnable() {
        @Override
        public void run() {
            setState(VisibleState.Loading);
        }
    };

    // Theme the action bar
    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    // Get the query String
    mFilterString = getIntent().getStringExtra(SearchManager.QUERY);

    // if we have a non-empty search string, this is a 2nd lvl search
    if (!TextUtils.isEmpty(mFilterString)) {
        mTopLevelSearch = false;

        // get the search type to filter by
        int type = getIntent().getIntExtra(SearchManager.SEARCH_MODE, -1);
        if (type >= 0 && type < ResultType.values().length) {
            mSearchType = ResultType.values()[type];
        }

        int resourceId = 0;
        switch (mSearchType) {
        case Artist:
            resourceId = R.string.search_title_artists;
            break;
        case Album:
            resourceId = R.string.search_title_albums;
            break;
        case Playlist:
            resourceId = R.string.search_title_playlists;
            break;
        case Song:
            resourceId = R.string.search_title_songs;
            break;
        }
        actionBar.setTitle(getString(resourceId, mFilterString).toUpperCase());
        actionBar.setDisplayHomeAsUpEnabled(true);

        // Set the prefix
        mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);

        // Start the loader for the query
        getSupportLoaderManager().initLoader(SEARCH_LOADER, null, this);
    } else {
        mTopLevelSearch = true;
        mSearchHistoryCallback = new SearchHistoryCallback();

        // Start the loader for the search history
        getSupportLoaderManager().initLoader(HISTORY_LOADER, null, mSearchHistoryCallback);
    }

    // set the background on the root view
    getWindow().getDecorView().getRootView()
            .setBackgroundColor(getResources().getColor(R.color.background_color));
}