Example usage for java.util SortedSet size

List of usage examples for java.util SortedSet size

Introduction

In this page you can find the example usage for java.util SortedSet size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.coordinator.ManageFinalDegreeWorkDispatchAction.java

private void fillGroupsSpreadSheet(final ExecutionDegree executionDegree, final Spreadsheet spreadsheet) {
    final Scheduleing scheduleing = executionDegree.getScheduling();
    final SortedSet<FinalDegreeWorkGroup> groups = scheduleing.getGroupsWithProposalsSortedByStudentNumbers();
    int numberGroups = 0;
    int maxNumStudentsPerGroup = 0;
    for (final FinalDegreeWorkGroup group : groups) {
        final Row row = spreadsheet.addRow();
        row.setCell(Integer.toString(++numberGroups));
        final SortedSet<GroupStudent> groupStudents = CollectionUtils
                .constructSortedSet(group.getGroupStudentsSet(), GroupStudent.COMPARATOR_BY_STUDENT_NUMBER);
        for (final GroupStudent groupStudent : groupStudents) {
            row.setCell(groupStudent.getRegistration().getNumber().toString());
        }/* ww w. j a v a  2  s .  co  m*/
        maxNumStudentsPerGroup = Math.max(maxNumStudentsPerGroup, groupStudents.size());
    }
    spreadsheet.setHeader("Grupo");
    for (int i = 0; i < maxNumStudentsPerGroup; spreadsheet.setHeader("Aluno " + ++i)) {
        ;
    }
    int groupCounter = 0;
    int maxNumberGroupProposals = 0;
    if (scheduleing.getMaximumNumberOfProposalCandidaciesPerGroup() != null) {
        maxNumberGroupProposals = scheduleing.getMaximumNumberOfProposalCandidaciesPerGroup().intValue();
    } else {
        for (final FinalDegreeWorkGroup group : groups) {
            maxNumberGroupProposals = Math.max(maxNumberGroupProposals,
                    group.getGroupProposalsSortedByPreferenceOrder().size());
        }
    }
    for (final FinalDegreeWorkGroup group : groups) {
        final Row row = spreadsheet.getRow(groupCounter++);
        for (int i = group.getGroupStudentsSet().size(); i++ < maxNumStudentsPerGroup; row.setCell("")) {
            ;
        }
        final SortedSet<GroupProposal> groupProposals = group.getGroupProposalsSortedByPreferenceOrder();
        for (final GroupProposal groupProposal : groupProposals) {
            row.setCell(groupProposal.getFinalDegreeWorkProposal().getProposalNumber().toString());
        }
        for (int i = groupProposals.size(); i++ < maxNumberGroupProposals; row.setCell("")) {
            ;
        }
        if (group.getProposalAttributed() != null) {
            row.setCell(group.getProposalAttributed().getProposalNumber().toString());
        } else if (group.getProposalAttributedByTeacher() != null) {
            row.setCell(group.getProposalAttributedByTeacher().getProposalNumber().toString());
        } else {
            row.setCell("");
        }
    }
    for (int i = 0; i < maxNumberGroupProposals; spreadsheet.setHeader("Proposta de pref. " + ++i)) {
        ;
    }
    spreadsheet.setHeader("Proposta Atribuida");
}

From source file:org.apache.pulsar.broker.admin.impl.NamespacesBase.java

protected BundlesData validateBundlesData(BundlesData initialBundles) {
    SortedSet<String> partitions = new TreeSet<String>();
    for (String partition : initialBundles.getBoundaries()) {
        Long partBoundary = Long.decode(partition);
        partitions.add(String.format("0x%08x", partBoundary));
    }/*  w  w  w  . ja  va  2s  .co  m*/
    if (partitions.size() != initialBundles.getBoundaries().size()) {
        log.debug("Input bundles included repeated partition points. Ignored.");
    }
    try {
        NamespaceBundleFactory.validateFullRange(partitions);
    } catch (IllegalArgumentException iae) {
        throw new RestException(Status.BAD_REQUEST, "Input bundles do not cover the whole hash range. first:"
                + partitions.first() + ", last:" + partitions.last());
    }
    List<String> bundles = Lists.newArrayList();
    bundles.addAll(partitions);
    return new BundlesData(bundles);
}

