BIRT PDF render: fonts register time - pdf

We use BIRT since version 2 (currently using 4.2.2) and have always been plagued by the PDF (itext?) fonts register time.
org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManagerFactory$2 run
INFO: register fonts in c:/windows/fonts cost:17803ms
This process only occurs the first time the render is used. Subsequent renders are not problematic.
The problem seems to be the time wasted when accessing ALL the system connected DRIVES.
Editing the fontsConfig.xml in org.eclipse.birt.report.engine.fonts plugin, reducing the search paths does not resolve the issue. ALL connected drives are accessed by BIRT.
<font-paths>
<path path="/windows/fonts" />
</font-paths>
Is there a simple solution for this without having to render a "dummy" report to initialize BIRT in the background??

This isn't necessarily a solution, but potentially another option as a workaround that I came up with after we noticed the same issue and did some investigating. It's also (IMO) better than generating a dummy report.
On startup (or at some other point depending on your needs), make the following call:
FontMappingManagerFactory.getInstance().getFontMappingManager(format, Locale.getDefault());
Why?
BIRT uses com.lowagie.text.FontFactory (iText) to register the fonts. Calls to that class are made from
org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManagerFactory which also spits out the log entries given in the question.
Within FontMappingManagerFactory we can see where the log entries are coming from:
private static void registerFontPath( final String fontPath )
{
AccessController.doPrivileged( new PrivilegedAction<Object>( ) {
public Object run( )
{
long start = System.currentTimeMillis( );
File file = new File( fontPath );
if ( file.exists( ) )
{
if ( file.isDirectory( ) )
{
FontFactory.registerDirectory( fontPath );
}
else
{
FontFactory.register( fontPath );
}
}
long end = System.currentTimeMillis( );
logger.info( "register fonts in " + fontPath + " cost:"
+ ( end - start ) + "ms" ); // <-- Here!
return null;
}
} );
}
Working backwards, we see that registerFontPath(String) is called by loadFontMappingConfig(URL), etc etc resulting in the following call hierarchy:
getFontMappingManager(String, Locale)
`-- createFontMappingManager(String, Locale)
`-- loadFontMappingConfig(String)
`-- loadFontMappingConfig(URL)
`-- registerFontPath(String)
And getFontMappingManager(String, Locale) is the public method we can call. More importantly, however, is that the method also caches the FontMappingManager that gets created:
public synchronized FontMappingManager getFontMappingManager(
String format, Locale locale )
{
HashMap managers = (HashMap) cachedManagers.get( format );
if ( managers == null )
{
managers = new HashMap( );
cachedManagers.put( format, managers );
}
FontMappingManager manager = (FontMappingManager) managers.get( locale );
if ( manager == null )
{
manager = createFontMappingManager( format, locale );
managers.put( locale, manager );
}
return manager;
}
As a result, when you're ready to go generate your PDF, it will already be in the cache and BIRT won't have to go call down to the FontFactory and re-register the fonts.
But what about the format String?
This bit is some speculation, but I think the valid options are the OUTPUT_FORMAT_XXX Strings in IRenderOption. For our purposes I debugged to see that we want the String to be pdf. Considering that's also conveniently the desired output format, I assume IRenderOption.OUTPUT_FORMAT_PDF is the route to go.
If you're ultimately creating both PDFs and HTML files, it appears that you could make the call twice (once with IRenderOption.OUTPUT_FORMAT_PDF and once with IRenderOption.OUTPUT_FORMAT_HTML) and only the font config files which are different will be considered (ie. you won't be reading from c:/windows/fonts twice).
All that said, take this with a grain of salt. I believe this is completely safe, since the purpose of getFontMappingManager(String, Locale) is to get an object for accessing available fonts, etc., and it conveniently caches the result. However, if that were to change in the future you may end up with a tricky-to-find bug on your hands.

I would suggest that you can modify the fontsConfig.xml and remove the fonts that you no longer need. Also remove the drives that you dont want birt to check for fonts.

Related

why read tsconfig.json using readConfigFile instead of directly requiring the path of tsconfig.json?

