Example usage for java.lang IllegalArgumentException getCause

List of usage examples for java.lang IllegalArgumentException getCause

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:jh.tools.office.ConvertOutPDF.java

public static void main(String[] args) throws Exception {

    try {/*from   w  ww .java2 s.c o  m*/
        getInputFilePath(args);
    } catch (IllegalArgumentException e) {
    }

    // Font regex (optional)
    // Set regex if you want to restrict to some defined subset of fonts
    // Here we have to do this before calling createContent,
    // since that discovers fonts
    String regex = null;
    // Windows:
    // String
    // regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
    //regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
    // Mac
    // String
    // 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).*";
    PhysicalFonts.setRegex(regex);

    // Document loading (required)
    WordprocessingMLPackage wordMLPackage;

    // Load .docx or Flat OPC .xml
    System.out.println("Loading file from " + inputfilepath);
    wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));

    // Refresh the values of DOCPROPERTY fields
    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    //updater.update(true);

    String outputfilepath;
    if (inputfilepath == null) {
        outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
    } else {
        outputfilepath = inputfilepath + ".pdf";
    }

    // All methods write to an output stream
    OutputStream os = new java.io.FileOutputStream(outputfilepath);

    if (!Docx4J.pdfViaFO()) {

        // Since 3.3.0, Plutext's PDF Converter is used by default

        System.out.println("Using Plutext's PDF Converter; add docx4j-export-fo if you don't want that");

        try {
            Docx4J.toPDF(wordMLPackage, os);
        } catch (Docx4JException e) {
            e.printStackTrace();
            // What did we write?
            IOUtils.closeQuietly(os);
            System.out.println(FileUtils.readFileToString(new File(outputfilepath)));
            if (e.getCause() != null && e.getCause() instanceof ConversionException) {

                ConversionException ce = (ConversionException) e.getCause();
                ce.printStackTrace();
            }
        }
        System.out.println("Saved: " + outputfilepath);

        return;
    }

    System.out.println("Attempting to use XSL FO");

    /**
     * Demo of PDF output.
     *
     * PDF output is via XSL FO.
     * First XSL FO is created, then FOP
     * is used to convert that to PDF.
     *
     * Don't worry if you get a class not
     * found warning relating to batik. It
     * doesn't matter.
     *
     * If you don't have logging configured,
     * your PDF will say "TO HIDE THESE MESSAGES,
     * TURN OFF debug level logging for
     * org.docx4j.convert.out.pdf.viaXSLFO".  The thinking is
     * that you need to be able to be warned if there
     * are things in your docx which the PDF output
     * doesn't support...
     *
     * docx4j used to also support creating
     * PDF via iText and via HTML. As of docx4j 2.5.0,
     * only viaXSLFO is supported.  The viaIText and
     * viaHTML source code can be found in src/docx4j-extras directory
     *
     */

    /*
     * NOT WORKING?
     *
     * If you are getting:
     *
     *   "fo:layout-master-set" must be declared before "fo:page-sequence"
     *
     * please check:
     *
     * 1.  the jaxb-xslfo jar is on your classpath
     *
     * 2.  that there is no stack trace earlier in the logs
     *
     * 3.  your JVM has adequate memory, eg
     *
     *           -Xmx1G -XX:MaxPermSize=128m
     *
     */

    // Set up font mapper (optional)
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);
    fontMapper.put("", PhysicalFonts.get("LiSu"));
    fontMapper.put("", PhysicalFonts.get("SimSun"));
    fontMapper.put("", PhysicalFonts.get("Microsoft Yahei"));
    fontMapper.put("", PhysicalFonts.get("SimHei"));
    fontMapper.put("", PhysicalFonts.get("KaiTi"));
    fontMapper.put("", PhysicalFonts.get("NSimSun"));
    fontMapper.put("?", PhysicalFonts.get("STXingkai"));
    fontMapper.put("?", PhysicalFonts.get("STFangsong"));
    fontMapper.put("", PhysicalFonts.get("simsun-extB"));
    fontMapper.put("", PhysicalFonts.get("FangSong"));
    fontMapper.put("_GB2312", PhysicalFonts.get("FangSong_GB2312"));
    fontMapper.put("", PhysicalFonts.get("YouYuan"));
    fontMapper.put("?", PhysicalFonts.get("STSong"));
    fontMapper.put("?", PhysicalFonts.get("STZhongsong"));

    // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
    // eg Glyph "" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
    // eg Glyph "" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
    // to a font which does
    PhysicalFont font = PhysicalFonts.get("Arial Unicode MS");
    // make sure this is in your regex (if any)!!!
    //      if (font!=null) {
    //         fontMapper.put("Times New Roman", font);
    //         fontMapper.put("Arial", font);
    //      }
    //      fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun"));

    // FO exporter setup (required)
    // .. the FOSettings object
    FOSettings foSettings = Docx4J.createFOSettings();
    if (saveFO) {
        foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
    }
    foSettings.setWmlPackage(wordMLPackage);

    // Document format:
    // The default implementation of the FORenderer that uses Apache Fop will output
    // a PDF document if nothing is passed via
    // foSettings.setApacheFopMime(apacheFopMime)
    // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
    // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
    //foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);

    // Specify whether PDF export uses XSLT or not to create the FO
    // (XSLT takes longer, but is more complete).

    // Don't care what type of exporter you use
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that uses a xsl transformation
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
    // .. faster, but not yet at feature parity
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);

    System.out.println("Saved: " + outputfilepath);

    // Clean up, so any ObfuscatedFontPart temp files can be deleted
    if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
        wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
    }
    // This would also do it, via finalize() methods
    updater = null;
    foSettings = null;
    wordMLPackage = null;

}

