Using Custom Fonts [java.io.IOException: Error reading font data.] - java

The title doesn't allow me to say Problem, so the actual error message was -
java.io.IOException: Problem reading font data.
at java.awt.Font.createFont(Unknown Source)
at AddFont.createFont(AddFont.java:11)
at MainFrame$1.run(MainFrame.java:105)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The code is -
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
AddFont addFont = new AddFont();
addFont.createFont();
} catch (Exception e) {
e.printStackTrace();
}
createGUI();
} //public void run() Closing
});
}
and the file that I used to get the AddFont addFont-
import java.awt.Font;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class AddFont extends MainFrame{
public void createFont(){
Font ttfBase = null;
Font telegraficoFont = null;{
try {
InputStream myStream = new BufferedInputStream(new FileInputStream(FONT_PATH_TELEGRAFICO));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
telegraficoFont = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Font not loaded.");
}
}
}
}
I was instructed to make a new thread because this is a separate problem from my other one.
Why am I getting this problem, and how can I fix it?
I have my TELEGRAFICO.TTF font in my imageFolder, which is really just my resources folder. I use
public static final String FONT_PATH_TELEGRAFICO = "imageFolder/TELEGRAFICO.TTF";
to call in my path.
What am I doing wrong?
EDIT - I no longer get that error message, and I don't get "Font not loaded". How can I use the font in other class files other than the one I made that method in?
(I want to use that font on buttons in multiple class files. I tried using it here -
regButton = new JButton();
regButton.setText("Foo");
regButton.setAlignmentX(Component.CENTER_ALIGNMENT);
regButton.setFont(telegraficoFont);
But it said telegraficoFont cannot be resolved to a variable. (Because it was in a different class file.)
How can I fix this? Thanks again for the help.

In some cases the cause is the running instance not being able to write to the Java temp directory (java.io.tmpdir).
If your are running it on tomcat maybe you deleted the temp directory of the tomcat installation, or the folder have wrong permissions.
(tomcat folder)/temp

As you have a problem with possible font file locating and font stream creation,
Try this >> Issue loading custom font AND http://forums.devshed.com/showpost.php?p=2268351&postcount=2
To answer your question "how to make this function easy to use everywhere", do as this:
public class AddFont extends MainFrame {
private static Font ttfBase = null;
private static Font telegraficoFont = null;
private static InputStream myStream = null;
private static final String FONT_PATH_TELEGRAFICO = "imageFolder/TELEGRAFICO.TTF";
public Font createFont() {
try {
myStream = new BufferedInputStream(
new FileInputStream(FONT_PATH_TELEGRAFICO));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
telegraficoFont = ttfBase.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("Font not loaded.");
}
return telegraficoFont;
}
}
And then in your calling class:
public class Test {
public static Font font = null;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
if (font == null) {
font = AddFont.createFont();
}
} catch (Exception e) {
e.printStackTrace();
}
createGUI();
} // public void run() Closing
});
}
}

In some cases, maybe the Fontconfig is lack in your running environment. After installing, everything is OK.
For example,
yum install fontconfig

you could try to install "dejavu-sans-fonts" and fontconfig, it works

Related

btrace visualvm interfaces require ASM 5

