Java Code Examples for org.pentaho.reporting.libraries.resourceloader.ResourceManager#create()

The following examples show how to use org.pentaho.reporting.libraries.resourceloader.ResourceManager#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractXmlReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses an external file using LibLoader and returns the parsed result as an object of type
 * <code>targetClass</code>. The file is given as relative pathname (relative to the current source file). The current
 * helper-methods are used as parse-parameters for the external parsing.
 *
 * @param file        the file to be parsed.
 * @param targetClass the target type of the parse operation.
 * @param map         the map of parse parameters.
 * @return the result, never null.
 * @throws ParseException           if parsing the result failed for some reason.
 * @throws ResourceLoadingException if there was an IO error loading the resource.
 * @see #deriveParseParameters()
 */
protected Object performExternalParsing( final String file, final Class targetClass, final Map map )
  throws ParseException, ResourceLoadingException {
  try {
    final ResourceManager resourceManager = rootHandler.getResourceManager();
    final ResourceKey source = rootHandler.getSource();

    final ResourceKey target = resourceManager.deriveKey( source, file, map );
    final DependencyCollector dc = rootHandler.getDependencyCollector();

    final Resource resource = resourceManager.create( target, rootHandler.getContext(), targetClass );
    dc.add( resource );
    return resource.getResource();
  } catch ( ResourceLoadingException rle ) {
    throw rle;
  } catch ( ResourceException e ) {
    throw new ParseException( "Failure while loading data: " + file, e, getLocator() );
  }

}
 
Example 2
Source File: StaticDocumentMetaData.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public StaticDocumentMetaData( final ResourceManager resourceManager,
                               final ResourceKey bundleKey ) throws ResourceException {
  if ( resourceManager == null ) {
    throw new NullPointerException();
  }
  if ( bundleKey == null ) {
    throw new NullPointerException();
  }


  this.resourceManager = resourceManager;
  this.bundleKey = bundleKey;

  // A bundle without a manifest is not valid.
  final ResourceKey manifestDataKey = resourceManager.deriveKey( bundleKey, "/META-INF/manifest.xml" );
  final Resource manifestDataResource = resourceManager.create( manifestDataKey, null, BundleManifest.class );
  manifest = (BundleManifest) manifestDataResource.getResource();

  metaData = createMetaData( resourceManager, bundleKey );

  bundleType = readBundleType();
  if ( bundleType == null ) {
    bundleType = manifest.getMimeType( "/" );
  }
  // bundle type can still be null.
}
 
Example 3
Source File: ReportReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Starts parsing.
 *
 * @param attrs
 *          the attributes.
 * @throws org.xml.sax.SAXException
 *           if there is a parsing error.
 */
protected void startParsing( final Attributes attrs ) throws SAXException {
  targetType = attrs.getValue( getUri(), "target-type" );
  if ( targetType == null ) {
    throw new ParseException( "Mandatory attribute 'target-type' is missing.", getLocator() );
  }
  final String href = attrs.getValue( getUri(), "href" );
  if ( href == null ) {
    throw new ParseException( "Mandatory attribute 'href' is missing.", getLocator() );
  }

  try {
    final ResourceManager resourceManager = getRootHandler().getResourceManager();
    final ResourceKey key = resourceManager.deriveKey( getRootHandler().getSource(), href );
    final Resource resource = resourceManager.create( key, null, MasterReport.class );
    report = (MasterReport) resource.getResource();
  } catch ( ResourceException re ) {
    throw new ParseException( "Mandatory attribute 'href' is not pointing to a valid report.", re, getLocator() );
  }
}
 
Example 4
Source File: ReportGenerator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses the report from a given URL.
 *
 * @param file
 *          the report definition location.
 * @param contentBase
 *          the report's context (used to load content that has been referenced with relative URLs).
 * @return the parsed report.
 * @throws ResourceException
 *           if parsing or loading failed for some reason.
 */
private MasterReport parse( final URL file, final URL contentBase ) throws ResourceException {
  final ResourceManager resourceManager = new ResourceManager();
  final ResourceKey contextKey = resourceManager.createKey( contentBase );

  // Build the main key. That key also contains all context/parse-time
  // parameters as they will influence the resulting report. It is not
  // wise to keep caching independent from that.
  final HashMap map = new HashMap();
  final Iterator it = this.helperObjects.keySet().iterator();
  while ( it.hasNext() ) {
    final String name = (String) it.next();
    map.put( new FactoryParameterKey( name ), helperObjects.get( name ) );
  }

  final ResourceKey key = resourceManager.createKey( file, map );
  final Resource resource = resourceManager.create( key, contextKey, MasterReport.class );
  return (MasterReport) resource.getResource();
}
 
