Upgrading to 11.4.6 causes java.lang.NoClassDefFoundError: Could not initialize class org.docx4j.fonts.IdentityPlusMapper - docx4j

Case:
Writing a docx as pdf using WordprocessingMLPackage and setting the fontMapper using IdentityPlusMapper() from org.docx4j.fonts to map the fonts in the document we receive:
java.lang.NoClassDefFoundError: Could not initialize class org.docx4j.fonts.IdentityPlusMapper
at: getFontMapper()
This happens after upgrading from docx4j 11.2.8 to 11.4.6.
Dependencies in usage are:
org.docx4j:docx4j-core:11.4.6
org.docx4j:docx4j-export-fo:11.4.6
org.docx4j:docx4j-JAXB-ReferenceImpl:11.4.6
Is this a known issue already?
Looking forward to a possible reply!
Thanks in advance.

This assertion error is appearing from the static block of the IdentityPlusMapper or the BestMatchingMapper whatever we use. The exact line is:
PhysicalFonts.discoverPhysicalFonts();
The fix of the problem is to restrict fonts loading before the static block using font selection regex as stated in the javadoc of:
PhysicalFonts.setRegex()
The following way quickly solved the problem along with that it reduces memory utilization and the static block's execution time:
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new ByteArrayInputStream(os.toByteArray()));
String fontRegex = ".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*";
if(System.getProperty("os.name").startsWith("Windows")) {
fontRegex = ".*(calibri|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
}
PhysicalFonts.setRegex(fontRegex);
wordMLPackage.setFontMapper(new BestMatchingMapper());
Docx4J.toPDF(wordMLPackage, outputStream);

This seems to be a font loading problem. I'm on a Mac (latest Monterey) and I'm getting the same exception in the contructor call:
java.lang.AssertionError:
Expecting code not to raise a throwable but caught
java.lang.AssertionError
at org.docx4j.fonts.fop.complexscripts.fonts.GlyphPositioningTable$DeviceTable.<init>(GlyphPositioningTable.java:1778)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readPosDeviceTable(OTFAdvancedTypographicTableReader.java:1729)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readPosAnchor(OTFAdvancedTypographicTableReader.java:2053)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readMarkToLigaturePosTableFormat1(OTFAdvancedTypographicTableReader.java:2347)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readMarkToLigaturePosTable(OTFAdvancedTypographicTableReader.java:2373)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readGPOSSubtable(OTFAdvancedTypographicTableReader.java:3124)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readLookupTable(OTFAdvancedTypographicTableReader.java:3193)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readLookupList(OTFAdvancedTypographicTableReader.java:3220)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readCommonLayoutTables(OTFAdvancedTypographicTableReader.java:3241)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readGPOS(OTFAdvancedTypographicTableReader.java:3501)
at org.docx4j.fonts.fop.complexscripts.fonts.OTFAdvancedTypographicTableReader.readAll(OTFAdvancedTypographicTableReader.java:88)
at org.docx4j.fonts.fop.fonts.truetype.OpenFont.handleCharacterSpacing(OpenFont.java:895)
at org.docx4j.fonts.fop.fonts.truetype.OpenFont.readFont(OpenFont.java:867)
at org.docx4j.fonts.fop.fonts.truetype.OFFontLoader.read(OFFontLoader.java:121)
at org.docx4j.fonts.fop.fonts.truetype.OFFontLoader.read(OFFontLoader.java:105)
at org.docx4j.fonts.fop.fonts.FontLoader.getFont(FontLoader.java:130)
at org.docx4j.fonts.fop.fonts.FontLoader.loadFont(FontLoader.java:114)
at org.docx4j.fonts.fop.fonts.autodetect.FontInfoFinder.find(FontInfoFinder.java:262)
at org.docx4j.fonts.PhysicalFonts.getPhysicalFont(PhysicalFonts.java:307)
at org.docx4j.fonts.PhysicalFonts.addPhysicalFonts(PhysicalFonts.java:246)
at org.docx4j.fonts.PhysicalFonts.addPhysicalFont(PhysicalFonts.java:236)
at org.docx4j.fonts.PhysicalFonts.discoverPhysicalFonts(PhysicalFonts.java:183)
at org.docx4j.fonts.IdentityPlusMapper.<clinit>(IdentityPlusMapper.java:74)
at foo(...)
open fun foo(...) {
...
val mlPackage = WordprocessingMLPackage.load(ByteArrayInputStream(input))
mlPackage.fontMapper = IdentityPlusMapper() //<-- boom
}
Update (August 29th 2022): I fixed the issue by upgrading Docx4j to 11.4.7 . Additionally I had to add the following code before the call to Docx4J.toFO(...):
val fopFactoryBuilder: FopFactoryBuilder = FORendererApacheFOP.getFopFactoryBuilder(foSettings)
FORendererApacheFOP.getFOUserAgent(foSettings, fopFactoryBuilder.build())

