Java 类net.sf.jasperreports.engine.JRDataSource 实例源码

项目:lams    文件:JasperReportsUtils.java   
/**
 * Convert the given report data value to a {@code JRDataSource}.
 * <p>In the default implementation, a {@code JRDataSource},
 * {@code java.util.Collection} or object array is detected.
 * The latter are converted to {@code JRBeanCollectionDataSource}
 * or {@code JRBeanArrayDataSource}, respectively.
 * @param value the report data value to convert
 * @return the JRDataSource (never {@code null})
 * @throws IllegalArgumentException if the value could not be converted
 * @see net.sf.jasperreports.engine.JRDataSource
 * @see net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
 * @see net.sf.jasperreports.engine.data.JRBeanArrayDataSource
 */
public static JRDataSource convertReportData(Object value) throws IllegalArgumentException {
    if (value instanceof JRDataSource) {
        return (JRDataSource) value;
    }
    else if (value instanceof Collection) {
        return new JRBeanCollectionDataSource((Collection<?>) value);
    }
    else if (value instanceof Object[]) {
        return new JRBeanArrayDataSource((Object[]) value);
    }
    else {
        throw new IllegalArgumentException("Value [" + value + "] cannot be converted to a JRDataSource");
    }
}
项目:jasperreports    文件:VirtualizerApp.java   
private static JasperPrint fillReport(JRFileVirtualizer virtualizer) throws JRException
{
    long start = System.currentTimeMillis();

    // Virtualization works only with in memory JasperPrint objects.
    // All the operations will first fill the report and then export
    // the filled object.

    // creating the data source
    JRDataSource dataSource = new JREmptyDataSource(1000);

    // Preparing parameters
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

    // filling the report
    JasperPrint jasperPrint = JasperFillManager.fillReport("build/reports/VirtualizerReport.jasper", parameters, dataSource);

    virtualizer.setReadOnly(true);

    System.err.println("Filling time : " + (System.currentTimeMillis() - start));
    return jasperPrint;
}
项目:TrabalhoCrisParte2    文件:ReportUtils.java   
/**
 * Abre um relatório usando um datasource genérico.
 *
 * @param titulo Título usado na janela do relatório.
 * @param inputStream InputStream que contém o relatório.
 * @param parametros Parâmetros utilizados pelo relatório.
 * @param dataSource Datasource a ser utilizado pelo relatório.
 * @throws JRException Caso ocorra algum problema na execução do relatório
 */
public static void openReport(
        String titulo,
        InputStream inputStream,
        Map parametros,
        JRDataSource dataSource ) throws JRException {

    /*
     * Cria um JasperPrint, que é a versão preenchida do relatório,
     * usando um datasource genérico.
     */
    JasperPrint print = JasperFillManager.fillReport(
            inputStream, parametros, dataSource );

    // abre o JasperPrint em um JFrame
    viewReportFrame( titulo, print );

}
项目:hmftools    文件:VariantDataSource.java   
@NotNull
public static JRDataSource fromVariants(@NotNull final List<VariantReport> variantReports,
        @NotNull final HmfReporterData reporterData) {
    final DRDataSource variantDataSource =
            new DRDataSource(GENE_FIELD.getName(), POSITION_FIELD.getName(), VARIANT_FIELD.getName(), DEPTH_VAF_FIELD.getName(),
                    COSMIC_FIELD.getName(), COSMIC_NR_FIELD.getName(), HGVS_CODING_FIELD.getName(), HGVS_PROTEIN_FIELD.getName(),
                    CONSEQUENCE_FIELD.getName(), PLOIDY_TAF_FIELD.getName());

    for (final VariantReport variantReport : variantReports) {
        final String displayGene = reporterData.drupFilter().test(variantReport) ? variantReport.gene() + " *" : variantReport.gene();
        variantDataSource.add(displayGene, variantReport.variant().chromosomePosition(), variantReport.variantField(),
                variantReport.depthVafField(), variantReport.cosmicID(), stripCosmicIdentifier(variantReport.cosmicID()),
                variantReport.hgvsCoding(), variantReport.hgvsProtein(), variantReport.consequence(), variantReport.ploidyTafField());
    }

    return variantDataSource;
}
项目:jasperreports    文件:JRJpaQueryExecuter.java   
/**
 * Creates a data source out of the query result.
 * 
 * @return the data source
 */