Example 5
Source File: ReportGenerator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses an XML file which is loaded using the given file. All needed relative file- and resourcespecification are
 * loaded using the parent directory of the file <code>file</code> as base.
 *
 * @param file
 *          the report template file.
 * @return the parsed report.
 * @throws java.io.IOException
 *           if an I/O error occurs.
 */
public MasterReport parseReport( final File file ) throws IOException, ResourceException {
  if ( file == null ) {
    throw new NullPointerException();
  }
  if ( file.isDirectory() ) {
    throw new IOException( "File is not a directory." );
  }
  final File contentBase = file.getCanonicalFile().getParentFile();
  final ResourceManager resourceManager = new ResourceManager();
  final ResourceKey contextKey = resourceManager.createKey( contentBase );

  // Build the main key. That key also contains all context/parse-time
  // parameters as they will influence the resulting report. It is not
  // wise to keep caching independent from that.
  final HashMap map = new HashMap();
  final Iterator it = this.helperObjects.keySet().iterator();
  while ( it.hasNext() ) {
    final String name = (String) it.next();
    map.put( new FactoryParameterKey( name ), helperObjects.get( name ) );
  }

  final ResourceKey key = resourceManager.createKey( file, map );
  final Resource resource = resourceManager.create( key, contextKey, MasterReport.class );
  return (MasterReport) resource.getResource();
}
 
Example 6
Source File: MetaDataReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Starts parsing.
 *
 * @param attrs
 *          the attributes.
 * @throws SAXException
 *           if there is a parsing error.
 */
protected void startParsing( final Attributes attrs ) throws SAXException {
  super.startParsing( attrs );

  final ResourceManager resourceManager = getRootHandler().getResourceManager();
  final ResourceKey context = getRootHandler().getContext();

  final Configuration configuration = ClassicEngineBoot.getInstance().getGlobalConfig();
  final Iterator keys = configuration.findPropertyKeys( ElementMetaDataParser.GLOBAL_INCLUDES_PREFIX );
  while ( keys.hasNext() ) {
    final String key = (String) keys.next();
    final String href = configuration.getConfigProperty( key );
    if ( StringUtils.isEmpty( href, true ) ) {
      continue;
    }

    try {
      final ResourceKey resourceKey = resourceManager.deriveKey( context, href );
      final Resource resource = resourceManager.create( resourceKey, null, GlobalMetaDefinition.class );
      globalMetaDefinition.merge( (GlobalMetaDefinition) resource.getResource() );
    } catch ( ResourceException e ) {
      logger.warn( "Failed to parse included global definitions: " + getLocator(), e );
    }
  }

}
 
Example 7
Source File: IncludeGlobalMetaDataReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Starts parsing.
 *
 * @param attrs
 *          the attributes.
 * @throws SAXException
 *           if there is a parsing error.
 */
protected void startParsing( final Attributes attrs ) throws SAXException {
  final String href = attrs.getValue( getUri(), "src" );
  if ( href == null ) {
    throw new ParseException( "Required attribute 'src' is missing", getLocator() );
  }

  final ResourceManager resourceManager = getRootHandler().getResourceManager();
  final ResourceKey context = getRootHandler().getContext();
  try {
    final ResourceKey resourceKey = resourceManager.deriveKey( context, href );
    final Resource resource = resourceManager.create( resourceKey, null, GlobalMetaDefinition.class );
    result = (GlobalMetaDefinition) resource.getResource();
  } catch ( ResourceException e ) {
    throw new ParseException( "Failed to parse included global definitions", e, getLocator() );
  }

  if ( globalMetaDefinition != null ) {
    globalMetaDefinition.merge( result );
  }
}
 
Example 8
Source File: SampleReport.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String computeNameFromReport( final ResourceManager resourceManager, final ResourceKey key ) {
  try {
    final Resource res = resourceManager.create( key, null, new Class[] { MasterReport.class } );
    final MasterReport rawResource = (MasterReport) res.getResource();
    final Object possibleTitle = rawResource.getName();
    if ( possibleTitle != null ) {
      return possibleTitle.toString();
    }
    return null;
  } catch ( ResourceException re ) {
    return null;
  }
}
 