From source file:org.docx4j.samples.ConvertOutPDF.java

public static void main(String[] args) throws Exception {

    try {/*from ww  w . ja  v a2s.c  o  m*/
        getInputFilePath(args);
    } catch (IllegalArgumentException e) {
    }

    // Font regex (optional)
    // Set regex if you want to restrict to some defined subset of fonts
    // Here we have to do this before calling createContent,
    // since that discovers fonts
    String regex = null;
    // Windows:
    // String
    // regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
    //regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
    // Mac
    // String
    // 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).*";
    PhysicalFonts.setRegex(regex);

    // Document loading (required)
    WordprocessingMLPackage wordMLPackage;
    if (inputfilepath == null) {
        // Create a docx
        System.out.println("No imput path passed, creating dummy document");
        wordMLPackage = WordprocessingMLPackage.createPackage();
        SampleDocument.createContent(wordMLPackage.getMainDocumentPart());
    } else {
        // Load .docx or Flat OPC .xml
        System.out.println("Loading file from " + inputfilepath);
        wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
    }

    // Refresh the values of DOCPROPERTY fields 
    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    updater.update(true);

    String outputfilepath;
    if (inputfilepath == null) {
        outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
    } else {
        outputfilepath = inputfilepath + ".pdf";
    }

    // All methods write to an output stream
    OutputStream os = new java.io.FileOutputStream(outputfilepath);

    if (!Docx4J.pdfViaFO()) {

        // Since 3.3.0, Plutext's PDF Converter is used by default

        System.out.println("Using Plutext's PDF Converter; add docx4j-export-fo if you don't want that");

        try {
            Docx4J.toPDF(wordMLPackage, os);
        } catch (Docx4JException e) {
            e.printStackTrace();
            // What did we write?
            IOUtils.closeQuietly(os);
            System.out.println(FileUtils.readFileToString(new File(outputfilepath)));
            if (e.getCause() != null && e.getCause() instanceof ConversionException) {

                ConversionException ce = (ConversionException) e.getCause();
                ce.printStackTrace();
            }
        }
        System.out.println("Saved: " + outputfilepath);

        return;
    }

    System.out.println("Attempting to use XSL FO");

    /**
     * Demo of PDF output.
     * 
     * PDF output is via XSL FO.
     * First XSL FO is created, then FOP
     * is used to convert that to PDF.
     * 
     * Don't worry if you get a class not
     * found warning relating to batik. It
     * doesn't matter.
     * 
     * If you don't have logging configured, 
     * your PDF will say "TO HIDE THESE MESSAGES, 
     * TURN OFF debug level logging for 
     * org.docx4j.convert.out.pdf.viaXSLFO".  The thinking is
     * that you need to be able to be warned if there
     * are things in your docx which the PDF output
     * doesn't support...
     * 
     * docx4j used to also support creating
     * PDF via iText and via HTML. As of docx4j 2.5.0, 
     * only viaXSLFO is supported.  The viaIText and 
     * viaHTML source code can be found in src/docx4j-extras directory
     *
     */

    /*
     * NOT WORKING?
     * 
     * If you are getting:
     * 
     *   "fo:layout-master-set" must be declared before "fo:page-sequence"
     * 
     * please check:
     * 
     * 1.  the jaxb-xslfo jar is on your classpath
     * 
     * 2.  that there is no stack trace earlier in the logs
     * 
     * 3.  your JVM has adequate memory, eg
     * 
     *           -Xmx1G -XX:MaxPermSize=128m
     * 
     */

    // Set up font mapper (optional)
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);

    // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
    // eg Glyph "" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
    // eg Glyph "" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
    // to a font which does
    PhysicalFont font = PhysicalFonts.get("Arial Unicode MS");
    // make sure this is in your regex (if any)!!!
    //      if (font!=null) {
    //         fontMapper.put("Times New Roman", font);
    //         fontMapper.put("Arial", font);
    //      }
    //      fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun"));

    // FO exporter setup (required)
    // .. the FOSettings object
    FOSettings foSettings = Docx4J.createFOSettings();
    if (saveFO) {
        foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
    }
    foSettings.setWmlPackage(wordMLPackage);

    // Document format: 
    // The default implementation of the FORenderer that uses Apache Fop will output
    // a PDF document if nothing is passed via 
    // foSettings.setApacheFopMime(apacheFopMime)
    // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
    // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
    //foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);

    // Specify whether PDF export uses XSLT or not to create the FO
    // (XSLT takes longer, but is more complete).

    // Don't care what type of exporter you use
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that uses a xsl transformation
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
    // .. faster, but not yet at feature parity
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);

    System.out.println("Saved: " + outputfilepath);

    // Clean up, so any ObfuscatedFontPart temp files can be deleted 
    if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
        wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
    }
    // This would also do it, via finalize() methods
    updater = null;
    foSettings = null;
    wordMLPackage = null;

}