protected JRDataSource createResultDatasource() {
    JRDataSource resDatasource;

    try {
        int pageSize = getPropertiesUtil().getIntegerProperty(dataset, 
                JRJpaQueryExecuterFactory.PROPERTY_JPA_QUERY_PAGE_SIZE,
                0);

        resDatasource = new JRJpaDataSource(this, pageSize);
    }
    catch (NumberFormatException e) {
        throw 
            new JRRuntimeException(
                EXCEPTION_MESSAGE_KEY_NUMERIC_TYPE_REQUIRED,
                new Object[]{JRJpaQueryExecuterFactory.PROPERTY_JPA_QUERY_PAGE_SIZE},
                e);
    }

    return resDatasource;
}
项目:jasperreports    文件:JRHibernateQueryExecuter.java   
/**
 * Creates an instance of {@link JRHibernateListDataSource JRHibernateListDataSource},
 * {@link JRHibernateIterateDataSource JRHibernateIterateDataSource} or
 * {@link JRHibernateScrollDataSource JRHibernateScrollDataSource}, depending on the 
 */
@Override
public JRDataSource createDatasource() throws JRException
{
    JRDataSource datasource = null;
    String queryString = getQueryString();

    if (session != null && queryString != null && queryString.trim().length() > 0)
    {
        createQuery(queryString);

        datasource = createResultDatasource();
    }

    return datasource;
}
项目:jasperreports    文件:JRCsvDataSourceProvider.java   
@Override
public JRDataSource create(JasperReport report) throws JRException
{
    JRCsvDataSource ds;
    if (reader != null)
    {
         ds = new JRCsvDataSource(reader);
    }
    else 
    {
        throw 
        new JRException(
            EXCEPTION_MESSAGE_KEY_CANNOT_FIND_SOURCE,
            (Object[])null);
    }

    ds.setDateFormat(dateFormat);
    ds.setNumberFormat(numberFormat);
    ds.setFieldDelimiter(fieldDelimiter);
    ds.setRecordDelimiter(recordDelimiter);
    ds.setColumnNames(columnNames);

    return ds;
}
项目:jasperreports    文件:JRFillDataset.java   
/**
 * Creates the data source from a connection.
 * 
 * @return the data source to be used
 * @throws JRException
 */
