Measuring string bounds in headless mode on a server?

I have a problem with calculating screen string width for the browser client.
I'm outputting a stream of content type application/vnd.ms-excel and sending back an XML spreadsheet. (No complaints about using Mc$oft products, it's what's needed!)
Excel does not autosize columns which contain string data, so the text columns are the standard Excel width, and the text is wrapped onto about 7 lines. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnexcl2k2/html/odc_xmlss.asp for details of the XML format.
Excel does allow you to specify the with of a column in points, so I was using the awt Font classes to calculate the string bounds in pixels. I explicitly set the resolution to be used to 72dpi by creating a FontRenderContext with an AffineTransform with a scaling factor of (1.0, 1.0), so that asking the pixel width, gets the point width.
This worked fine testing it on my windoze machine, but on the Unix server, it's obviously running in headless mode, and anyway, it doesn't have the Arial font which I'm specifying in my spreadsheet as the font to use.
Is there any way of calculating the width of a string in points knowing its font and the point size of the font? You shouldn't need a graphcs environment, just the font information. I have all the .TTF files, I could copy them to the Unix machine if Java could use them and do the calculation.
I hate leaving the user interface looking so shoddy with wrong sized columns!
It SHOULD have worked in a headless environment according to http://java.sun.com/j2se/1.4.2/docs/guide/awt/AWTChanges.html#headless and we are on version 1.4.2_01. It actually blew up in awt code:
java.lang.NoClassDefFoundError
     at java.lang.Class.forName0(Native Method)
     at java.lang.Class.forName(Class.java:141)
     at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62)
     at java.awt.Font.initializeFont(Font.java:308)
     at java.awt.Font.<init>(Font.java:344)That's when I'm trying to instantiate a new Font("Arial", Font.PLAIN, 10);I've looked at the FOP project wondering whether that has a solution but it's a huge, confusing thing. There must be a way. Can anyone help?