When I run this simple Java8 program
package test;
public class TraceInt {
public static void main(String args[]) throws InterruptedException{
TraceInt ti = new TraceInt();
while(true){
Integer.valueOf((int)System.currentTimeMillis());
ti.sleep(1000);
//System.getProperty("user.dir");
}
}
public void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And run this btrace script against it
#OnMethod(
clazz = "/.*/",
method = "/java.lang.*/",
location = #Location(value = Kind.ENTRY, where = Where.BEFORE)
)
public static void onEntry(Object obj) {
println(Strings.strcat("on entry: ", identityStr(obj)));
}
I get this error in the program
java.lang.IllegalArgumentException: INVOKESPECIAL/STATIC on interfaces require ASM 5
at com.sun.btrace.org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source)
at com.sun.btrace.util.templates.TemplateExpanderVisitor.visitMethodInsn(TemplateExpanderVisitor.java:85)
at com.sun.btrace.org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.a(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.b(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.accept(Unknown Source)
at com.sun.btrace.org.objectweb.asm.ClassReader.accept(Unknown Source)
at com.sun.btrace.runtime.InstrumentUtils.accept(InstrumentUtils.java:66)
at com.sun.btrace.runtime.InstrumentUtils.accept(InstrumentUtils.java:62)
at com.sun.btrace.agent.Client.instrument(Client.java:392)
at com.sun.btrace.agent.Client.doTransform(Client.java:213)
at com.sun.btrace.agent.Client.transform(Client.java:165)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
at com.sun.btrace.agent.Main$4.run(Main.java:464)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Any help appreciated
After a while I realised I was using an old version of btrace against Java8. As soon as I moved to the latest version everything was fine.

SWT window runnable on Linux but not on Mac

I added a SWT window to my project as
public class swtUI {
protected Shell shell;
protected Display display;
public static void launch() {
try {
swtUI window = new swtUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
// create all controls
blablabal
}
}
and call it in main() as
public static void main(String[] args) {
swtUI.launch();
System.out.println("\nComplete");
}
No problem running on Linux.
But when I replace the linux swt.jar with maxos swt.jar and run on mac, I got exception:
***WARNING: Display must be created on main thread due to Cocoa restrictions.
org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Display.error(Unknown Source)
at org.eclipse.swt.widgets.Display.createDisplay(Unknown Source)
at org.eclipse.swt.widgets.Display.create(Unknown Source)
at org.eclipse.swt.graphics.Device.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.<init>(Unknown Source)
at org.eclipse.swt.widgets.Display.getDefault(Unknown Source)
at edu.rockefeller.casanovaLab.csvCheck.CsvSuiteGUI.open(CsvSuiteGUI.java:129)
at edu.rockefeller.casanovaLab.csvCheck.CsvSuiteGUI.launch(CsvSuiteGUI.java:119)
at edu.rockefeller.casanovaLab.csvCheck.Program.main(Program.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I am pretty new to SWT. How should I change my code to make it work on mac?
Thanks
Seems this is mentioned in this FAQ. From the same link:
To work around this problem you'll have to pass the -XstartOnFirstThread option to the java executable as follows:
java -XstartOnFirstThread -cp swt.jar:. ControlExample

How to read a pdf from a url without downloading it?

I am trying to read a pdf from a url without downloading and then i am trying to flatten it .
This is the code :
import java.io.FileOutputStream;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class FormFillAndMakeItFlattenPDF {
public static void main(String[] args) {
try {
PdfReader reader = new PdfReader("http://www.irs.gov/pub/irs-pdf/fw4.pdf");
PdfStamper stamp2 = new PdfStamper(reader, new FileOutputStream("C:\\Flattened.pdf"));
AcroFields form2 = stamp2.getAcroFields();
stamp2.setFormFlattening(true);
stamp2.close();
}
catch (Exception de) {
de.printStackTrace();
}
}
}
However, this is throwing an error/exception . This is the stacktrace :
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:352)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:214)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:201)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:377)
at java.net.Socket.connect(Socket.java:530)
at java.net.Socket.connect(Socket.java:480)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:406)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:541)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:245)
at sun.net.www.http.HttpClient.New(HttpClient.java:318)
at sun.net.www.http.HttpClient.New(HttpClient.java:335)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:832)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:773)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:698)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1021)
at java.net.URL.openStream(URL.java:1009)
at com.lowagie.text.pdf.RandomAccessFileOrArray.<init>(Unknown Source)
at com.lowagie.text.pdf.RandomAccessFileOrArray.<init>(Unknown Source)
at com.lowagie.text.pdf.PRTokeniser.<init>(Unknown Source)
at com.lowagie.text.pdf.PdfReader.<init>(Unknown Source)
at com.lowagie.text.pdf.PdfReader.<init>(Unknown Source)
at FormFillAndMakeItFlattenPDF.main(FormFillAndMakeItFlattenPDF.java:18)
Can anybody tell me , what i am doing wrong here ?
If the problem happens because of proxy, call this at application startup.
System.setProperty("http.proxyHost", Config.PROXY_HOST);
System.setProperty("http.proxyPort", Config.PROXY_PORT);
where you change Config.X to your system values.
Note: for https you need to add similar lines with https.proxyHost and https.proxyPort
Your exact code works for me. I am using iText-4.2.0 (*) on Windows with Java 7.
Here is the code I ran, the test is green and "Flattened.pdf" is created correctly:
public class PdfTest {
#Test
public void testFlatten() throws Exception {
PdfReader reader = new PdfReader("http://www.irs.gov/pub/irs-pdf/fw4.pdf");
PdfStamper stamp2 = new PdfStamper(reader, new FileOutputStream("C:\\Users\\david\\Flattened.pdf"));
AcroFields form2 = stamp2.getAcroFields();
stamp2.setFormFlattening(true);
stamp2.close();
}
}
(*) https://github.com/ymasory/iText-4.2.0

JFileChooser remote view