private JRDataSource createQueryDatasource() throws JRException
{
    if (query == null)
    {
        return null;
    }

    try
    {
        if (log.isDebugEnabled())
        {
            log.debug("Fill " + filler.fillerId + ": Creating " + query.getLanguage() + " query executer");
        }

        QueryExecuterFactory queryExecuterFactory = JRQueryExecuterUtils.getInstance(getJasperReportsContext()).getExecuterFactory(query.getLanguage());
        queryExecuter = queryExecuterFactory.createQueryExecuter(getJasperReportsContext(), this, parametersMap);
        filler.fillContext.setRunningQueryExecuter(queryExecuter);

        return queryExecuter.createDatasource();
    }
    finally
    {
        filler.fillContext.clearRunningQueryExecuter();
    }
}
项目:jasperreports    文件:BaseFillHandle.java   
protected BaseFillHandle (
        JasperReportsContext jasperReportsContext,
        JasperReport jasperReport,
        Map<String,Object> parameters,
        JRDataSource dataSource,
        Connection conn
        ) throws JRException
{
    this.jasperReportsContext = jasperReportsContext;
    this.jasperReport = jasperReport;
    this.parameters = parameters;
    this.dataSource = dataSource;
    this.conn = conn;
    this.filler = JRFiller.createReportFiller(jasperReportsContext, jasperReport);
    this.listeners = new ArrayList<AsynchronousFilllListener>();
    lock = this;
}
项目:jasperreports    文件:JRMondrianQueryExecuter.java   
@Override
public JRDataSource createDatasource() throws JRException
{
    JRDataSource dataSource = null;

    String queryStr = getQueryString();
    if (connection != null && queryStr != null)
    {
        if (log.isDebugEnabled())
        {
            log.debug("MDX query: " + queryStr);
        }

        Query query = connection.parseQuery(queryStr);
        result = connection.execute(query);
        logResult();

        dataSource = new JRMondrianDataSource(dataset, result);
    }

    return dataSource;
}
项目:Java-Danfe    文件:DanfeNfe.java   
private static void gerarDanfe(String url, List<String> emit, List<String> dest, List<String> nota, JRDataSource itens, String qrcode){
    try {
        // Teste
        //String compilado = System.getProperty("user.dir") + "/danfe_nfce_80.jasper";;
        String output = "danfe.pdf"; 
        map.put("emit", emit);
        map.put("dest", dest);
        map.put("nota", nota);
        map.put("qrcode", qrcode);
        // Relatório compilado
        JasperReport report = (JasperReport) JRLoader.loadObjectFromFile(url);
        //InputStream jasperStream = getClass().getResourceAsStream("/Foo.jasper");
        //JasperReport report = (JasperReport) JRLoader.loadObject(jasperStream);
        // Relatório nao compilado
        //JasperReport report = JasperCompileManager.compileReport(jrxml);
        JasperPrint print = JasperFillManager.fillReport(report, map, itens);
        JasperExportManager.exportReportToPdfFile(print, output);
    } catch (JRException e) {
        System.out.println("erro: "+e.getMessage());
    }
}
项目:Java-Danfe    文件:DanfeNfe.java   
private static void gerarDanfeNFe(String url, List<String> emit, List<String> dest, List<String> nota, JRDataSource itens) {
    try {
        // Teste
        //String compilado = System.getProperty("user.dir") + "/danfe_nfce_80.jasper";;
        String output = "danfe.pdf"; 
        map.put("emit", emit);
        map.put("dest", dest);
        map.put("nota", nota);
        // Relatório compilado
        JasperReport report = (JasperReport) JRLoader.loadObjectFromFile(url);
        JasperPrint print = JasperFillManager.fillReport(report, map, itens);
        JasperExportManager.exportReportToPdfFile(print, output);
    } catch (JRException e) {
        System.out.println("erro: "+e.getMessage());
    }
}
项目:Java-Danfe    文件:DanfeNfe.java   
private static void gerarDanfeNfse(String url, List<String> emit, List<String> dest, List<String> ser, List<String> nota, String xml, String logo) {
    try {
        // Teste
        //String compilado = System.getProperty("user.dir") + "/danfe_nfce_80.jasper";;
        String output = "danfe.pdf"; 
        map.put("emit", emit);
        map.put("dest", dest);
        map.put("ser", ser);
        map.put("nota", nota);
        map.put("logo", logo);
        // brasao
        String brasao = Paths.get(System.getProperty("user.dir"), "danfe","brasao.png").toAbsolutePath().toString();
        map.put("brasao", brasao);
        // JrDataSource
        JRDataSource jr = new JRXmlDataSource(xml);
        // Relatório compilado
        JasperReport report = (JasperReport) JRLoader.loadObjectFromFile(url);
        JasperPrint print = JasperFillManager.fillReport(report, map, jr);
        JasperExportManager.exportReportToPdfFile(print, output);
    } catch (JRException e) {
        System.out.println("erro: "+e.getMessage());
    }
}
项目:genomeartist    文件:JRDataSourceFinalResult.java   
/**
 * Obtin data source-ul pentru tabelul de gene
 * @param sourceResult
 * @return
 */