I have fixed the same by setting regex for fonts available in Mac which's recommened by PhysicalFonts class set regex method as well.
PhysicalFonts.regex = ".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*"

Related

No interface method putArray in class WritableMap React-Native

I use RN version: "0.61.5"
The problem is that I installed react-native-beacons-manager 1.0.7 (note that the npm version the last time was updated a long time ago, but I tried the last Github version as well) but I can't use it as when I try to run my application the app crashes. Moreover, it doesn't show the red screen with an error stack trace. I looked into logs and found out that the problem is connected with WrittableArray, here's logs
2020-05-05 06:20:49.500 5218-5306/com.freeline E/AndroidRuntime: FATAL EXCEPTION: IntentService[BeaconIntentProcessor]
Process: com.freeline, PID: 5218
java.lang.NoSuchMethodError: No interface method putArray(Ljava/lang/String;Lcom/facebook/react/bridge/WritableArray;)V in class Lcom/facebook/react/bridge/WritableMap; or its super classes (declaration of 'com.facebook.react.bridge.WritableMap' appears in /data/app/com.freeline-BgN5GbjFCm9weblBl35oBw==/base.apk)
at com.mackentoch.beaconsandroid.BeaconsAndroidModule.createRangingResponse(BeaconsAndroidModule.java:299)
at com.mackentoch.beaconsandroid.BeaconsAndroidModule.access$300(BeaconsAndroidModule.java:37)
at com.mackentoch.beaconsandroid.BeaconsAndroidModule$2.didRangeBeaconsInRegion(BeaconsAndroidModule.java:280)
at org.altbeacon.beacon.BeaconIntentProcessor.onHandleIntent(BeaconIntentProcessor.java:68)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:76)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.os.HandlerThread.run(HandlerThread.java:65)
I found the function that caused the crashes, here it is:
private WritableMap createRangingResponse(Collection<Beacon> beacons, Region region) {
WritableMap map = new WritableNativeMap();
map.putString("identifier", region.getUniqueId());
map.putString("uuid", region.getId1() != null ? region.getId1().toString() : "");
WritableArray a = new WritableNativeArray();
for (Beacon beacon : beacons) {
WritableMap b = new WritableNativeMap();
b.putString("uuid", beacon.getId1().toString());
b.putInt("major", beacon.getId2().toInt());
b.putInt("minor", beacon.getId3().toInt());
b.putInt("rssi", beacon.getRssi());
b.putDouble("distance", beacon.getDistance());
b.putString("proximity", getProximity(beacon.getDistance()));
a.pushMap(b);
}
map.putArray("beacons", a); // <- The line that produces the exception
return map;
}
Then I read a bunch of posts and understand that the problem is in the implementation of WritableMap in new versions of RN.
So, my question is: Is there any method to resolve it, I've already addressed the issue here. I'm aware of the possibility of downgrading the RN version to ^60, but I'd keep it as the last possible method.
Appreciate your help
I solved the problem simply by downgrading to the version 60.6 of RN.

#HystrixProperty cannot be resolved to a type