From source file:org.bibsonomy.recommender.tags.database.DBAccess.java

@Override
public int addRecommendation(Long queryId, Long settingsId, SortedSet<RecommendedTag> tags, long latency)
        throws SQLException {
    if (tags == null)
        return 0;

    SqlMapClient sqlMap = getSqlMapInstance();
    try {/*from www . java  2 s  .c  o m*/
        sqlMap.startTransaction();
        sqlMap.startBatch();
        // insert recommender response
        // #qid#, #sid#, #latency#, #score#, #confidence#, #tagName# )
        RecResponseParam response = new RecResponseParam();
        response.setQid(queryId);
        response.setSid(settingsId);
        response.setLatency(latency);
        for (RecommendedTag tag : tags) {
            response.setTagName(tag.getName());
            response.setConfidence(tag.getConfidence());
            response.setScore(tag.getScore());
            sqlMap.insert("addRecommenderResponse", response);
        }
        sqlMap.executeBatch();
        sqlMap.commitTransaction();
    } finally {
        sqlMap.endTransaction();
    }

    return tags.size();
}

From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java

public synchronized static void addFormTab(HttpServletRequest request, SessionDataInfo sessionData,
        DatabaseInfo databaseDefn)/*from w  ww .j  av  a 2 s  .c  om*/
        throws DisallowedException, MissingParametersException, ObjectNotFoundException {
    TableInfo table = ServletUtilMethods.getTableForRequest(sessionData, request, databaseDefn, true);
    AuthManagerInfo authManager = databaseDefn.getAuthManager();
    if (!authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE, table)) {
        throw new DisallowedException(authManager.getLoggedInUser(request), PrivilegeType.MANAGE_TABLE, table);
    }
    String tabTableId = request.getParameter("tabtable");
    if (tabTableId == null) {
        throw new MissingParametersException("tabtable must be supplied to add a form tab to a table");
    }
    TableInfo tabTable = databaseDefn.getTable(request, tabTableId);
    SortedSet<FormTabInfo> formTabs = table.getFormTabs();
    int newIndex = 0;
    if (formTabs.size() > 0) {
        newIndex = formTabs.last().getIndex() + 1;
    }
    FormTabInfo formTab = new FormTab(table, tabTable, newIndex);
    try {
        HibernateUtil.startHibernateTransaction();
        HibernateUtil.currentSession().save(formTab);
        HibernateUtil.activateObject(table);
        table.addFormTab(formTab);
        HibernateUtil.currentSession().getTransaction().commit();
    } finally {
        HibernateUtil.closeSession();
    }
}

From source file:org.apache.accumulo.core.util.shell.commands.CreateTableCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException,
        IOException, ClassNotFoundException {

    final String testTableName = cl.getArgs()[0];

    if (!testTableName.matches(Tables.VALID_NAME_REGEX)) {
        shellState.getReader()/*w  w  w .j  a v  a2  s  .  com*/
                .println("Only letters, numbers and underscores are allowed for use in table names.");
        throw new IllegalArgumentException();
    }

    final String tableName = cl.getArgs()[0];
    if (shellState.getConnector().tableOperations().exists(tableName)) {
        throw new TableExistsException(null, tableName, null);
    }
    final SortedSet<Text> partitions = new TreeSet<Text>();
    final boolean decode = cl.hasOption(base64Opt.getOpt());

    if (cl.hasOption(createTableOptSplit.getOpt())) {
        final String f = cl.getOptionValue(createTableOptSplit.getOpt());

        String line;
        Scanner file = new Scanner(new File(f), Constants.UTF8.name());
        try {
            while (file.hasNextLine()) {
                line = file.nextLine();
                if (!line.isEmpty())
                    partitions.add(decode ? new Text(Base64.decodeBase64(line.getBytes(Constants.UTF8)))
                            : new Text(line));
            }
        } finally {
            file.close();
        }
    } else if (cl.hasOption(createTableOptCopySplits.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopySplits.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
        partitions.addAll(shellState.getConnector().tableOperations().listSplits(oldTable));
    }

    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopyConfig.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
    }

    TimeType timeType = TimeType.MILLIS;
    if (cl.hasOption(createTableOptTimeLogical.getOpt())) {
        timeType = TimeType.LOGICAL;
    }

    // create table
    shellState.getConnector().tableOperations().create(tableName, true, timeType);
    if (partitions.size() > 0) {
        shellState.getConnector().tableOperations().addSplits(tableName, partitions);
    }

    shellState.setTableName(tableName); // switch shell to new table context

    if (cl.hasOption(createTableNoDefaultIters.getOpt())) {
        for (String key : IteratorUtil.generateInitialTableProperties(true).keySet()) {
            shellState.getConnector().tableOperations().removeProperty(tableName, key);
        }
    }

    // Copy options if flag was set
    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        if (shellState.getConnector().tableOperations().exists(tableName)) {
            final Iterable<Entry<String, String>> configuration = shellState.getConnector().tableOperations()
                    .getProperties(cl.getOptionValue(createTableOptCopyConfig.getOpt()));
            for (Entry<String, String> entry : configuration) {
                if (Property.isValidTablePropertyKey(entry.getKey())) {
                    shellState.getConnector().tableOperations().setProperty(tableName, entry.getKey(),
                            entry.getValue());
                }
            }
        }
    }

    if (cl.hasOption(createTableOptEVC.getOpt())) {
        try {
            shellState.getConnector().tableOperations().addConstraint(tableName,
                    VisibilityConstraint.class.getName());
        } catch (AccumuloException e) {
            Shell.log.warn(e.getMessage() + " while setting visibility constraint, but table was created");
        }
    }

    // Load custom formatter if set
    if (cl.hasOption(createTableOptFormatter.getOpt())) {
        final String formatterClass = cl.getOptionValue(createTableOptFormatter.getOpt());

        shellState.getConnector().tableOperations().setProperty(tableName,
                Property.TABLE_FORMATTER_CLASS.toString(), formatterClass);
    }

    return 0;
}

From source file:ubc.pavlab.gotrack.beans.TrackView.java

/**
 * create timeline based on data//from  ww  w . j av a 2 s  .com
 * 
 * @param timelineData timeline data, map of terms to map of date to boolean representing whether the term existed
 *        on that date
 * @param timelineGroups
 * @return
 */
private List<CustomTimelineModel<GeneOntologyTerm>> createTimelines(
        Map<GeneOntologyTerm, Map<Date, Set<String>>> timelineData,
        Map<GeneOntologyTerm, Set<String>> timelineGroups) {
    List<CustomTimelineModel<GeneOntologyTerm>> timelines = new ArrayList<>();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();

    // Categories

    for (Entry<GeneOntologyTerm, Map<Date, Set<String>>> esTermData : timelineData.entrySet()) {

        GeneOntologyTerm term = esTermData.getKey();

        CustomTimelineModel<GeneOntologyTerm> model = new CustomTimelineModel<>(term);

        Map<Date, Set<String>> data = esTermData.getValue();
        Set<String> setGroups = timelineGroups.get(term);

        List<TimelineGroup> groups = new ArrayList<TimelineGroup>();
        List<TimelineEvent> events = new ArrayList<TimelineEvent>();

        for (String grp : setGroups) {
            groups.add(new TimelineGroup(grp, grp));
        }

        SortedSet<Date> dates = new TreeSet<Date>(data.keySet());
        Date prevDate = null;
        for (Date date : dates) {
            if (prevDate != null) {

                for (String grp : setGroups) {
                    boolean exists = data.get(prevDate).contains(grp);
                    TimelineEvent event = new TimelineEvent(df.format(prevDate), prevDate, date, false, grp,
                            exists ? "timeline-true timeline-hidden" : "timeline-false timeline-hidden");
                    // model.add( event );
                    events.add(event);
                }

            }

            prevDate = date;
        }

        // give the last edition a span of 1 month
        if (dates.size() > 1) {
            for (String grp : setGroups) {
                boolean exists = data.get(prevDate).contains(grp);
                cal.setTime(prevDate);
                cal.add(Calendar.MONTH, 1);
                TimelineEvent event = new TimelineEvent(df.format(prevDate), prevDate, cal.getTime(), false,
                        grp, exists ? "timeline-true timeline-hidden" : "timeline-false timeline-hidden");
                // model.add( event );
                events.add(event);
            }
        }

        model.setGroups(groups);
        model.addAll(events);

        timelines.add(model);

    }

    return timelines;

}

From source file:org.jclouds.blobstore.integration.internal.StubAsyncBlobStore.java

public Future<? extends ListContainerResponse<? extends ResourceMetadata>> list(final String name,
        ListContainerOptions... optionsList) {
    final ListContainerOptions options = (optionsList.length == 0) ? new ListContainerOptions()
            : optionsList[0];/*  w  w w  . j  av a 2s .  c om*/
    return new FutureBase<ListContainerResponse<ResourceMetadata>>() {
        public ListContainerResponse<ResourceMetadata> get() throws InterruptedException, ExecutionException {
            final Map<String, Blob> realContents = getContainerToBlobs().get(name);

            if (realContents == null)
                throw new ContainerNotFoundException(name);

            SortedSet<ResourceMetadata> contents = Sets.newTreeSet(
                    Iterables.transform(realContents.keySet(), new Function<String, ResourceMetadata>() {
                        public ResourceMetadata apply(String key) {
                            return copy(realContents.get(key).getMetadata());
                        }
                    }));

            if (options.getMarker() != null) {
                final String finalMarker = options.getMarker();
                ResourceMetadata lastMarkerMetadata = Iterables.find(contents,
                        new Predicate<ResourceMetadata>() {
                            public boolean apply(ResourceMetadata metadata) {
                                return metadata.getName().equals(finalMarker);
                            }
                        });
                contents = contents.tailSet(lastMarkerMetadata);
                contents.remove(lastMarkerMetadata);
            }

            final String prefix = options.getPath();
            if (prefix != null) {
                contents = Sets.newTreeSet(Iterables.filter(contents, new Predicate<ResourceMetadata>() {
                    public boolean apply(ResourceMetadata o) {
                        return (o != null && o.getName().startsWith(prefix));
                    }
                }));
            }

            int maxResults = contents.size();
            boolean truncated = false;
            String marker = null;
            if (options.getMaxResults() != null && contents.size() > 0) {
                SortedSet<ResourceMetadata> contentsSlice = firstSliceOfSize(contents,
                        options.getMaxResults().intValue());
                maxResults = options.getMaxResults();
                if (!contentsSlice.contains(contents.last())) {
                    // Partial listing
                    truncated = true;
                    marker = contentsSlice.last().getName();
                } else {
                    marker = null;
                }
                contents = contentsSlice;
            }

            final String delimiter = options.isRecursive() ? null : "/";
            if (delimiter != null) {
                SortedSet<String> commonPrefixes = null;
                Iterable<String> iterable = Iterables.transform(contents,
                        new CommonPrefixes(prefix != null ? prefix : null, delimiter));
                commonPrefixes = iterable != null ? Sets.newTreeSet(iterable) : new TreeSet<String>();
                commonPrefixes.remove(CommonPrefixes.NO_PREFIX);

                contents = Sets.newTreeSet(Iterables.filter(contents,
                        new DelimiterFilter(prefix != null ? prefix : null, delimiter)));

                Iterables.<ResourceMetadata>addAll(contents,
                        Iterables.transform(commonPrefixes, new Function<String, ResourceMetadata>() {
                            public ResourceMetadata apply(String o) {
                                MutableResourceMetadata md = new MutableResourceMetadataImpl();
                                md.setType(ResourceType.RELATIVE_PATH);
                                md.setName(o);
                                return md;
                            }
                        }));
            }
            return new ListContainerResponseImpl<ResourceMetadata>(contents, prefix, marker, maxResults,
                    truncated);
        }
    };
}