public static JRDataSource getDataSourceMapping(FinalResultItem sourceResult) {
    int imageWidth = DrawingConstants.REPORT_WIDTH;
    int imageHeight = sourceResult.getImageHeight(new JLabel());

    //Obtin canvasul pe care se va desena
    BufferedImage mappedImage = new BufferedImage(imageWidth, imageHeight,
         BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = (Graphics2D) mappedImage.getGraphics();

    //~~~~~~~~~Desenez resultatul final~~~~~~~~~~~~~~
    sourceResult.paintImage(g2d, imageWidth, imageHeight, Color.WHITE, Color.BLACK);

    //Convertesc vectorul de imagni intr-o singura imagine
    ImageVector splitedImages = ImageManipulation.splitImage(mappedImage,
            DrawingConstants.REPORT_MAPPING_CELL_HEIGHT);

    //Fac un data source
    return new JRDataSourceImageVector(splitedImages);
}
项目:genomeartist    文件:JRDataSourceFinalResult.java   
/**
 * Obtin data source-ul pentru tabelul de gene
 * @param sourceResult
 * @return
 */
public static JRDataSource getDataSourceGenes(FinalResultItem sourceResult) {
    //Calculez dimensiuniile componentelor
    LinkedHashSet<GeneItem> geneItemSanitizer = new LinkedHashSet<GeneItem>();
    IntervalMappingSet intervalMappingSet = sourceResult.getIntervalMappingSet();
    Iterator <IntervalMappingItem> iteratorMapping = intervalMappingSet.iterator();
    while (iteratorMapping.hasNext()) {
        IntervalMappingItem mappingItem = iteratorMapping.next();
        GeneItemWrapper geneItemWrapper = mappingItem.getGeneItemWrapper();

        //Pastrez genele pentru desenare ulterioara
        geneItemSanitizer.addAll(geneItemWrapper.getFullGeneVector());
    }

    //Vectorul de gene
    GeneVector geneVector = new GeneVector();
    geneVector.addAll(geneItemSanitizer);
    Collections.sort(geneVector);

    //Fac un data source
    return new JRDataSourceSubGenes(geneVector);
}
项目:ESJasperAdapter    文件:ESQueryExecuter.java   
@Override
public JRDataSource createDatasource() throws JRException {
    ESSearch connection = (ESSearch) ((Map<?, ?>) getParameterValue(JRParameter.REPORT_PARAMETERS_MAP))
            .get(JRParameter.REPORT_CONNECTION);
    if (connection == null) {
        connection = processConnection(reportParameters
                .get(JRParameter.REPORT_CONNECTION));
        if (connection == null) {
            throw new JRException("No ES connection");
        }
    }
    // We create a new connection
    // for the datasource based on
    // the one that was handed over
    // to us.
    ESSearch newSearch = connection.clone();
    newSearch.setSearch(getQueryString());

    esSearch = connection;
       logger.debug("Create new DataSource witha clone of the current connection.");
       logger.debug("Setting the search to query: " + getQueryString());
    return new ESDataSource(newSearch);
}
项目:PDFReporter-Studio    文件:ThriftQueryExecuter.java   
/**
 * Creates a new {@link ThriftDataSource} from the query and parameters
 */
public JRDataSource createDatasource() throws JRException {
    ThriftConnection connection = (ThriftConnection) ((Map<?, ?>) getParameterValue(JRParameter.REPORT_PARAMETERS_MAP)).get(ThriftDataSource.CONNECTION);
    if (connection == null) {
        logger.error("No Thrift connection");
        System.out.println("Testing as default connection");
        connection = (ThriftConnection) ((Map<?, ?>) getParameterValue(JRParameter.REPORT_PARAMETERS_MAP)).get(JRParameter.REPORT_CONNECTION);
        if (connection == null) {
            logger.error("No data source");
            return null;
        }
    }
    wrapper = new ThriftQueryWrapper(connection, getQueryString());
    boolean sorted = wrapper.sortFields != null && !wrapper.sortFields.isEmpty();
    if (sorted) {
        System.out.println("THRIFT: Fields will be sorted");
        sortResults(wrapper);
    } else {
        System.out.println("THRIFT: Record set is active");
    }
    return new ThriftDataSource(wrapper);
}
项目:karaku    文件:KarakuBaseReportDetail.java   
@Override
public void generateReport(KarakuReportDetails report, Align align,
        Map<String, Object> params, String type, T bean, Class<?> clazz) {

    try {
        JRDataSource datasource = new JRBeanCollectionDataSource(
                getDetails(bean));
        exportReport.exportDetailReport(report, align,
                withCriteriaVisible(), clazz, datasource, params, type);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_SUCCESS);
    } catch (Exception e) {
        log.warn("Can't create report", e);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_FAILURE);
    }

}
项目:karaku    文件:KarakuBaseReportDetail.java   
@Override
public void generateReport(String path, KarakuReportDetails report,
        Map<String, Object> params, String type, T bean, Class<?> clazz) {

    try {
        JRDataSource datasource = new JRBeanCollectionDataSource(
                getDetails(bean));
        exportReport.exportDetailReport(path, report, clazz, datasource,
                params, type);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_SUCCESS);
    } catch (Exception e) {
        log.warn(ERROR_MESSAGE, e);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_FAILURE);
    }

}
项目:karaku    文件:KarakuBaseReportDetail.java   
@Override
public void generateReport(String path, Map<String, Object> params,
        String type, T bean, Class<?> clazz) {

    try {
        JRDataSource datasource = new JRBeanCollectionDataSource(
                getDetails(bean));
        exportReport.exportReportStatic(path, datasource, params, type);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_SUCCESS);
    } catch (Exception e) {
        log.warn(ERROR_MESSAGE, e);
        controllerHelper.createGlobalFacesMessage(
                FacesMessage.SEVERITY_INFO, BASE_REPORT_CREATE_FAILURE);
    }

}
项目:kfs    文件:TravelReportFactoryServiceImpl.java   
/**
 * A {@link ReportInfo} can have one type that represents the structure that all data will be. This method determines what
 * that is by accessing the parameterized type of a setter method  who's getter returns a {@link JRDataSource} instance.
 *
 * @param report is the report to get the data class for
 * @return {@link Class} instance that is the type for the data
 */