I have a method marked with #HystrixCommand that has a fallback method defined. I'm trying to add a hystrix property to it so that in case of a timeout it degrades gracefully into a fallback method.
But when I add the #HystrixProperty it shows an error in the STS IDE (3.8.2 Release) saying #HystrixProperty cannot be resolved to a type.
Here is what I'm trying to do:
#HystrixCommand(fallbackMethod="fallbackPerformOperation",
commandProperties={#HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000")})
public Future<Object> performOperation(String requestString) throws InterruptedException {
return new AsyncResult<Object>() {
#Override
public Object invoke() {.......
}}}
and this is the error being shown in the IDE:
I'm unable to figure out what the problem is.
Do I need to clear the STS Cache? If so how do I do it?
Thank You.
With in the IDE it is not obvious to suggest the import HystrixProperty class, thus you need to manually import this
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
Then the error should be gone

Get broken constrains in OptaPanner with non-reversible accumulator

I am trying to obtains list of broken constrains from a problem instance in OptaPlanner. I am using OptaPlanner version 7.0.0.Final and drools for rules engine (also 7.0.0.Final). The problem is solved correctly and without any error, but when I try to obtain broken constrains I get a NullPointer exception.
As far as I have researched, I found out, that this only happens, when I use drools accumulator without reverse operation (like max or min). Further I have made a custom accumulator, which is the exact copy from org.drools.core.base.accumulators.LongSumAccumulateFunction and everything works as expected, but as soon as I change the supportsReverse() function to return false, the NullPointer exception rises.
I have managed to reconstruct this problem in one of the provided examples - CloudBalancing. This is the change to CloudBalancingHelloWorld, it's only purpose is to obtain list of broken constraints as mentioned in this post.
public class CloudBalancingHelloWorld {
public static void main(String[] args) {
// Build the Solver
SolverFactory<CloudBalance> solverFactory = SolverFactory.createFromXmlResource(
"org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml");
Solver<CloudBalance> solver = solverFactory.buildSolver();
// Load a problem with 400 computers and 1200 processes
CloudBalance unsolvedCloudBalance = new CloudBalancingGenerator().createCloudBalance(400, 1200);
// Solve the problem
CloudBalance solvedCloudBalance = solver.solve(unsolvedCloudBalance);
// Display the result
System.out.println("\nSolved cloudBalance with 400 computers and 1200 processes:\n"
+ toDisplayString(solvedCloudBalance));
//
//A Piece of code added - start
//
ScoreDirector<CloudBalance> scoreDirector = solver.getScoreDirectorFactory().buildScoreDirector();
scoreDirector.setWorkingSolution(solvedCloudBalance);
Collection<ConstraintMatchTotal> constrains = scoreDirector.getConstraintMatchTotals();
System.out.println(constrains.size());
//
//A Piece of code added - end
//
}
public static String toDisplayString(CloudBalance cloudBalance) {
StringBuilder displayString = new StringBuilder();
for (CloudProcess process : cloudBalance.getProcessList()) {
CloudComputer computer = process.getComputer();
displayString.append(" ").append(process.getLabel()).append(" -> ")
.append(computer == null ? null : computer.getLabel()).append("\n");
}
return displayString.toString();
}
}
And this is the change to requiredCpoPowerTotal rule. Please note that I have done this only to demonstrate the problem. Basicaly I have changed sum to max.
rule "requiredCpuPowerTotal"
when
$computer : CloudComputer($cpuPower : cpuPower)
accumulate(
CloudProcess(
computer == $computer,
$requiredCpuPower : requiredCpuPower);
$requiredCpuPowerTotal : max($requiredCpuPower);
(Integer) $requiredCpuPowerTotal > $cpuPower
)
then
scoreHolder.addHardConstraintMatch(kcontext, $cpuPower - (Integer) $requiredCpuPowerTotal);
end
I am really confused, because the error does not happen during planing phase, but when the scoreDirector recomputes the score to obtain broken constrains it does. I mean the same calculations must have happened during the planning phase right?
Anyway here is the stack trace
Exception in thread "main" Exception executing consequence for rule "requiredCpuPowerTotal" in org.optaplanner.examples.cloudbalancing.solver: java.lang.NullPointerException
at org.drools.core.runtime.rule.impl.DefaultConsequenceExceptionHandler.handleException(DefaultConsequenceExceptionHandler.java:39)
at org.drools.core.common.DefaultAgenda.handleException(DefaultAgenda.java:1256)
at org.drools.core.phreak.RuleExecutor.innerFireActivation(RuleExecutor.java:438)
at org.drools.core.phreak.RuleExecutor.fireActivation(RuleExecutor.java:379)
at org.drools.core.phreak.RuleExecutor.fire(RuleExecutor.java:135)
at org.drools.core.phreak.RuleExecutor.evaluateNetworkAndFire(RuleExecutor.java:88)
at org.drools.core.concurrent.AbstractRuleEvaluator.internalEvaluateAndFire(AbstractRuleEvaluator.java:34)
at org.drools.core.concurrent.SequentialRuleEvaluator.evaluateAndFire(SequentialRuleEvaluator.java:43)
at org.drools.core.common.DefaultAgenda.fireLoop(DefaultAgenda.java:1072)
at org.drools.core.common.DefaultAgenda.internalFireAllRules(DefaultAgenda.java:1019)
at org.drools.core.common.DefaultAgenda.fireAllRules(DefaultAgenda.java:1011)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.internalFireAllRules(StatefulKnowledgeSessionImpl.java:1321)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.fireAllRules(StatefulKnowledgeSessionImpl.java:1312)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.fireAllRules(StatefulKnowledgeSessionImpl.java:1296)
at org.optaplanner.core.impl.score.director.drools.DroolsScoreDirector.getConstraintMatchTotals(DroolsScoreDirector.java:134)
at org.optaplanner.examples.cloudbalancing.app.CloudBalancingHelloWorld.main(CloudBalancingHelloWorld.java:52)
Caused by: java.lang.NullPointerException
at org.drools.core.base.accumulators.JavaAccumulatorFunctionExecutor$JavaAccumulatorFunctionContext.getAccumulatedObjects(JavaAccumulatorFunctionExecutor.java:208)
at org.drools.core.reteoo.FromNodeLeftTuple.getAccumulatedObjects(FromNodeLeftTuple.java:94)
at org.drools.core.common.AgendaItem.getObjectsDeep(AgendaItem.java:78)
at org.drools.core.reteoo.RuleTerminalNodeLeftTuple.getObjectsDeep(RuleTerminalNodeLeftTuple.java:359)
at org.optaplanner.core.api.score.holder.AbstractScoreHolder.extractJustificationList(AbstractScoreHolder.java:118)
at org.optaplanner.core.api.score.holder.AbstractScoreHolder.registerConstraintMatch(AbstractScoreHolder.java:88)
at org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder.addHardConstraintMatch(HardSoftScoreHolder.java:53)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313.defaultConsequence(Rule_requiredCpuPowerTotal1284553313.java:14)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313DefaultConsequenceInvokerGenerated.evaluate(Unknown Source)
at org.optaplanner.examples.cloudbalancing.solver.Rule_requiredCpuPowerTotal1284553313DefaultConsequenceInvoker.evaluate(Unknown Source)
at org.drools.core.phreak.RuleExecutor.innerFireActivation(RuleExecutor.java:431)
... 13 more
Thank you for any help in advance.
That NPE sounds like a bug in Drools. The ConstraintMatch API should always just work. Very that you get it against the latest master version. If so, please create a jira for this with a minimal reproducer and we'll look into it.

Found 'UR'-anomaly for variable

I have this sonar error Major:
Found 'UR'-anomaly for variable 'language' (lines '83'-'85')
in this function:
public void saveAll(List<Language> languages){
//Found 'UR'-anomaly for variable 'country' (lines '83'-'85').
//Code Smell Major Open Not assigned 20min effort Comment
for (Language language: languages) {
save(language);
}
}
how to fix this major error please, thanks for advance
Edit:
Found even more information it this other SO post. While that is more PMD centric, the background information can be of interest to you.
Java for each loop being flagged as UR anomaly by PMD.
This is a rule from PMD it seems. Definition:
The dataflow analysis tracks local definitions, undefinitions and
references to variables on different paths on the data flow. From
those informations there can be found various problems. 1. UR -
Anomaly: There is a reference to a variable that was not defined
before. This is a bug and leads to an error. 2. DU - Anomaly: A
recently defined variable is undefined. These anomalies may appear in
normal source text. 3. DD - Anomaly: A recently defined variable is
redefined. This is ominous but don't have to be a bug.
There is an open bug report for this:
https://sourceforge.net/p/pmd/bugs/1190/
In the example they report it for Arrays, but somebody commented that it happens for them also for collections.
Example:
public static void main(final String[] args) {
for (final String string : args) {
string.getBytes(); //UR Anomaly
}
for (int i = 0; i < args.length; i++) {
args[i].getBytes();
}
}
In our sonar setup we don't use this rule. Based on the available information you may wish not to use it in yours.

CoreText CopyFontsForRequest received mig IPC error

I've been working on a BIG project (there's no point of showing any actual code anyway) and I've notice that the following message appears in the logs:
CoreText CopyFontsForRequest received mig IPC error (FFFFFFFFFFFFFECC) from font server
The error pops up as soon as a WebView has finished loading. And I kinda believe it's the culprit behind a tiny lag.
Why is that happening? What can I do to fix this?
P.S. Tried the suggested solution here to check whether it was something system-specific, but it didn't work.
More details:
The error appears when using the AMEditorAppearance.car NSAppearance file, from the Appearance Maker project. Disabling it (= not loading it all) makes the error go away.
I don't really care about the error message, other than that it creates some weird issues with fonts. E.g. NSAlert panels, with input fiels, show a noticeable flicker and the font/text seems rather messed up, in a way I'm not sure I can accurately describe. (I could post a video with that if that'd help)
This is probably related to system font conflicts and can easily be fixed:
Open Font book
Select all fonts
Go to the file menu and select "Validate fonts"
Resolve all font conflicts (by removing duplets).
Source: Andreas Wacker
Answer by #Abrax5 is excellent. I just wanted to add my experience with this problem and could not fit it into a comment:
As far as I can tell, this error is raised only on the first failed attempt to initialise an NSFont with a font name that is not available. NSFont initialisers are failable and will return nil in such a case at which time you have an opportunity to do something about it.
You can check whether a font by a given name is available using:
NSFontDescriptor(fontAttributes: [NSFontNameAttribute: "<font name>"]).matchingFontDescriptorWithMandatoryKeys([NSFontNameAttribute]) != nil
Unfortunately, this also raises the error! The following method does not, but is deprecated:
let fontDescr = NSFontDescriptor(fontAttributes: [NSFontNameAttribute: "<font name>"])
let isAvailable = NSFontManager.sharedFontManager().availableFontNamesMatchingFontDescriptor(fontDescr)?.count ?? 0 > 0
So the only way I found of checking the availability of a font of a given name without raising that error is as follows:
public extension NSFont {
private static let availableFonts = (NSFontManager.sharedFontManager().availableFonts as? [String]).map { Set($0) }
public class func available(fontName: String) -> Bool {
return NSFont.availableFonts?.contains(fontName) ?? false
}
}
For example:
NSFont.available("Georgia") //--> true
NSFont.available("WTF?") //--> false
(I'm probably overly cautious with that optional constant there and if you are so inclined you can convert the returned [AnyObject] using as! [String]...)
Note that for the sake of efficiency this will not update until the app is started again, i.e. any fonts installed during the app's run will not be matched. If this is an important issue for your particular app, just turn the constant into a computed property:
public extension NSFont {
private static var allAvailable: Set<String>? {
return (NSFontManager.sharedFontManager().availableFonts as? [String]).map { Set($0) }
}
private static let allAvailableAtStart = allAvailable
public class func available(fontName: String) -> Bool {
return NSFont.allAvailable?.contains(fontName) ?? false
}
public class func availableAtStart(fontName: String) -> Bool {
return NSFont.allAvailableAtStart?.contains(fontName) ?? false
}
}
On my machine available(:) takes 0.006s. Of course, availableAtStart(:) takes virtually no time on all but the first call...
This is caused by calling NSFont fontWithFamily: with a family name argument which is not available on the system from within Chromium's renderer process. When Chromium's sandbox is active this call triggers the CoreText error that you're observing.
It happens during matching CSS font family names against locally installed system fonts.
Probably you were working on a Chromium-derived project. More info can be found in Chromium Bug 452849.