Example 9
Source File: StyleSheetHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Receive notification of a import statement in the style sheet.
 *
 * @param uri                 The URI of the imported style sheet.
 * @param media               The intended destination media for style information.
 * @param defaultNamespaceURI The default namespace URI for the imported style sheet.
 * @throws CSSException Any CSS exception, possibly wrapping another exception.
 */
public void importStyle( String uri,
                         SACMediaList media,
                         String defaultNamespaceURI )
  throws CSSException {
  //  instantiate a new parser and parse the stylesheet.
  final ResourceManager manager = getResourceManager();
  if ( manager == null ) {
    // there is no source set, so we have no resource manager, and thus
    // we do no parsing.
    //
    // This should only be the case if we parse style-values; in that case
    // include-statement are not supported anyway.
    return;
  }
  try {
    CSSParserContext.getContext().setDefaultNamespace( defaultNamespaceURI );
    final ResourceKey key;
    if ( source == null ) {
      key = manager.createKey( uri );
    } else {
      key = manager.deriveKey( source, uri );
    }

    final Resource res = manager.create( key, source, StyleSheet.class );
    if ( res == null ) {
      return;
    }
    final StyleSheet styleSheet = (StyleSheet) res.getResource();
    this.styleSheet.addStyleSheet( styleSheet );
  } catch ( ResourceException e ) {
    // ignore ..
  } finally {
    CSSParserContext.getContext().setStyleKeyRegistry( styleKeyRegistry );
    CSSParserContext.getContext().setSource( getSource() );
    CSSParserContext.getContext().setNamespaces( namespaces );
    CSSParserContext.getContext().setDefaultNamespace( defaultNamespace );
  }
}
 
Example 10
Source File: SampleReport.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String computeNameFromMetadata( final ResourceManager resourceManager, final ResourceKey key ) {
  try {
    final Resource res = resourceManager.create( key, null, new Class[] { DocumentBundle.class } );
    final DocumentBundle rawResource = (DocumentBundle) res.getResource();
    final Object possibleTitle = rawResource.getMetaData().getBundleAttribute
      ( ODFMetaAttributeNames.DublinCore.NAMESPACE, ODFMetaAttributeNames.DublinCore.TITLE );
    if ( possibleTitle != null ) {
      return possibleTitle.toString();
    }
    return null;
  } catch ( ResourceException re ) {
    return null;
  }
}
 
Example 11
Source File: LookAndFeelStep.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String computeNameFromReport( final ResourceManager resourceManager, final ResourceKey key ) {
  try {
    final Resource res = resourceManager.create( key, null, new Class[] { MasterReport.class } );
    final MasterReport rawResource = (MasterReport) res.getResource();
    final Object possibleTitle = rawResource.getName();
    if ( possibleTitle != null ) {
      return possibleTitle.toString();
    }
    return null;
  } catch ( ResourceException re ) {
    return null;
  }
}
 
Example 12
Source File: LookAndFeelStep.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String computeNameFromMetadata( final ResourceManager resourceManager, final ResourceKey key ) {
  try {
    final Resource res = resourceManager.create( key, null, new Class[] { DocumentBundle.class } );
    final DocumentBundle rawResource = (DocumentBundle) res.getResource();
    final Object possibleTitle = rawResource.getMetaData().getBundleAttribute
      ( ODFMetaAttributeNames.DublinCore.NAMESPACE, ODFMetaAttributeNames.DublinCore.TITLE );
    if ( possibleTitle != null ) {
      return possibleTitle.toString();
    }
    return null;
  } catch ( ResourceException re ) {
    return null;
  }
}
 
Example 13
Source File: ExternalElementType.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Object filter( final ExpressionRuntime runtime, final ReportElement element, final Object value ) {
  if ( value instanceof Element ) {
    return value;
  }

  try {
    final ResourceKey contentBase = runtime.getProcessingContext().getContentBase();
    final ResourceManager resManager = runtime.getProcessingContext().getResourceManager();
    final Object contentBaseValue =
        element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.CONTENT_BASE );
    final ResourceKey key = resManager.createOrDeriveKey( contentBase, value, contentBaseValue );
    if ( key == null ) {
      return null;
    }

    final Object targetRaw = element.getAttribute( AttributeNames.Core.NAMESPACE, AttributeNames.Core.TARGET_TYPE );
    final Class target;
    if ( targetRaw instanceof String ) {
      final ClassLoader loader = ObjectUtilities.getClassLoader( ExternalElementType.class );
      target = Class.forName( (String) targetRaw, false, loader );

      if ( target == null ) {
        return null;
      }
    } else {
      target = SubReport.class;
    }

    final Resource resource = resManager.create( key, contentBase, target );
    final Object resourceContent = resource.getResource();
    if ( resourceContent instanceof Element ) {
      return resourceContent;
    }
  } catch ( Exception e ) {
    logger.warn( "Failed to load content using value " + value, e );
  }
  return null;
}
 