protected Class findDataClassFor(final ReportInfo report) throws Exception {
    final Class reportClass = report.getClass();

    // Digging up all the setters
    for (final Field field : reportClass.getDeclaredFields()) {
        LOG.debug("Examinine field "+ field+ " with type "+ field.getType());
        if (field.getType().equals(JRDataSource.class)) {
            // get the dataset for this class
            final String setterName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            final Method setter = reportClass.getMethod(setterName, new Class[] {Collection.class});
            LOG.debug("Determining what that data class should be. Found dataset setter method "+ setter.getName());

            // Should only have one parameter
            final ParameterizedType methodParamType = (ParameterizedType) (setter.getGenericParameterTypes()[0]);
            return (Class) methodParamType.getActualTypeArguments()[0];
        }
    }
    return null;
}
项目:kfs    文件:TravelReportFactoryServiceImpl.java   
/**
 * Create a subreport {@link JRDesignSubreport}. Since all kinds of reports are created through the {@link TravelReportFactoryServiceImpl} class,
 * even sub report instances will be considered normal reports and created individually. This method just marks where in the
 * parent report to place the sub report. This does not actually create another report.
 *
 * @param report is the parent report
 * @field is the field that is a {@link SubReport}
 * @return {@link JRDesignSubreport} to be added to report
 */
protected JRDesignSubreport createSubreport(final ReportInfo report, final Field field) throws Exception {
    final JRDesignSubreport retval = new JRDesignSubreport(new JasperDesign());
    final JRDesignExpression dsExpression = new JRDesignExpression();
    final String getterName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
    dsExpression.setText("$P{report}." + getterName + "()");
    dsExpression.setValueClass(JRDataSource.class);
    retval.setDataSourceExpression(dsExpression);

    final JRDesignExpression expression = new JRDesignExpression();
    expression.setValueClass(JasperReport.class);
    expression.setText("$P{" + field.getName() + "Subreport}");
    retval.setExpression(expression);

    retval.setHeight(SUBREPORT_HEIGHT);

    return retval;
}
项目:kfs    文件:ReportGenerationServiceImpl.java   
/**
 * @see org.kuali.kfs.sys.batch.service.ReportGenerationService#generateReportToOutputStream(java.util.Map, java.lang.Object,
 *      java.lang.String, java.io.ByteArrayOutputStream)
 */
