Project

General

Profile

« Previous | Next » 

Revision 5752

use detected XML encoding when reading/writing files
use UTF-8 as default when performing queries in the DB (assume DB is using UTF-8)
remove as many PrintWriters (uses system default character encoding only) as possible and construct OutputStreamWriters where explicit encoding can be given.
http://bugzilla.ecoinformatics.org/show_bug.cgi?id=2495

View differences:

test/clienttestfiles/unicodeEML.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<eml:eml xmlns:eml="eml://ecoinformatics.org/eml-2.1.0"
3
	packageId="jscientist.7.2" system="knb"
4
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
	xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.0 eml.xsd">
6
	<access authSystem="knb" order="allowFirst">
7
		<allow>
8
			<principal>public</principal>
9
			<permission>read</permission>
10
		</allow>
11
	</access>
12
	<dataset>
13
		<title>測試中的數據包 (Test Chinese data package) _DOCID_</title>
14
		<creator>
15
			<individualName>
16
				<givenName>Joe</givenName>
17
				<surName>Scientist</surName>
18
			</individualName>
19
			<address>
20
				<deliveryPoint>Marine Science Institute</deliveryPoint>
21
				<city>Santa Barbara</city>
22
				<administrativeArea>CA</administrativeArea>
23
				<postalCode>90024</postalCode>
24
				<country>USA</country>
25
			</address>
26
			<phone>(310) 206-1984</phone>
27
			<electronicMailAddress>jsci@msi.ucsb.edu</electronicMailAddress>
28
		</creator>
29
		<associatedParty>
30
			<individualName>
31
				<givenName>Joe</givenName>
32
				<surName>Scientist</surName>
33
			</individualName>
34
			<address>
35
				<deliveryPoint>Marine Science Institute</deliveryPoint>
36
				<city>Santa Barbara</city>
37
				<administrativeArea>CA</administrativeArea>
38
				<postalCode>90024</postalCode>
39
				<country>USA</country>
40
			</address>
41
			<phone>(310) 206-1984</phone>
42
			<electronicMailAddress>jsci@msi.ucsb.edu</electronicMailAddress>
43
			<role>owner</role>
44
		</associatedParty>
45
		<abstract>