From source file:org.openconcerto.xml.persistence.XMLFactory.java

/**
 * Renvoie un objet  partir d'un lment XML.
 * /*  w  ww. j av  a2  s.c o  m*/
 * @param elem l'lment XML.
 * @return l'objet Java correspondant.
 */
public static XMLable fromXML(Element elem) {
    Class clazz = getClass(elem.getName());
    if (clazz == null)
        throw new IllegalArgumentException("class of element unknown:" + elem.getName() + ":" + elementNames);
    final Method fromXML = methods.get(clazz);
    XMLable obj = null;
    try {
        obj = (XMLable) fromXML.invoke(null, new Object[] { elem });
    } catch (IllegalArgumentException e) {
        // impossible
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // impossible, test dans addClass
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // fromXML ne renvoie pas d'exn
        throw (RuntimeException) e.getCause();
    }
    return obj;
}

From source file:org.alfresco.rest.framework.core.ResourceInspectorUtil.java

/**
 * Invokes a method and returns the result
 * @param annotatedMethod Method/*from   www . ja v a  2s.c  o  m*/
 * @param obj Object
 * @return result of method call
 */
public static Object invokeMethod(Method annotatedMethod, Object obj, Object... args) throws Throwable {
    if (annotatedMethod != null) {
        try {
            return annotatedMethod.invoke(obj, args);
        } catch (IllegalArgumentException error) {
            logger.warn("Invocation error", error);
        } catch (IllegalAccessException error) {
            logger.warn("IllegalAccessException", error);
        } catch (InvocationTargetException error) {
            logger.warn("InvocationTargetException", error);
            throw error.getCause();
        }
    }
    return null;
}

From source file:org.jiemamy.utils.sql.ResultSetUtil.java

private static <T> T getValueInternal(Class<T> returnType, ResultSet rs, Class<?> parameterType,
        Object[] parameter, T defaultValue) {
    Method method = findMethod(returnType, parameterType);
    if (method == null) {
        return defaultValue;
    }//  w  ww  .  ja v a2  s.c o m
    try {
        // bug in JDK http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6456930
        //         return clazz.cast(method.invoke(rs, parameter));
        @SuppressWarnings("unchecked")
        T result = (T) method.invoke(rs, parameter);
        return result;
    } catch (IllegalArgumentException e) {
        throw new JiemamyError("The signature of the method must be verified.", e);
    } catch (IllegalAccessException e) {
        throw new JiemamyError("The method returned by getMethods() must be public.", e);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        }
        if (e.getCause() instanceof SQLException == false) {
            throw new JiemamyError("Checked exception which the invocation target thrown is not SQLException.",
                    e.getCause());
        }

        // ignore
    }
    return defaultValue;
}

From source file:cherry.foundation.crypto.SecureStringEncoderTest.java

@Test
public void testDecoderException() throws Exception {
    SecureStringEncoder encoder = createSecureStringEncoder();
    try {/*  w ww .  j  a  v a2  s  .c om*/
        encoder.decode("XXXX");
        fail("Exception must be thrown");
    } catch (IllegalArgumentException ex) {
        assertTrue(ex.getCause() instanceof DecoderException);
    }
}

From source file:com.squarespace.template.cli.TemplateC.java

/**
 * Compile a template against a given json tree and emit the result.
 *//*w  w w .j  a  v  a 2s. c o m*/
protected int compile(String templatePath, String jsonPath, String partialsPath)
        throws CodeException, IOException {

    String template = readFile(templatePath);
    String json = "{}";
    if (jsonPath != null) {
        json = readFile(jsonPath);
    }

    String partials = null;
    if (partialsPath != null) {
        partials = readFile(partialsPath);
    }

    CompiledTemplate compiled = compiler().compile(template, false);
    Instruction code = compiled.code();

    // Parse the JSON context
    JsonNode jsonTree = null;
    try {
        jsonTree = JsonUtils.decode(json);
    } catch (IllegalArgumentException e) {
        System.err.println("Caught error trying to parse JSON: " + e.getCause().getMessage());
        return 1;
    }

    // Parse the optional JSON partials dictionary.
    JsonNode partialsTree = null;
    if (partials != null) {
        try {
            partialsTree = JsonUtils.decode(partials);
            if (!(partialsTree instanceof ObjectNode)) {
                System.err.println("Partials map JSON must be an object. Found " + partialsTree.getNodeType());
                return 1;
            }
        } catch (IllegalArgumentException e) {
            System.err.println("Caught error trying to parse partials: " + e.getCause().getMessage());
            return 1;
        }
    }

    // Perform the compile.
    Context context = compiler().newExecutor().code(code).json(jsonTree).partialsMap((ObjectNode) partialsTree)
            .execute();

    // If compile was successful, print the output.
    System.out.print(context.buffer().toString());
    return 0;
}

From source file:org.echocat.redprecursor.annotations.ParametersPassesExpressionUnitTest.java

@Test
public void testEvaluationThrowsException() throws Exception {
    final MethodCall<ParametersPassesExpressionUnitTest> methodCall = toMethodCall(
            ParametersPassesExpressionUnitTest.class, this, "test", "a", 1, "b", '2');
    try {//from w w w . j  a v  a 2  s.c o  m
        new Evaluator().evaluate(proxyAnnotation(ParametersPassesExpression.class, "value", "a eq b"), METHOD,
                "test", methodCall);
        fail("Expected exception missing.");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), is("Expression not passed: a eq b"));
        assertThat(e.getCause() instanceof SpelEvaluationException, is(true));
    }
}

From source file:edu.vt.middleware.crypt.AbstractCli.java

/**
 * Parses command line options and invokes the proper handler to perform the
 * requested action, or the default action if no action is specified.
 *
 * @param  args  Command line arguments.
 *//*  w  ww .ja v a2s . com*/
public final void performAction(final String[] args) {
    initOptions();
    try {
        if (args.length > 0) {
            final CommandLineParser parser = new GnuParser();
            final CommandLine line = parser.parse(options, args);
            if (line.hasOption(OPT_EXAMPLE)) {
                printExamples();
            } else {
                dispatch(line);
            }
        } else {
            printHelp();
        }
    } catch (ParseException pex) {
        System.err.println("Failed parsing command arguments: " + pex.getMessage());
    } catch (IllegalArgumentException iaex) {
        String msg = "Operation failed: " + iaex.getMessage();
        if (iaex.getCause() != null) {
            msg += " Underlying reason: " + iaex.getCause().getMessage();
        }
        System.err.println(msg);
    } catch (Exception ex) {
        System.err.println("Operation failed:");
        ex.printStackTrace(System.err);
    }
}