public void generateReportToOutputStream(Map<String, Object> reportData, Object dataSource, String template, ByteArrayOutputStream baos) {
    ClassPathResource resource = getReportTemplateClassPathResource(template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    if (resource == null || !resource.exists()) {
        throw new IllegalArgumentException("Cannot find the template file: " + template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
    }

    try {
        if (reportData != null && reportData.containsKey(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME)) {
            Map<String, String> subReports = (Map<String, String>) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME);
            String subReportDirectory = (String) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR);
            compileSubReports(subReports, subReportDirectory);
        }

        String designTemplateName = template.concat(ReportGeneration.DESIGN_FILE_EXTENSION);
        InputStream jasperReport = new FileInputStream(compileReportTemplate(designTemplateName));

        JRDataSource jrDataSource = JasperReportsUtils.convertReportData(dataSource);

         JasperRunManager.runReportToPdfStream(jasperReport, baos, decorateReportData(reportData), jrDataSource);
    }
    catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException("Fail to generate report.", e);
    }
}
项目:opennmszh    文件:ResourceCommandTest.java   
@Test
public void testDatasourceWithNoFilters() throws JRException {
    JRDataSource dataSource = new ResourceQueryCommand().executeCommand(getCommand());
    assertNotNull(dataSource);
    assertTrue(dataSource.next());

    JRDesignField pathField = new JRDesignField();
    pathField.setName("path");
    String pathVal = (String) dataSource.getFieldValue(pathField);
    assertNotNull(pathVal);
    assertTrue(String.format("Path does not match: %s", pathVal), pathVal.matches(".*src/test/resources/share/rrd/snmp/10/nsVpnMonitor/tun_id_1"));

    JRDesignField filterField = new JRDesignField();
    filterField.setName("icmp");
    String val = (String) dataSource.getFieldValue(filterField);
    assertNull(val);

}
项目:opennmszh    文件:ResourceCommandTest.java   
@Test
public void testDatasourceWithFilters() throws JRException {
    JRDataSource dataSource = new ResourceQueryCommand().executeCommand(getCommandWithFilter());
    assertNotNull(dataSource);
    assertTrue(dataSource.next());

    JRDesignField pathField = new JRDesignField();
    pathField.setName("path");
    assertNotNull("", dataSource.getFieldValue(pathField));

    JRDesignField filterField = new JRDesignField();
    filterField.setName("nsVpnMonBytesIn");

    String dsFieldValue = (String) dataSource.getFieldValue(filterField);
    assertNotNull(dsFieldValue);
    assertTrue(dsFieldValue.matches(".*src/test/resources/share/rrd/snmp/10/nsVpnMonitor/tun_id_1/nsVpnMonBytesIn.jrb"));
}
项目:dynamicreports-jasper    文件:JasperSubreportTest.java   
@Override
public JRDataSource evaluate(ReportParameters reportParameters) {
    int masterRowNumber = reportParameters.getReportRowNumber();
    String[] columns = new String[masterRowNumber];
    for (int i = 1; i <= masterRowNumber; i++) {
        columns[i - 1] = "column" + i;
    }
    DRDataSource dataSource = new DRDataSource(columns);

    for (int i = 1; i <= masterRowNumber; i++) {
        Object[] values = new Object[masterRowNumber];
        for (int j = 1; j <= masterRowNumber; j++) {
            values[j - 1] = "row" + i + "_column" + j;
        }
        dataSource.add(values);
    }

    return dataSource;
}
项目:OpenNMS    文件:ResourceCommandTest.java   
@Test
   public void testDatasourceWithNoFilters() throws JRException {
       JRDataSource dataSource = new ResourceQueryCommand().executeCommand(getCommand());
       assertNotNull(dataSource);
       assertTrue(dataSource.next());

       JRDesignField pathField = new JRDesignField();
       pathField.setName("path");
       String pathVal = (String) dataSource.getFieldValue(pathField);
       assertNotNull("", pathVal);
assertTrue(pathVal.matches(".*src/test/resources/share/rrd/snmp/10/nsVpnMonitor/tun_id_1"));

       JRDesignField filterField = new JRDesignField();
       filterField.setName("icmp");
       String val = (String) dataSource.getFieldValue(filterField);
       assertNull(val);

   }
