/ojc-core/encodersl/encoder-coco/test/com/sun/encoder/coco/CocoEncoderTest.java
Java | 688 lines | 563 code | 44 blank | 81 comment | 104 complexity | efa74443778bf59824fb3fec44526520 MD5 | raw file
- /*
- * BEGIN_HEADER - DO NOT EDIT
- *
- * The contents of this file are subject to the terms
- * of the Common Development and Distribution License
- * (the "License"). You may not use this file except
- * in compliance with the License.
- *
- * You can obtain a copy of the license at
- * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
- * See the License for the specific language governing
- * permissions and limitations under the License.
- *
- * When distributing Covered Code, include this CDDL
- * HEADER in each file and include the License file at
- * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html.
- * If applicable add the following below this CDDL HEADER,
- * with the fields enclosed by brackets "[]" replaced with
- * your own identifying information: Portions Copyright
- * [year] [name of copyright owner]
- */
- /*
- * @(#)CocoEncoderTest.java
- *
- * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
- *
- * END_HEADER - DO NOT EDIT
- */
- package com.sun.encoder.coco;
- import com.sun.encoder.coco.runtime.HexDump;
- import com.sun.encoder.coco.xsdbuilder.CocoXsdBuilder;
- import com.sun.encoder.coco.xsdbuilder.CocoXsdBuilderException;
- import com.sun.encoder.coco.xsdbuilder.CocoXsdBuilderSpec;
- import com.sun.encoder.tools.xml.SchemaLocationAttributes;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.LineNumberReader;
- import java.io.StringWriter;
- import java.util.Properties;
- import java.util.StringTokenizer;
- import javax.xml.namespace.QName;
- import javax.xml.transform.Source;
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerConfigurationException;
- import javax.xml.transform.TransformerException;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.TransformerFactoryConfigurationError;
- import javax.xml.transform.stream.StreamResult;
- import javax.xml.transform.stream.StreamSource;
- import junit.framework.Test;
- import junit.framework.TestCase;
- import junit.framework.TestResult;
- import junit.framework.TestSuite;
- import com.sun.encoder.Encoder;
- import com.sun.encoder.EncoderConfigurationException;
- import com.sun.encoder.EncoderException;
- import com.sun.encoder.EncoderFactory;
- import com.sun.encoder.EncoderType;
- import com.sun.encoder.MetaRef;
- import com.sun.encoder.util.UnicodeFile;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- * A simple test suite for unit testing COBOL Copybook encoder.
- *
- * @author Jun Xu
- * @since 6.0
- */
- public class CocoEncoderTest extends TestSuite {
-
- //Fields:
- // test case type ("B" for building XSD,
- // "E" for encode to bytes,
- // "D" for decode from bytes,
- // "ES" for encode to string,
- // "DS" for decode from string)
- // test case name
- // expected result ("T" for succeed and "F" for fail)
- // XML Schema file (if case type is "B" put build spec property
- // file name here)
- // root element qualified name (absent if case type is "B")
- // input file (for case type "B", put COBOL Copybook file name here)
- // output file (optional for case type "D" or "E".
- // for case type "B", put XSD file name here)
- // expected result file (optional)
- private static final int NUM_OF_FIELDS = 8;
- private static final int CASE_TYPE = 0;
- private static final int CASE_NAME = 1;
- private static final int EXPECTED_RESULT = 2;
- private static final int SCHEMA_OR_SPEC_FILE = 3;
- private static final int ROOT_ELEMENT = 4;
- private static final int INPUT_FILE = 5;
- private static final int OUTPUT_FILE = 6;
- private static final int EXPECTED_OUTPUT = 7;
- static Logger sLog = Logger.getLogger(CocoEncoderTest.class.getName());
- /** Creates a new instance of CocoEncoderTest */
- public CocoEncoderTest(String testName) {
- super(testName);
- }
-
- /**
- * suite method automatically generated by JUnit module
- */
- public static Test suite() {
- TestSuite suite =
- new CocoEncoderTest(
- "COBOL Copybook Encoder Test Suite");
- LineNumberReader lnReader = null;
- try {
- lnReader =
- new LineNumberReader(
- new BufferedReader(
- new InputStreamReader(
- new FileInputStream("test/testcases.txt"),
- UnicodeFile.ENC)));
- String line;
- while ((line = lnReader.readLine()) != null) {
- line = line.trim();
- if (line.length() == 0 || line.charAt(0) == '#') {
- continue;
- }
- StringTokenizer st = new StringTokenizer(line, ",");
- if (st.countTokens() != NUM_OF_FIELDS) {
- throw new RuntimeException(
- "Invalid test case entry. count="
- + st.countTokens() + ", line=" + line);
- }
- String tokens[] = new String[NUM_OF_FIELDS];
- for (int i = 0; i < NUM_OF_FIELDS; i++) {
- tokens[i] = st.nextToken();
- }
- boolean isPositiveTest = true;
- if ("F".equals(tokens[EXPECTED_RESULT].trim())) {
- isPositiveTest = false;
- }
- QName rootElement = null;
- if (!tokens[CASE_TYPE].equals("B")) {
- String rootElementName = tokens[ROOT_ELEMENT].trim();
- if (rootElementName.charAt(0) == '{') {
- int pos = rootElementName.indexOf('}');
- rootElement =
- new QName(rootElementName.substring(1, pos),
- rootElementName.substring(pos + 1));
- } else {
- rootElement = new QName(rootElementName);
- }
- }
- File outputFile = null;
- tokens[OUTPUT_FILE] = tokens[OUTPUT_FILE].trim();
- if (tokens[OUTPUT_FILE].length() > 0) {
- outputFile = new File(tokens[OUTPUT_FILE]);
- }
- File expectedFile = null;
- tokens[EXPECTED_OUTPUT] = tokens[EXPECTED_OUTPUT].trim();
- if (tokens[EXPECTED_OUTPUT].length() > 0) {
- expectedFile = new File(tokens[EXPECTED_OUTPUT]);
- }
- if ("B".equals(tokens[CASE_TYPE])) {
- //XSD builder test case
- suite.addTest(
- new XsdBuilderTest(
- tokens[CASE_NAME].trim(),
- isPositiveTest,
- new File(tokens[SCHEMA_OR_SPEC_FILE].trim()),
- new File(tokens[INPUT_FILE].trim()),
- outputFile,
- expectedFile) {
-
- @Override
- public void runTest() {
- testXsdBuilder();
- }
- }
- );
- } else if ("D".equals(tokens[CASE_TYPE])
- || "DS".equals(tokens[CASE_TYPE])) {
- //decode test case
- suite.addTest(
- new DecodeTest(
- tokens[CASE_NAME].trim(),
- "DS".equals(tokens[CASE_TYPE]),
- isPositiveTest,
- new File(tokens[SCHEMA_OR_SPEC_FILE].trim()),
- rootElement,
- new File(tokens[INPUT_FILE].trim()),
- outputFile,
- expectedFile) {
- @Override
- public void runTest() {
- testDecode();
- }
- });
- } else {
- //encode test case
- suite.addTest(
- new EncodeTest(
- tokens[CASE_NAME].trim(),
- "ES".equals(tokens[CASE_TYPE]),
- isPositiveTest,
- new File(tokens[SCHEMA_OR_SPEC_FILE].trim()),
- rootElement,
- new File(tokens[INPUT_FILE].trim()),
- outputFile,
- expectedFile) {
- @Override
- public void runTest() {
- testEncode();
- }
- });
- }
- }
- return suite;
- } catch (IOException e) {
- throw new RuntimeException("Failed to load test cases.", e);
- } finally {
- if (lnReader != null) {
- try {
- lnReader.close();
- } catch (Exception e) {
- //Ignore
- }
- }
- }
- }
- /**
- * XSD builder test.
- */
- public static class XsdBuilderTest extends TestCase {
- private final boolean mIsPositiveTest;
- private final File mBuildSpecFile;
- private final File mCopybookFile;
- private final File mXsdFile;
- private final File mExpectedFile;
-
- public XsdBuilderTest(String testName, boolean isPositiveTest,
- File buildSpecFile, File copybookFile,
- File xsdFile, File expectedFile) {
- super(testName);
- mIsPositiveTest = isPositiveTest;
- mBuildSpecFile = buildSpecFile;
- mCopybookFile = copybookFile;
- mXsdFile = xsdFile;
- mExpectedFile = expectedFile;
- }
- @Override
- protected void setUp() throws Exception {
- }
- @Override
- protected void tearDown() throws Exception {
- }
- public void testXsdBuilder() {
- sLog.info("testXsdBuilder --> [" + getName() + "]");
- // expected content
- String expected = null;
- try {
- if (mExpectedFile != null && mExpectedFile.exists()) {
- expected = UnicodeFile.getText(mExpectedFile);
- }
- Properties props = new Properties();
- props.load(new FileInputStream(mBuildSpecFile));
- CocoXsdBuilderSpec buildSpec = new CocoXsdBuilderSpec();
- buildSpec.setCheckNamesForReservedWords(
- Boolean.valueOf(
- props.getProperty(
- CocoXsdBuilderSpec
- .CHECK_NAMES_FOR_RESERVED_WORDS)));
- buildSpec.setCopybookCharEncoding(
- props.getProperty(
- CocoXsdBuilderSpec.COPYBOOK_CHAR_ENCODING));
- buildSpec.setDisplay1CharEncoding(
- props.getProperty(
- CocoXsdBuilderSpec.DISPLAY1_CHAR_ENCODING));
- buildSpec.setDisplayCharEncoding(
- props.getProperty(
- CocoXsdBuilderSpec.DISPLAY_CHAR_ENCODING));
- buildSpec.setIgnoreContentBeyondCol72(
- Boolean.valueOf(
- props.getProperty(
- CocoXsdBuilderSpec
- .IGNORE_CONTENT_BEYOND_COLUMN72)));
- buildSpec.setTargetNamespace(
- props.getProperty(
- CocoXsdBuilderSpec.TARGET_NAMESPACE));
- if (props.containsKey(
- CocoXsdBuilderSpec.PREDECODE_CHAR_CODING)) {
- buildSpec.setPreDecodeCharCoding(
- props.getProperty(
- CocoXsdBuilderSpec.PREDECODE_CHAR_CODING));
- }
- if (props.containsKey(
- CocoXsdBuilderSpec.POSTENCODE_CHAR_CODING)) {
- buildSpec.setPostEncodeCharCoding(
- props.getProperty(
- CocoXsdBuilderSpec.POSTENCODE_CHAR_CODING));
- }
- buildSpec.setCopybookLocation(mCopybookFile.getPath());
- buildSpec.setXsdLocation(mXsdFile.getPath());
-
- CocoXsdBuilder builder = new CocoXsdBuilder();
- builder.setOtdBuilderSpec(buildSpec);
- builder.buildXsd();
- String result = UnicodeFile.getText(mXsdFile);
- result = result.replaceAll("\r\n", "\n");
- String copybookPath;
- try {
- copybookPath = mCopybookFile.getCanonicalPath();
- } catch (IOException e) {
- copybookPath = mCopybookFile.getAbsolutePath();
- }
- String xsdPath;
- try {
- xsdPath = mXsdFile.getCanonicalPath();
- } catch (IOException e) {
- xsdPath = mXsdFile.getAbsolutePath();
- }
- copybookPath = copybookPath.replaceAll("\\\\", "\\\\\\\\");
- xsdPath = xsdPath.replaceAll("\\\\", "\\\\\\\\");
- if (mIsPositiveTest && expected != null) {
- expected = expected.replaceAll("\\$\\{COPYBOOK_LOCATION\\}",
- copybookPath);
- expected = expected.replaceAll("\\$\\{XSD_LOCATION\\}",
- xsdPath);
- expected = expected.replaceAll("\\$\\{BUILDER_VERSION\\}",
- CocoXsdBuilder.BUILDER_VERSION);
- expected = expected.replaceAll("\r\n", "\n");
- }
- if (mIsPositiveTest) {
- assertEquals("Check result with expected: "
- + getName(), expected, result);
- } else {
- if (expected.equals(result)) {
- fail("Expecting difference but got same: "
- + getName());
- }
- }
- } catch (FileNotFoundException e) {
- fail(getName() + " - " + e.toString());
- } catch (CocoXsdBuilderException e) {
- if (mIsPositiveTest) {
- fail(getName() + " - " + e.toString());
- } else {
- // handle negative test with expected exception message
- if (expected != null) {
- assertEquals("Check " + e.getClass().getName()
- + " with expected error message: "
- + getName(), expected, e.getMessage());
- }
- return;
- }
- } catch (IOException e) {
- fail(getName() + " - " + e.toString());
- } catch (TransformerFactoryConfigurationError e) {
- //fatal error
- throw new RuntimeException(e);
- }
- if (!mIsPositiveTest) {
- fail("Expecting failure but no error occurred: "
- + getName());
- }
- }
- }
-
- public static String[] getExpectedXMLContent(File expectedFile,
- String schemaLocation, String testName)
- throws IOException {
- String[] expectedContent = null;
- if (expectedFile != null) {
- expectedContent = UnicodeFile.getTexts(expectedFile.getPath());
- if (expectedContent.length > 1 && sLog.isLoggable(Level.INFO)) {
- sLog.info("There are " + expectedContent.length
- + " expected files for decode: " + testName);
- }
- if (schemaLocation != null) {
- // replace ${SCHEMA_LOCATION} in expected contents
- // with actual mSchemaLocation.
- for (int i = 0; i < expectedContent.length; i++) {
- expectedContent[i] = expectedContent[i].replaceAll(
- "\\$\\{SCHEMA_LOCATION\\}", schemaLocation);
- }
- }
- }
- // remove "/bld" in expected content if present
- if (expectedContent != null) {
- for (int i = 0; i < expectedContent.length; i++) {
- if (expectedContent[i] != null) {
- expectedContent[i] = expectedContent[i].replaceAll("/bld/", "/").trim();
- }
- }
- }
- return expectedContent;
- }
- /**
- * Decode test.
- */
- public static class DecodeTest extends TestCase {
- private final boolean mFromString;
- private final boolean mIsPositiveTest;
- private final File mSchemaFile;
- private final QName mRootElement;
- private final File mInputFile;
- private final File mOutputFile;
- private final File mExpectedFile;
-
- private String mSchemaLocation = null;
-
- public DecodeTest(String testName, boolean fromString,
- boolean isPositiveTest, File schemaFile, QName rootElement,
- File inputFile, File outputFile, File expectedFile) {
- super(testName);
- mFromString = fromString;
- mIsPositiveTest = isPositiveTest;
- mSchemaFile = schemaFile;
- mRootElement = rootElement;
- mInputFile = inputFile;
- mOutputFile = outputFile;
- mExpectedFile = expectedFile;
- }
- @Override
- protected void setUp() throws Exception {
- SchemaLocationAttributes schemaLocationAttr =
- new SchemaLocationAttributes(mRootElement.getNamespaceURI(),
- mSchemaFile.toURL());
- if (schemaLocationAttr.getLength() > 0) {
- mSchemaLocation = schemaLocationAttr.getValue(0);
- }
- }
- @Override
- protected void tearDown() throws Exception {
- }
- public void testDecode() {
- sLog.info("testDecode --> [" + getName() + "]");
- EncoderFactory factory;
- // expected content
- String[] expected = null;
- try {
- expected = getExpectedXMLContent(mExpectedFile,
- mSchemaLocation, getName());
- factory = EncoderFactory.newInstance();
- EncoderType type = factory.makeType(CocoEncoderProvider.STYLE_ID);
- MetaRef metaRef =
- factory.makeMeta(mSchemaFile.getAbsolutePath(),
- mRootElement);
- Encoder encoder = factory.newEncoder(type, metaRef);
- Source source;
- if (mFromString) {
- source = encoder.decodeFromString(
- UnicodeFile.getText(mInputFile));
- } else {
- source = encoder.decodeFromBytes(getBytes(mInputFile));
- }
- StringWriter swResult = new StringWriter();
- StreamResult streamResult = new StreamResult(swResult);
- Transformer transformer =
- TransformerFactory.newInstance().newTransformer();
- transformer.transform(source, streamResult);
- String resultGot = swResult.toString();
- if (mOutputFile != null) {
- UnicodeFile.setText(mOutputFile, resultGot);
- }
- // remove "/bld" if present
- if (resultGot != null) {
- resultGot = resultGot.replaceAll("/bld/", "/").trim();
- }
- boolean matchFound = false;
- for (int i = 0; i < expected.length; i++) {
- if (expected[i] != null && expected[i].equals(resultGot)) {
- matchFound = true;
- break;
- }
- }
- if (mIsPositiveTest) {
- if (!matchFound) {
- for (int i = 0; i < expected.length; i++) {
- assertEquals("Check result with expected #" + i
- + ": " + getName(), expected[i], resultGot);
- }
- }
- } else {
- if (matchFound) {
- fail("Expecting difference but got same: "
- + getName());
- }
- }
- } catch (EncoderConfigurationException e) {
- //fatal error
- throw new RuntimeException(e);
- } catch (FileNotFoundException e) {
- fail(getName() + " - " + e.toString());
- } catch (IOException e) {
- fail(getName() + " - " + e.toString());
- } catch (TransformerConfigurationException e) {
- //fatal error
- throw new RuntimeException(e);
- } catch (TransformerFactoryConfigurationError e) {
- //fatal error
- throw new RuntimeException(e);
- } catch (EncoderException e) {
- if (mIsPositiveTest) {
- fail(getName() + " - " + e.toString());
- } else {
- // handle negative test with expected exception message
- if (expected != null && expected.length > 0 && expected[0] != null) {
- assertEquals("Check " + e.getClass().getName()
- + " with expected error message: "
- + getName(), expected[0], e.getMessage());
- }
- return;
- }
- } catch (TransformerException e) {
- if (mIsPositiveTest) {
- fail(getName() + " - " + e.toString());
- } else {
- // handle negative test with expected exception message
- if (expected != null && expected.length > 0 && expected[0] != null) {
- assertEquals("Check " + e.getClass().getName()
- + " with expected error message: "
- + getName(), expected[0], e.getMessage());
- }
- return;
- }
- }
- if (!mIsPositiveTest) {
- fail("Expecting failure but no error occurred: "
- + getName());
- }
- }
- }
- /**
- * Encode test.
- */
- public static class EncodeTest extends TestCase {
- private final boolean mToString;
- private final boolean mIsPositiveTest;
- private final File mSchemaFile;
- private final QName mRootElement;
- private final File mInputFile;
- private final File mOutputFile;
- private final File mExpectedFile;
-
- public EncodeTest(String testName, boolean toString,
- boolean isPositiveTest, File schemaFile, QName rootElement,
- File inputFile, File outputFile, File expectedFile) {
- super(testName);
- mToString = toString;
- mIsPositiveTest = isPositiveTest;
- mSchemaFile = schemaFile;
- mRootElement = rootElement;
- mInputFile = inputFile;
- mOutputFile = outputFile;
- mExpectedFile = expectedFile;
- }
- @Override
- protected void setUp() throws Exception {
- }
- @Override
- protected void tearDown() throws Exception {
- }
- public void testEncode() {
- sLog.info("testEncode --> [" + getName() + "]");
- EncoderFactory factory;
- String expected = null;
- String result = null;
- try {
- if (mToString) {
- if (mExpectedFile != null) {
- expected = UnicodeFile.getText(mExpectedFile);
- }
- } else {
- if (mExpectedFile != null) {
- StringBuffer buf = new StringBuffer();
- HexDump.dump(getBytes(mExpectedFile), buf, 0);
- expected = buf.toString();
- }
- }
- factory = EncoderFactory.newInstance();
- EncoderType type = factory.makeType(CocoEncoderProvider.STYLE_ID);
- MetaRef metaRef =
- factory.makeMeta(mSchemaFile.getAbsolutePath(),
- mRootElement);
- Encoder encoder = factory.newEncoder(type, metaRef);
- StreamSource streamSource = new StreamSource(mInputFile);
- if (mToString) {
- result = encoder.encodeToString(streamSource);
- if (mOutputFile != null) {
- UnicodeFile.setText(mOutputFile, result);
- }
- } else {
- byte[] resultBytes = encoder.encodeToBytes(streamSource);
- if (mOutputFile != null) {
- FileOutputStream out =
- new FileOutputStream(mOutputFile);
- out.write(resultBytes);
- out.close();
- }
- StringBuffer buf = new StringBuffer();
- HexDump.dump(resultBytes, buf, 0);
- result = buf.toString();
- }
- if (expected != null) {
- if (mIsPositiveTest) {
- assertEquals("Check result with expected: "
- + getName(), expected, result);
- } else {
- if (expected.equals(result)) {
- fail("Expecting difference but got same: "
- + getName());
- }
- }
- }
- } catch (EncoderConfigurationException e) {
- //fatal error
- throw new RuntimeException(e);
- } catch (FileNotFoundException e) {
- fail(getName() + " - " + e.toString());
- } catch (IOException e) {
- fail(getName() + " - " + e.toString());
- } catch (TransformerFactoryConfigurationError e) {
- //fatal error
- throw new RuntimeException(e);
- } catch (EncoderException e) {
- if (mIsPositiveTest) {
- fail(getName() + " - " + e.toString());
- } else {
- if (expected != null) {
- assertEquals("Check " + e.getClass().getName()
- + " with expected error message: "
- + getName(), expected, e.getMessage());
- }
- return;
- }
- }
- if (!mIsPositiveTest) {
- fail("Expecting failure but no error occurred: "
- + getName());
- }
- }
- }
- private static byte[] getBytes(File file)
- throws IOException {
- FileInputStream fis = new FileInputStream(file);
- byte[] bytes = new byte[(int) file.length()];
- fis.read(bytes);
- return bytes;
- }
-
- public static void main(String arg[]) {
- CocoEncoderTest.suite().run(new TestResult());
- }
- }