46
			<para>人口抽樣數據的各種浮游動物物種在大湖區,2000年。抽樣樣本採用凡德恩在1米,深5米放置一個隨機抽樣的網格。物種名稱根據 ITIS的分類數據庫(http://www.itis.usda.gov/)。這是虛構的樣本數據,並應以任何方式被解釋為有意義的信息!</para>
47
		</abstract>
48
		<keywordSet>
49
			<keyword keywordType="theme">zooplankton</keyword>
50
			<keyword keywordType="theme">Van Dorn sampling</keyword>
51
			<keyword keywordType="theme">population survey</keyword>
52
			<keyword keywordType="theme">fictitious sample data</keyword>
53
			<keyword keywordType="place">Great Lakes</keyword>
54
		</keywordSet>
55
		<contact>
56
			<individualName>
57
				<givenName>Joe</givenName>
58
				<surName>Scientist</surName>
59
			</individualName>
60
			<address>
61
				<deliveryPoint>Marine Science Institute</deliveryPoint>
62
				<city>Santa Barbara</city>
63
				<administrativeArea>CA</administrativeArea>
64
				<postalCode>90024</postalCode>
65
				<country>USA</country>
66
			</address>
67
			<phone>(310) 206-1984</phone>
68
			<electronicMailAddress>jsci@msi.ucsb.edu</electronicMailAddress>
69
		</contact>
70
	</dataset>
71
</eml:eml>
0 72

  
test/edu/ucsb/nceas/metacattest/NonAsciiCharacterTest.java
43 43
import edu.ucsb.nceas.metacat.client.MetacatFactory;
44 44
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
45 45
import edu.ucsb.nceas.metacat.properties.PropertyService;
46
import edu.ucsb.nceas.utilities.FileUtil;
46 47
import edu.ucsb.nceas.utilities.IOUtil;
47 48
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
48 49
import junit.framework.Test;
......
204 205
    
205 206
    /**
206 207
     * Returns an xml squery that searches for the doc id in the
207
     * title of documents. This function is for eml-2.0.1 only. For 
208
     * title of documents. This function is for eml-2.0.1+ only. For 
208 209
     * other eml versions, this function might have to modified.
209 210
     */
210
    private String getTestEmlQuery(String docid, String emlVersion) {
211
    private String getTestEmlQuery(String titlePart, String emlVersion) {
211 212

  
212 213
    	String docType;
213 214
    	if (emlVersion.equals(EML2_0_1)) {
......
227 228
        		"<returndoctype>" + docType + "</returndoctype>" +
228 229
        		"<querygroup operator=\"UNION\">" +
229 230
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
230
        				"<value>" + docid + "</value>" +
231
        				"<value>" + titlePart + "</value>" +
231 232
        				"<pathexpr>dataset/title</pathexpr>" +
232 233
        			"</queryterm>" +
233 234
        		"</querygroup>" +
......
280 281
        suite.addTest(new NonAsciiCharacterTest("quote210Test"));
281 282
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat201Test"));
282 283
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat210Test"));*/
283
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter201Test"));
284
        //suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter201Test"));
284 285
        //suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter210Test"));
286
        suite.addTest(new NonAsciiCharacterTest("unicodeCharacterTest"));
285 287

  
288

  
286 289
        return suite;
287 290
    }
288 291

  
......
506 509
     * Test inserting and reading an EML 2.0.1 document with the code representation 
507 510
     * of a micro sign (&#181). Read should succeed since the same document should be 
508 511
     * read back from disk that was submitted.  Query should succeed because we look 
509
     * for the converted character (µ).
512
     * for the converted character (µ).
510 513
     */
511 514
    public void numericCharacterReferenceFormat201Test() {
512 515
    	debug("\nRunning: numericCharacterReferenceFormat201Test");
......
515 518
            m.login(username, password);
516 519
            
517 520
            String testTitle = "Checking &#181; in doc: " + newdocid  + ".1";
518
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
521
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
519 522
            
520 523
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
521 524
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
......
546 549
     * Test inserting and reading an EML 2.1.0 document with the code representation 
547 550
     * of a micro sign (&#181). Read should succeed since the same document should be 
548 551
     * read back from disk that was submitted.  Query should succeed because we look 
549
     * for the converted character (µ).
552
     * for the converted character (µ).
550 553
     */
551 554
    public void numericCharacterReferenceFormat210Test() {
552 555
    	debug("\nRunning: numericCharacterReferenceFormat210Test");
......
555 558
            m.login(username, password);
556 559
            
557 560
            String testTitle = "Checking &#181; in doc: " + newdocid  + ".1";
558
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
561
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
559 562
            
560 563
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
561 564
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
......
583 586
    }
584 587

  
585 588
    /**
586
     * Test inserting and reading an EML 2.0.1 document with the micro sign (µ). 
589
     * Test inserting and reading an EML 2.0.1 document with the micro sign (µ). 
587 590
     * Read should succeed since the same document should be read back from disk 
588 591
     * that was submitted.  Query should succeed because we look for the same 
589
     * character (µ).
592
     * character (µ).
590 593
     */
591 594
    public void nonLatinUnicodeCharacter201Test() {
592 595
    	debug("\nRunning: nonLatinUnicodeCharacter201Test");
......
597 600
            String testTitle = "Checking characters like µ in doc: " + newdocid  + ".1";
598 601
            
599 602
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
603
            
604
            debug("original test document:	" + testdocument);
605
            
600 606
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
601 607
            
602 608
            // this tests reading the document back from disk
......
633 639
            String newdocid = generateDocid();
634 640
            m.login(username, password);
635 641
            
636
            String testTitle = "Checking characters like µ in doc: " + newdocid  + ".1";
642
            String testTitle = "Checking characters like µ in doc: " + newdocid  + ".1";
637 643
            
638 644
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
639 645
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
......
659 665
            fail("General exception:\n" + e.getMessage());
660 666
        }
661 667
    }
668
    
669
    /**
670
     * Test inserting and reading an EML 2.1.0 with Chinese
671
     */
672
    public void unicodeCharacterTest() {
673
    	debug("\nRunning: unicodeCharacterTest");
674
        try {
675
            
676
        	String filePath = "test/clienttestfiles/unicodeEML.xml";
677
            String testTitle = "測試中的數據包 (Test Chinese data package) _DOCID_";
678
            String newdocid = generateDocid() + ".1";
679
            testdocument = FileUtil.readFileToString(filePath, "UTF-8");
680
            
681
            // include the docid
682
            testdocument = testdocument.replaceAll("_DOCID_", newdocid);
683
            testTitle = testTitle.replaceAll("_DOCID_", newdocid);
684
            
685
            // login
686
            m.login(username, password);
687
            
688
            // insert
689
            insertDocid(newdocid, testdocument, SUCCESS, false);
662 690

  
691
            // this tests reading the document back from disk
692
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
693
            
694
            // this tests searching for the document in the database
695
            Thread.sleep(3000);
696
            queryDocWhichHasTitle(testTitle, testTitle, EML2_1_0, SUCCESS);
697
            
698
            // clean up
699
            //deleteDocid(newdocid, SUCCESS, false);
700
            
701
            m.logout();
702
        }
703
        catch (MetacatAuthException mae) {
704
            fail("Authorization failed:\n" + mae.getMessage());
705
        }
706
        catch (MetacatInaccessibleException mie) {
707
            fail("Metacat Inaccessible:\n" + mie.getMessage());
708
        }
709
        catch (Exception e) {
710
            fail("General exception:\n" + e.getMessage());
711
        }
712
    }
713

  
663 714
    /**
664 715
     * Insert a document into metacat. The expected result is passed as result
665 716
     */
......
667 718
                               boolean expectMetacatException) {
668 719
        String response = null;
669 720
        try {
721
        	
722
        	debug("doctext: " + docText);
723
        	
670 724
            response = m.insert(docid,
671 725
                                new StringReader(docText), null);
672 726
            System.err.println(response);
......
883 937
    }
884 938
    
885 939
    /**
886
     * Query a document by looking for it's doc id in the title element.
940
     * Query a document by looking for a part of the title in the title element.
887 941
     * Then check if the testTitle exists in the doc.
888
     * @param docId the id of the doc to look for
942
     * @param titlePart the part of the title of the doc to look for
889 943
     * @param testTitle the title containing special characters
890 944
     * @param result are we expecting SUCCESS or FAILURE
891 945
     * @param expextedKarmaFailure
892 946
     */
893
    private void queryDocWhichHasTitle(String docId, String testTitle,
947
    private void queryDocWhichHasTitle(String titlePart, String testTitle,
894 948
                                         String emlVersion, boolean result) {
895 949
        try {
896
            String sQuery = getTestEmlQuery(docId, emlVersion);
950
            String sQuery = getTestEmlQuery(titlePart, emlVersion);
897 951
        	Reader queryReader = new StringReader(sQuery);
898 952
            Reader resultReader = m.query(queryReader);
899 953
            String queryResult = IOUtil.getAsString(resultReader, true);
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
27 27
package edu.ucsb.nceas.metacat;
28 28

  
29 29
import java.io.IOException;
30
import java.io.OutputStreamWriter;
30 31
import java.io.PrintWriter;
32
import java.io.Writer;
31 33
import java.sql.PreparedStatement;
32 34
import java.sql.ResultSet;
33 35
import java.sql.SQLException;
......
263 265
    private static final String TRUE  = "true";
264 266
    private static String LOG_CONFIG_NAME = null;
265 267
    public static final String APPLICATION_NAME = "metacat";
268
	public static final String DEFAULT_ENCODING = "UTF-8";
266 269
    
267 270
    /**
268 271
     * Initialize the servlet by creating appropriate database connections
......
631 634
			HttpServletResponse response) throws ServletException, IOException {
632 635
		Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
633 636

  
637
		String requestEncoding = request.getCharacterEncoding();
638
		logMetacat.warn("requestEncoding: " + requestEncoding);
639
		
634 640
		// Update the last update time for this user if they are not new
635 641
		HttpSession httpSession = request.getSession(false);
636 642
		if (httpSession != null) {
......
829 835
			// Now that we know the session is valid, we can delegate the
830 836
			// request to a particular action handler
831 837
			if (action.equals("query")) {
832
				ServletOutputStream streamOut = response.getOutputStream();
833
				PrintWriter out = new PrintWriter(streamOut);
838
		        Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
834 839
				handler.handleQuery(out, params, response, userName, groupNames, sessionId);
835 840
				out.close();
836 841
			} else if (action.equals("squery")) {
837
				ServletOutputStream streamOut = response.getOutputStream();
838
				PrintWriter out = new PrintWriter(streamOut);
842
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
839 843
				if (params.containsKey("query")) {
840 844
					handler.handleSQuery(out, params, response, userName, groupNames, sessionId);
841 845
					out.close();
842 846
				} else {
843
					out.println("Illegal action squery without \"query\" parameter");
847
					out.write("Illegal action squery without \"query\" parameter");
844 848
					out.close();
845 849
				}
846 850
			} else if (action.trim().equals("spatial_query")) {
847 851

  
848 852
				logMetacat
849 853
						.debug("MetaCatServlet.handleGetOrPost - ******************* SPATIAL QUERY ********************");
850
				ServletOutputStream streamOut = response.getOutputStream();
851
				PrintWriter out = new PrintWriter(streamOut);
854
				Writer out = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
852 855
				handler.handleSpatialQuery(out, params, response, userName, groupNames, sessionId);
853 856
				out.close();
854 857

  
src/edu/ucsb/nceas/metacat/DocumentImpl.java
32 32
import java.io.ByteArrayOutputStream;
33 33
import java.io.File;
34 34
import java.io.FileOutputStream;
35
import java.io.FileWriter;
36 35
import java.io.IOException;
37 36
import java.io.InputStream;
38
import java.io.PrintWriter;
37
import java.io.OutputStream;
38
import java.io.OutputStreamWriter;
39 39
import java.io.Reader;
40 40
import java.io.StringReader;
41
import java.io.StringWriter;
42 41
import java.io.Writer;
43 42
import java.net.URL;
44 43
import java.sql.PreparedStatement;
......
76 75
import edu.ucsb.nceas.utilities.UtilException;
77 76

  
78 77
import org.apache.commons.io.IOUtils;
78
import org.apache.commons.io.input.XmlStreamReader;
79 79
import org.apache.log4j.Logger;
80 80
import org.xml.sax.ContentHandler;
81 81
import org.xml.sax.DTDHandler;
......
933 933

  
934 934
    /**
935 935
     * Print a string representation of the XML document
936
     * NOTE: this detects the character encoding, or uses the XML default
936 937
     */
937 938
    public String toString(String user, String[] groups, boolean withInlinedata)
938 939
    {
939
        StringWriter docwriter = new StringWriter();
940
    	ByteArrayOutputStream out = new ByteArrayOutputStream();
940 941
        try {
941
            this.toXml(docwriter, user, groups, withInlinedata);
942
            this.toXml(out, user, groups, withInlinedata);
942 943
        } catch (McdbException mcdbe) {
943 944
            return null;
944 945
        }
945
        String document = docwriter.toString();
946
        String encoding = null;
947
        String document = null;
948
        try {
949
        	XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(out.toByteArray()));
950
        	encoding = xsr.getEncoding();
951
        	document = out.toString(encoding);
952
        } catch (Exception e) {
953
        	document = out.toString();
954
		}
946 955
        return document;
947 956
    }
948 957

  
949 958
    /**
950 959
     * Print a string representation of the XML document
960
     * NOTE: this detects the character encoding, or uses the XML default
951 961
     */
952 962
    public String toString()
953 963
    {
954
        StringWriter docwriter = new StringWriter();
955
        String userName = null;
964
    	ByteArrayOutputStream out = new ByteArrayOutputStream();
965
    	String userName = null;
956 966
        String[] groupNames = null;
957 967
        boolean withInlineData = true;
958 968
        try {
959
            this.toXml(docwriter, userName, groupNames, withInlineData);
969
            this.toXml(out, userName, groupNames, withInlineData);
960 970
        } catch (McdbException mcdbe) {
961 971
        	logMetacat.warn("Could not convert documentImpl to xml: " + mcdbe.getMessage());
962 972
            return null;
963 973
        }
964
        String document = docwriter.toString();
974
        String encoding = null;
975
        String document = null;
976
        try {
977
        	XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(out.toByteArray()));
978
        	encoding = xsr.getEncoding();
979
        	document = out.toString(encoding);
980
        } catch (Exception e) {
981
        	document = out.toString();
982
		}
965 983
        return document;
966 984
    }
985
    
986
	public byte[] getBytes() {
987
		ByteArrayOutputStream out = new ByteArrayOutputStream();
988
    	String userName = null;
989
        String[] groupNames = null;
990
        boolean withInlineData = true;
991
        try {
992
            this.toXml(out, userName, groupNames, withInlineData);
993
        } catch (McdbException mcdbe) {
994
        	logMetacat.warn("Could not convert documentImpl to xml: " + mcdbe.getMessage());
995
            return null;
996
        }
997
        return out.toByteArray();
998
	}
967 999

  
968 1000
    /**
969 1001
     * Get a text representation of the XML document as a string This older
......
1010 1042
	 *            matter withinInlineData's value, the document will
1011 1043
	 * 
1012 1044
	 */
1013
	public void toXml(Writer pw, String user, String[] groups, boolean withInLineData)
1045
	public void toXml(OutputStream out, String user, String[] groups, boolean withInLineData)
1014 1046
			throws McdbException {
1015 1047
		String documentDir = null;
1016 1048
		String documentPath = null;
......
1021 1053

  
1022 1054
			if (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST
1023 1055
					|| FileUtil.getFileSize(documentPath) == 0) {
1024
				FileWriter fileWriter = new FileWriter(documentPath);
1025
				toXmlFromDb(fileWriter, user, groups, true);
1056
				FileOutputStream fos = new FileOutputStream(documentPath);
1057
				toXmlFromDb(fos, user, groups, true);
1026 1058
			}
1027 1059
		} catch (PropertyNotFoundException pnfe) {
1028 1060
			throw new McdbException("Could not write file: " + documentPath + " : "
......
1036 1068
			throw new McdbException("Attempting to read a zero length document from disk: " + documentPath);
1037 1069
		}
1038 1070
		
1039
		readFromFileSystem(pw, user, groups, documentPath);
1071
		readFromFileSystem(out, user, groups, documentPath);
1040 1072
	}
1041 1073
    
1042 1074
    /**
......
1047 1079
	 *            matter withinInlineData's value, the document will
1048 1080
	 * 
1049 1081
	 */
1050
    public void toXmlFromDb(Writer pw, String user, String[] groups,
1051
            boolean withInLineData) throws McdbException
1082
    public void toXmlFromDb(OutputStream outputStream, String user, String[] groups,
1083
            boolean withInLineData) throws McdbException, IOException
1052 1084
    {
1053 1085
        // flag for process eml2
1054 1086
        boolean proccessEml2 = false;
......
1070 1102
        boolean processInlineData = false;
1071 1103

  
1072 1104
        TreeSet<NodeRecord> nodeRecordLists = null;
1073
        PrintWriter out = null;
1074
        if (pw instanceof PrintWriter) {
1075
            out = (PrintWriter) pw;
1076
        } else {
1077
            out = new PrintWriter(pw);
1078
        }
1105
        
1106
        // Note: we haven't stored the encoding, so we use the default for XML
1107
        String encoding = "UTF-8";
1108
        Writer out = new OutputStreamWriter(outputStream, encoding);
1079 1109
       
1080 1110
        // Here add code to handle subtree access control
1081 1111
        /*
......
1134 1164
                        logMetacat.debug("\n POPPED: "
1135 1165
                                + currentElement.getNodeName());
1136 1166
                        if (previousNodeWasElement) {
1137
                            out.print(">");
1167
                            out.write(">");
1138 1168
                            previousNodeWasElement = false;
1139 1169
                        }
1140 1170
                        if (currentElement.getNodePrefix() != null) {
1141
                            out.print("</" + currentElement.getNodePrefix() + ":"
1171
                            out.write("</" + currentElement.getNodePrefix() + ":"
1142 1172
                                    + currentElement.getNodeName() + ">");
1143 1173
                        } else {
1144
                            out.print("</" + currentElement.getNodeName() + ">");
1174
                            out.write("</" + currentElement.getNodeName() + ">");
1145 1175
                        }
1146 1176
                        currentElement = openElements.peek();
1147 1177
                    }
......
1150 1180

  
1151 1181
            // Handle the DOCUMENT node
1152 1182
            if (currentNode.getNodeType().equals("DOCUMENT")) {
1153
                out.print("<?xml version=\"1.0\"?>");
1183
                out.write("<?xml version=\"1.0\"?>");
1154 1184

  
1155 1185
                // Handle the ELEMENT nodes
1156 1186
            } else if (currentNode.getNodeType().equals("ELEMENT")) {
......
1158 1188
                    atRootElement = false;
1159 1189
                } else {
1160 1190
                    if (previousNodeWasElement) {
1161
                        out.print(">");
1191
                        out.write(">");
1162 1192
                    }
1163 1193
                }
1164 1194

  
......
1169 1199
                            && validateType.equals(DTD)) {
1170 1200
                        if ((doctype != null) && (system_id != null)) {
1171 1201

  
1172
                            out.print("<!DOCTYPE " + docname + " PUBLIC \""
1202
                            out.write("<!DOCTYPE " + docname + " PUBLIC \""
1173 1203
                                    + doctype + "\" \"" + system_id + "\">");
1174 1204
                        } else {
1175 1205

  
1176
                            out.print("<!DOCTYPE " + docname + ">");
1206
                            out.write("<!DOCTYPE " + docname + ">");
1177 1207
                        }
1178 1208
                    }
1179 1209
                }
......
1182 1212
                logMetacat.debug("\n PUSHED: " + currentNode.getNodeName());
1183 1213
                previousNodeWasElement = true;
1184 1214
                if (currentNode.getNodePrefix() != null) {
1185
                    out.print("<" + currentNode.getNodePrefix() + ":"
1215
                    out.write("<" + currentNode.getNodePrefix() + ":"
1186 1216
                            + currentNode.getNodeName());
1187 1217
                } else {
1188
                    out.print("<" + currentNode.getNodeName());
1218
                    out.write("<" + currentNode.getNodeName());
1189 1219
                }
1190 1220

  
1191 1221
                // if currentNode is inline and handle eml2, set flag process
......
1199 1229
                // Handle the ATTRIBUTE nodes
1200 1230
            } else if (currentNode.getNodeType().equals("ATTRIBUTE")) {
1201 1231
                if (currentNode.getNodePrefix() != null) {
1202
                    out.print(" " + currentNode.getNodePrefix() + ":"
1232
                    out.write(" " + currentNode.getNodePrefix() + ":"
1203 1233
                            + currentNode.getNodeName() + "=\""
1204 1234
                            + currentNode.getNodeData() + "\"");
1205 1235
                } else {
1206
                    out.print(" " + currentNode.getNodeName() + "=\""
1236
                    out.write(" " + currentNode.getNodeName() + "=\""
1207 1237
                            + currentNode.getNodeData() + "\"");
1208 1238
                }
1209 1239

  
......
1215 1245
                  nsprefix = " xmlns";
1216 1246
                }
1217 1247
                
1218
                out.print(nsprefix + currentNode.getNodeName() + "=\""
1248
                out.write(nsprefix + currentNode.getNodeName() + "=\""
1219 1249
                          + currentNode.getNodeData() + "\"");
1220 1250

  
1221 1251
                // Handle the TEXT nodes
1222 1252
            } else if (currentNode.getNodeType().equals("TEXT")) {
1223 1253
                if (previousNodeWasElement) {
1224
                    out.print(">");
1254
                    out.write(">");
1225 1255
                }
1226 1256
                if (!processInlineData) {
1227 1257
                    // if it is not inline data just out put data
1228
                    out.print(currentNode.getNodeData());
1258
                    out.write(currentNode.getNodeData());
1229 1259
                } else {
1230 1260
                    // if it is inline data first to get the inline data
1231 1261
                    // internal id
......
1253 1283
                    	// inline data file path, to get it
1254 1284

  
1255 1285
                        Reader reader = Eml200SAXHandler
1256
                                .readInlineDataFromFileSystem(fileName);
1286
                                .readInlineDataFromFileSystem(fileName, encoding);
1257 1287
                        char[] characterArray = new char[4 * 1024];
1258 1288
                        try {
1259 1289
                            int length = reader.read(characterArray);
1260 1290
                            while (length != -1) {
1261
                                out.print(new String(characterArray, 0,
1291
                                out.write(new String(characterArray, 0,
1262 1292
                                                length));
1263 1293
                                out.flush();
1264 1294
                                length = reader.read(characterArray);
......
1271 1301
                    else {
1272 1302
                        // if user can't read it, we only send it back a empty
1273 1303
                        // string in inline element.
1274
                        out.print("");
1304
                        out.write("");
1275 1305
                    }// else can't read inlinedata
1276 1306
                    // reset proccess inline data false
1277 1307
                    processInlineData = false;
......
1280 1310
                // Handle the COMMENT nodes
1281 1311
            } else if (currentNode.getNodeType().equals("COMMENT")) {
1282 1312
                if (previousNodeWasElement) {
1283
                    out.print(">");
1313
                    out.write(">");
1284 1314
                }
1285
                out.print("<!--" + currentNode.getNodeData() + "-->");
1315
                out.write("<!--" + currentNode.getNodeData() + "-->");
1286 1316
                previousNodeWasElement = false;
1287 1317

  
1288 1318
                // Handle the PI nodes
1289 1319
            } else if (currentNode.getNodeType().equals("PI")) {
1290 1320
                if (previousNodeWasElement) {
1291
                    out.print(">");
1321
                    out.write(">");
1292 1322
                }
1293
                out.print("<?" + currentNode.getNodeName() + " "
1323
                out.write("<?" + currentNode.getNodeName() + " "
1294 1324
                        + currentNode.getNodeData() + "?>");
1295 1325
                previousNodeWasElement = false;
1296 1326
                // Handle the DTD nodes (docname, publicid, systemid)
......
1309 1339
                        if ((dbPublicID != null) && (dbSystemID != null)) {
1310 1340

  
1311 1341
                            out
1312
                                    .print("<!DOCTYPE " + dbDocName
1342
                                    .write("<!DOCTYPE " + dbDocName
1313 1343
                                            + " PUBLIC \"" + dbPublicID
1314 1344
                                            + "\" \"" + dbSystemID + "\">");
1315 1345
                        } else {
1316 1346

  
1317
                            out.print("<!DOCTYPE " + dbDocName + ">");
1347
                            out.write("<!DOCTYPE " + dbDocName + ">");
1318 1348
                        }
1319 1349
                    }
1320 1350

  
......
1338 1368
            NodeRecord currentElement = (NodeRecord) openElements.pop();
1339 1369
            logMetacat.debug("\n POPPED: " + currentElement.getNodeName());
1340 1370
            if (currentElement.getNodePrefix() != null) {
1341
                out.print("</" + currentElement.getNodePrefix() + ":"
1371
                out.write("</" + currentElement.getNodePrefix() + ":"
1342 1372
                        + currentElement.getNodeName() + ">");
1343 1373
            } else {
1344
                out.print("</" + currentElement.getNodeName() + ">");
1374
                out.write("</" + currentElement.getNodeName() + ">");
1345 1375
            }
1346 1376
        }
1347 1377
        out.flush();
......
1361 1391
	 *            the location of the document on disk
1362 1392
	 * 
1363 1393
	 */
1364
    public void readFromFileSystem(Writer pw, String user, String[] groups,
1365
            String documentPath) throws McdbException {
1394
    public void readFromFileSystem(
1395
    		OutputStream out, String user, String[] groups, String documentPath) throws McdbException {
1366 1396
        
1367 1397
		String xmlFileContents = "";
1368 1398
		
1369 1399
		try {
1400
			// detect and use correct encoding
1370 1401
            xmlFileContents = FileUtil.readFileToString(documentPath);
1371
       
1372
            
1402
            // guess the encoding from default bytes
1403
			XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(xmlFileContents.getBytes()));
1404
			String encoding = xsr.getEncoding();
1405
			// reread the contents using the correct encoding
1406
			if (encoding != null) {
1407
				xmlFileContents = FileUtil.readFileToString(documentPath, encoding);
1408
			}
1409
			
1373 1410
			// get a list of inline data sections that are not readable
1374 1411
			// by this user
1375 1412
            Hashtable<String, String> unReadableInlineDataList =
......
1401 1438
				}
1402 1439
			}
1403 1440
            
1441
			// write with the detected encoding
1442
			Writer pw = new OutputStreamWriter(out, encoding);
1404 1443
            // write the doc
1405 1444
			pw.write(xmlFileContents);
1406 1445
			pw.close();	
......
1420 1459
	 * @param accNumber
1421 1460
	 *            the document id which is used to name the output file
1422 1461
	 */
1423
    private static void writeToFileSystem(InputStream xml, String accNumber) throws McdbException {
1462
    private static void writeToFileSystem(String xml, String accNumber, String encoding) throws McdbException {
1424 1463

  
1425 1464
		// write the document to disk
1426
//		FileWriter fileWriter = null;
1427 1465
		String documentDir = null;
1428 1466
		String documentPath = null;
1429 1467

  
......
1448 1486
					&& (FileUtil.getFileStatus(documentPath) == FileUtil.DOES_NOT_EXIST 
1449 1487
							|| FileUtil.getFileSize(documentPath) == 0)) {
1450 1488

  
1451
				//FileUtil.writeFile(documentPath, xml);
1452 1489
			    try
1453 1490
			    {
1454
			        String s = IOUtils.toString(xml);
1455
			        //TODO: the doc gets put into memory here.  I can't get
1456
			        //it to write to the filesystem correctly without doing 
1457
			        //this.  Need to revisit at some point.
1458
			        if(s.endsWith("\n"))
1459
			        {
1460
			          s += "\n";
1461
			        }
1462
			        //HACK: For some reason, FileOutputStream is cutting off the last
1463
			        //byte of the file if there is a newline present.  The only
1464
			        //way I could find to fix this was to add another newline.
1465
			         
1491
			        
1466 1492
			        FileOutputStream fos = new FileOutputStream(documentPath);
1467
			        IOUtils.write(s.getBytes(), fos);
1468
			        byte[] b = new byte[1024];
1469
			        int numread = xml.read(b, 0, 1024);
1470
			        /*while(numread != -1)
1471
			        {
1472
			            System.out.println("numread: " + numread + " s: \"" + new String(b, 0, numread) + "\"");
1473
			            System.out.println("last byte: " + b[numread] + "  one less: " + b[numread - 1] + " one more: " + b[numread + 1]);
1474
			            fos.write(b, 0, numread);
1475
			            numread = xml.read(b, 0, 1024);
1476
			        }*/
1493
			        IOUtils.write(xml.getBytes(encoding), fos);
1494
			  
1477 1495
			        fos.flush();
1478 1496
			        fos.close();
1479 1497
			    }
......
1487 1505
		} catch (PropertyNotFoundException pnfe) {
1488 1506
			throw new McdbException("Could not write file: " + documentPath + " : "
1489 1507
					+ pnfe.getMessage());
1490
		} /*catch (UtilException ue) {
1491
			throw new McdbException("Could not write file: " + documentPath + " : "
1492
					+ ue.getMessage());
1493
		}*/
1508
		}
1494 1509
	}	
1495 1510
    
1496 1511
    /**
......
2647 2662
                    //System.out.println("In lockgranted");
2648 2663
                	logReplication.info("lock granted for " + accnum
2649 2664
                            + " from " + server);
2665
                	
2666
                	// detect encoding
2667
                    XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(xmlString.getBytes()));
2668
			        String encoding = xsr.getEncoding();
2669
			        
2650 2670
                    /*
2651 2671
                     * XMLReader parser = initializeParser(conn, action, docid,
2652 2672
                     * updaterev, validate, user, groups, pub, serverCode, dtd);
......
2654 2674
                    logMetacat.debug("DocumentImpl.write - initializing parser");
2655 2675
                    parser = initializeParser(conn, action, docid, xmlReader, updaterev,
2656 2676
                            user, groups, pub, serverCode, dtd, ruleBase,
2657
                            needValidation, false, null, null);// false means it is not a revision doc
2677
                            needValidation, false, null, null, encoding);
2678
                    	// false means it is not a revision doc
2658 2679
                                   //null, null are createdate and updatedate
2659 2680
                                   //null will use current time as create date time
2660 2681
                    conn.setAutoCommit(false);
......
2664 2685
                    conn.setAutoCommit(true);
2665 2686
                    
2666 2687
                    //write the file to disk
2667
                    logMetacat.debug("DocumentImpl.write - Writing xml to file system");
2668
                    
2669
                    ByteArrayInputStream xmlBAOS = new ByteArrayInputStream(xmlString.getBytes());
2670
                	writeToFileSystem(xmlBAOS, accnum);
2688
                    logMetacat.debug("DocumentImpl.write - Writing xml to file system");                    
2689
                	writeToFileSystem(xmlString, accnum, encoding);
2671 2690

  
2672 2691
                    // write to xml_node complete. start the indexing thread.
2673 2692
                    addDocidToIndexingQueue(docid, rev);
......
2733 2752
        }
2734 2753
        XMLReader parser = null;
2735 2754
        try {
2755
            // detect encoding
2756
        	XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(xmlString.getBytes()));
2757
	        String encoding = xsr.getEncoding();
2758
	        
2736 2759
            parser = initializeParser(conn, action, docid, xmlReader, rev, user, groups,
2737
                    pub, serverCode, dtd, ruleBase, needValidation, false, null, null);
2760
                    pub, serverCode, dtd, ruleBase, needValidation, false, null, null, encoding);
2738 2761
                    // null and null are createtime and updatetime
2739 2762
                    // null will create current time
2740 2763
                    //false means it is not a revision doc
......
2747 2770
            conn.setAutoCommit(true);
2748 2771
            
2749 2772
            //write the file to disk
2750
            ByteArrayInputStream xmlBAOS = new ByteArrayInputStream(xmlString.getBytes());
2751
        	writeToFileSystem(xmlBAOS, accnum);
2752 2773

  
2774
        	writeToFileSystem(xmlString, accnum, encoding);
2775

  
2753 2776
            addDocidToIndexingQueue(docid, rev);
2754 2777
        } catch (Exception e) {
2755 2778
        	logMetacat.error("DocumentImpl.write - Problem with parsing: " + e.getMessage());
......
2916 2939
            {
2917 2940
                isRevision = true;
2918 2941
            }
2942
            // detect encoding
2943
            XmlStreamReader xsr = new XmlStreamReader(new ByteArrayInputStream(xmlString.getBytes()));
2944
	        String encoding = xsr.getEncoding();
2945
	       
2919 2946
            parser = initializeParser(conn, action, docid, xmlReader, rev, user, groups,
2920 2947
                    pub, serverCode, dtd, ruleBase, needValidation, 
2921
                    isRevision, createDate, updateDate);
2948
                    isRevision, createDate, updateDate, encoding);
2922 2949
         
2923 2950
            conn.setAutoCommit(false);
2924 2951
            parser.parse(new InputSource(xmlReader));
......
2926 2953
            conn.setAutoCommit(true);
2927 2954
            
2928 2955
            // Write the file to disk
2929
            ByteArrayInputStream xmlBAOS = new ByteArrayInputStream(xmlString.getBytes());
2930
        	writeToFileSystem(xmlBAOS, accnum);
2956
        	writeToFileSystem(xmlString, accnum, encoding);
2931 2957
            
2932 2958
            // write to xml_node complete. start the indexing thread.
2933 2959
            // this only for xml_documents
......
3432 3458
            String action, String docid, Reader xml, String rev, String user,
3433 3459
            String[] groups, String pub, int serverCode, Reader dtd,
3434 3460
            String ruleBase, boolean needValidation, boolean isRevision,
3435
            String createDate, String updateDate) throws Exception
3461
            String createDate, String updateDate, String encoding) throws Exception
3436 3462
    {
3437 3463
        XMLReader parser = null;
3438 3464
        try {
......
3449 3475
                chandler = new Eml200SAXHandler(dbconn, action, docid, rev,
3450 3476
                        user, groups, pub, serverCode, createDate, updateDate);
3451 3477
                chandler.setIsRevisionDoc(isRevision);
3478
                chandler.setEncoding(encoding);
3452 3479
                parser.setContentHandler((ContentHandler) chandler);
3453 3480
                parser.setErrorHandler((ErrorHandler) chandler);
3454 3481
                parser.setProperty(DECLARATIONHANDLERPROPERTY, chandler);
......
3475 3502
                chandler = new Eml210SAXHandler(dbconn, action, docid, rev,
3476 3503
                        user, groups, pub, serverCode, createDate, updateDate);
3477 3504
                chandler.setIsRevisionDoc(isRevision);
3505
                chandler.setEncoding(encoding);
3478 3506
                parser.setContentHandler((ContentHandler) chandler);
3479 3507
                parser.setErrorHandler((ErrorHandler) chandler);
3480 3508
                parser.setProperty(DECLARATIONHANDLERPROPERTY, chandler);
......
3501 3529
                chandler = new DBSAXHandler(dbconn, action, docid, rev, user,
3502 3530
                        groups, pub, serverCode, createDate, updateDate);
3503 3531
                chandler.setIsRevisionDoc(isRevision);
3532
                chandler.setEncoding(encoding);
3504 3533
                parser.setContentHandler((ContentHandler) chandler);
3505 3534
                parser.setErrorHandler((ErrorHandler) chandler);
3506 3535
                parser.setProperty(DECLARATIONHANDLERPROPERTY, chandler);
......
4071 4100
                if (useOldReadAlgorithm) {
4072 4101
                    logMetacat.error("DocumentImpl.main - " + xmldoc.readUsingSlowAlgorithm());
4073 4102
                } else {
4074
                    xmldoc.toXml(new PrintWriter(System.out), null, null, true);
4103
                    xmldoc.toXml(System.out, null, null, true);
4075 4104
                }
4076 4105
            } else if (action.equals("DELETE")) {
4077 4106
                DocumentImpl.delete(docid, null, null,null);
......
4105 4134
            }
4106 4135
            dbconn.close();
4107 4136
        } catch (McdbException me) {
4108
            me.toXml(new PrintWriter(System.err));
4137
            me.toXml(new OutputStreamWriter(System.err));
4109 4138
        } catch (AccessionNumberException ane) {
4110 4139
            System.err.println(ane.getMessage());
4111 4140
        } catch (Exception e) {
src/edu/ucsb/nceas/metacat/MetacatHandler.java
27 27
import java.io.BufferedInputStream;
28 28
import java.io.File;
29 29
import java.io.FileInputStream;
30
import java.io.FileReader;
31 30
import java.io.IOException;
31
import java.io.InputStreamReader;
32 32
import java.io.OutputStream;
33 33
import java.io.OutputStreamWriter;
34 34
import java.io.PrintWriter;
35
import java.io.Reader;
35 36
import java.io.StringReader;
36 37
import java.io.ByteArrayOutputStream;
38
import java.io.UnsupportedEncodingException;
37 39
import java.io.Writer;
38 40
import java.net.MalformedURLException;
39 41
import java.net.URL;
......
53 55
import java.util.zip.ZipEntry;
54 56
import java.util.zip.ZipOutputStream;
55 57

  
56
import javax.servlet.ServletContext;
57 58
import javax.servlet.ServletOutputStream;
58 59
import javax.servlet.http.HttpServletRequest;
59 60
import javax.servlet.http.HttpServletResponse;
60 61
import javax.servlet.http.HttpSession;
61 62
import javax.activation.MimetypesFileTypeMap;
62 63

  
64
import org.apache.commons.io.input.XmlStreamReader;
63 65
import org.apache.log4j.Logger;
64 66
import org.ecoinformatics.eml.EMLParser;
65 67

  
......
83 85
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
84 86
import edu.ucsb.nceas.metacat.service.SessionService;
85 87
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
88
import edu.ucsb.nceas.metacat.shared.HandlerException;
86 89
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
87 90
import edu.ucsb.nceas.metacat.shared.ServiceException;
88 91
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
......
109 112
public class MetacatHandler {
110 113

  
111 114
    private static boolean _sitemapScheduled = false;
115
    
116
    private static Logger logMetacat = Logger.getLogger(MetacatHandler.class);
112 117

  
113 118
    // Constants -- these should be final in a servlet    
114 119
    private static final String PROLOG = "<?xml version=\"1.0\"?>";
......
219 224
     * queries supported by the WFS / WMS standards
220 225
     * 
221 226
     * handleSQuery(out, params, response, username, groupnames, sess_id);
227
     * @throws HandlerException 
222 228
     */
223
    protected void handleSpatialQuery(PrintWriter out, Hashtable<String, String[]> params,
229
    protected void handleSpatialQuery(Writer out, Hashtable<String, String[]> params,
224 230
            HttpServletResponse response,
225 231
            String username, String[] groupnames,
226
            String sess_id) throws PropertyNotFoundException {
232
            String sess_id) throws PropertyNotFoundException, HandlerException {
227 233
        
228 234
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
229 235
        
230 236
        if ( !PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
231 237
            response.setContentType("text/html");
232
            out.println("<html> Metacat Spatial Option is turned off </html>");
233
            out.close();
234
            return ;
238
            try {
239
				out.write("<html> Metacat Spatial Option is turned off </html>");
240
	            out.close();
241
			} catch (IOException e) {
242
				throw new HandlerException(e.getMessage());
243
			}
244
            return;
235 245
        }
236 246
        
237 247
        /*
......
458 468
     * @param response the response object linked to the client
459 469
     * @param conn the database connection
460 470
     */
461
    protected void handleSQuery(PrintWriter out, Hashtable<String, String[]> params,
471
    protected void handleSQuery(Writer out, Hashtable<String, String[]> params,
462 472
            HttpServletResponse response, String user, String[] groups,
463 473
            String sessionid) throws PropertyNotFoundException {
464 474
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
......
485 495
     * @param params the Hashtable of parameters that should be included in the
486 496
     *            squery.
487 497
     * @param response the response object linked to the client
498
     * @throws IOException 
499
     * @throws UnsupportedEncodingException 
488 500
     */
489
    protected void handleQuery(PrintWriter out, Hashtable<String, String[]> params,
501
    protected void handleQuery(Writer out, Hashtable<String, String[]> params,
490 502
            HttpServletResponse response, String user, String[] groups,
491
            String sessionid) throws PropertyNotFoundException {
503
            String sessionid) throws PropertyNotFoundException, UnsupportedEncodingException, IOException {
492 504
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
493 505
        long queryWarnLimit = Long.parseLong(PropertyService.getProperty("database.queryTimeWarnLimit"));
494 506
        
......
920 932
      throws Exception
921 933
    {
922 934
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
923
        PrintWriter out = new PrintWriter(baos);
935
     // use UTF-8 encoding for DB query
936
        Writer out = new OutputStreamWriter(baos, MetaCatServlet.DEFAULT_ENCODING);
924 937
        handleQuery(out, params, null, username, groups, sessionid);
925 938
        out.flush();
926 939
        baos.flush();
927 940
        //baos.close(); 
928 941
        //System.out.println("result from query: " + baos.toString());
929
        MetacatResultSet rs = new MetacatResultSet(baos.toString());
942
        MetacatResultSet rs = new MetacatResultSet(baos.toString(MetaCatServlet.DEFAULT_ENCODING));
930 943
        return rs;
931 944
    }
932 945
    
......
1047 1060
                    // Try to get the metadata file from disk. If it isn't
1048 1061
                    // found, create it from the db and write it to disk then.
1049 1062
                    try {
1050
                        PrintWriter pw = new PrintWriter(out);
1051
                        doc.toXml(pw, user, groups, withInlineData);               
1063
                        doc.toXml(out, user, groups, withInlineData);               
1052 1064
                    } catch (McdbException e) {
1053 1065
                        // any exceptions in reading the xml from disc, and we go back to the
1054 1066
                        // old way of creating the xml directly.
1055 1067
                        logMetacat.error("MetaCatServlet.readFromMetacat - could not read from document file " + docid 
1056 1068
                                + ": " + e.getMessage());
1057 1069
                        e.printStackTrace(System.out);
1058
                        PrintWriter pw = new PrintWriter(out);
1059
                        doc.toXmlFromDb(pw, user, groups, withInlineData);
1070
                        doc.toXmlFromDb(out, user, groups, withInlineData);
1060 1071
                    }
1061 1072
                } else {
1062 1073
                    // TODO MCD, this should read from disk as well?
......
1074 1085
                        response.setContentType("text/html"); //MIME type
1075 1086
                    }
1076 1087
                    
1077
                    PrintWriter pw = new PrintWriter(out);
1088
                    // TODO: detect actual encoding
1089
                    Writer w = new OutputStreamWriter(out, response.getCharacterEncoding());
1078 1090
                    
1079 1091
                    // Look up the document type
1080 1092
                    String doctype = doc.getDoctype();
1081 1093
                    // Transform the document to the new doctype
1082 1094
                    DBTransform dbt = new DBTransform();
1083
                    dbt.transformXMLDocument(doc.toString(user, groups,
1084
                            withInlineData), doctype, "-//W3C//HTML//EN",
1085
                            qformat, pw, params, null);
1095
                    dbt.transformXMLDocument(
1096
                    		doc.toString(user, groups, withInlineData), 
1097
                    		doctype, "-//W3C//HTML//EN",
1098
                            qformat, 
1099
                            w, 
1100
                            params, 
1101
                            null);
1086 1102
                }
1087 1103
                
1088 1104
            }
......
1280 1296
                    
1281 1297
                } else {
1282 1298
                    // this is metadata doc; add doc to zip
1283
                    bytestring = doc.toString().getBytes();
1299
                    bytestring = doc.getBytes();
1284 1300
                    //use provided file name if given
1285 1301
                    if (providedFileName != null && providedFileName.length() > 1) {
1286 1302
                        zentry = new ZipEntry(providedFileName);
......
2436 2452
                logMetacat.info("MetaCatServlet.handleInsertMultipartAction - Uploading the following to Metacat:" +
2437 2453
                        fileName + ", " + docid + ", " +
2438 2454
                        username + ", " + groupnames);
2439
                FileReader fr = new FileReader(newFile);
2440 2455
                
2456
                // Read the file with appropriate encoding
2457
                XmlStreamReader xsr = new XmlStreamReader(new FileInputStream(newFile));
2458
                String encoding = xsr.getEncoding();
2459
                Reader fr = new InputStreamReader(new FileInputStream(newFile), encoding);
2460
                
2441 2461
                char[] c = new char[1024];
2442 2462
                int numread = fr.read(c, 0, 1024);
2443 2463
                StringBuffer sb = new StringBuffer();
......
2652 2672
     */
2653 2673
    protected void handleSetAccessAction(PrintWriter out, Hashtable<String, String[]> params,
2654 2674
            String username, HttpServletRequest request, HttpServletResponse response) {
2655
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2675
        
2656 2676
        String permission = null;
2657 2677
        String permType = null;
2658 2678
        String permOrder = null;
......
2788 2808
                    //insert permission
2789 2809
                    AccessControlForSingleFile accessControl = 
2790 2810
                        new AccessControlForSingleFile(accessionNumber);
2791
                    Long l = new Long(permission);
2792 2811
                    //System.out.println("permission in MetacatHandler: " + l.longValue());
2793 2812
                    //System.out.println("permission in MetacatHandler: " + Integer.valueOf(AccessControlList.intValue(permission)).longValue());
2794 2813
                    accessControl.insertPermissions(principal, Integer.valueOf(AccessControlList.intValue(permission)).longValue(), permType, permOrder);
......
2835 2854
     */
2836 2855
    private String getFieldValueForDoc(String accessionNumber, String fieldName)
2837 2856
    throws Exception {
2838
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2839 2857
        if (accessionNumber == null || accessionNumber.equals("")
2840 2858
        || fieldName == null || fieldName.equals("")) { throw new Exception(
2841 2859
                "Docid or field name was not specified"); }
......
2936 2954
     * A method to output setAccess action result
2937 2955
     */
2938 2956
    private void outputResponse(Vector<String> successList, Vector<String> errorList,
2939
            PrintWriter out) {
2940
        boolean error = false;
2941
        boolean success = false;
2942
        // Output prolog
2943
        out.println(PROLOG);
2944
        // output success message
2945
        if (successList != null) {
2946
            for (int i = 0; i < successList.size(); i++) {
2947
                out.println(SUCCESS);
2948
                out.println(successList.elementAt(i));
2949
                out.println(SUCCESSCLOSE);
2950
                success = true;
2951
            }
2952
        }
2953
        // output error message
2954
        if (errorList != null) {
2955
            for (int i = 0; i < errorList.size(); i++) {
2956
                out.println(ERROR);
2957
                out.println(errorList.elementAt(i));
2958
                out.println(ERRORCLOSE);
2959
                error = true;
2960
            }
2961
        }
2962
        
2963
        // if no error and no success info, send a error that nothing happened
2964
        if (!error && !success) {
2965
            out.println(ERROR);
2966
            out.println("Nothing happend for setaccess action");
2967
            out.println(ERRORCLOSE);
2968
        }
2957
            Writer out) {
2958
    	try {
2959
	        boolean error = false;
2960
	        boolean success = false;
2961
	        // Output prolog
2962
	        out.write(PROLOG);
2963
	        // output success message
2964
	        if (successList != null) {
2965
	            for (int i = 0; i < successList.size(); i++) {
2966
	                out.write(SUCCESS);
2967
	                out.write(successList.elementAt(i));
2968
	                out.write(SUCCESSCLOSE);
2969
	                success = true;
2970
	            }
2971
	        }
2972
	        // output error message
2973
	        if (errorList != null) {
2974
	            for (int i = 0; i < errorList.size(); i++) {
2975
	                out.write(ERROR);
2976
	                out.write(errorList.elementAt(i));
2977
	                out.write(ERRORCLOSE);
2978
	                error = true;
2979
	            }
2980
	        }
2981
	        
2982
	        // if no error and no success info, send a error that nothing happened
2983
	        if (!error && !success) {
2984
	            out.write(ERROR);
2985
	            out.write("Nothing happend for setaccess action");
2986
	            out.write(ERRORCLOSE);
2987
	        }
2988
    	} catch (Exception e) {
2989
			logMetacat.error(e.getMessage(), e);
2990
		} 
2969 2991
    }
2970 2992
    
2971 2993
    /*
......
2973 2995
     * append rev for it. The rev come from xml_documents
2974 2996
     */
2975 2997
    private static String appendRev(String docid) throws PropertyNotFoundException, SQLException, McdbDocNotFoundException {
2976
//        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
2977 2998
        String newAccNum = null;
2978 2999
        String separator = PropertyService.getProperty("document.accNumSeparator");
2979 3000
        int firstIndex = docid.indexOf(separator);
......
3003 3024
     * @param request a servlet request, from which we determine the context
3004 3025
     */
3005 3026
    protected void scheduleSitemapGeneration(HttpServletRequest request) {
3006
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3007 3027
        if (!_sitemapScheduled) {
3008 3028
            String directoryName = null;
3009 3029
            String skin = null;
src/edu/ucsb/nceas/metacat/McdbException.java
27 27

  
28 28
package edu.ucsb.nceas.metacat;
29 29

  
30
import java.io.IOException;
30 31
import java.io.PrintWriter;
32
import java.io.Writer;
31 33

  
32 34
/**
33 35
 * Exception thrown when an error occurs because a problem occurred in
......
113 115
   * is null, and if the tunnelled exception is not null, then
114 116
   * it returns the message from the tunnelled exception.
115 117
   */
116
  public void toXml(PrintWriter pw) {
118
  public void toXml(Writer pw) {
117 119
    String msg = super.getMessage();
118 120

  
119 121
    if (msg == null && exception != null) {
120 122
      msg = exception.getMessage();
121 123
    }
122 124

  
123
    pw.println("<?xml version=\"1.0\"?>");
124
    pw.println("<error>" + msg + "</error>");
125
    pw.flush();
125
    try {
126
		pw.write("<?xml version=\"1.0\"?>");
127
		pw.write("<error>" + msg + "</error>");
128
	    pw.flush();
129
	} catch (IOException e) {
130
		e.printStackTrace();
131
	}
132
    
126 133
  }
127 134
}
src/edu/ucsb/nceas/metacat/DBQuery.java
30 30

  
31 31
package edu.ucsb.nceas.metacat;
32 32

  
33
import java.io.*;
34
import java.util.zip.*;
33
import java.io.BufferedWriter;
34
import java.io.File;
35
import java.io.FileInputStream;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.InputStreamReader;
40
import java.io.OutputStreamWriter;
41
import java.io.Reader;
42
import java.io.StringReader;
43
import java.io.StringWriter;
44
import java.io.Writer;
35 45
import java.sql.PreparedStatement;
36 46
import java.sql.ResultSet;
37 47
import java.sql.SQLException;
38
import java.util.*;
48
import java.util.Enumeration;
49
import java.util.Hashtable;
50
import java.util.Iterator;
51
import java.util.StringTokenizer;
52
import java.util.Vector;
53
import java.util.zip.ZipEntry;
54
import java.util.zip.ZipOutputStream;
39 55

  
40 56
import javax.servlet.ServletOutputStream;
41 57
import javax.servlet.http.HttpServletResponse;
42
import javax.servlet.http.HttpSession;
43 58

  
44 59
import org.apache.log4j.Logger;
45 60

  
46
import org.w3c.dom.*;
47
import javax.xml.parsers.DocumentBuilderFactory;
48
import org.xml.sax.InputSource;
49
import org.w3c.dom.ls.*;
50

  
51 61
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
52 62
import edu.ucsb.nceas.metacat.database.DBConnection;
53 63
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
......
113 123
     * the main routine used to test the DBQuery utility.
114 124
     * <p>
115 125
     * Usage: java DBQuery <xmlfile>
116
     *
126
     * NOTE: encoding should be provided for best results
117 127
     * @param xmlfile the filename of the xml file containing the query
118 128
     */
119 129
    static public void main(String[] args)
......
149 159

  
150 160
                // Execute the query
151 161
                DBQuery queryobj = new DBQuery();
152
                FileReader xml = new FileReader(new File(xmlfile));
162
                Reader xml = new InputStreamReader(new FileInputStream(new File(xmlfile)));
153 163
                Hashtable nodelist = null;
154 164
                //nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
155 165

  
......
187 197
                //write into a file "result.txt"
188 198
                if (!showRuntime) {
189 199
                    File f = new File("./result.txt");
190
                    FileWriter fw = new FileWriter(f);
200
                    Writer fw = new OutputStreamWriter(new FileOutputStream(f));
191 201
                    BufferedWriter out = new BufferedWriter(fw);
192 202
                    out.write(result.toString());
193 203
                    out.flush();
......
288 298
   * @param sessionid  the sessionid
289 299
   */
290 300
  public void findDocuments(HttpServletResponse response,
291
                                       PrintWriter out, Hashtable params,
301
                                       Writer out, Hashtable params,
292 302
                                       String user, String[] groups,
293 303
                                       String sessionid) throws PropertyNotFoundException
294 304
  {
......
309 319
     * @param sessionid  the sessionid
310 320
     */
311 321
    public void findDocuments(HttpServletResponse response,
312
                                         PrintWriter out, Hashtable params,
322
                                         Writer out, Hashtable params,
313 323
                                         String user, String[] groups,
314 324
                                         String sessionid, boolean useXMLIndex)
315 325
    {
......
379 389
      {
380 390
        //knb format, in this case we will get whole result and sent it out
381 391
        response.setContentType("text/html");
382
        PrintWriter nonout = null;
392
        Writer nonout = null;
383 393
        StringBuffer xml = createResultDocument(xmlquery, qspec, nonout, user,
384 394
                                                groups, useXMLIndex, pagesize, 
385 395
                                                pagestart, sessionid, qformat);
......
440 450
   */
441 451
    public StringBuffer createResultDocument(String xmlquery,
442 452
                                              QuerySpecification qspec,
443
                                              PrintWriter out,
453
                                              Writer out,
444 454
                                              String user, String[] groups,
445 455
                                              boolean useXMLIndex)
446 456
    {
......
455 465
   */
456 466
  public StringBuffer createResultDocument(String xmlquery,
457 467
                                            QuerySpecification qspec,
458
                                            PrintWriter out,
468
                                            Writer out,
459 469
                                            String user, String[] groups,
460 470
                                            boolean useXMLIndex, int pagesize,
461 471
                                            int pagestart, String sessionid, 
......
481 491
    //send out a new query
482 492
    if (out != null)
483 493
    {
484
      out.println(resultset.toString());
494
    	try {
495
    	  out.write(resultset.toString());
496
		} catch (IOException e) {
497
			logMetacat.error(e.getMessage(), e);
498
		}
485 499
    }
486 500
    if (qspec != null)
487 501
    {
......
543 557
    resultset.append(closeRestultset);
544 558
    if (out != null)
545 559
    {
546
      out.println(closeRestultset);
560
      try {
561
		out.write(closeRestultset);
562
		} catch (IOException e) {
563
			logMetacat.error(e.getMessage(), e);
564
		}
547 565
    }
548 566

  
549 567
    //default to returning the whole resultset
......
554 572
     * Find the doc list which match the query
555 573
     */
556 574
    private StringBuffer findResultDoclist(QuerySpecification qspec,
557
                                      PrintWriter out,
575
                                      Writer out,
558 576
                                      String user, String[]groups,
559 577
                                      DBConnection dbconn, boolean useXMLIndex,
560 578
                                      int pagesize, int pagestart, String sessionid, 
......
651 669
   	    	logMetacat.info("DBQuery.findResultDoclist - result from cache !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
652 670
   	    	 if (out != null)
653 671
   	         {
654
   	             out.println(cachedResult);
672
   	             out.write(cachedResult);
655 673
   	         }
656 674
   	    	 resultsetBuffer.append(cachedResult);
657 675
   	    	 return resultsetBuffer;
......
793 811
     resultsetBuffer.append("\n<lastpage>" + lastpage + "</lastpage>\n");
794 812
     if (out != null)
795 813
     {
796
         out.println("\n<lastpage>" + lastpage + "</lastpage>\n");
814
         out.write("\n<lastpage>" + lastpage + "</lastpage>\n");
797 815
     }
798 816
     
799 817
     // now we only cached none-paged query and user is public
......
814 832
     */
815 833
    private StringBuffer handleSubsetResult(QuerySpecification qspec,
816 834
                                           StringBuffer resultset,
817
                                           PrintWriter out, ResultDocumentSet partOfDoclist,
835
                                           Writer out, ResultDocumentSet partOfDoclist,
818 836
                                           String user, String[]groups,
819 837
                                       DBConnection dbconn, boolean useXMLIndex,
820 838
                                       String qformat)
......
951 969
         //send single element to output
952 970
         if (out != null)
953 971
         {
954
             out.println(xmlElement);
972
             out.write(xmlElement);
955 973
         }
956 974
         resultset.append(xmlElement);
957 975
     }//while
......
978 996
         //send single element to output
979 997
         if (out != null)
980 998
         {
981
             out.println(xmlElement);
999
             out.write(xmlElement);
982 1000
         }
983 1001
         resultset.append(xmlElement);
984 1002
     }//while
src/edu/ucsb/nceas/metacat/DBTransform.java
27 27

  
28 28
package edu.ucsb.nceas.metacat;
29 29

  
30
import java.io.*;
31
import java.sql.*;
30
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.FileNotFoundException;
33
import java.io.IOException;
34
import java.io.OutputStreamWriter;
35
import java.io.StringReader;
36
import java.io.StringWriter;
37
import java.io.Writer;
38
import java.sql.SQLException;
32 39
import java.util.Enumeration;
33 40
import java.util.Hashtable;
34 41
import java.util.Iterator;
......
100 107
   */
101 108
  public void transformXMLDocument(String doc, String sourceType,
102 109
                                   String targetType, String qformat,
103
                                   PrintWriter pw, Hashtable<String, String[]> param,
110
                                   Writer w, Hashtable<String, String[]> param,
104 111
                                   String sessionid)
105 112
 {
106 113

  
107
    // Look up the stylesheet for this type combination
108
    String xslSystemId = getStyleSystemId(qformat, sourceType, targetType);
109
    if (xslSystemId != null)
110
    {
111
      try
112
      {// Create a stylesheet from the system id that was found
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff