Search in sources :

Example 1 with CandlepinQuery

use of org.candlepin.model.CandlepinQuery in project candlepin by candlepin.

the class CandlepinQueryInterceptor method postProcess.

@Override
public void postProcess(ServerResponse response) {
    Object entity = response.getEntity();
    if (entity instanceof CandlepinQuery) {
        final PageRequest pageRequest = ResteasyProviderFactory.getContextData(PageRequest.class);
        final Session session = this.openSession();
        final CandlepinQuery query = (CandlepinQuery) entity;
        final ObjectMapper mapper = this.jsonProvider.locateMapper(Object.class, MediaType.APPLICATION_JSON_TYPE);
        // Use a separate session so we aren't at risk of lazy loading or interceptors closing
        // our cursor mid-stream.
        query.useSession(session);
        // Apply any paging config we may have
        if (pageRequest != null) {
            // Impl note:
            // Sorting will always be required (for consistency) if a page request object is
            // present -- either isPaging() will be true, or we'll have ordering config.
            String sortField = pageRequest.getSortBy() != null ? pageRequest.getSortBy() : AbstractHibernateObject.DEFAULT_SORT_FIELD;
            PageRequest.Order order = pageRequest.getOrder() != null ? pageRequest.getOrder() : PageRequest.DEFAULT_ORDER;
            query.addOrder(order == PageRequest.Order.DESCENDING ? Order.desc(sortField) : Order.asc(sortField));
            if (pageRequest.isPaging()) {
                query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
                query.setMaxResults(pageRequest.getPerPage());
                // Create a page object for the link header response
                Page page = new Page();
                // This is expensive :(
                page.setMaxRecords(query.getRowCount());
                page.setPageRequest(pageRequest);
                // Note: we don't need to store the page data in the page
                ResteasyProviderFactory.pushContext(Page.class, page);
            }
        }
        // Set the output streamer that will stream our query result
        response.setEntity(new StreamingOutput() {

            @Override
            public void write(OutputStream stream) throws IOException, WebApplicationException {
                JsonGenerator generator = null;
                ResultIterator<Object> iterator = null;
                try {
                    generator = mapper.getJsonFactory().createGenerator(stream);
                    iterator = query.iterate();
                    generator.writeStartArray();
                    while (iterator.hasNext()) {
                        mapper.writeValue(generator, iterator.next());
                    }
                    generator.writeEndArray();
                } finally {
                    if (generator != null) {
                        generator.flush();
                        generator.close();
                    }
                    if (iterator != null) {
                        iterator.close();
                    }
                    if (session != null) {
                        session.close();
                    }
                }
            }
        });
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) ResultIterator(org.candlepin.model.ResultIterator) CandlepinQuery(org.candlepin.model.CandlepinQuery) Page(org.candlepin.common.paging.Page) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) PageRequest(org.candlepin.common.paging.PageRequest) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) AbstractHibernateObject(org.candlepin.model.AbstractHibernateObject) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Session(org.hibernate.Session)

Example 2 with CandlepinQuery

use of org.candlepin.model.CandlepinQuery in project candlepin by candlepin.

the class InstalledProductStatusCalculatorTest method mockOwnerProducts.

private void mockOwnerProducts(Owner owner, Collection<Product> products) {
    final Map<String, Product> productMap = new HashMap<>();
    for (Product product : products) {
        productMap.put(product.getId(), product);
    }
    doAnswer(new Answer<CandlepinQuery<Product>>() {

        @Override
        public CandlepinQuery<Product> answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Collection<String> productIds = (Collection<String>) args[1];
            Collection<Product> products = new LinkedList<>();
            for (String productId : productIds) {
                Product product = productMap.get(productId);
                if (product != null) {
                    products.add(product);
                }
            }
            CandlepinQuery cqmock = mock(CandlepinQuery.class);
            when(cqmock.iterator()).thenReturn(products.iterator());
            when(cqmock.iterate()).thenReturn(new MockResultIterator(products.iterator()));
            return cqmock;
        }
    }).when(this.ownerProductCurator).getProductsByIds(eq(owner.getId()), anyCollection());
}
Also used : HashMap(java.util.HashMap) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Product(org.candlepin.model.Product) ConsumerInstalledProduct(org.candlepin.model.ConsumerInstalledProduct) Collection(java.util.Collection) CandlepinQuery(org.candlepin.model.CandlepinQuery) MockResultIterator(org.candlepin.test.MockResultIterator)

Example 3 with CandlepinQuery

use of org.candlepin.model.CandlepinQuery in project candlepin by candlepin.

the class StatusResourceTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    CandlepinModeChange mockModeChange = new CandlepinModeChange(new Date(), Mode.NORMAL, Reason.STARTUP);
    CandlepinQuery mockCPQuery = mock(CandlepinQuery.class);
    when(mockCPQuery.list()).thenReturn(new ArrayList<Rules>());
    when(rulesCurator.listAll()).thenReturn(mockCPQuery);
    when(rulesCurator.getRules()).thenReturn(new Rules("// Version: 2.0\nBLAH"));
    when(mockedStatusCache.getStatus()).thenReturn(null);
    when(candlepinCache.getStatusCache()).thenReturn(mockedStatusCache);
    when(modeManager.getLastCandlepinModeChange()).thenReturn(mockModeChange);
}
Also used : CandlepinQuery(org.candlepin.model.CandlepinQuery) CandlepinModeChange(org.candlepin.model.CandlepinModeChange) Rules(org.candlepin.model.Rules) Date(java.util.Date) Before(org.junit.Before)

Example 4 with CandlepinQuery

use of org.candlepin.model.CandlepinQuery in project candlepin by candlepin.

the class ExporterTest method exportConsumer.

@Test
public void exportConsumer() throws ExportCreationException, IOException {
    config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/");
    config.setProperty(ConfigProperties.PREFIX_WEBURL, "localhost:8443/weburl");
    config.setProperty(ConfigProperties.PREFIX_APIURL, "localhost:8443/apiurl");
    Rules mrules = mock(Rules.class);
    Consumer consumer = mock(Consumer.class);
    Principal principal = mock(Principal.class);
    when(mrules.getRules()).thenReturn("foobar");
    when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes());
    when(rc.getRules()).thenReturn(mrules);
    when(pprov.get()).thenReturn(principal);
    when(principal.getUsername()).thenReturn("testUser");
    // specific to this test
    IdentityCertificate idcert = new IdentityCertificate();
    idcert.setSerial(new CertificateSerial(10L, new Date()));
    idcert.setKey("euh0876puhapodifbvj094");
    idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#");
    idcert.setCreated(new Date());
    idcert.setUpdated(new Date());
    when(consumer.getIdCert()).thenReturn(idcert);
    ConsumerType ctype = new ConsumerType(ConsumerTypeEnum.CANDLEPIN);
    ctype.setId("test-ctype");
    KeyPair keyPair = createKeyPair();
    when(consumer.getKeyPair()).thenReturn(keyPair);
    when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes());
    when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes());
    when(consumer.getUuid()).thenReturn("8auuid");
    when(consumer.getName()).thenReturn("consumer_name");
    when(consumer.getContentAccessMode()).thenReturn("access_mode");
    when(consumer.getTypeId()).thenReturn(ctype.getId());
    when(ctc.getConsumerType(eq(consumer))).thenReturn(ctype);
    when(ctc.find(eq(ctype.getId()))).thenReturn(ctype);
    CandlepinQuery cqmock = mock(CandlepinQuery.class);
    when(cqmock.iterator()).thenReturn(Arrays.asList(new ConsumerType("system")).iterator());
    when(ctc.listAll()).thenReturn(cqmock);
    CandlepinQuery emptyIteratorMock = mock(CandlepinQuery.class);
    when(emptyIteratorMock.iterate()).thenReturn(new MockResultIterator(Arrays.asList().iterator()));
    when(cdnc.listAll()).thenReturn(emptyIteratorMock);
    // FINALLY test this badboy
    Exporter e = new Exporter(ctc, oc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov, dvc, dve, cdnc, cdne, pc, su, exportExtensionAdapter, translator);
    File export = e.getFullExport(consumer);
    verifyContent(export, "export/consumer.json", new VerifyConsumer("consumer.json"));
}
Also used : KeyPair(org.candlepin.model.KeyPair) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CertificateSerial(org.candlepin.model.CertificateSerial) CandlepinQuery(org.candlepin.model.CandlepinQuery) Rules(org.candlepin.model.Rules) ExportRules(org.candlepin.policy.js.export.ExportRules) Date(java.util.Date) Consumer(org.candlepin.model.Consumer) ConsumerType(org.candlepin.model.ConsumerType) File(java.io.File) Principal(org.candlepin.auth.Principal) IdentityCertificate(org.candlepin.model.IdentityCertificate) MockResultIterator(org.candlepin.test.MockResultIterator) Test(org.junit.Test)

