1 package org.kuali.ole;
2
3 import org.marc4j.MarcReader;
4 import org.marc4j.MarcStreamReader;
5 import org.marc4j.MarcWriter;
6 import org.marc4j.MarcXmlWriter;
7 import org.marc4j.marc.*;
8 import org.marc4j.marc.impl.Verifier;
9
10 import java.io.*;
11
12
13
14
15
16
17
18
19
20
21 public class MRKToMARCXMLConverter {
22 MarcFactory marcFactory = MarcFactory.newInstance();
23
24 public String convert(String content) {
25 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
26 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
27 MarcWriter writer = new MarcXmlWriter(byteArrayOutputStream, true);
28
29 Record record;
30 String inline;
31
32 BufferedReader br = null;
33 br = new BufferedReader(new InputStreamReader(byteArrayInputStream));
34 record = marcFactory.newRecord();
35
36 try {
37 while ((inline = br.readLine()) != null) {
38 if (inline.equals("") || inline.startsWith(" ")) {
39 writer.write(record);
40 record = marcFactory.newRecord();
41 } else {
42 record = addLineToRecord(inline, record);
43 }
44 }
45 } catch (IOException e) {
46
47 }
48
49 writer.write(record);
50 writer.close();
51 return new String(byteArrayOutputStream.toByteArray());
52
53 }
54
55 public Record addLineToRecord(String inline, Record record) {
56 String tag = "";
57
58 tag = inline.substring(1, 4);
59
60 if (tag.equals("LDR")) {
61 Leader leader = marcFactory.newLeader(inline.substring(6, 30));
62 record.setLeader(leader);
63 } else if (Verifier.isControlField(tag)) {
64 ControlField cf = marcFactory.newControlField(tag, inline.substring(6));
65 record.addVariableField(cf);
66 } else {
67 record.addVariableField(processDatafield(inline));
68 }
69
70 return record;
71 }
72
73 private DataField processDatafield(String inline) {
74 String tag;
75 char ind1;
76 char ind2;
77
78 tag = inline.substring(1, 4);
79
80 if (inline.substring(6, 7).equals("\""))
81 ind1 = ' ';
82 else
83 ind1 = inline.charAt(6);
84
85 if (inline.substring(7, 8).equals("\""))
86 ind2 = ' ';
87 else
88 ind2 = inline.charAt(7);
89
90 DataField df = marcFactory.newDataField(tag, ind1, ind2);
91
92 String[] tagSplit = inline.substring(8).split("\\$");
93 Subfield sf = null;
94 for (String text : tagSplit) {
95 if (!text.equals("") && !text.equals(" ")) {
96 char subfield = text.charAt(0);
97 String subfieldText = text.substring(1);
98 sf = marcFactory.newSubfield(subfield, subfieldText);
99 df.addSubfield(sf);
100 }
101 }
102 return df;
103 }
104 }