I've already obtained bookmarks but I need to know where these bookmarks are located in the PDF. (Bookmark 1 = page 1,..., Bookmark 54= page 72 etc..). Anyone can help me? Thanks for the support.
PDDocument doc = PDDocument.load( ... );
PDDocumentOutline root = doc.getDocumentCatalog().getDocumentOutline();
PDOutlineItem item = root.getFirstChild();
while( item != null )
{
System.out.println( "Item:" + item.getTitle() );
item = item.getNextSibling();
}
Excerpt from the PrintBookmarks.java example from the source code download:
if (item.getDestination() instanceof PDPageDestination)
{
PDPageDestination pd = (PDPageDestination) item.getDestination();
System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
else if (item.getDestination() instanceof PDNamedDestination)
{
PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) item.getDestination());
if (pd != null)
{
System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
}
if (item.getAction() instanceof PDActionGoTo)
{
PDActionGoTo gta = (PDActionGoTo) item.getAction();
if (gta.getDestination() instanceof PDPageDestination)
{
PDPageDestination pd = (PDPageDestination) gta.getDestination();
System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
else if (gta.getDestination() instanceof PDNamedDestination)
{
PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) gta.getDestination());
if (pd != null)
{
System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
}
}
I'm having the docx file with the following string
"My name is santhanam"
"I'm from India"
"I love docx4j"
And I bookmarked the above three paragraph with the bookmark name para0,para1,para2. I need to get the output as text file with following string
{para0}My name is santhanam{para0}
{para1}I'm from India{para1}
{para2}I love docx4j{para2}
Which I already succeeded with following code.
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "5.txt";
String inputfilepath = "bookmark.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// String bookmark[] = new String[100000];
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
// this to suit
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results)
{
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
// System.out.println("Document\n---------------\n" + docString);
try {
// BufferedWriter bw = new BufferedWriter(new
// FileWriter(outputfilepath));
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement)
obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private P findBookmarkedParagraphInMainDocumentPart(String name, MainDocumentPart documentPart)
throws JAXBException, Docx4JException {
final String xpath = "//w:bookmarkStart[#w:name='" + name + "']/..";
List<Object> objects = documentPart.getJAXBNodesViaXPath(xpath, false);
return (org.docx4j.wml.P) XmlUtils.unwrap(objects.get(0));
}
// No xpath implementation for other parts than main document; traverse
// manually
private P findBookmarkedParagraphInPart(Object parent, String bookmark) {
P p = traversePartForBookmark(parent, bookmark);
return p;
}
// Used internally by findBookmarkedParagrapghInPart().
private P traversePartForBookmark(Object parent, String bookmark) {
P p = null;
List children = TraversalUtil.getChildrenImpl(parent);
if (children != null) {
for (Object o : children) {
o = XmlUtils.unwrap(o);
if (o instanceof CTBookmark) {
if (((CTBookmark) o).getName().toLowerCase().equals(bookmark)) {
return (P) parent; // If bookmark found, the surrounding
// P is what is interesting.
}
}
p = traversePartForBookmark(o, bookmark);
if (p != null) {
break;
}
}
}
return p;
}
}
Now I bookmarked the docx file which contains tables with table0 to table(etc) with bookmarked (Tr)rows and (Tc)cells.Is it possible to get the output as
{table0}{row0}{cello}{para0}text string{para0}{para1}text string{para1}{cell0}{row0}
{row1}{cell1}{para2}text string{para2}{para3}text string{para3}{cell1}{row1}{table0}
Thanks in advance.
UPDATE
Now,I'm halfway there with the following code
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "BMChapter 14.txt";
String inputfilepath = "BMTable.docx";
String rowbm = null;
String tblbm = null;
String parabm = null;
String cellbm = null;
String tblparabm = null;
List<Object> tblTexts = null;
String partDocString = null;
String prtblbm = null;
String prrowbm = null;
String prcellbm = null;
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results) {
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
} else {
if (BookMarkName.startsWith("table")) {
// rowbm = "</"+BookMarkName+">";
// tblbm = "<"+BookMarkName+">";
tblbm = BookMarkName;
}
if (BookMarkName.startsWith("row")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm +="<"+BookMarkName+">";
rowbm = BookMarkName;
}
if (BookMarkName.startsWith("cell")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
cellbm = BookMarkName;
}
if (BookMarkName.startsWith("tble")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
tblparabm = BookMarkName;
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
if (prtblbm != tblbm) {
docString += "<" + tblbm + ">";
}
if (prrowbm != rowbm) {
docString += "<" + rowbm + ">";
}
if (prcellbm != cellbm) {
docString += "<" + cellbm + ">";
}
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + tblparabm + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + tblparabm + ">");
}
prtblbm = tblbm;
prrowbm = rowbm;
prcellbm = cellbm;
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
System.out.println(docString);
}
I am getting a string response from server like this..
[
Anchor{anchorName='&loreal_lip_balm',
clientName='loreal india',
anchorPrice=10,
campaigns=[
Campaign{
campaignId='loreal_camp1',
question='How to Turn Your Melted Lipstick into a Tinted Lip Balm',
startDate=2015-08-04,
endDate=2015-08-04,
imageURL='null',
regionCountry='ALL',
rewardInfo='null',
campaignPrice=20,
options=null
}
]},
Anchor{
anchorName='&loreal_total_repair_5',
clientName='loreal india',
anchorPrice=125,
campaigns=[
Campaign{
campaignId='loreal_camp2',
question='Is it a good
product to buy?',
startDate=2015-08-04,
endDate=2015-08-04,
imageURL='null',
regionCountry='ALL',
rewardInfo='null',
campaignPrice=20,
options=null
}
]
}
].
can anybody tell me how to parse this.It is not a json response.
I used hand coded parsers for simple languages where I felt that using http://www.antlr.org/ or https://javacc.java.net to be a bit heavy. I used the same structure for parsing JSON, CSS a simple template. Modified it to parse your response. See whether it helps.
package snippet;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import snippet.RecursiveDescentParser.Token.TokenType;
public class RecursiveDescentParser {
// #formatter:off
final static String text = "" +
"[" +
" Anchor{anchorName='&loreal_lip_balm'," +
" clientName='loreal india'," +
"" +
" anchorPrice=10," +
" campaigns=[" +
" Campaign{" +
" campaignId='loreal_camp1'," +
"" +
" question='How to Turn Your Melted Lipstick into a Tinted Lip Balm'," +
"" +
" startDate=2015-08-04," +
" endDate=2015-08-04," +
" imageURL='null'," +
"" +
" regionCountry='ALL'," +
" rewardInfo='null'," +
" campaignPrice=20," +
"" +
" options=null" +
" }" +
" ]}," +
" Anchor{" +
"" +
" anchorName='&loreal_total_repair_5'," +
" clientName='loreal india'," +
" anchorPrice=125," +
"" +
" campaigns=[" +
" Campaign{" +
" campaignId='loreal_camp2'," +
" question='Is it a good" +
" product to buy?'," +
" startDate=2015-08-04," +
" endDate=2015-08-04," +
"" +
" imageURL='null'," +
" regionCountry='ALL'," +
" rewardInfo='null'," +
"" +
" campaignPrice=20," +
" options=null" +
" }" +
" ]" +
" }" +
" ]" +
"";
// #formatter:on
static class Token {
enum TokenType {
OPEN_BRACKET, CLOSE_BRACKET, OPEN_BRACE, CLOSE_BRACE, STRING, NAME, COMMA, EQUALS, INTEGER, DATE, EOF, NULL;
}
private String text;
private TokenType type;
public Token(TokenType type) {
this(type, null);
}
public Token(TokenType type, String text) {
this.type = type;
this.text = text;
}
public TokenType getType() {
return type;
}
public String getText() {
return text;
}
#Override public String toString() {
return "Token [text=" + text + ", type=" + type + "]";
}
}
static class TokenReader {
private PushbackReader reader;
public TokenReader(Reader reader) {
this.reader = new PushbackReader(reader);
}
public Token nextToken() throws IOException {
Token t = nextTokenx();
System.out.println("Got: " + t);
return t;
}
public Token nextTokenx() throws IOException {
int c;
while ((c = reader.read()) != -1 && Character.isWhitespace((char) c))
;
if (c == -1)
return new Token(TokenType.EOF);
switch (c) {
case '[':
return new Token(TokenType.OPEN_BRACKET);
case ']':
return new Token(TokenType.CLOSE_BRACKET);
case '{':
return new Token(TokenType.OPEN_BRACE);
case '}':
return new Token(TokenType.CLOSE_BRACE);
case ',':
return new Token(TokenType.COMMA);
case '=':
return new Token(TokenType.EQUALS);
default:
if (Character.isDigit(c))
return readIntegerOrDate(c);
if (c == '\'')
return readString(c);
if (Character.isJavaIdentifierStart(c))
return readName(c);
throw new RuntimeException("Invalid character '" + ((char) c) + "' in input");
}
}
private Token readName(int c) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isJavaIdentifierPart(c))
sb.append((char) c);
if (c != -1)
reader.unread(c);
if ("null".equals(sb.toString()))
return new Token(TokenType.NULL);
return new Token(TokenType.NAME, sb.toString());
}
private Token readString(int end) throws IOException {
StringBuilder sb = new StringBuilder();
int c;
while ((c = reader.read()) != -1 && c != end)
sb.append((char) c);
return new Token(TokenType.STRING, sb.toString());
}
private Token readIntegerOrDate(int c) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c == '-') {
sb.append((char) c);
return readDate(sb);
}
if (c != -1)
reader.unread(c);
return new Token(TokenType.INTEGER, sb.toString());
}
private Token readDate(StringBuilder sb) throws IOException {
int c;
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c == -1)
throw new RuntimeException("EOF while reading date");
if (c != '-')
throw new RuntimeException("Invalid character '" + (char) c + "' while reading date");
sb.append((char) c);
while ((c = reader.read()) != -1 && Character.isDigit((char) c))
sb.append((char) c);
if (c != -1)
reader.unread(c);
return new Token(TokenType.DATE, sb.toString());
}
}
static class Lexer {
private TokenReader reader;
private Token current;
public Lexer(Reader reader) {
this.reader = new TokenReader(reader);
}
public Token expect(TokenType... tt) throws IOException {
if (current == null)
current = reader.nextToken();
for (TokenType tokenType : tt) {
if (current.getType() == tokenType) {
Token r = current;
current = null;
return r;
}
}
throw new RuntimeException("Expecting one of " + Arrays.asList(tt) + " but got " + current);
}
public Token expect1or0(TokenType... tt) throws IOException {
if (current == null)
current = reader.nextToken();
for (TokenType tokenType : tt) {
if (current.getType() == tokenType) {
Token r = current;
current = null;
return r;
}
}
return null;
}
}
public Object parse(String text) throws IOException {
return parse(new StringReader(text));
}
private Object parse(Reader reader) throws IOException {
Lexer lexer = new Lexer(reader);
return parse(lexer);
}
private Object parse(Lexer lexer) throws IOException {
Token t = lexer.expect1or0(TokenType.OPEN_BRACE, TokenType.OPEN_BRACKET, TokenType.EOF);
if (t == null || t.getType() == TokenType.EOF)
return null;
else if (t.getType() == TokenType.OPEN_BRACKET) {
return parseList(lexer);
} else {
return parseMap(null, lexer);
}
}
private List<Object> parseList(Lexer lexer) throws IOException {
ArrayList<Object> result = new ArrayList<Object>();
Token tName = lexer.expect1or0(TokenType.NAME);
while (tName != null) {
lexer.expect(TokenType.OPEN_BRACE);
result.add(parseMap(tName.getText(), lexer));
if (lexer.expect1or0(TokenType.COMMA) != null)
tName = lexer.expect(TokenType.NAME);
else
tName = null;
}
lexer.expect(TokenType.CLOSE_BRACKET);
return result;
}
private Object parseMap(String oname, Lexer lexer) throws IOException {
Map<String, Object> result = new HashMap<String, Object>();
if (oname != null)
result.put("objectName", oname);
Token tName = lexer.expect1or0(TokenType.NAME);
while (tName != null) {
String name = tName.getText();
lexer.expect(TokenType.EQUALS);
Token next = lexer.expect(TokenType.STRING, TokenType.DATE, TokenType.INTEGER, TokenType.OPEN_BRACKET,
TokenType.OPEN_BRACE, TokenType.NULL);
TokenType tt = next.getType();
if (tt == TokenType.STRING) {
result.put(name, next.getText());
} else if (tt == TokenType.DATE) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
result.put(name, sdf.parse(next.getText()));
} catch (ParseException e) {
return new RuntimeException(e);
}
} else if (tt == TokenType.INTEGER) {
result.put(name, Integer.valueOf(next.getText()));
} else if (tt == TokenType.OPEN_BRACKET) {
result.put(name, parseList(lexer));
} else if (tt == TokenType.OPEN_BRACE) {
result.put(name, parseMap(null, lexer));
} else {
result.put(name, null);
}
if (lexer.expect1or0(TokenType.COMMA) != null)
tName = lexer.expect(TokenType.NAME);
else
tName = null;
}
lexer.expect(TokenType.CLOSE_BRACE);
return result;
}
public static void main(String[] args) throws IOException {
RecursiveDescentParser parser = new RecursiveDescentParser();
Object o = parser.parse(text);
System.out.println(o);
}
}
Here is my suggestion.
I assume as you said that your input from the server is String.
I have build a little method that return the value of the required key.
public String valueFinder(String data, String key){
int keyValueStart = data.indexOf(key) + key.length() + 1;
String keyValueRaw = data.substring(keyValueStart, data.length());
int keyValueEnd = keyValueRaw.indexOf(",");
String keyValue = keyValueRaw.substring(0, keyValueEnd);
String value = keyValue.replaceAll("^\'|\'$", "");
return value;
}
So if you pass the String data generated by the server to the method and the ask for the required key for example for "clientName" it will return loreal india, if you pass/look-for "anchorName" it will return &loreal_lip_balm.
Now you have the concept, you are welcome to change/modify/customize it as you wish to fetch more detailed information in your campaigns or other scenarios.
It is possible to further develop the method to return single key value, a set of keys and values, convert keys and values to JSON or Array, and just name it.
All this can be done on the same concept.
There is a tool called ANTLR which is useful to read data like this.
I have a java applicato that use the thermal print to printer a text. I use this printer to print the order for the bar.
This is an example of the ticket:
--> BAR
Coca Cola 1 x 1.5
Fanta 1 x 1.5
-------------------
TOTALE 3.00 euro
And the code to print this ticket works.
But I wanto to change the font size because the font is to small. How can I change the font ??
This is the code that I use to create and printer a ticket:
PrinterBean localPrinterBean = null;
StringBuffer localStringBuffer = null;
HashMap localHashMap=null;
if(emettiScontrinoCartaceo){
//PER LA STAMPA SCOTRNIO
localPrinterBean = getPrinterBean();
localStringBuffer = new StringBuffer();
localHashMap = null;
if ((localPrinterBean.isPrn_Enabled()) && (!localPrinterBean.isPrn_Onlyticket()))
{
//log.info("" + localPrinterBean.getPrn_driver());
localHashMap = PrinterManager.loadEscDriver(localPrinterBean);
//localStringBuffer.append("\n");
localStringBuffer.append(String.format("\t%s->> %s%s\n", new Object[] { localHashMap.get("size2w"), "BAR", localHashMap.get("size2w-off") }));
localStringBuffer.append("\n");
}
//FINE STAMPA SCOTNRINO
}
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
ArticoliScontrini artSco = (ArticoliScontrini) (entry.getValue());
//devo inserire nella lista le righe di stampa dello scontrino
//INIZIO STAMPA SCONTRINO
localStringBuffer.append(String.format("%s\n", new Object[] { artSco.getDescrizioneArticolo() }));
String quantita = artSco.getQuantita() + " x " +artSco.getPrezzoTotStringFormattato();//toString(artSco.getQuantita(), true);
localStringBuffer.append(String.format("\t %s", new Object[] { quantita }));
localStringBuffer.append("\n");
//FINE STAMPA SCONTRINO
}
localStringBuffer.append("------------------------------------------");
localStringBuffer.append("\n");
String totale = "TOTALE " + decimalFormatter2.format(totaleScontrinoCartaceo) + " euro";
localStringBuffer.append(String.format("%s\n", new Object[] { totale }));
String str = localStringBuffer.toString();
try{
cbPrintBuffer(localPrinterBean);
}
catch(Exception e){
VisualMessageScontrini.getErroreStampaScontrino();
}
public void cbPrintBuffer(PrinterBean paramPrinterBean)
throws Exception
{
/*Object localObject1 = JabirCfg.hexItIfn(paramPrinterBean.getPrn_Hexinit());
if ((localObject1 != null) && (!((String)localObject1).equals(""))) {
printRawBytes(paramPrinterBean, ((String)localObject1).getBytes());
}*/
Object localObject1 = null;
if (paramPrinterBean.hasPrn_Bitopt(2))
{
localObject1 = new FileOutputStream(paramPrinterBean.getPrn_driver());
((FileOutputStream)localObject1).write(cbGetFlow());
((FileOutputStream)localObject1).close();
return;
}
localObject1 = PrinterManager.getPrintService_cached(paramPrinterBean);
if (paramPrinterBean.isPrnGd())
{
boolean bool = paramPrinterBean.hasPrn_Bitopt(32);
PrinterJob localObject2 = PrinterJob.getPrinterJob();
((PrinterJob)localObject2).setPrintService((PrintService)localObject1);
((PrinterJob)localObject2).setJobName("easy ticket");
PageFormat localPageFormat = ((PrinterJob)localObject2).defaultPage();
PrinterExtra.deserialize_pagejson_to_PageFormat(paramPrinterBean.getPrn_pagejson(), localPageFormat);
Printable localPrintable = null;
for (int i = 0;; i++)
{
if (bool) {
localPrintable = cbPrintable(i);
} else {
localPrintable = cbPrintable(-1);
}
if (localPrintable == null) {
break;
}
((PrinterJob)localObject2).setPrintable(localPrintable, ((PrinterJob)localObject2).validatePage(localPageFormat));
((PrinterJob)localObject2).print();
if (!bool) {
break;
}
String str = JabirCfg.hexItIfn("0x1b 0x6d");
printRawBytes(paramPrinterBean, str.getBytes());
}
return;
}
DocPrintJob localDocPrintJob = ((PrintService)localObject1).createPrintJob();
Object localObject2 = new SimpleDoc(cbGetFlow(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
localDocPrintJob.print((Doc)localObject2, new HashPrintRequestAttributeSet());
}
Before I wander off and re-create the wheel, does anyone know of a JPA wrapper that turns the unchecked exceptions JPA throws into checked exceptions?
Not looking for an argument about why I should not want checked exceptions, I do want them :-)
You can do 99% of rolling your own using the code below. It will leave you with two compile errors due to the members of a Collection needing to be encapsulated, but it does take you past the point where it is no longer worth automating.
package so;
import javax.persistence.*;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.*;
public class CheckedPersistenceMaker {
static final String PACKAGE = "stackoverflow.javax.persistence";
static final String PACKAGE_DIR = PACKAGE.replace('.', '/');
static Class<?>[] CLASSES = new Class<?>[] { Cache.class,
EntityManager.class, EntityManagerFactory.class,
EntityTransaction.class, Parameter.class,
PersistenceUnitUtil.class, PersistenceUtil.class,
Persistence.class, Query.class, Tuple.class, TupleElement.class,
TypedQuery.class };
private static String getName(Class<?> c) {
String name = c.getName();
for(Class<?> p:CLASSES) {
if (p.equals(c))
return PACKAGE + ".Checked"
+ name.substring(name.lastIndexOf('.') + 1);
}
return c.getName();
}
static void generateWrapper(Class<?> c) throws Exception {
String name = c.getName();
TypeVariable<?>[] genType = c.getTypeParameters();
String varNames = "";
if (genType != null && genType.length != 0) {
StringBuilder b = new StringBuilder();
b.append("<");
for(int i = 0;i < genType.length;i++) {
if (i > 0) b.append(",");
b.append(genType[i].getName());
}
b.append(">");
varNames = b.toString();
}
name = "Checked" + name.substring(name.lastIndexOf('.') + 1);
File javaFile = new File(PACKAGE_DIR + "/" + name + ".java");
javaFile.getParentFile().mkdirs();
FileWriter w = new FileWriter(javaFile);
w.write("package " + PACKAGE + ";\n");
w.write("public class " + name + varNames + " {\n");
w.write(" private final " + c.getName() + varNames
+ " wrapped;\n\n ");
w.write(name + "(" + c.getName() + varNames
+ " original) {\nwrapped=original;\n}\n\n");
w.write(" public " + c.getName() + varNames
+ " getOriginal() { return wrapped; }\n\n");
Method[] ms = c.getDeclaredMethods();
for(Method m:ms) {
if (!Modifier.isPublic(m.getModifiers())) continue;
w.write(" ");
String s = m.toGenericString();
s = s.replace(" abstract ", " ");
s = s.replace(c.getName() + ".", "");
String q = s.substring(0, s.indexOf('('));
if (q.indexOf('<',10) != -1) q = q.substring(0, q.indexOf('<',10));
boolean needsTranslate = false;
for(Class<?> cc:CLASSES) {
String ccn = cc.getName();
if (q.indexOf(ccn) != -1) needsTranslate = true;
String ccc = ccn.replace(cc.getPackage().getName() + ".",
PACKAGE + ".Checked");
s = s.replace(ccn, ccc);
}
int pc = 0;
int p = s.indexOf('(');
if (s.charAt(p + 1) != ')') {
StringBuilder b = new StringBuilder(s);
int g = 0;
char ch;
do {
ch = b.charAt(p);
switch (ch) {
case '<': {
g++;
break;
}
case '>': {
g--;
break;
}
case ',':
case ')': {
if (g == 0) {
String pa = " p" + pc;
b.insert(p, pa);
pc++;
p += pa.length();
}
break;
}
}
p++;
} while( ch != ')' );
s = b.toString();
}
w.write(s);
w.write(" throws CheckedPersistenceException");
Class<?>[] excs = m.getExceptionTypes();
for(Class<?> e:excs) {
w.write(", " + e.getName());
}
w.write(" {\n try {\n ");
Class<?> ret = m.getReturnType();
if (!ret.equals(Void.TYPE)) {
w.write("return ");
if (needsTranslate) {
String retName = ret.getName();
retName = retName.replace(c.getPackage().getName() + ".",
PACKAGE + ".Checked");
w.write("new " + retName + "(");
}
}
if (Modifier.isStatic(m.getModifiers())) {
w.write(c.getName() + "." + m.getName() + "(");
} else {
w.write("wrapped." + m.getName() + "(");
}
Class<?> paramTypes[] = m.getParameterTypes();
for(int i = 0;i < pc;i++) {
if (i > 0) w.write(',');
boolean isChecked = false;
for(int j=0;j<CLASSES.length;j++) {
if( CLASSES[j].equals(paramTypes[i]) ) isChecked=true;
}
w.write("p" + i);
if(isChecked) w.write(".getOriginal()");
}
w.write(')');
if (needsTranslate) w.write(')');
w.write(";\n } catch ( javax.persistence.PersistenceException e ) { throw new CheckedPersistenceException(e); }\n }\n\n");
}
w.write("}\n");
w.close();
}
public static void main(String[] args) throws Exception {
for(Class<?> c:CLASSES) {
generateWrapper(c);
}
}
}