Example 5 with CandlepinQuery

use of org.candlepin.model.CandlepinQuery in project candlepin by candlepin.

the class ExporterTest method doNotExportDirtyEntitlements.

@Test(expected = ExportCreationException.class)
public void doNotExportDirtyEntitlements() throws Exception {
    config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/");
    Consumer consumer = mock(Consumer.class);
    Entitlement ent = mock(Entitlement.class);
    Principal principal = mock(Principal.class);
    IdentityCertificate idcert = new IdentityCertificate();
    List<Entitlement> entitlements = new ArrayList<>();
    entitlements.add(ent);
    when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes());
    when(pprov.get()).thenReturn(principal);
    when(principal.getUsername()).thenReturn("testUser");
    when(ec.listByConsumer(consumer)).thenReturn(entitlements);
    when(ent.isDirty()).thenReturn(true);
    idcert.setSerial(new CertificateSerial(10L, new Date()));
    idcert.setKey("euh0876puhapodifbvj094");
    idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#");
    idcert.setCreated(new Date());
    idcert.setUpdated(new Date());
    when(consumer.getIdCert()).thenReturn(idcert);
    KeyPair keyPair = createKeyPair();
    when(consumer.getKeyPair()).thenReturn(keyPair);
    when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes());
    when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes());
    CandlepinQuery cqmock = mock(CandlepinQuery.class);
    when(cqmock.iterator()).thenReturn(Arrays.asList(new ConsumerType("system")).iterator());
    when(ctc.listAll()).thenReturn(cqmock);
    Exporter e = new Exporter(ctc, oc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov, dvc, dve, cdnc, cdne, pc, su, exportExtensionAdapter, translator);
    e.getFullExport(consumer);
}
Also used : KeyPair(org.candlepin.model.KeyPair) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) CertificateSerial(org.candlepin.model.CertificateSerial) CandlepinQuery(org.candlepin.model.CandlepinQuery) Date(java.util.Date) Consumer(org.candlepin.model.Consumer) Entitlement(org.candlepin.model.Entitlement) ConsumerType(org.candlepin.model.ConsumerType) Principal(org.candlepin.auth.Principal) IdentityCertificate(org.candlepin.model.IdentityCertificate) Test(org.junit.Test)

Aggregations

CandlepinQuery (org.candlepin.model.CandlepinQuery)50 Test (org.junit.Test)42 ArrayList (java.util.ArrayList)25 Date (java.util.Date)21 Consumer (org.candlepin.model.Consumer)20 Entitlement (org.candlepin.model.Entitlement)14 Owner (org.candlepin.model.Owner)14 Pool (org.candlepin.model.Pool)14 ConsumerType (org.candlepin.model.ConsumerType)12 Product (org.candlepin.model.Product)11 List (java.util.List)10 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)10 MockResultIterator (org.candlepin.test.MockResultIterator)10 LinkedList (java.util.LinkedList)9 CertificateSerial (org.candlepin.model.CertificateSerial)9 InputStream (java.io.InputStream)8 HashSet (java.util.HashSet)8 Rules (org.candlepin.model.Rules)8 Matchers.anyString (org.mockito.Matchers.anyString)8 File (java.io.File)7