Upon investigating create-react-app's configuration, I found something interesting.
// config/modules.js
...
if (hasTsConfig) {
const ts = require(resolve.sync("typescript", {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
...
Unlike reading jsconfig.json file using direct require(paths.appJsConfig), why is here using resolve.sync and ts.readConfigFile to read the tsconfig.json?
...
if (hasTsConfig) {
config = require(paths.appTsConfig)
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
...
If I change the code like just above, the result is same. (at least the console output is same.)
There must be a reason why create-react-app using such a complicated way to read the typescript config file.
Why is that?
The ts config reader is a bit smarter than simply reading and parsing a json file. There's two differences I can think of right now:
in tsconfig files, you can use comments. JSON.parse will throw an exception because / is not an allowed character at an arbitrary position
ts config files can extend each other. Simply parsing a JSON file will ignore the extension and you'll receive a config object that doesn't represent what typescript actually uses.

Mojolicious template cache is stale

I'm currently developing a small single-page Web app using Mojolicious. The app has a Javascript frontend (using Backbone) that talks to a REST-ish API; the layout of the source is roughly:
use Mojolicious::Lite;
# ... setup code ...
get '/' => sub {
my $c = shift;
# fetch+stash data for bootstrapped collections...
$c->render('app_template');
};
get '/api_endpoint' => sub {
my $c = shift;
# fetch appropriate API data...
$c->render(json => $response);
};
# ... more API endpoints ...
app->start;
The app template uses EP, but very minimally; the only server-side template directives just insert JSON for bootstrapped collections. It's deployed via Apache as a plain CGI script. (This isn't optimal, but it's for low-traffic internal use, and more intricate server configuration is problematic in context.) Perl CGI is configured via mod_perl.
This works most of the time, but occasionally the renderer somehow gets the idea that it should cache the template and ignore changes to it. The debug records in error_log show "Rendering cached template" rather than the normal "Rendering template", and my new changes to the template stop appearing in the browser. I can't find a reliable way to stop this, though it will eventually stop on its own according to conditions I can't discern.
How can I make the app notice template changes reliably? Alternatively, how can I disable template caching completely?
How can I make the app notice template changes reliably?
This is what the morbo development server is for. Morbo wouldn't be used for your live code deployment, but for a development environment where you are continually changing your code and templates. Generally changes to live code and templates are meant to be handled by restarting the application server, or Apache in your case. (Hypnotoad has a hot-restart capability for this purpose)
Alternatively, how can I disable template caching completely?
To do this, add the following setup code (outside of routes, after use Mojolicious::Lite):
app->renderer->cache->max_keys(0);
For old answer see below.
I turned the findings of this answer into a plugin and released it on CPAN as Mojolicious::Plugin::Renderer::WithoutCache after discussing wit Grinnz on IRC, where they encouraged a release.
You can use it like this:
use Mojolicious::Lite;
plugin 'Renderer::WithoutCache';
It will create a new Cache object that does nothing, and install that globally into the renderer. That way, it doesn't need to be created every time like my initial answer below did.
In theory, this should be faster than Grinnz' approach (which is more sensible), and since you explicitly don't want to cache, you obviously want things to be as fast as possible, right? It's supposedly faster because the real Mojo::Cache would still need to go and try to set the cache, but then abort because there are no more free keys, and it also would try to look up the values from the cache every time.
I benchmarked this with both Dumbbench and Benchmark. Both of them showed negligible results. I ran them each a couple of times, but they fluctuated a lot, and it's not clear which one is faster. I included output of a run where my implementation was faster, but it still shows how minuscule the difference is.
Benchmark with Dumbbench:
use Dumbbench;
use Mojolicious::Renderer;
use Mojolicious::Controller;
use Mojolicious::Plugin::Renderer::WithoutCache::Cache;
my $controller = Mojolicious::Controller->new;
my $renderer_zero_keys = Mojolicious::Renderer->new;
$renderer_zero_keys->cache->max_keys(0);
my $renderer_nocache = Mojolicious::Renderer->new;
$renderer_nocache->cache( Mojolicious::Plugin::Renderer::WithoutCache::Cache->new );
my $bench = Dumbbench->new(
target_rel_precision => 0.005,
initial_runs => 5000,
);
$bench->add_instances(
Dumbbench::Instance::PerlSub->new(
name => 'max_keys',
code => sub {
$renderer_zero_keys->render( $controller, { text => 'foobar' } );
}
),
Dumbbench::Instance::PerlSub->new(
name => 'WithoutCache',
code => sub {
$renderer_nocache->render( $controller, { text => 'foobar' } );
}
),
);
$bench->run;
$bench->report;
__END__
max_keys: Ran 8544 iterations (3335 outliers).
max_keys: Rounded run time per iteration: 5.19018e-06 +/- 4.1e-10 (0.0%)
WithoutCache: Ran 5512 iterations (341 outliers).
WithoutCache: Rounded run time per iteration: 5.0802e-06 +/- 5.6e-09 (0.1%)
Benchmark with Benchmark:
use Benchmark 'cmpthese';
use Mojolicious::Renderer;
use Mojolicious::Controller;
use Mojolicious::Plugin::Renderer::WithoutCache::Cache;
my $controller = Mojolicious::Controller->new;
my $renderer_zero_keys = Mojolicious::Renderer->new;
$renderer_zero_keys->cache->max_keys(0);
my $renderer_nocache = Mojolicious::Renderer->new;
$renderer_nocache->cache( Mojolicious::Plugin::Renderer::WithoutCache::Cache->new );
cmpthese(
-5,
{
'max_keys' => sub {
$renderer_zero_keys->render( $controller, { text => 'foobar' } );
},
'WithoutCache' => sub {
$renderer_nocache->render( $controller, { text => 'foobar' } );
},
}
);
__END__
Rate max_keys WithoutCache
max_keys 190934/s -- -2%
WithoutCache 193846/s 2% --
I recon in a heavy load environment with lots of calls it would eventually make a difference, but that is very hard to prove. So if you don't like to think about the internals of the cache, this plugin might be useful.
Old answer:
Looking at Mojolicious::Plugin::EPRenderer I found out that there is a cache. It's a Mojo::Cache instance, which has the methods get, set and max_keys, and inherits from Mojo::Base (like probably everything in Mojolicious).
The ::EPRenderer gets a $renderer, which is a Mojolicious::Renderer. It holds the Mojo::Cache instance. I looked at $c with Data::Printer, and found out that there is a $c->app that holds all of those.
Knowing this, you can easily make your own cache class that does nothing.
package Renderer::NoCache;
use Mojo::Base -base;
sub get {}
sub set {}
sub max_keys {}
Now you stick it into $c.
package Foo;
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
$c->app->renderer->cache( Renderer::NoCache->new );
$c->render(template => 'foo', name => 'World');
};
app->start;
__DATA__
## foo.html.ep
Hello <%= $name =%>.
Now every attempt to get or set the cache simply does nothing. It will try caching, but it will never find anything.
Of course it's not great to make a new object every time. It would be better to make that object once at startup and get it into the internal permanent version of app. You have CGI, so it might not make a difference.
You could also just monkey-patch the get out of Mojo::Cache. This more hacky approach will do the same thing:
package Foo;
use Mojolicious::Lite;
*Mojo::Cache::get = sub { };
get '/' => sub {
my $c = shift;
$c->render(template => 'foo', name => 'World');
};
app->start;
But beware: we just disabled fetching from every cache in your application that uses Mojo::Cache. This might not be what you want.

Print SSRSReport to file (.PDF)

I need to find a way to "print" a SrsReport, in my case SalesInvoice, as .PDF (or any kind of file) to a specific location.
For this I modified the SRSPrintDestinationSettings to output the SalesInvoice-Report as a .PDF:
settings = controller.parmReportContract().parmPrintSettings();
settings.printMediumType(SRSPrintMediumType::File);
settings.fileFormat(SRSReportFileFormat::PDF);
settings.overwriteFile(true);
settings.fileName(#'\\AXDEV\Bottomline\Test\test.pdf');
Somehow this gets ignored and I recive a Email with the report as .PDF attached.
For example this will run on ax 2012 but won't print to PDF for me.
SRSPrintDestinationSettings settings;
CustInvoiceJour custInvoiceJour;
SrsReportRunController controller = new SrsReportRunController();
PurchPurchaseOrderContract rdpContract = new PurchPurchaseOrderContract();
SalesInvoiceContract salesInvoiceContract = new SalesInvoiceContract();
select firstOnly1 * from custInvoiceJour where custInvoiceJour.SalesId != "";
// Define report and report design to use
controller.parmReportName(ssrsReportStr(SalesInvoice,Report));
// Use execution mode appropriate to your situation
controller.parmExecutionMode(SysOperationExecutionMode::Synchronous);
rdpContract.parmRecordId(custInvoiceJour.RecId);
controller.parmReportContract().parmRdpContract(rdpContract);
// Explicitly provide all required parameters
salesInvoiceContract.parmRecordId(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty
controller.parmReportContract().parmRdpContract(salesInvoiceContract);
salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo()); // comment this code if tested in pre release
// Change print settings as needed
settings = controller.parmReportContract().parmPrintSettings();
settings.printMediumType(SRSPrintMediumType::File);
settings.fileFormat(SRSReportFileFormat::PDF);
settings.overwriteFile(true);
settings.fileName(#'\\AXDEV\Bottomline\Test\test.pdf');
//tokens = settings as SrsPrintDestinationTokens();
//controller.parmPrintDestinationTokens(null);
//Suppress report dialog
controller.parmShowDialog(false);
// Execute the report
controller.startOperation();
Questions:
Is this the correct way to print a srsReport to .pdf?
Am I passing/setting the printerSettings correctly?
Where does it say "Send Email"?
EDIT: Code is working fine. We are using external code of a company which simply doesnt implement this.
Use the cleaner code of Alex Kwitny
Here is working code for me. I just quickly coded this from scratch/memory based off of glancing at yours, so compare for differences.
I have two things marked (1) and (2) for you to try with your code, or just copy/paste mine.
static void JobSendToPDFInvoice(Args _args)
{
SrsReportRunController controller = new SrsReportRunController();
SRSPrintDestinationSettings settings;
CustInvoiceJour custInvoiceJour = CustInvoiceJour::findRecId(5637925275);
SalesInvoiceContract salesInvoiceContract = new SalesInvoiceContract();
Args args = new Args();
controller.parmReportName(ssrsReportStr(SalesInvoice, Report));
controller.parmExecutionMode(SysOperationExecutionMode::Synchronous);
controller.parmShowDialog(false);
salesInvoiceContract.parmRecordId(custInvoiceJour.RecId);
salesInvoiceContract.parmDocumentTitle(CustInvoiceJour.InvoiceId);
salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo());
// (1) Try by passing args
args.record(custInvoiceJour);
args.parmEnum(PrintCopyOriginal::Original);
args.parmEnumType(enumNum(PrintCopyOriginal));
controller.parmReportContract().parmRdpContract(salesInvoiceContract);
controller.parmArgs(args);
// (2) Try explicitly preventing loading from last value
// controller.parmLoadFromSysLastValue(false);
// Change print settings as needed
settings = controller.parmReportContract().parmPrintSettings();
settings.printMediumType(SRSPrintMediumType::File);
settings.fileFormat(SRSReportFileFormat::PDF);
settings.overwriteFile(true);
settings.fileName(#'C:\Temp\Invoice.pdf');
controller.startOperation();
}
Since you are talking about the sales invoice the report is using the print management feature and you cannot simply override the print settings like that.
You need to override the runPrintMgmt on the controller class and determine there whether you want default print management or your own code.
See this post for an example: http://www.winfosoft.com/blog/microsoft-dynamics-ax/manipulating-printer-settings-with-x

Google Drive Android Api Completion Event for Folder Creation

The completion events in Google Drive Android Api (GDAA) seem to be invoked only by contents change (file create, file contents update). Since I need to retrieve a Resource Id of a folder (seen here for a file with contents), referring to this method:
DriveFolder.createFolder(mGAC, meta).setResultCallback(...);
I need a completion event for a folder creation, but I can't find a solution.
Any hints? Thank you.
No, takers for this question, so I assume there is no straightforward solution. Meanwhile, I slammed together a hack until this gets fixed (if ever).
1/ Create a folder, you get the 'preliminary' DriveId that YIELDS NO ResourceId (nothing's commited).
2/ Use this DriveId as a parent of a dummy file with a dummy content and a completion event request attached. The folder creation is now apparently forced by it's child.
3/ In the completion event (as seen here), get the dummy file's DriveId and retrieve it's parent ID:
com.google.android.gms.common.api.GoogleApiClient GAC;
//...
DriveId parentID(DriveId dId) {
MetadataBuffer mdb = null;
DriveApi.MetadataBufferResult mbRslt = dId.asDriveResource().listParents(GAC).await();
if (mbRslt.getStatus().isSuccess()) try {
mdb = mbRslt.getMetadataBuffer();
if (mdb.getCount() > 0)
return mdb.get(0).getDriveId();
} catch (Exception e) { e.printStackTrace();}
finally {
if (mdb != null) mdb.close();
}
return null;
}
('await()' flavor works here since 'DriveEventService' is off-UI)
Now you get folder's 'real' DriveId that can produce a valid ResourceId:
String resourceId = driveId.getResourceId()
4/ zap the dummy file that has served it's lifetime mission
Is there a better solution? Please let me know.

Where is |DataDirectory| defined?

This is a follow up question of Where is that file on my system?
Tons of questions and answers all over SO and the internet but I can't find any that gives an answer to this specific question.
All is default but I can't find the file itself,
IT'S NOT THERE.
Where/how gets |DataDirectory| defined?
Where is the file saved, does it even exist? If not, what is going on?
edit: The file isn't located at AppDomain.CurrentDomain.GetData("DataDirectory").ToString(); all (sqattered) answers tell me it should be. It must be somewhere as the debugger breaks nagging about the model unequals the table when I change the model. It's not there.
The |DataDirectory| isn't a file per se. A quote from a rather old MSDN article:
By default, the |DataDirectory| variable will be expanded as follow:
For applications placed in a directory on the user machine, this will be the app's (.exe) folder.
For apps running under ClickOnce, this will be a special data folder created by ClickOnce
For Web apps, this will be the App_Data folder
Under the hood, the value for |DataDirectory| simply comes from a property on the app domain. It is possible to change that value and override the default behavior by doing this:
AppDomain.CurrentDomain.SetData("DataDirectory", newpath)
A further quote regarding your schema inconsistencies:
One of the things to know when working with local database files is that they are treated as any other content files. For desktop projects, it means that by default, the database file will be copied to the output folder (aka bin) each time the project is built. After F5, here's what it would look like on disk
MyProject\Data.mdf
MyProject\MyApp.vb
MyProject\Bin\Debug\Data.mdf
MyProject\Bin\Debug\MyApp.exe
At design-time, MyProject\Data.mdf is used by the data tools. At run-time, the app will be using the database under the output folder. As a result of the copy, many people have the impression that the app did not save the data to the database file. In fact, this is simply because there are two copies of the data file involved. Same applies when looking at the schema/data through the database explorer. The tools are using the copy in the project, not the one in the bin folder.
The |datadirectory| algorithm is located in the System.Data.dll assembly, in the internal System.Data.Common.DbConnectionOptions class. Here it as displayed by ILSpy (note the source it's now available in the reference source repository: https://github.com/Microsoft/referencesource/blob/e458f8df6ded689323d4bd1a2a725ad32668aaec/System.Data.Entity/System/Data/EntityClient/DbConnectionOptions.cs):
internal static string ExpandDataDirectory(string keyword,
string value,
ref string datadir)
{
string text = null;
if (value != null &&
value.StartsWith("|datadirectory|", StringComparison.OrdinalIgnoreCase))
{
string text2 = datadir;
if (text2 == null)
{
// 1st step!
object data = AppDomain.CurrentDomain.GetData("DataDirectory");
text2 = (data as string);
if (data != null && text2 == null)
throw ADP.InvalidDataDirectory();
if (ADP.IsEmpty(text2))
{
// 2nd step!
text2 = AppDomain.CurrentDomain.BaseDirectory;
}
if (text2 == null)
{
text2 = "";
}
datadir = text2;
}
// 3rd step, checks and normalize
int length = "|datadirectory|".Length;
bool flag = 0 < text2.Length && text2[text2.Length - 1] == '\\';
bool flag2 = length < value.Length && value[length] == '\\';
if (!flag && !flag2)
{
text = text2 + '\\' + value.Substring(length);
}
else
{
if (flag && flag2)
{
text = text2 + value.Substring(length + 1);
}
else
{
text = text2 + value.Substring(length);
}
}
if (!ADP.GetFullPath(text).StartsWith(text2, StringComparison.Ordinal))
throw ADP.InvalidConnectionOptionValue(keyword);
}
return text;
}
So it looks in the current AppDomain data first (by default, there is no "DataDirectory" data defined I believe) and then gets to the current AppDomain base directory. The rest is mostly checks for path roots and paths normalization.
On the MSDN forum there is a similiar but simplified question about this, which says:
By default the |DataDirectory| points to your application folder (as you figured out yourself in the original question: to the App_Data).
Since is just a substitution path to your database, you can define the path yourself with the AppDomain.SetData.