Example 14
Source File: ReportGenerator.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parses the report from a given SAX-InputSource.
 *
 * @param input
 *          the report definition location.
 * @param contentBase
 *          the report's context (used to load content that has been referenced with relative URLs).
 * @return the parsed report.
 * @throws ResourceException
 *           if parsing or loading failed for some reason.
 * @throws IOException
 *           if an IO-related error occurs.
 */
public MasterReport parseReport( final InputSource input, final URL contentBase ) throws IOException,
  ResourceException {
  if ( input.getCharacterStream() != null ) {
    // Sourceforge Bug #1712734. We cannot safely route the character-stream through libloader.
    // Therefore we skip libloader and parse the report directly. This is for backward compatibility,
    // all other xml-based objects will still rely on LibLoader.

    return parseReportDirectly( input, contentBase );
  }

  final byte[] bytes = extractData( input );
  final ResourceManager resourceManager = new ResourceManager();
  final ResourceKey contextKey;
  if ( contentBase != null ) {
    contextKey = resourceManager.createKey( contentBase );
  } else {
    contextKey = null;
  }
  final HashMap map = new HashMap();

  final Iterator it = this.helperObjects.keySet().iterator();
  while ( it.hasNext() ) {
    final String name = (String) it.next();
    map.put( new FactoryParameterKey( name ), helperObjects.get( name ) );
  }

  final ResourceKey key = resourceManager.createKey( bytes, map );
  final Resource resource = resourceManager.create( key, contextKey, MasterReport.class );
  return (MasterReport) resource.getResource();
}
 
Example 15
Source File: KettleTransFromFileProducer.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected TransMeta loadTransformation( final Repository repository,
                                        final ResourceManager resourceManager,
                                        final ResourceKey contextKey )
  throws ReportDataFactoryException, KettleException {
  if ( transformationFile == null ) {
    throw new ReportDataFactoryException( "No Transformation file given" );
  }

  if ( resourceManager == null || contextKey == null ) {
    return new TransMeta( transformationFile, repository );
  }

  try {
    final ResourceKey resourceKey = createKey( resourceManager, contextKey );
    final Resource resource = resourceManager.create( resourceKey, contextKey, Document.class );
    final Document document = (Document) resource.getResource();
    final Node node = XMLHandler.getSubNode( document, TransMeta.XML_TAG );
    final TransMeta meta = new TransMeta();
    meta.loadXML( node, repository, true, null, null );
    final String filename = computeFullFilename( resourceKey );
    if ( filename != null ) {
      logger.debug( "Computed Transformation Location: " + filename );
      meta.setFilename( filename );
    } else {
      logger.debug( "No Computed Transformation Location, using raw name: " + transformationFile );
      meta.setFilename( transformationFile );
    }
    return meta;
  } catch ( ResourceException re ) {
    throw new ReportDataFactoryException( "Unable to load Kettle-Transformation", re );
  }
}
 
Example 16
Source File: MemDocBundleUpdateTest.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testBug() throws IOException, ResourceException, InterruptedException {
  final Properties p1 = new Properties();
  p1.setProperty( "key", "value1" );

  final MemoryDocumentBundle bundle = new MemoryDocumentBundle();
  bundle.getWriteableDocumentMetaData().setBundleType( "text/plain" );
  final OutputStream outputStream = bundle.createEntry( "test.properties", "text/plain" );
  p1.store( outputStream, "run 1" );
  outputStream.close();

  final ResourceManager resourceManager = bundle.getResourceManager();
  final ResourceKey key = resourceManager.deriveKey( bundle.getBundleMainKey(), "test.properties" );
  final Resource res1 = resourceManager.create( key, null, Properties.class );
  assertEquals( p1, res1.getResource() );

  bundle.removeEntry( "test.properties" );

  final Properties p2 = new Properties();
  p2.setProperty( "key", "value2" );

  final OutputStream outputStream2 = bundle.createEntry( "test.properties", "text/plain" );
  p2.store( outputStream2, "run 2" );
  outputStream2.close();

  final Resource res2 = resourceManager.create( key, null, Properties.class );
  assertEquals( p2, res2.getResource() );
}
 