When you say "unix doesn't have Arial" you obviously aren't using Solaris where Arial most certainly
ships and is in fact the main font used to support dialog & sanserif.
There are numerous APIs to calculate the width of a string in pixels, depending on whether
you want the integer metrics, fp metrics , logical bounds, pixel bounds (which guarantees to enclose
every pixel if you correctly specify the graphics/FRC)
Every single one of these works in headless mode.
Even the most simple-minded FontMetrics.stringWidth(String) call should be good enough
for your requirements.
The error you show looks like you have a misconfigured environment.. It can't find
the correct implementation class of GraphicsEnvironment which is nothing to do with
fonts. Moreover this DOES work for me :
import java.awt.*;
public class Arial {
public static void main(String args[]) {
Font arial = new Font("Arial", Font.PLAIN, 10);
System.out.println(arial);
% java -version
java version "1.4.2_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
% java -Djava.awt.headless=true Arial
java.awt.Font[family=Arial,name=Arial,style=plain,size=10]
QED.
-Phil.

Similar Messages

  • A short and fundamental question: Java3D in headless mode

    To begin I would like to introduce myself as a complete Java3D newbie.
    What I would like to accomplish is to produce an application which, in headless mode, will read in data and generate 3d images as files, without ever making any GUI components to appear on the screen.
    Is this possible?
    Thanks!

    When you say "unix doesn't have Arial" you obviously aren't using Solaris where Arial most certainly
    ships and is in fact the main font used to support dialog & sanserif.
    There are numerous APIs to calculate the width of a string in pixels, depending on whether
    you want the integer metrics, fp metrics , logical bounds, pixel bounds (which guarantees to enclose
    every pixel if you correctly specify the graphics/FRC)
    Every single one of these works in headless mode.
    Even the most simple-minded FontMetrics.stringWidth(String) call should be good enough
    for your requirements.
    The error you show looks like you have a misconfigured environment.. It can't find
    the correct implementation class of GraphicsEnvironment which is nothing to do with
    fonts. Moreover this DOES work for me :
    import java.awt.*;
    public class Arial {
    public static void main(String args[]) {
    Font arial = new Font("Arial", Font.PLAIN, 10);
    System.out.println(arial);
    % java -version
    java version "1.4.2_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
    Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
    % java -Djava.awt.headless=true Arial
    java.awt.Font[family=Arial,name=Arial,style=plain,size=10]
    QED.
    -Phil.

  • JTable in Headless Mode

    Is it possible to create a JTable (with the table header) in headless mode?
    Thanks,
    Steve Sinai

    You don't know what headless mode is??? Then you're in the majority. It's one of those things I've seen mentioned in Swing books, but I've never had to deal with it before. On a server, we're trying to fill JTables with data, and then convert the JTables to pdf using iText. If you're wondering why we don't go straight to pdf using iText, thus bypassing JTables, you'll have to talk to our architect.
    An explanation of headless mode is at the following link.
    http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/
    I stole some example code from that site, and have been trying to use it to create a JTable. It's below. Some code that creates a JLabel works fine, and I commented it out. Now I'm trying to get it to create a JTable. The example displays the output on a printer, which is a little bit of a hassle, but it is what it is. If anyone can get the table (with header) to show up, it would be pretty nice.
    import java.awt.*;
    import java.io.*;
    import java.awt.print.*;
    import java.util.*;
    import javax.swing.*;
    public class HeadlessBasics
        public static void main(String[] args)
            // Set system property.
            // Call this BEFORE the toolkit has been initialized, that is,
            // before Toolkit.getDefaultToolkit() has been called.
            System.setProperty("java.awt.headless", "true");
            // This triggers creation of the toolkit.
            // Because java.awt.headless property is set to true, this
            // will be an instance of headless toolkit.
            Toolkit tk = Toolkit.getDefaultToolkit();
            // Standard beep is available.
            tk.beep();
            // Check whether the application is
            // running in headless mode.
            GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
            System.out.println("Headless mode: " + ge.isHeadless());
              /**     The JLabel works.
                     final JLabel c = new JLabel("I'm a Label!");
                     Dimension dim = c.getPreferredSize();
                     c.setBounds(0,0,dim.width,dim.height);
                     Vector data = new Vector();
                   for (int i = 0 ; i < 5 ; i++) {
                        Vector row = new Vector();
                        for (int j = 0 ; j < 4 ; j++) {
                             row.add(i+","+j);
                        data.add(row);
                   Vector columns = new Vector();
                   for (int i = 0 ; i < 4 ; i++) {
                        columns.add("Col "+i);
                   JTable table = new JTable(data, columns);
                   final JScrollPane c = new JScrollPane(table);
                   Dimension dim = c.getPreferredSize();
                   c.setBounds(0,0,dim.width,dim.height);
            // Print system is available.
            PrinterJob pj = PrinterJob.getPrinterJob();
            pj.setPrintable(new Printable()
                public int print(Graphics g, PageFormat pf, int pageIndex)
                    if (pageIndex > 0)
                        return Printable.NO_SUCH_PAGE;
                    ((Graphics2D)g).translate(pf.getImageableX(),
                                              pf.getImageableY());
                    // Paint the canvas.
                    c.paint(g);
                    return Printable.PAGE_EXISTS;
            try
                pj.print();
            catch (Exception z)
                z.printStackTrace(System.err);
    }

  • In report layout, can format a long string display as Column mode?

    Hi,
    Just want to check in report builder any way can format a long string into a column mode?
    Example: I have a field to hold 8000 character, and would like to print
    30 character in each line, when reach 50 line, then print in column i/o to print next page?
    Any idea ? Thanks a lot if you can share your experience with me.
    best Regards,
    Klnghau

    hi let say your field name is x
    then if your want it word wrap then it's simple just get one field and make it's vertical
    elasticity variable. and asign the field to it..
    but if you want your field to be displayed as
    first colunm and then beside continuation of that column but in 2nd one...
    then create 2 formula columns make your field legth been distributed half in each.
    so cf_1 is:
    decalre
    t varchar2(1510);
    begin
    if length(:x) > 1500
    t := substr(x, 1, 1500); -- as 30 x 50 = 1500
    else
    t := :x;
    end if;
    return t;
    so cf_2 is:
    decalre
    t varchar2(1510);
    begin
    if length(:x) > 1500
    t := substr(x, 1500, length(:x)-1500); -- as 30 x 50 = 1500
    else
    t := '';
    end if;
    return t;
    and then in design view
    field1 field2
    for field1 source is cf_1 and
    for field2 source is cf_2
    that's all
    Enjoy Oracle...

  • Is it possible to install a JDev extension bundle in headless mode.

    We are looking to see if there is a way to automate install of JDev and application of an extension in "headless" mode, or some other command line option that could enable this.
    This is for internal development purposes aiming at reducing the number of steps dev has to get through to be in a position to run JDev setup with the required extension.
    I could not find anything related to this in the forum, or help guide, apologies if I missed it.
    thanks
    Nick

    For most of the extensions the check for update simply download the zip file, and extracts the jar file from within into the extensions directory.
    I think you should be able to just manually copy the jar file to the specific location and this will be enough.
    Some extensions specify in their bundle.xml file another location for install (like the JDev root directory) and then you'll need to copy the files to the specific locations under the root.

  • How to run adt.jar in headless mode?

    Hi,
    I am facing issues packaging flex iOS applicaition in headless mode. Here is the error I am getting: After googling, I found this error might not occur when run in headless mode. I have already set the <headless-server>true</headless-server> in the air-config.xml and others.
         [java] Exception in thread "main" java.lang.InternalError: Can't connect to window server - not enough permissions.
         [java]     at java.lang.ClassLoader$NativeLibrary.load(Native Method)
         [java]     at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1827)
         [java]     at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1724)
         [java]     at java.lang.Runtime.loadLibrary0(Runtime.java:823)
         [java]     at java.lang.System.loadLibrary(System.java:1045)
         [java]     at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
         [java]     at java.security.AccessController.doPrivileged(Native Method)
         [java]     at java.awt.Toolkit.loadLibraries(Toolkit.java:1605)
         [java]     at java.awt.Toolkit.<clinit>(Toolkit.java:1627)
         [java]     at java.awt.Dimension.<clinit>(Dimension.java:70)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator.validateImageUri(ApplicationDescri ptorValidator.java:183)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator20.validateElement(ApplicationDescr iptorValidator20.java:121)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator25.validateElement(ApplicationDescr iptorValidator25.java:65)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator26.validateElement(ApplicationDescr iptorValidator26.java:62)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator30.validateElement(ApplicationDescr iptorValidator30.java:52)
         [java]     at com.adobe.air.validator.ApplicationDescriptorValidator31.validateElement(ApplicationDescr iptorValidator31.java:46)
         [java]     at com.adobe.air.validator.DescriptorValidator.endElement(DescriptorValidator.java:239)
         [java]     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser .java:601)
         [java]     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XML DocumentFragmentScannerImpl.java:1782)
         [java]     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDri ver.next(XMLDocumentFragmentScannerImpl.java:2939)
         [java]     at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImp l.java:648)
         [java]     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScanne rImpl.java:140)
         [java]     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDo cumentFragmentScannerImpl.java:511)
         [java]     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.ja va:808)
         [java]     at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.ja va:737)
         [java]     at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
         [java]     at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java :1205)
         [java]     at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.j ava:522)
         [java]     at javax.xml.parsers.SAXParser.parse(SAXParser.java:395)
         [java]     at javax.xml.parsers.SAXParser.parse(SAXParser.java:198)
         [java]     at com.adobe.air.Descriptor.validateXML(Descriptor.java:182)
         [java]     at com.adobe.air.Descriptor.<init>(Descriptor.java:56)
         [java]     at com.adobe.air.ApplicationDescriptor.<init>(ApplicationDescriptor.java:84)
         [java]     at com.adobe.air.ApplicationPackager.validateApplicationDescriptor(ApplicationPackager.java: 101)
         [java]     at com.adobe.air.ApplicationPackager.createPackage(ApplicationPackager.java:64)
         [java]     at com.adobe.air.ipa.IPAPackager.createPackage(IPAPackager.java:217)
         [java]     at com.adobe.air.ADT.parseArgsAndGo(ADT.java:557)
         [java]     at com.adobe.air.ADT.run(ADT.java:414)
         [java]     at com.adobe.air.ADT.main(ADT.java:464)
    Please help.
    Thanks,
    Swathi.

    Hi Swathi,
    Can you quickly check the following:
    1) Are you using the <headless-server> tag correctly, i.e. inside the <compiler> tag?
    2) Are you able to run it as a normal user and the problem is only when running via Jenkins?
    3) Can you check that the libraries you are trying to load are loadable via a daemon process?
    4) Does your daemon process have sufficient permissions for reading/writing/executing as per your requirements?
    5) Does the issue exist for an application not using native extensions(ANE) or is it specific to when using extensions?
    Also, please check your firewall settings.

  • AdvanceCache throwing NPE in headless mode

    Using jCharts (cross-posted there too), axisChart.render() is throwing this NullPointerException, but only some of the time. Looks like about half the time, the other half everything works great. I'm at a loss. It's a servlet that generates a JPEG chart, running in Caucho's Resin engine, 1.4 jdk running in headless mode, on a Linux box. Any ideas are appreciated...
    dataSeries.addIAxisChartDataSet( new AxisChartDataSet( data, legendLabels, paints, ChartType.BAR, barChartProperties ) );
    AxisChart axisChart= new AxisChart( dataSeries, chartProperties, axisProperties, legendProperties, width, height );
    BufferedImage awtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    axisChart.setGraphics2D(awtImage.createGraphics());
    axisChart.render();
    try {
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
    encoder.encode(awtImage);
    } catch (Exception e) {
    System.out.println(e);
    java.lang.NullPointerException
    at sun.awt.font.AdvanceCache.get(AdvanceCache.java:125)
    at java.awt.font.TextLayout$OptInfo.handleGetVisualBounds(TextLayout.java:280)
    at sun.awt.font.Decoration.getVisualBounds(Decoration.java:105)
    at java.awt.font.TextLayout$OptInfo.getVisualBounds(TextLayout.java:309)
    at java.awt.font.TextLayout.getBounds(TextLayout.java:1109)
    at org.jCharts.Chart.renderChartTitle(Unknown Source)
    at org.jCharts.axisChart.AxisChart.renderChart(Unknown Source)
    at org.jCharts.Chart.render(Unknown Source)
    at ChartGen.doGet(ChartGen.java:76)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:126)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)
    at com.caucho.server.http.FilterChainServlet.doFilter(FilterChainServlet.java:96)
    at com.caucho.server.http.Invocation.service(Invocation.java:311)
    at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:342)
    at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:272)
    at com.caucho.server.TcpConnection.run(TcpConnection.java:137)
    at java.lang.Thread.run(Thread.java:536)

    I'm also running into this. It seems after having Tomcat running for a while (days) it suddenly starts happening. It's as if it caches something that is then forgotten (or closed), and when called, it throws NPE. I'd love to know if this turns out to be a JDK bug or if there's a logical explanation.

  • Java 5, AWT in headless mode and X11 Libraries

    Hi All,
    In Java 5, does AWT still require X11 libs to be present (not running or started) when using AWT in headless mode ?
    What level of grahpics (non GUI) activities can you perform with Java 5 and AWT in headless mode.
    Cheers

    i found something here...
    http://forum.java.sun.com/thread.jspa?threadID=444149&start=10&tstart=0

  • Run Firefox in headless mode, for automated testing. Ideally other concurrent instances will operate normally for other tasks.

    I'm currently writing a Selenium 2 (Ruby) automated testing suite.
    I would like to be able to pass something that invokes an instance of firefox in headless mode.
    This would allow me to run automated tests whilst carrying on with manual tasks on another, standard set-up instance of Firefox.
    If this is possible, that would be fantastic.

    A good place to ask advice about web development is at the MozillaZine "Web Development/Standards Evangelism" forum.
    *http://forums.mozillazine.org/viewforum.php?f=25
    The helpers at that forum are more knowledgeable about web development issues.<br>
    You need to register at the MozillaZine forum site in order to post at that forum.

  • Q: Commands in headless mode( with "-suppress" parameter ) alway failed.

    If the command execution requires administrative privileges and the current permission is insufficient, the execution will fail in headless mode. Please run it again as administrator.

    Might sound stupid, but do you have php-fpm running?
    Means, is there a php-fpm process on your box, and does the socket exist like in:
    └» ps -ef|grep php-fpm
    root 3045 1 0 Mär04 ? 00:00:09 php-fpm: master process (/etc/php/php-fpm.conf)
    http 13534 3045 0 18:22 ? 00:00:10 php-fpm: pool www
    http 13545 3045 0 18:22 ? 00:00:08 php-fpm: pool www
    http 22807 3045 0 19:46 ? 00:00:01 php-fpm: pool www
    tom 27863 28055 0 20:16 pts/1 00:00:00 grep --colour=auto php-fpm
    └» ls -l /run/php-fpm/php-fpm.sock
    srw-rw---- 1 http http 0 4. Mär 22:24 /run/php-fpm/php-fpm.sock
    EDIT: somehow missed your output regarding the php-fpm socket. Ignore above then, I have no idea about chroot, I use LXC.
    Last edited by teekay (2013-03-07 19:24:04)

  • Executing ExtendScript in Headless mode

    Is there anyway to execute/compile a .JSX ExtendScript file on an indesign document in headless mode, meaning, without having to open the Toolkit application and Indesign. I'm thinking of a command that could be sent to the toolkit executable to run a particular script on an indesign file. This would be great if event remotely possible for automating certain scripts and not require user interaction.

    Hi Maxim,
    PL check the following threads..
    Reading session log
    Re: Urgent -  Doubt in Session
    Regards,
    Suresh Datti

  • J2sdk1.4 headless mode

    Hello,
    Can u help me set the headless mode in my linux server? I'm not familiar with command line stuff, I'm having a hard time! What I've done so far:
    - I downloaded j2sdk1.4 for linux and installed it in my linux server.
    - I set the system variable JAVA_HOME to my java home directory: /usr/java/j2sdk1.4.0
    Now I know I'm supposed to start my JVM with the -Djava.awt.headless=true option, but I don't know how to do this. How does this apply to a servlet generating images? Can I run a servlet from the command line? How can I set the headless mode once and for all? Should I start ANY java program with the headless option, and then it will apply to any other java program, including my servlet?
    I will really appreciate any help!
    Miguel

    java -Djava.awt.headless=true classname

  • Draw image using headless mode

    We use a 3rd-party swing chart package to draw chart on the backend. Basically what we did is to add the chart(JComponent) to a JFrame, and take a snapshot. In the normal case with display device available, it works ok. If we use headless mode, it throws HeadlessException, and the frame is null.
    Besides Xvfb, is there any simple way to generate JComponent image on the backend? Or can I render the chart in different container to generate the image?
    Thanks

    you need to override one of the container class where you put your graph component such that it works with default values or uses variable values for its methods from alternate sources.

  • Printerjob, awt headless mode and mac os x server

    hello
    i've an application that print a page using classes like jframe, jpanel, jtable, etc
    when i run it on a linux server or on a windows one there are no problems, but when i try to print this page on mac os x server 10.6.8 i get this error:
    on system dock appear a java icon named org.apache.catalina.startup.Bootstrap and the printed page comes empty. if i set the visibility property to true i can see the correct page, but i can't print!
    I've searched on google and i found various articles that say to set JAVA_OPTS to awt headless = true. i've tryed but i've obtained an headlessexception, because i use jframe etc that need headless mode disactive...so what can i do?
    i want to print with a shared network windows printer, if i print with textedit all go well, the problem appears only using java PrinterService class
    thanks in advance

    Paolo - Welcome to Discussions!
    At the moment - this is partly implemented.
    Networked home directories only are searched (new to tiger)
    Although there appear to be stubs of routines (and some low level documentation) that seem to point to support for indexing entire shares, it is not enabled.
    I know your case seems like a good one for this - but in general, it makes little sense for a lot of clients to hammer a network volume - all of them making their own index. I would presume there is a plan to allow the server to make one index and have the clients either refer to that index or download a copy of that index as needed to reduce the overhead on the server... (but that's just an educated guess - with no way of knowing)
    For more information, see http://docs.info.apple.com/article.html?artnum=301533 and http://discussions.apple.com/message.jspa?messageID=1303423#1303423

  • MS-DOS.This system doesn't support fullscreen mode in windows server 2008

    MS-DOS.This system doesn't support fullscreen mode.Choose close to terminate the application. Unable to open full size screen mode for MS-DOS in virtual windows server 2008

    Please anybody could suggest why the MS-DOS does not open full size mode in Windows server 2008. PC cate shell for windows application Is running and alerting this error msg. This system doesn't support fullscreen mode. Choose close to terminate the application.
    Please can any body help on this regard.

Maybe you are looking for

  • AR Invoice Crystal Sub-report Editing

    Hi experts, please i need a help on editing AR invoice crystal report  version in SAP business one . i want to add some fields to the sub report named summary section. For this particular customer he or she wants to see the sum of the individual row

  • WebEngine unexpectly throws java.lang.IllegalArgumentException: Image scanl

    When I use webEngine load below site: http://w133.hg3088.com/ (Need login in), I always get below exception(throw in endless loop). While I do nothing, just load this site, I don't know why throw this exception, and who to fix it. java.lang.IllegalAr

  • No service in new ipone 4s

    I bought a new iPhone 4s , it got activated , but the signal shows no service, while I am able to use the same sim in my friends phone it shows Aircel and good signal

  • IBook won't boot into OS X

    Hi I was using my iBook the other day when the screen unexpectedly went gray, it then went into standby shortly afterwards and would not power up. A three-fingered and power-switch salute later, and I was back at the login screen, but it would not bo

  • What's "\u" meaning in a string literal ?

    hi , I met a code like this : String cstr = "\u932f\u8aa4"; Would somebody Pls tell me what's the \u meaning ? Thanks Samuel