I've been implementing a JFileChooser as a view for remote file system. When getFiles() is called from the FileSystemView I send request to the remote system with the directory location data.
Then asynchronously I receive back packet containing all files in the directory I am browsing, after that I am setting the files ready for updating view(so that next time getFiles() is called it will return the received array of files) but the problem is that I don't know how to update the JFileChoosers view.
I've tried
fileChooser.updateUI();
but it throws the following exception:
Exception in thread "pool-1-thread-31" java.lang.NullPointerException
at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.setDirectorySelected(Unknown Source)
at javax.swing.plaf.basic.BasicFileChooserUI$Handler.valueChanged(Unknown Source)
at javax.swing.JList.fireSelectionValueChanged(Unknown Source)
at javax.swing.JList$ListSelectionHandler.valueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.moveLeadSelectionIndex(Unknown Source)
at sun.swing.FilePane.clearSelection(Unknown Source)
at sun.swing.FilePane.doFilterChanged(Unknown Source)
at sun.swing.FilePane.propertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.fire(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.awt.Component.firePropertyChange(Unknown Source)
at javax.swing.JFileChooser.setFileFilter(Unknown Source)
at javax.swing.JFileChooser.addChoosableFileFilter(Unknown Source)
at javax.swing.JFileChooser.updateUI(Unknown Source)
at com.ruuhkis.remoteserver.ui.RemoteView.updateFiles(RemoteView.java:252)
at com.ruuhkis.remoteserver.ui.RemoteApplication.onFileListReceived(RemoteApplication.java:122)
at com.ruuhkis.remoteserver.packets.impl.FileListPacket.handlePacket(FileListPacket.java:32)
at com.ruuhkis.remoteserver.packets.PacketHandler$1.run(PacketHandler.java:57)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
when I am on the directory and I know it has received new file list and I press f5 it will show the new files it just loaded, how can I make it so I don't have to press f5? Also by pressing f5 it causes the system to reload the pre existing data for the directory.
current code is basically:
view = new FileSystemView() {
int c;
#Override
public File[] getFiles(File dir, boolean useFileHiding) {
if(!auto) {
PacketBuilder builder = new PacketBuilder(OpCodes.FILE_LIST_REQUEST_PACKET.getOpCode());
root = dir.getAbsolutePath();
builder.writeString(dir.getAbsolutePath());
builder.write(RemoteView.this.remote.getChannel());
}
auto = false;
if(dirContent == null)
return new File[]{new File((c++) + ".txt")};
else
return dirContent;
}
#Override
public Boolean isTraversable(File arg0) {
return true;
}
#Override
public File createNewFolder(File arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
};
c was basically just for testing so I can see if the system gets refreshed
when I receive the file list I do this:
public void updateFiles(String list) {
String[] parts = list.split("" + ((char)10));
File[] files = new File[parts.length];
for(int i = 0 ; i < parts.length; i++) {
files[i] = new File(root + File.separatorChar + parts[i]);
}
dirContent = files;
fileChooser.setCurrentDirectory(new File(root));
fileChooser.updateUI();
auto = true;
}
don't to call fileChooser.updateUI(); this is for apply custom UI or to change methods from Look and Feel
I think that better could be to use JList, or JTree as FileSystemView, then to create new File, Folder e.i. programatically
examples here
After browsing other JFileChooser projects I found method
fileChooser.rescanCurrentDirectory();
which seems to update file system view..
everytime I ask a question I find answer shortly after :/

On the fly class loading with jars

I've got a ClassLoader extending class with following method
#Override
public Class<?> findClass(String className) throws ClassNotFoundException {
try {
/**
* Get a bytecode from file
*/
byte b[] = fetchClassFromFS(pathtobin + File.separator
+ className.replaceAll("\\.", escapeSeparator(File.separator)) + ".class");
return defineClass(className, b, 0, b.length);
} catch (FileNotFoundException ex) {
return super.findClass(className);
} catch (IOException ex) {
return super.findClass(className);
}
}
That as u can see uses defineClass() method from its parent - ClassLoader. The issue is when i'm trying to execute a class' (i recieve with my ClassLoader extension - let it be ru.xmppTesting.test.Disco) method getMethods() while getting an instance of this class i get the following
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/Header
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.getMethods(Unknown Source)
at DOTGraphCreator.createGraphFromClasses(DOTGraphCreator.java:85)
at DOTGraphCreator.generateDotGraphFile(DOTGraphCreator.java:56)
at DOTGraphCreator.main(DOTGraphCreator.java:46)
Caused by: java.lang.ClassNotFoundException: org.apache.http.Header
at java.lang.ClassLoader.findClass(Unknown Source)
at SourceClassLoader.findClass(SourceClassLoader.java:27)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 7 more
As far as i can see that is because class org.apache.http.Header could not be found as defined. Because it is not.
So here's a question:
how can and must i define and link this Header class (and lots of others from my .jar libs) along with definition of ru.xmppTesting.test.Disco and others similar to have them defined on the fly?
If your are importing org.apache.http.Header from your dinamic loaded class, you need it to be accesible at your classpath.
If you don't want to load all the potentially needed jars on your classpath, you could try with a hack i have found here:
import java.lang.reflect.*;
import java.io.*;
import java.net.*;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL",parameters);
method.setAccessible(true);
method.invoke(sysloader,new Object[]{ u });
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
But, I must say, it could not be portable to some JVMs (not always the SystemClassLoader is a subclass of URLClassLoader)...
*EDIT: * In fact, as you have replaced the classloader with your own, perhaps you have some troubles...

Categories

Resources