Example 17
Source File: FunctionUtilities.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static CSSResourceValue loadResource( final DocumentContext process,
                                             final Object value,
                                             final Class[] type )
  throws FunctionEvaluationException {
  // ok, this is going to be expensive. Kids, you dont wanna try this at home ...
  final ResourceManager manager = process.getResourceManager();
  final ResourceKey baseKey = process.getContextKey();
  try {
    final ResourceKey key;
    if ( value instanceof ResourceKey ) {
      key = (ResourceKey) value;
    } else if ( baseKey == null ) {
      key = manager.createKey( value );
    } else if ( value instanceof String ) {
      key = manager.deriveKey( baseKey, (String) value );
    } else {
      throw new FunctionEvaluationException
        ( "Failed to create URI: Resource loading failed: Key not derivable" );
    }

    final Resource res = manager.create( key, baseKey, type );
    return new CSSResourceValue( res );
  } catch ( Exception e ) {
    throw new FunctionEvaluationException
      ( "Failed to create URI: Resource loading failed: " + e.getMessage(), e );
  }
}
 
Example 18
Source File: AbstractChartExpression.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void configureChart( final JFreeChart chart ) {
  // Misc Properties
  final TextTitle chartTitle = chart.getTitle();
  if ( chartTitle != null ) {
    final Font titleFont = Font.decode( getTitleFont() );
    chartTitle.setFont( titleFont );
  }

  if ( isAntiAlias() == false ) {
    chart.setAntiAlias( false );
  }

  chart.setBorderVisible( isShowBorder() );

  final Color backgroundColor = parseColorFromString( getBackgroundColor() );
  if ( backgroundColor != null ) {
    chart.setBackgroundPaint( backgroundColor );
  }

  if ( plotBackgroundColor != null ) {
    chart.getPlot().setBackgroundPaint( plotBackgroundColor );
  }
  chart.getPlot().setBackgroundAlpha( plotBackgroundAlpha );
  chart.getPlot().setForegroundAlpha( plotForegroundAlpha );
  final Color borderCol = parseColorFromString( getBorderColor() );
  if ( borderCol != null ) {
    chart.setBorderPaint( borderCol );
  }

  //remove legend if showLegend = false
  if ( !isShowLegend() ) {
    chart.removeLegend();
  } else { //if true format legend
    final LegendTitle chLegend = chart.getLegend();
    if ( chLegend != null ) {
      final RectangleEdge loc = translateEdge( legendLocation.toLowerCase() );
      if ( loc != null ) {
        chLegend.setPosition( loc );
      }
      if ( getLegendFont() != null ) {
        chLegend.setItemFont( Font.decode( getLegendFont() ) );
      }
      if ( !isDrawLegendBorder() ) {
        chLegend.setBorder( BlockBorder.NONE );
      }
      if ( legendBackgroundColor != null ) {
        chLegend.setBackgroundPaint( legendBackgroundColor );
      }
      if ( legendTextColor != null ) {
        chLegend.setItemPaint( legendTextColor );
      }
    }

  }

  final Plot plot = chart.getPlot();
  plot.setNoDataMessageFont( Font.decode( getLabelFont() ) );

  final String message = getNoDataMessage();
  if ( message != null ) {
    plot.setNoDataMessage( message );
  }

  plot.setOutlineVisible( isChartSectionOutline() );

  if ( backgroundImage != null ) {
    if ( plotImageCache != null ) {
      plot.setBackgroundImage( plotImageCache );
    } else {
      final ExpressionRuntime expressionRuntime = getRuntime();
      final ProcessingContext context = expressionRuntime.getProcessingContext();
      final ResourceKey contentBase = context.getContentBase();
      final ResourceManager manager = context.getResourceManager();
      try {
        final ResourceKey key = createKeyFromString( manager, contentBase, backgroundImage );
        final Resource resource = manager.create( key, null, Image.class );
        final Image image = (Image) resource.getResource();
        plot.setBackgroundImage( image );
        plotImageCache = image;
      } catch ( Exception e ) {
        logger.error( "ABSTRACTCHARTEXPRESSION.ERROR_0007_ERROR_RETRIEVING_PLOT_IMAGE", e ); //$NON-NLS-1$
        throw new IllegalStateException( "Failed to process chart" );
      }
    }
  }
}