项目:dynamicreports-jasper    文件:GroupSubtotal1Test.java   
@Override
protected JRDataSource createDataSource() {
    DRDataSource dataSource = new DRDataSource("field1", "field2", "field3");
    int count = 1;
    for (int i = 0; i < 3; i++) {
        dataSource.add("group1", "group1_1", count++);
    }
    for (int i = 0; i < 3; i++) {
        dataSource.add("group1", "group1_2", count++);
    }
    for (int i = 0; i < 3; i++) {
        dataSource.add("group2", "group2_1", count++);
    }
    for (int i = 0; i < 3; i++) {
        dataSource.add("group2", "group2_2", count++);
    }
    return dataSource;
}
项目:OpenNMS    文件:ResourceCommandTest.java   
@Test
public void testDatasourceWithFilters() throws JRException {
    JRDataSource dataSource = new ResourceQueryCommand().executeCommand(getCommandWithFilter());
    assertNotNull(dataSource);
    assertTrue(dataSource.next());

    JRDesignField pathField = new JRDesignField();
    pathField.setName("path");
    assertNotNull("", dataSource.getFieldValue(pathField));

    JRDesignField filterField = new JRDesignField();
    filterField.setName("nsVpnMonBytesIn");

    String dsFieldValue = (String) dataSource.getFieldValue(filterField);
    assertNotNull(dsFieldValue);
    assertTrue(dsFieldValue.matches(".*src/test/resources/share/rrd/snmp/10/nsVpnMonitor/tun_id_1/nsVpnMonBytesIn.jrb"));
}
项目:dynamicreports-jasper    文件:CrosstabPosition4Test.java   
@Override
protected JRDataSource createDataSource() {
    DRDataSource dataSource = new DRDataSource("field1", "field2", "field3", "field4");
    dataSource.add("a", "c", 106, 2d);
    dataSource.add("a", "c", 252, 3d);
    dataSource.add("a", "d", 312, 4d);
    dataSource.add("a", "d", 456, 5d);
    dataSource.add("b", "c", 515, 6d);
    dataSource.add("b", "c", 678, 7d);
    dataSource.add("b", "d", 779, 8d);
    dataSource.add("b", "d", 823, 9d);
    dataSource.add("c", "c", 515, 6d);
    dataSource.add("c", "c", 678, 7d);
    dataSource.add("c", "d", 779, 8d);
    dataSource.add("c", "d", 823, 9d);
    return dataSource;
}
项目:dynamicreports-jasper    文件:BooleanColumn3Test.java   
@Test
public void test() {
   try {
     JasperReportBuilder rb = createReport();
     JRDataSource dataSource = createDataSource();

     JasperReport report = rb.toJasperReport();
     Map<String, Object> params = new HashMap<String, Object>();
     params.putAll(rb.getJasperParameters());

     ByteArrayOutputStream bos = new ByteArrayOutputStream();
        JasperFillManager.fillReportToStream(report, bos, params, dataSource);

     JasperExportManager.exportReportToPdfStream(new ByteArrayInputStream(bos.toByteArray()), new ByteArrayOutputStream());

     bos.flush();
     bos.close();
   }
   catch ( Exception e ) {
    e.printStackTrace();
    Assert.fail(e.getMessage());
   }
}
项目:spring4-understanding    文件:AbstractJasperReportsView.java   
/**
 * Create a report using the given provider.
 * @param provider the JRDataSourceProvider to use
 * @return the created report
 */
protected JRDataSource createReport(JRDataSourceProvider provider) {
    try {
        JasperReport report = getReport();
        if (report == null) {
            throw new IllegalStateException("No main report defined for JRDataSourceProvider - " +
                    "specify a 'url' on this view or override 'getReport()'");
        }
        return provider.create(report);
    }
    catch (JRException ex) {
        throw new IllegalArgumentException("Supplied JRDataSourceProvider is invalid", ex);
    }
}
项目:spring4-understanding    文件:JasperReportsUtils.java   
/**
 * Convert the given report data value to a {@code JRDataSource}.
 * <p>In the default implementation, a {@code JRDataSource},
 * {@code java.util.Collection} or object array is detected.
 * The latter are converted to {@code JRBeanCollectionDataSource}
 * or {@code JRBeanArrayDataSource}, respectively.
 * @param value the report data value to convert
 * @return the JRDataSource (never {@code null})
 * @throws IllegalArgumentException if the value could not be converted
 * @see net.sf.jasperreports.engine.JRDataSource
 * @see net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
 * @see net.sf.jasperreports.engine.data.JRBeanArrayDataSource
 */
public static JRDataSource convertReportData(Object value) throws IllegalArgumentException {
    if (value instanceof JRDataSource) {
        return (JRDataSource) value;
    }
    else if (value instanceof Collection) {
        return new JRBeanCollectionDataSource((Collection<?>) value);
    }
    else if (value instanceof Object[]) {
        return new JRBeanArrayDataSource((Object[]) value);
    }
    else {
        throw new IllegalArgumentException("Value [" + value + "] cannot be converted to a JRDataSource");
    }
}
项目:openbravo-brazil    文件:ReportingUtils.java   
/**
 * @see ReportingUtils#exportJR(String, ExportType, Map, File, boolean, ConnectionProvider,
 *      JRDataSource, Map)
 */