From source file:net.sf.jasperreports.engine.fill.DefaultChartTheme.java

/**
 *
 *//*from  ww  w.  j  a  v  a 2 s  .  c  om*/
protected void configurePlot(Plot plot) {
    plot.setOutlinePaint(null);

    if (getPlot().getOwnBackcolor() == null)// in a way, plot backcolor inheritence from chart is useless
    {
        plot.setBackgroundPaint(null);
    } else {
        plot.setBackgroundPaint(getPlot().getBackcolor());
    }

    float backgroundAlpha = getPlot().getBackgroundAlphaFloat() == null ? 1f
            : getPlot().getBackgroundAlphaFloat();
    float foregroundAlpha = getPlot().getForegroundAlphaFloat() == null ? 1f
            : getPlot().getForegroundAlphaFloat();
    plot.setBackgroundAlpha(backgroundAlpha);
    plot.setForegroundAlpha(foregroundAlpha);

    if (plot instanceof CategoryPlot) {
        // Handle rotation of the category labels.
        CategoryAxis axis = ((CategoryPlot) plot).getDomainAxis();
        // it's OK to use deprecated method here; avoiding it means attempting cast operations  
        double labelRotation = getLabelRotation();
        if (labelRotation == 90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
        } else if (labelRotation == -90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        } else if (labelRotation < 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions((-labelRotation / 180.0) * Math.PI));
        } else if (labelRotation > 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createDownRotationLabelPositions((labelRotation / 180.0) * Math.PI));
        }
    }

    // Set any color series
    SortedSet<JRSeriesColor> seriesColors = getPlot().getSeriesColors();
    if (seriesColors != null && seriesColors.size() > 0) {
        if (seriesColors.size() == 1) {
            // Add the single color to the beginning of the color cycle, using all the default
            // colors.  To replace the defaults you have to specify at least two colors.
            Paint[] colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + 1];
            colors[0] = seriesColors.first().getColor();
            System.arraycopy(DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE, 0, colors, 1,
                    DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length);
            plot.setDrawingSupplier(
                    new DefaultDrawingSupplier(colors, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
        } else if (seriesColors.size() > 1) {
            // Set up a custom drawing supplier that cycles through the user's colors
            // instead of the default colors.
            Color[] colors = new Color[seriesColors.size()];
            JRSeriesColor[] colorSequence = new JRSeriesColor[seriesColors.size()];
            seriesColors.toArray(colorSequence);
            for (int i = 0; i < colorSequence.length; i++) {
                colors[i] = colorSequence[i].getColor();
            }

            plot.setDrawingSupplier(
                    new DefaultDrawingSupplier(colors, DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                            DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.AbstractAPIManagerTestCase.java

@Test
public void testSearchPaginatedAPIs()
        throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException {
    Map<String, Object> subContextResult = new HashMap<String, Object>();
    subContextResult.put("1", new Object());
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapperExtended(null, registryService,
            registry, tenantManager);//  w w w .ja  v  a2 s .  c  o m
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1234);
    Mockito.when(registryService.getGovernanceUserRegistry(Mockito.anyString(), Mockito.anyInt()))
            .thenThrow(RegistryException.class).thenReturn(registry);

    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString()))
            .thenAnswer((Answer<String>) invocation -> {
                Object[] args = invocation.getArguments();
                return (String) args[0];
            });

    try {
        abstractAPIManager.searchPaginatedAPIs("search", API_PROVIDER, 0, 5, false);
        Assert.fail("Exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
    }
    API api = new API(getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
    Documentation documentation = new Documentation(DocumentationType.HOWTO, "DOC1");
    Map<Documentation, API> documentationAPIMap = new HashMap<>();
    BDDMockito.when(APIUtil.searchAPIsByDoc(Mockito.any(), Mockito.anyInt(), Mockito.anyString(),
            Mockito.anyString(), Mockito.anyString())).thenReturn(documentationAPIMap);
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs("doc=search", SAMPLE_TENANT_DOMAIN_1, 0, 5, false).get("length"), 0);
    documentationAPIMap.put(documentation, api);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("doc=search", null, 0, 5, false).get("length"),
            5);
    Map<String, Object> contextApis = new HashMap<>();
    contextApis.put("api2", new Object());
    BDDMockito.when(APIUtil.searchAPIsByURLPattern(Mockito.any(), Mockito.anyString(), Mockito.anyInt(),
            Mockito.anyInt())).thenReturn(contextApis);
    Assert.assertTrue(
            abstractAPIManager.searchPaginatedAPIs("subcontext=search", null, 0, 5, false).containsKey("api2"));

    // Test related with searches with custom properties
    Map<String, Object> actualAPIs = abstractAPIManager.searchPaginatedAPIs("secured=*true*",
            SAMPLE_TENANT_DOMAIN_1, 0, 5, false);
    List<API> retrievedAPIs = (List<API>) actualAPIs.get("apis");
    Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
    Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
    Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
    Assert.assertEquals("Search with additional property failed", "sxy",
            retrievedAPIs.get(0).getId().getApiName());

    actualAPIs = abstractAPIManager.searchPaginatedAPIs("name=*test*&secured=*true*", SAMPLE_TENANT_DOMAIN_1, 0,
            5, false);
    retrievedAPIs = (List<API>) actualAPIs.get("apis");
    Assert.assertEquals("Searching with additional property failed", 1, actualAPIs.get("length"));
    Assert.assertNotNull("Search with additional property failed", retrievedAPIs);
    Assert.assertEquals("Search with additional property failed", 1, retrievedAPIs.size());
    Assert.assertEquals("Search with additional property failed", "sxy12",
            retrievedAPIs.get(0).getId().getApiName());

    TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, null, -1234);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
    TestUtils.mockAPIMConfiguration(APIConstants.API_STORE_APIS_PER_PAGE, "5", -1234);
    GovernanceArtifact governanceArtifact = getGenericArtifact(SAMPLE_API_NAME, API_PROVIDER,
            SAMPLE_API_VERSION, "qname");
    List<GovernanceArtifact> governanceArtifactList = new ArrayList<GovernanceArtifact>();
    governanceArtifactList.add(governanceArtifact);
    Assert.assertEquals(abstractAPIManager.searchPaginatedAPIs("search", null, 0, 5, false).get("length"), 0);
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("length"), 0);
    BDDMockito
            .when(GovernanceUtils.findGovernanceArtifacts(Mockito.anyString(), Mockito.any(Registry.class),
                    Mockito.anyString(), Mockito.anyBoolean()))
            .thenThrow(RegistryException.class).thenReturn(governanceArtifactList);
    try {
        abstractAPIManager.searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false);
        Assert.fail("APIM exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Failed to Search APIs"));
    }
    API api1 = new API(getAPIIdentifier("api1", API_PROVIDER, "v1"));
    BDDMockito.when(APIUtil.getAPI((GovernanceArtifact) Mockito.any(), (Registry) Mockito.any()))
            .thenReturn(api1);
    SortedSet<API> apiSet = (SortedSet<API>) abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, false).get("apis");
    Assert.assertEquals(apiSet.size(), 1);
    Assert.assertEquals(apiSet.first().getId().getApiName(), "api1");
    Assert.assertEquals(abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("length"), 0);
    PowerMockito.when(paginationContext.getLength()).thenReturn(12);
    Assert.assertTrue((Boolean) abstractAPIManager
            .searchPaginatedAPIs(APIConstants.API_OVERVIEW_PROVIDER, null, 0, 5, true).get("isMore"));
}