public static void exportJR(String jasperFilePath, ExportType expType,
    Map<String, Object> parameters, String strFileName, boolean addProcessDefinitionParameters,
    ConnectionProvider connectionProvider, JRDataSource data,
    Map<Object, Object> additionalExportParameters) throws OBException {
  File target = new File(getTempFolder(), strFileName);
  exportJR(jasperFilePath, expType, parameters, target, addProcessDefinitionParameters,
      connectionProvider, data, additionalExportParameters);
}
项目:openbravo-brazil    文件:ReportingUtils.java   
/**
 * @see ReportingUtils#exportJR(String, ExportType, Map, File, boolean, ConnectionProvider,
 *      JRDataSource, Map, boolean)
 */
public static void exportJR(String jasperFilePath, ExportType expType,
    Map<String, Object> parameters, File target, boolean addProcessDefinitionParameters,
    ConnectionProvider connectionProvider, JRDataSource data,
    Map<Object, Object> additionalExportParameters) throws OBException {
  exportJR(jasperFilePath, expType, parameters, target, addProcessDefinitionParameters,
      connectionProvider, data, additionalExportParameters, false);
}
项目:openbravo-brazil    文件:ReportingUtils.java   
/**
 * @see ReportingUtils#exportJR(String, ExportType, Map, OutputStream, boolean,
 *      ConnectionProvider, JRDataSource, Map, boolean)
 */
public static void exportJR(String jasperFilePath, ExportType expType,
    Map<String, Object> parameters, OutputStream outputStream,
    boolean addProcessDefinitionParameters, ConnectionProvider connectionProvider,
    JRDataSource data, Map<Object, Object> additionalExportParameters) throws OBException {
  exportJR(jasperFilePath, expType, parameters, outputStream, addProcessDefinitionParameters,
      connectionProvider, data, additionalExportParameters, false);
}
项目:openbravo-brazil    文件:HttpSecureAppServlet.java   
protected void renderJR(VariablesSecureApp variables, HttpServletResponse response,
    String strReportName, String strFileName, String strOutputType,
    HashMap<String, Object> designParameters, FieldProvider[] data,
    Map<Object, Object> exportParameters, boolean forceRefresh) throws ServletException {
  if (data != null) {
    renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
        new JRFieldProviderDataSource(data, variables.getJavaDateFormat()), exportParameters,
        forceRefresh);
  } else {
    renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
        (JRDataSource) null, exportParameters, forceRefresh);
  }
}
项目:4mila-1.0    文件:GenericTableDynamicReport.java   
@Override
public JRDataSource evaluate(ReportParameters reportParameters) {
  int masterRowNumber = reportParameters.getReportRowNumber();
  GenericTableReportContent reportContent = contents.get(masterRowNumber - 1);
  ITable table = reportContent.getTable();
  JRMapCollectionDataSource ds = new JRMapCollectionDataSource(DataSourceUtility.createCollectionFromTable(table, true, false));
  return ds;
}
项目:hmftools    文件:CopyNumberDataSource.java   
@NotNull
public static JRDataSource fromCopyNumbers(@NotNull final List<CopyNumberReport> copyNumbers) {
    final DRDataSource copyNumberDatasource =
            new DRDataSource(CHROMOSOME_FIELD.getName(), BAND_FIELD.getName(), GENE_FIELD.getName(), COPY_NUMBER_TYPE_FIELD.getName(),
                    COPY_NUMBER_FIELD.getName());

    for (final CopyNumberReport copyNumber : copyNumbers) {
        copyNumberDatasource.add(copyNumber.chromosome(), copyNumber.chromosomeBand(), copyNumber.gene(), copyNumber.description(),
                Integer.toString(copyNumber.copyNumber()));
    }
    return copyNumberDatasource;
}
项目:hmftools    文件:GeneDisruptionDataSource.java   
@NotNull
public static JRDataSource fromGeneDisruptions(@NotNull List<GeneDisruptionData> disruptions) {

    final DRDataSource dataSource =
            new DRDataSource(GENE_FIELD.getName(), TRANSCRIPT_FIELD.getName(), POSITION_FIELD.getName(), SV_TYPE_FIELD.getName(),
                    SV_PARTNER_POSITION_FIELD.getName(), SV_ORIENTATION_FIELD.getName(), SV_GENE_CONTEXT.getName(), SV_VAF.getName());

    disruptions.forEach(
            g -> dataSource.add(g.geneName(), g.transcript(), g.location(), g.type(), g.partner(), g.orientation(), g.geneContext(),
                    g.vaf()));

    return dataSource;
}