code
stringlengths
3
1.18M
language
stringclasses
1 value
package cx.hell.android.pdfview; public class BookmarkEntry implements Comparable<BookmarkEntry> { public int numberOfPages; public int page; public float absoluteZoomLevel; public int rotation; public int offsetX; public String comment; public BookmarkEntry(int numberOfPages, int page, float absoluteZoomLevel, int rotation, int offsetX) { this(null, numberOfPages, page, absoluteZoomLevel, rotation, offsetX); } public BookmarkEntry(String comment, int numberOfPages, int page, float absoluteZoomLevel, int rotation, int offsetX) { this.comment = comment; this.numberOfPages = numberOfPages; this.page = page; this.absoluteZoomLevel = absoluteZoomLevel; this.rotation = rotation; this.offsetX = offsetX; } public BookmarkEntry(String s) { this(null, s); } public BookmarkEntry(String comment, String s) { this.comment = comment; String data[] = s.split(" "); if (0 < data.length) { this.numberOfPages = Integer.parseInt(data[0]); } else { this.numberOfPages = 0; } if (1 < data.length) { this.page = Integer.parseInt(data[1]); } else { this.page = 0; } if (2 < data.length) { this.absoluteZoomLevel = Float.parseFloat(data[2]); } else { this.absoluteZoomLevel = 0f; } if (3 < data.length) { this.rotation = Integer.parseInt(data[3]); } else { this.rotation = 0; } if (4 < data.length) { this.offsetX = Integer.parseInt(data[4]); } else { this.offsetX = 0; } } public String toString() { return ""+numberOfPages+" "+page+" "+absoluteZoomLevel+" "+rotation+" "+offsetX; } public int compareTo(BookmarkEntry entry) { if (this.page < entry.page) return -1; else if (entry.page < this.page) return 1; else return this.comment.compareTo(entry.comment); } public boolean equals(BookmarkEntry entry) { return this.toString() == entry.toString() && this.comment == entry.comment; } }
Java
package cx.hell.android.pdfview; import java.io.File; public class FileListEntry { private String label = null; private File file = null; private boolean isDirectory = false; private int type = NORMAL; private int recentNumber = -1; static final int NORMAL = 0; static final int HOME = 1; static final int RECENT = 2; public FileListEntry(int type, int recentNumber, File file, String label) { this.file = file; this.label = file.getName(); this.isDirectory = file.isDirectory(); this.type = type; this.label = label; this.recentNumber = recentNumber; } public FileListEntry(int type, int recentNumber, File file, Boolean showPDFExtension) { this(type, recentNumber, file, getLabel(file, showPDFExtension)); } public FileListEntry(int type, String label) { this.type = type; this.label = label; } private static String getLabel(File file, boolean showPDFExtension) { String label = file.getName(); if (!showPDFExtension && label.length() > 4 && ! file.isDirectory() && label.substring(label.length()-4, label.length()).equalsIgnoreCase(".pdf")) { return label.substring(0, label.length()-4); } else { return label; } } public int getRecentNumber() { return this.recentNumber; } public int getType() { return this.type; } public File getFile() { return this.file; } public String getLabel() { return this.label; } public boolean isDirectory() { return this.isDirectory; } public boolean isUpFolder() { return this.isDirectory && this.label.equals(".."); } }
Java
/* * Copyright 2010 Ludovic Drolez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package cx.hell.android.pdfview; import java.io.File; import java.util.Collections; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Class to manage the last opened page and bookmarks of PDF files * * @author Ludovic Drolez * */ public class Bookmark { /** db fields */ public static final String KEY_ID = "_id"; public static final String KEY_BOOK = "book"; public static final String KEY_NAME = "name"; public static final String KEY_COMMENT = "comment"; public static final String KEY_TIME = "time"; public static final String KEY_ENTRY = "entry"; private static final int DB_VERSION = 1; private static final String DATABASE_CREATE = "create table bookmark " + "(_id integer primary key autoincrement, " + "book text not null, name text not null, " + "entry text, comment text, time integer);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; /** * Constructor * * @param ctx * application context */ public Bookmark(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } /** * Database helper class */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, "bookmarks.db", null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } /** * open the bookmark database * * @return the Bookmark object * @throws SQLException */ public Bookmark open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } /** * close the database */ public void close() { DBHelper.close(); } /** * Set the last page seen for a file * * @param file * full file path * @param page * last page */ public void setLast(String file, BookmarkEntry entry) { String md5 = nameToMD5(file); ContentValues cv = new ContentValues(); cv.put(KEY_BOOK, md5); cv.put(KEY_ENTRY, entry.toString()); cv.put(KEY_NAME, "last"); cv.put(KEY_TIME, System.currentTimeMillis() / 1000); if (db.update("bookmark", cv, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null) == 0) { db.insert("bookmark", null, cv); } } public BookmarkEntry getLast(String file) { BookmarkEntry entry = null; String md5 = nameToMD5(file); Cursor cur = db.query(true, "bookmark", new String[] { KEY_ENTRY }, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null, null, null, null, "1"); if (cur != null) { if (cur.moveToFirst()) { entry = new BookmarkEntry(cur.getString(0)); } cur.close(); } return entry; } public ArrayList<BookmarkEntry> getBookmarks(String file) { ArrayList<BookmarkEntry> list = new ArrayList<BookmarkEntry>(); String md5 = nameToMD5(file); Cursor cur = db.query(true, "bookmark", new String[] { KEY_ENTRY, KEY_COMMENT }, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'user'", null, null, null, null, "1"); if (cur != null) { if (cur.moveToFirst()) { do { list.add(new BookmarkEntry(cur.getString(1), cur.getString(0))); } while (cur.moveToNext()); } cur.close(); } Collections.sort(list); return list; } public void deleteBookmark(String file, BookmarkEntry entry) { String md5 = nameToMD5(file); db.delete("bookmark", KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'user' AND " + KEY_ENTRY + "= ? AND " + KEY_COMMENT + "= ?", new String[] { entry.toString(), entry.comment }); } public void changeBookmark(String file, BookmarkEntry oldEntry, BookmarkEntry newEntry) { deleteBookmark(file, oldEntry); addBookmark(file, newEntry); } public void addBookmark(String file, BookmarkEntry entry) { deleteBookmark(file, entry); // Avoid duplicates String md5 = nameToMD5(file); ContentValues cv = new ContentValues(); cv.put(KEY_BOOK, md5); cv.put(KEY_ENTRY, entry.toString()); cv.put(KEY_COMMENT, entry.comment); cv.put(KEY_NAME, "user"); cv.put(KEY_TIME, System.currentTimeMillis() / 1000); db.insert("bookmark", null, cv); } /** * Hash the file name to be sure that no strange characters will be in the * DB, and include file length. * * @param file * path * @return md5 */ private String nameToMD5(String file) { // Create MD5 Hash MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } String message = file + ":" + (new File(file)).length(); digest.update(message.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } }
Java
package cx.hell.android.pdfview; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.app.Activity; import android.graphics.Bitmap; import android.os.SystemClock; import android.util.Log; import cx.hell.android.lib.pagesview.OnImageRenderedListener; import cx.hell.android.lib.pagesview.PagesProvider; import cx.hell.android.lib.pagesview.RenderingException; import cx.hell.android.lib.pagesview.Tile; import cx.hell.android.lib.pdf.PDF; /** * Provide rendered bitmaps of pages. */ public class PDFPagesProvider extends PagesProvider { /** * Const used by logging. */ private final static String TAG = "cx.hell.android.pdfview"; /* render a little more than twice the screen height, so the next page will be ready */ private float renderAhead = 2.1f; private boolean doRenderAhead = true; private boolean gray; private int extraCache = 0; private boolean omitImages; Activity activity = null; private static final int MB = 1024*1024; public void setGray(boolean gray) { if (this.gray == gray) return; this.gray = gray; if (this.bitmapCache != null) { this.bitmapCache.clearCache(); } setMaxCacheSize(); } public void setExtraCache(int extraCache) { this.extraCache = extraCache; setMaxCacheSize(); } /* also calculates renderAhead */ private void setMaxCacheSize() { long availLong = (long)(Runtime.getRuntime().maxMemory() - 4 * MB); int avail; if (availLong > 256*MB) avail = 256*MB; else avail = (int)availLong; int maxMax = 7*MB + this.extraCache; /* at most allocate this much unless absolutely necessary */ if (maxMax < avail) maxMax = avail; int minMax = 4*MB; /* at least allocate this much */ if (maxMax < minMax) maxMax = minMax; int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight(); int screenWidth = activity.getWindowManager().getDefaultDisplay().getWidth(); int displaySize = screenWidth * screenHeight; if (displaySize <= 320*240) displaySize = 320*240; if (!this.gray) displaySize *= 2; int m = (int)(displaySize * 1.25f * 1.0001f); if (doRenderAhead) { if ((int)(m * 2.1f) <= maxMax) { renderAhead = 2.1f; m = (int)(m * renderAhead); } else { renderAhead = 1.0001f; } } else { /* The extra little bit is to compensate for round-off */ renderAhead = 1.0001f; } if (m < minMax) m = minMax; if (m + 20*MB <= maxMax) m = maxMax - 20 * MB; if (m < maxMax) { m += this.extraCache; if (maxMax < m) m = maxMax; } Log.v(TAG, "Setting cache size="+m+ " renderAhead="+renderAhead+" for "+screenWidth+"x"+screenHeight+" (avail="+avail+")"); this.bitmapCache.setMaxCacheSizeBytes((int)m); } public void setOmitImages(boolean skipImages) { if (this.omitImages == skipImages) return; this.omitImages = skipImages; if (this.bitmapCache != null) { this.bitmapCache.clearCache(); } } /** * Smart page-bitmap cache. * Stores up to approx maxCacheSizeBytes of images. * Dynamically drops oldest unused bitmaps. * TODO: Return high resolution bitmaps if no exact res is available. * Bitmap images are tiled - tile size is specified in PagesView.TILE_SIZE. */ private static class BitmapCache { /** * Stores cached bitmaps. */ private Map<Tile, BitmapCacheValue> bitmaps; private int maxCacheSizeBytes = 4*1024*1024; /** * Stats logging - number of cache hits. */ private long hits; /** * Stats logging - number of misses. */ private long misses; BitmapCache() { this.bitmaps = new HashMap<Tile, BitmapCacheValue>(); this.hits = 0; this.misses = 0; } public void setMaxCacheSizeBytes(int maxCacheSizeBytes) { this.maxCacheSizeBytes = maxCacheSizeBytes; } /** * Get cached bitmap. Updates last access timestamp. * @param k cache key * @return bitmap found in cache or null if there's no matching bitmap */ Bitmap get(Tile k) { BitmapCacheValue v = this.bitmaps.get(k); Bitmap b = null; if (v != null) { // yeah b = v.bitmap; assert b != null; v.millisAccessed = System.currentTimeMillis(); this.hits += 1; } else { // le fu this.misses += 1; } if ((this.hits + this.misses) % 100 == 0 && (this.hits > 0 || this.misses > 0)) { Log.d("cx.hell.android.pdfview.pagecache", "hits: " + hits + ", misses: " + misses + ", hit ratio: " + (float)(hits) / (float)(hits+misses) + ", size: " + this.bitmaps.size()); } return b; } /** * Put rendered tile in cache. * @param tile tile definition (page, position etc), cache key * @param bitmap rendered tile contents, cache value */ synchronized void put(Tile tile, Bitmap bitmap) { while (this.willExceedCacheSize(bitmap) && !this.bitmaps.isEmpty()) { Log.v(TAG, "Removing oldest"); this.removeOldest(); } this.bitmaps.put(tile, new BitmapCacheValue(bitmap, System.currentTimeMillis(), 0)); } /** * Check if cache contains specified bitmap tile. Doesn't update last-used timestamp. * @return true if cache contains specified bitmap tile */ synchronized boolean contains(Tile tile) { return this.bitmaps.containsKey(tile); } /** * Estimate bitmap memory size. * This is just a guess. */ private static int getBitmapSizeInCache(Bitmap bitmap) { int numPixels = bitmap.getWidth() * bitmap.getHeight(); if (bitmap.getConfig() == Bitmap.Config.RGB_565) { return numPixels * 2; } else if (bitmap.getConfig() == Bitmap.Config.ALPHA_8) return numPixels; else return numPixels * 4; } /** * Get estimated sum of byte sizes of bitmaps stored in cache currently. */ private synchronized int getCurrentCacheSize() { int size = 0; Iterator<BitmapCacheValue> it = this.bitmaps.values().iterator(); while(it.hasNext()) { BitmapCacheValue bcv = it.next(); Bitmap bitmap = bcv.bitmap; size += getBitmapSizeInCache(bitmap); } Log.v(TAG, "Cache size: "+size); return size; } /** * Determine if adding this bitmap would grow cache size beyond max size. */ private synchronized boolean willExceedCacheSize(Bitmap bitmap) { return (this.getCurrentCacheSize() + BitmapCache.getBitmapSizeInCache(bitmap) > maxCacheSizeBytes); } /** * Remove oldest bitmap cache value. */ private void removeOldest() { Iterator<Tile> i = this.bitmaps.keySet().iterator(); long minmillis = 0; Tile oldest = null; while(i.hasNext()) { Tile k = i.next(); BitmapCacheValue v = this.bitmaps.get(k); if (oldest == null) { oldest = k; minmillis = v.millisAccessed; } else { if (minmillis > v.millisAccessed) { minmillis = v.millisAccessed; oldest = k; } } } if (oldest == null) throw new RuntimeException("couldnt find oldest"); BitmapCacheValue v = this.bitmaps.get(oldest); v.bitmap.recycle(); this.bitmaps.remove(oldest); } synchronized public void clearCache() { Iterator<Tile> i = this.bitmaps.keySet().iterator(); while(i.hasNext()) { Tile k = i.next(); Log.v("Deleting", k.toString()); this.bitmaps.get(k).bitmap.recycle(); i.remove(); } } } private static class RendererWorker implements Runnable { /** * Worker stops rendering if error was encountered. */ private boolean isFailed = false; private PDFPagesProvider pdfPagesProvider; private BitmapCache bitmapCache; private Collection<Tile> tiles; /** * Internal worker number for debugging. */ private static int workerThreadId = 0; /** * Used as a synchronized flag. * If null, then there's no designated thread to render tiles. * There might be other worker threads running, but those have finished * their work and will finish really soon. * Only this one should pick up new jobs. */ private Thread workerThread = null; /** * Create renderer worker. * @param pdfPagesProvider parent pages provider */ RendererWorker(PDFPagesProvider pdfPagesProvider) { this.tiles = null; this.pdfPagesProvider = pdfPagesProvider; } /** * Called by outside world to provide more work for worker. * This also starts rendering thread if one is needed. * @param tiles a collection of tile objects, they carry information about what should be rendered next */ synchronized void setTiles(Collection<Tile> tiles, BitmapCache bitmapCache) { this.tiles = tiles; this.bitmapCache = bitmapCache; if (this.workerThread == null) { Thread t = new Thread(this); t.setPriority(Thread.MIN_PRIORITY); t.setName("RendererWorkerThread#" + RendererWorker.workerThreadId++); this.workerThread = t; t.start(); Log.d(TAG, "started new worker thread"); } else { //Log.i(TAG, "setTiles notices tiles is not empty, that means RendererWorkerThread exists and there's no need to start new one"); } } /** * Get tiles that should be rendered next. May not block. * Also sets this.workerThread to null if there's no tiles to be rendered currently, * so that calling thread may finish. * If there are more tiles to be rendered, then this.workerThread is not reset. * @return some tiles */ synchronized Collection<Tile> popTiles() { if (this.tiles == null || this.tiles.isEmpty()) { this.workerThread = null; /* returning null, so calling thread will finish it's work */ return null; } Tile tile = this.tiles.iterator().next(); this.tiles.remove(tile); return Collections.singleton(tile); } /** * Thread's main routine. * There might be more than one running, but only one will get new tiles. Others * will get null returned by this.popTiles and will finish their work. */ public void run() { while(true) { if (this.isFailed) { Log.i(TAG, "RendererWorker is failed, exiting"); break; } Collection<Tile> tiles = this.popTiles(); /* this can't block */ if (tiles == null || tiles.size() == 0) break; try { Map<Tile,Bitmap> renderedTiles = this.pdfPagesProvider.renderTiles(tiles, bitmapCache); if (renderedTiles.size() > 0) this.pdfPagesProvider.publishBitmaps(renderedTiles); } catch (RenderingException e) { this.isFailed = true; this.pdfPagesProvider.publishRenderingException(e); } } } } private PDF pdf = null; private BitmapCache bitmapCache = null; private RendererWorker rendererWorker = null; private OnImageRenderedListener onImageRendererListener = null; public float getRenderAhead() { return this.renderAhead; } public PDFPagesProvider(Activity activity, PDF pdf, boolean gray, boolean skipImages, boolean doRenderAhead) { this.gray = gray; this.pdf = pdf; this.omitImages = skipImages; this.bitmapCache = new BitmapCache(); this.rendererWorker = new RendererWorker(this); this.activity = activity; this.doRenderAhead = doRenderAhead; setMaxCacheSize(); } public void setRenderAhead(boolean doRenderAhead) { this.doRenderAhead = doRenderAhead; setMaxCacheSize(); } /** * Render tiles. * Called by worker, calls PDF's methods that in turn call native code. * @param tiles job description - what to render * @return mapping of jobs and job results, with job results being Bitmap objects */ private Map<Tile,Bitmap> renderTiles(Collection<Tile> tiles, BitmapCache ignore) throws RenderingException { Map<Tile,Bitmap> renderedTiles = new HashMap<Tile,Bitmap>(); Iterator<Tile> i = tiles.iterator(); Tile tile = null; while(i.hasNext()) { tile = i.next(); Bitmap bitmap = this.renderBitmap(tile); if (bitmap != null) renderedTiles.put(tile, bitmap); } return renderedTiles; } /** * Really render bitmap. Takes time, should be done in background thread. Calls native code (through PDF object). */ private Bitmap renderBitmap(Tile tile) throws RenderingException { synchronized(tile) { /* last minute check to make sure some other thread hasn't rendered this tile */ if (this.bitmapCache.contains(tile)) return null; PDF.Size size = new PDF.Size(tile.getPrefXSize(), tile.getPrefYSize()); int[] pagebytes = null; long t1 =SystemClock.currentThreadTimeMillis(); pagebytes = pdf.renderPage(tile.getPage(), tile.getZoom(), tile.getX(), tile.getY(), tile.getRotation(), gray, omitImages, size); /* native */ Log.v(TAG, "Time:"+(SystemClock.currentThreadTimeMillis()-t1)); if (pagebytes == null) throw new RenderingException("Couldn't render page " + tile.getPage()); /* create a bitmap from the 32-bit color array */ if (gray) { Bitmap b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.ARGB_8888); Bitmap b2 = b.copy(Bitmap.Config.ALPHA_8, false); b.recycle(); this.bitmapCache.put(tile, b2); return b2; } else { Bitmap b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.RGB_565); this.bitmapCache.put(tile, b); return b; } } } /** * Called by worker. */ private void publishBitmaps(Map<Tile,Bitmap> renderedTiles) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onImagesRendered(renderedTiles); } else { Log.w(TAG, "we've got new bitmaps, but there's no one to notify about it!"); } } /** * Called by worker. */ private void publishRenderingException(RenderingException e) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onRenderingException(e); } } @Override public void setOnImageRenderedListener(OnImageRenderedListener l) { this.onImageRendererListener = l; } /** * Get tile bitmap if it's already rendered. * @param tile which bitmap * @return rendered tile; tile represents rect of TILE_SIZE x TILE_SIZE pixels, * but might be of different size (should be scaled when painting) */ @Override public Bitmap getPageBitmap(Tile tile) { Bitmap b = null; b = this.bitmapCache.get(tile); if (b != null) return b; return null; } /** * Get page count. * @return number of pages */ @Override public int getPageCount() { int c = this.pdf.getPageCount(); if (c <= 0) throw new RuntimeException("failed to load pdf file: getPageCount returned " + c); return c; } /** * Get page sizes from pdf file. * @return array of page sizes */ @Override public int[][] getPageSizes() { int cnt = this.getPageCount(); int[][] sizes = new int[cnt][]; PDF.Size size = new PDF.Size(); int err; for(int i = 0; i < cnt; ++i) { err = this.pdf.getPageSize(i, size); if (err != 0) { throw new RuntimeException("failed to getPageSize(" + i + ",...), error: " + err); } sizes[i] = new int[2]; sizes[i][0] = size.width; sizes[i][1] = size.height; } return sizes; } /** * View informs provider what's currently visible. * Compute what should be rendered and pass that info to renderer worker thread, possibly waking up worker. * @param tiles specs of whats currently visible */ synchronized public void setVisibleTiles(Collection<Tile> tiles) { List<Tile> newtiles = null; for(Tile tile: tiles) { if (!this.bitmapCache.contains(tile)) { if (newtiles == null) newtiles = new LinkedList<Tile>(); newtiles.add(tile); } } if (newtiles != null) { this.rendererWorker.setTiles(newtiles, this.bitmapCache); } } }
Java
package cx.hell.android.lib.view; // #ifdef pro // // import java.util.Collections; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // import java.util.Stack; // // import android.content.Context; // import android.graphics.Color; // import android.util.Log; // import android.view.View; // import android.view.ViewGroup; // import android.widget.BaseAdapter; // import android.widget.Button; // import android.widget.LinearLayout; // import android.widget.ListView; // import android.widget.TextView; // import cx.hell.android.pdfview.R; // // /** // * Simple tree view used by APV for Table of Contents. // * // * This class' package is cx.hell.android.lib.view, since TreeView might be reusable in other projects. // * // * TODO: move data handling (getItemAtPosition) from TreeView to TreeAdapter, // * as it should be; TreeView should query TreeAdapter, not other way around :/ // * however, it would still be cool to have self contained simple-api class for all of tree related stuff // */ // public class TreeView extends ListView { // // public final static String TAG = "cx.hell.android.lib.view"; // // /** // * Tree node model. Contains links to first child and to next element. // */ // public interface TreeNode { // // /** // * Get numeric id. // */ // public long getId(); // /** // * Get next element. // */ // public TreeNode getNext(); // /** // * Get down element. // */ // public TreeNode getDown(); // /** // * Return true if this node has children. // */ // public boolean hasChildren(); // // /** // * Get list of children or null if there are no children. // */ // public List<TreeNode> getChildren(); // // /** // * Get text of given node. // * @return text that shows up on list // */ // public String getText(); // // /** // * Return 0-based level (depth) of this tree node. // * Top level elements have level 0, children of top level elements have level 1 etc. // */ // public int getLevel(); // } // // private final static class TreeAdapter extends BaseAdapter { // // /** // * Parent TreeView. // * For now each TreeAdapter is bound to exactly one TreeView, // * because TreeView is general purpose class that holds both tree // * data and tree state. // */ // private TreeView parent = null; // // /** // * TreeAdapter constructor. // * @param parent parent TreeView // */ // public TreeAdapter(TreeView parent) { // this.parent = parent; // } // // public int getCount() { // return this.parent.getVisibleCount(); // } // // public Object getItem(int position) { // TreeNode node = this.parent.getTreeNodeAtPosition(position); // return node; // } // // public long getItemId(int position) { // TreeNode node = this.parent.getTreeNodeAtPosition(position); // return node.getId(); // } // // /** // * Return item view type by position. Since all elements in TreeView // * are the same, this always returns 0. // * @param position item position // * @return 0 // */ // public int getItemViewType(int position) { // return 0; // } // // /** // * Get view for list item for given position. // * TODO: handle convertView // */ // public View getView(final int position, View convertView, ViewGroup parent) { // final TreeNode node = this.parent.getTreeNodeAtPosition(position); // if (node == null) throw new RuntimeException("no node at position " + position); // final LinearLayout l = new LinearLayout(parent.getContext()); // l.setOrientation(LinearLayout.HORIZONTAL); // Button b = new Button(parent.getContext()); // // /* TODO: do not use anonymous classes here */ // // if (node.hasChildren()) { // if (this.parent.isOpen(node)) { // b.setBackgroundResource(R.drawable.minus); // b.setOnClickListener(new OnClickListener() { // public void onClick(View v) { // Log.d(TAG, "click on " + position + ": " + node); // TreeAdapter.this.parent.close(node); // TreeAdapter.this.notifyDataSetChanged(); // } // }); // } else { // b.setBackgroundResource(R.drawable.plus); // b.setOnClickListener(new OnClickListener() { // public void onClick(View v) { // Log.d(TAG, "click on " + position + ": " + node); // TreeAdapter.this.parent.open(node); // TreeAdapter.this.notifyDataSetChanged(); // } // }); // } // } else { // b.setBackgroundColor(Color.TRANSPARENT); // b.setEnabled(false); // } // // /* TODO: don't create LinearLayout.LayoutParams for earch button */ // LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams(this.parent.tocButtonSizePx, this.parent.tocButtonSizePx); // blp.gravity = android.view.Gravity.CENTER; // l.addView(b, blp); // TextView tv = new TextView(parent.getContext()); // tv.setClickable(true); // tv.setOnClickListener(new OnClickListener() { // public void onClick(View v) { // TreeAdapter.this.parent.performItemClick(l, position, node.getId()); // } // }); // int nodeLevel = node.getLevel(); // int pixelsPerLevel = 4; // /* 4 + 4 for each level, but only for top 8 levels */ // tv.setPadding(4 + (nodeLevel > 7 ? 7*pixelsPerLevel : nodeLevel*pixelsPerLevel), 4, 4, 4); // tv.setText(node.getText()); // /* TODO: create only one */ // LinearLayout.LayoutParams tvlp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // tvlp.gravity = android.view.Gravity.CENTER_VERTICAL; // l.addView(tv, tvlp); // return l; // } // // public int getViewTypeCount() { // return 1; // } // // public boolean hasStableIds() { // return true; // } // // /** // * Since we refuse to show TreeView for docs without TOC, we can safely // * assume that TreeView is never empty, so this method always returns // * false. // * @return false // */ // @Override // public boolean isEmpty() { // return false; // } // // }; // // /** // * Tree root. // */ // private TreeNode root = null; // // /** // * State: either open or closed. // * If not found in map, then it's closed, unless it's top level element // * (those are always open, since they have no parents). // */ // private Map<Long, Boolean> state = null; // // private int tocButtonSizePx = -1; // // private float tocButtonSizeDp = 48; // // private int tocButtonMinSizePx = 24; // // /** // * Construct this tree view. // */ // public TreeView(Context context) { // super(context); // final float scale = getResources().getDisplayMetrics().density; // this.tocButtonSizePx = (int) (tocButtonSizeDp * scale + 0.5f); // if (this.tocButtonSizePx < this.tocButtonMinSizePx) this.tocButtonSizePx = this.tocButtonMinSizePx; // // } // // /** // * Set contents. // * @param root root (first top level node) of tree // */ // public synchronized void setTree(TreeNode root) { // if (root == null) throw new IllegalArgumentException("tree root can not be null"); // this.root = root; // this.state = new HashMap<Long, Boolean>(); // TreeAdapter adapter = new TreeAdapter(this); // this.setAdapter(adapter); // } // // /** // * Check if given node is open. // * Root node is always open. // * Node state is checked in this.state. // * If node state is not found in this.state, then it's assumed given node is closed. // * @return true if given node is open, false otherwise // */ // public synchronized boolean isOpen(TreeNode node) { // if (this.state.containsKey(node.getId())) { // return this.state.get(node.getId()); // } else { // return false; // } // } // // public synchronized void open(TreeNode node) { // this.open(node.getId()); // } // // public synchronized void open(long id) { // this.state.put(id, true); // } // // public synchronized void close(TreeNode node) { // this.close(node.getId()); // } // // public synchronized void close(long id) { // this.state.remove(id); // } // // /** // * Count visible tree elements. // */ // public synchronized int getVisibleCount() { // Stack<TreeNode> stack = new Stack<TreeNode>(); // /* walk visible part of tree by not descending into closed branches */ // stack.push(this.root); // int count = 0; // while(!stack.empty()) { // count += 1; // TreeNode node = stack.pop(); // if (this.isOpen(node) && node.hasChildren()) { // /* node is open - also count children */ // stack.push(node.getDown()); // } // /* now count other elements at this level */ // if (node.getNext() != null) stack.push(node.getNext()); // } // return count; // } // // /** // * Get text for position taking account current state. // * Iterates over tree taking state into account until position-th element is found. // * TODO: this is used quite frequently, so probably it would be worth to cache results // * @param position 0-based position in list // * @return text of currently visible item at given position // */ // public synchronized TreeNode getTreeNodeAtPosition(int position) { // Stack<TreeNode> stack = new Stack<TreeNode>(); // stack.push(this.root); // int i = 0; // TreeNode found = null; // while(!stack.empty() && found == null) { // TreeNode node = stack.pop(); // if (i == position) { // found = node; // break; // } // if (node.getNext() != null) stack.push(node.getNext()); // if (node.getDown() != null && this.isOpen(node)) { // stack.push(node.getDown()); // } // i++; // } // return found; // } // // /** // * Get tree state map. // * @return unmodifiable version of this.state // */ // public Map<Long, Boolean> getState() { // return Collections.unmodifiableMap(this.state); // } // } // // #endif
Java
package cx.hell.android.lib.pdf; import java.io.File; import java.io.FileDescriptor; import java.util.List; import cx.hell.android.lib.pagesview.FindResult; // #ifdef pro // import java.util.ArrayList; // import java.util.Stack; // import cx.hell.android.lib.view.TreeView; // import cx.hell.android.lib.view.TreeView.TreeNode; // #endif /** * Native PDF - interface to native code. */ public class PDF { private final static String TAG = "cx.hell.android.pdfview"; static { System.loadLibrary("pdfview2"); } /** * Simple size class used in JNI to simplify parameter passing. * This shouldn't be used anywhere outside of pdf-related code. */ public static class Size implements Cloneable { public int width; public int height; public Size() { this.width = 0; this.height = 0; } public Size(int width, int height) { this.width = width; this.height = height; } public Size clone() { return new Size(this.width, this.height); } } // #ifdef pro // /** // * Java version of fz_outline. // */ // public static class Outline implements TreeView.TreeNode { // // // /** // * Numeric id. Used in TreeView. // * Must uniquely identify each element in tree. // */ // private long id = -1; // // /** // * Text of the outline entry. // */ // public String title = null; // // /** // * Page number. // */ // public int page = 0; // // /** // * Next element at this level of TOC. // */ // public Outline next = null; // // /** // * Child. // */ // public Outline down = null; // // /** // * Level in TOC. Top level elements have level 0, children of top level elements have level 1 and so on. // */ // public int level = -1; // // // /** // * Set id. // * This is local to this TOC and its 0-based index of the element // * when list is displayed with all children expanded. // * @param id new id // */ // public void setId(long id) { // this.id = id; // } // // /** // * Get numeric id. // * @see id // */ // public long getId() { // return this.id; // } // // /** // * Get next element. // */ // public TreeNode getNext() { // return this.next; // } // // /** // * Get first child. // */ // public TreeNode getDown() { // return this.down; // } // // /** // * Return true if this outline element has children. // * @return true if has children // */ // public boolean hasChildren() { // return this.down != null; // } // // /** // * Get list of children of this tree node. // */ // public List<TreeNode> getChildren() { // ArrayList<TreeNode> children = new ArrayList<TreeNode>(); // for(Outline child = this.down; child != null; child = child.next) { // children.add(child); // } // return children; // } // // /** // * Return text. // */ // public String getText() { // return this.title; // } // // /** // * Get level. // * This is calculated in getOutline. // * @return value of level field // */ // public int getLevel() { // return this.level; // } // // /** // * Set level. // * @param level new level // */ // public void setLevel(int level) { // this.level = level; // } // // /** // * Return human readable description. // * @param human readable description of this object // */ // public String toString() { // return "Outline(" + this.id + ", \"" + this.title + "\", " + this.page + ")"; // } // } // #endif /** * Holds pointer to native pdf_t struct. */ private int pdf_ptr = -1; private int invalid_password = 0; public boolean isValid() { return pdf_ptr != 0; } public boolean isInvalidPassword() { return invalid_password != 0; } /** * Parse bytes as PDF file and store resulting pdf_t struct in pdf_ptr. * @return error code */ /* synchronized private native int parseBytes(byte[] bytes, int box); */ /** * Parse PDF file. * @param fileName pdf file name * @return error code */ synchronized private native int parseFile(String fileName, int box, String password); /** * Parse PDF file. * @param fd opened file descriptor * @return error code */ synchronized private native int parseFileDescriptor(FileDescriptor fd, int box, String password); /** * Construct PDF structures from bytes stored in memory. */ /* public PDF(byte[] bytes, int box) { this.parseBytes(bytes, box); } */ /** * Construct PDF structures from file sitting on local filesystem. */ public PDF(File file, int box) { this.parseFile(file.getAbsolutePath(), box, ""); } /** * Construct PDF structures from opened file descriptor. * @param file opened file descriptor */ public PDF(FileDescriptor file, int box) { this.parseFileDescriptor(file, box, ""); } /** * Return page count from pdf_t struct. */ synchronized public native int getPageCount(); /** * Render a page. * @param n page number, starting from 0 * @param zoom page size scaling * @param left left edge * @param right right edge * @param passes requested size, used for size of resulting bitmap * @return bytes of bitmap in Androids format */ synchronized public native int[] renderPage(int n, int zoom, int left, int top, int rotation, boolean gray, boolean skipImages, PDF.Size rect); /** * Get PDF page size, store it in size struct, return error code. * @param n 0-based page number * @param size size struct that holds result * @return error code */ synchronized public native int getPageSize(int n, PDF.Size size); /** * Export PDF to a text file. */ // synchronized public native void export(); /** * Find text on given page, return list of find results. */ synchronized public native List<FindResult> find(String text, int page); /** * Clear search. */ synchronized public native void clearFindResult(); /** * Find text on page, return find results. */ synchronized public native List<FindResult> findOnPage(int page, String text); // #ifdef pro // /** // * Get document outline. // */ // synchronized private native Outline getOutlineNative(); // // /** // * Get outline. // * Calls getOutlineNative and then calculates ids and levels. // * @return outline with correct id and level fields set. // */ // synchronized public Outline getOutline() { // Outline outlineRoot = this.getOutlineNative(); // if (outlineRoot == null) return null; // Stack<Outline> stack = new Stack<Outline>(); // // /* ids */ // stack.push(outlineRoot); // long id = 0; // while(!stack.empty()) { // Outline node = stack.pop(); // node.setId(id); // id++; // if (node.next != null) stack.push(node.next); // if (node.down != null) stack.push(node.down); // } // // /* levels */ // stack.clear(); // for(Outline node = outlineRoot; node != null; node = node.next) { // node.setLevel(0); // stack.push(node); // } // while(!stack.empty()) { // Outline node = stack.pop(); // for(Outline child = node.down; child != null; child = child.next) { // //parentMap.put(child.getId(), node); // child.setLevel(node.getLevel() + 1); // stack.push(child); // } // } // // return outlineRoot; // } // // /** // * Get page text (usually known as text reflow in some apps). Better text reflow coming... eventually. // */ // synchronized public native String getText(int page); // #endif /** * Free memory allocated in native code. */ synchronized private native void freeMemory(); public void finalize() { try { super.finalize(); } catch (Throwable e) { } this.freeMemory(); } }
Java
package cx.hell.android.lib.pagesview; // you're encouraged to use this piece of code for anything, either commercial or free, // either close-sourced or open-sourced. However, do put a line in your "About" section // saying that you used a code from dairyknight (dairyknight@gmail.com). That's the only request from me. import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class N2EpdController { /* * W/System.err( 6883): GC W/System.err( 6883): GU W/System.err( 6883): DU * W/System.err( 6883): A2 W/System.err( 6883): GL16 W/System.err( 6883): * AUTO * * W/System.err( 6982): APP_1 W/System.err( 6982): APP_2 W/System.err( * 6982): APP_3 W/System.err( 6982): APP_4 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void exitA2Mode() { System.err.println("APV::exitA2Mode"); try { Class epdControllerClass = Class .forName("android.hardware.EpdController"); Class epdControllerRegionClass = Class .forName("android.hardware.EpdController$Region"); Class epdControllerRegionParamsClass = Class .forName("android.hardware.EpdController$RegionParams"); Class epdControllerWaveClass = Class .forName("android.hardware.EpdController$Wave"); Object[] waveEnums = null; if (epdControllerWaveClass.isEnum()) { System.err .println("EpdController Wave Enum successfully retrived."); waveEnums = epdControllerWaveClass.getEnumConstants(); } Object[] regionEnums = null; if (epdControllerRegionClass.isEnum()) { System.err .println("EpdController Region Enum successfully retrived."); regionEnums = epdControllerRegionClass.getEnumConstants(); } Constructor RegionParamsConstructor = epdControllerRegionParamsClass .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass, Integer.TYPE }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[3], 16 }); // Wave = A2 Method epdControllerSetRegionMethod = epdControllerClass.getMethod( "setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass }); epdControllerSetRegionMethod .invoke(null, new Object[] { "APV-ReadingView", regionEnums[2], localRegionParams }); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static void enterA2Mode() { System.err.println("APV::enterA2Mode"); try { Class epdControllerClass = Class .forName("android.hardware.EpdController"); Class epdControllerRegionClass = Class .forName("android.hardware.EpdController$Region"); Class epdControllerRegionParamsClass = Class .forName("android.hardware.EpdController$RegionParams"); Class epdControllerWaveClass = Class .forName("android.hardware.EpdController$Wave"); Object[] waveEnums = null; if (epdControllerWaveClass.isEnum()) { System.err .println("EpdController Wave Enum successfully retrived."); waveEnums = epdControllerWaveClass.getEnumConstants(); } Object[] regionEnums = null; if (epdControllerRegionClass.isEnum()) { System.err .println("EpdController Region Enum successfully retrived."); regionEnums = epdControllerRegionClass.getEnumConstants(); } Constructor RegionParamsConstructor = epdControllerRegionParamsClass .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass, Integer.TYPE }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[2], 16 }); // Wave = DU Method epdControllerSetRegionMethod = epdControllerClass.getMethod( "setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass }); epdControllerSetRegionMethod .invoke(null, new Object[] { "APV-ReadingView", regionEnums[2], localRegionParams }); Thread.sleep(100L); localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[3], 14 }); // Wave = A2 epdControllerSetRegionMethod .invoke(null, new Object[] { "APV-ReadingView", regionEnums[2], localRegionParams }); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static void setGL16Mode() { System.err.println("APV::setGL16Mode"); try { /* * Loading the Epson EPD Controller Classes */ Class epdControllerClass = Class .forName("android.hardware.EpdController"); Class epdControllerRegionClass = Class .forName("android.hardware.EpdController$Region"); Class epdControllerRegionParamsClass = Class .forName("android.hardware.EpdController$RegionParams"); Class epdControllerWaveClass = Class .forName("android.hardware.EpdController$Wave"); Class epdControllerModeClass = Class .forName("android.hardware.EpdController$Mode"); /* * Creating EPD enums */ Object[] waveEnums = null; if (epdControllerWaveClass.isEnum()) { System.err .println("EpdController Wave Enum successfully retrived."); waveEnums = epdControllerWaveClass.getEnumConstants(); } Object[] regionEnums = null; if (epdControllerRegionClass.isEnum()) { System.err .println("EpdController Region Enum successfully retrived."); regionEnums = epdControllerRegionClass.getEnumConstants(); } Object[] modeEnums = null; if (epdControllerModeClass.isEnum()) { System.err .println("EpdController Region Enum successfully retrived."); modeEnums = epdControllerModeClass.getEnumConstants(); System.err.println(modeEnums); } Constructor RegionParamsConstructor = epdControllerRegionParamsClass .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[1] }); // Wave // = // GU Method epdControllerSetRegionMethod = epdControllerClass.getMethod( "setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass, epdControllerModeClass }); epdControllerSetRegionMethod.invoke(null, new Object[] { "APV-ReadingView", regionEnums[2], localRegionParams, modeEnums[2] }); // Mode = ONESHOT_ALL } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public static void setDUMode() { System.err.println("APV::setDUMode"); try { Class epdControllerClass = Class .forName("android.hardware.EpdController"); Class epdControllerRegionClass = Class .forName("android.hardware.EpdController$Region"); Class epdControllerRegionParamsClass = Class .forName("android.hardware.EpdController$RegionParams"); Class epdControllerWaveClass = Class .forName("android.hardware.EpdController$Wave"); Object[] waveEnums = null; if (epdControllerWaveClass.isEnum()) { System.err .println("EpdController Wave Enum successfully retrived."); waveEnums = epdControllerWaveClass.getEnumConstants(); } Object[] regionEnums = null; if (epdControllerRegionClass.isEnum()) { System.err .println("EpdController Region Enum successfully retrived."); regionEnums = epdControllerRegionClass.getEnumConstants(); } Constructor RegionParamsConstructor = epdControllerRegionParamsClass .getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, epdControllerWaveClass, Integer.TYPE }); Object localRegionParams = RegionParamsConstructor .newInstance(new Object[] { 0, 0, 600, 800, waveEnums[2], 14 }); Method epdControllerSetRegionMethod = epdControllerClass.getMethod( "setRegion", new Class[] { String.class, epdControllerRegionClass, epdControllerRegionParamsClass }); epdControllerSetRegionMethod .invoke(null, new Object[] { "APV-ReadingView", regionEnums[2], localRegionParams }); } catch (Exception e) { e.printStackTrace(); } } }
Java
package cx.hell.android.lib.pagesview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.graphics.Rect; import android.util.Log; /** * Find result. */ public class FindResult { /** * Logging tag. */ public static final String TAG = "cx.hell.android.pdfview"; /** * Page number. */ public int page; /** * List of rects that mark find result occurences. * In page dimensions (not scalled). */ public List<Rect> markers; /** * Add marker. */ public void addMarker(int x0, int y0, int x1, int y1) { if (x0 >= x1) throw new IllegalArgumentException("x0 must be smaller than x1: " + x0 + ", " + x1); if (y0 >= y1) throw new IllegalArgumentException("y0 must be smaller than y1: " + y0 + ", " + y1); if (this.markers == null) this.markers = new ArrayList<Rect>(); Rect nr = new Rect(x0, y0, x1, y1); if (this.markers.isEmpty()) { this.markers.add(nr); } else { this.markers.get(0).union(nr); } } public String toString() { StringBuilder b = new StringBuilder(); b.append("FindResult("); if (this.markers == null || this.markers.isEmpty()) { b.append("no markers"); } else { Iterator<Rect> i = this.markers.iterator(); Rect r = null; while(i.hasNext()) { r = i.next(); b.append(r); if (i.hasNext()) b.append(", "); } } b.append(")"); return b.toString(); } public void finalize() { Log.i(TAG, this + ".finalize()"); } }
Java
package cx.hell.android.lib.pagesview; /** * Tile definition. * Can be used as a key in maps (hashable, comparable). */ public class Tile { /** * X position of tile in pixels. */ private int x; /** * Y position of tile in pixels. */ private int y; private int zoom; private int page; private int rotation; private int prefXSize; private int prefYSize; int _hashCode; public Tile(int page, int zoom, int x, int y, int rotation, int prefXSize, int prefYSize) { this.prefXSize = prefXSize; this.prefYSize = prefYSize; this.page = page; this.zoom = zoom; this.x = x; this.y = y; this.rotation = rotation; } public String toString() { return "Tile(" + this.page + ", " + this.zoom + ", " + this.x + ", " + this.y + ", " + this.rotation + ")"; } @Override public int hashCode() { return this._hashCode; } @Override public boolean equals(Object o) { if (! (o instanceof Tile)) return false; Tile t = (Tile) o; return ( this._hashCode == t._hashCode && this.page == t.page && this.zoom == t.zoom && this.x == t.x && this.y == t.y && this.rotation == t.rotation ); } public int getPage() { return this.page; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZoom() { return this.zoom; } public int getRotation() { return this.rotation; } public int getPrefXSize() { return this.prefXSize; } public int getPrefYSize() { return this.prefYSize; } }
Java
package cx.hell.android.lib.pagesview; public class RenderingException extends Exception { private static final long serialVersionUID = 1010978161527539002L; public RenderingException(String message) { super(message); } }
Java
package cx.hell.android.lib.pagesview; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.SystemClock; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnDoubleTapListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; import android.widget.Scroller; import cx.hell.android.pdfview.Actions; import cx.hell.android.pdfview.Bookmark; import cx.hell.android.pdfview.BookmarkEntry; import cx.hell.android.pdfview.OpenFileActivity; import cx.hell.android.pdfview.Options; /** * View that simplifies displaying of paged documents. * TODO: redesign zooms, pages, margins, layout * TODO: use more floats for better align, or use more ints for performance ;) (that is, really analyse what should be used when) */ public class PagesView extends View implements View.OnTouchListener, OnImageRenderedListener, View.OnKeyListener { /** * Logging tag. */ private static final String TAG = "cx.hell.android.pdfview"; /* Experiments show that larger tiles are faster, but the gains do drop off, * and must be balanced against the size of memory chunks being requested. */ private static final int MIN_TILE_WIDTH = 256; private static final int MAX_TILE_WIDTH = 640; private static final int MIN_TILE_HEIGHT = 128; private static final int MAX_TILE_PIXELS = 640*360; // private final static int MAX_ZOOM = 4000; // private final static int MIN_ZOOM = 100; /** * Space between screen edge and page and between pages. */ private int marginX = 0; private int marginY = 10; /* multitouch zoom */ private boolean mtZoomActive = false; private float mtZoomValue; private float mtLastDistance; private float mtDistanceStart; private long mtDebounce; /* zoom steps */ float step = 1.414f; /* volume keys page */ boolean pageWithVolume = true; private Activity activity = null; /** * Source of page bitmaps. */ private PagesProvider pagesProvider = null; @SuppressWarnings("unused") private long lastControlsUseMillis = 0; private int colorMode; private float maxRealPageSize[] = {0f, 0f}; private float realDocumentSize[] = {0f, 0f}; /** * Current width of this view. */ private int width = 0; /** * Current height of this view. */ private int height = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int left = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int top = 0; /** * Current zoom level. * 1000 is 100%. */ private int zoomLevel = 1000; /** * Current rotation of pages. */ private int rotation = 0; /** * Base scaling factor - how much shrink (or grow) page to fit it nicely to screen at zoomLevel = 1000. * For example, if we determine that 200x400 image fits screen best, but PDF's pages are 400x800, then * base scaling would be 0.5, since at base scaling, without any zoom, page should fit into screen nicely. */ private float scaling0 = 0f; /** * Page sized obtained from pages provider. * These do not change. */ private int pageSizes[][]; /** * Find mode. */ private boolean findMode = false; /** * Paint used to draw find results. */ private Paint findResultsPaint = null; /** * Currently displayed find results. */ private List<FindResult> findResults = null; /** * hold the currently displayed page */ private int currentPage = 0; /** * avoid too much allocations in rectsintersect() */ private Rect r1 = new Rect(); /** * Bookmarked page to go to. */ private BookmarkEntry bookmarkToRestore = null; /** * Construct this view. * @param activity parent activity */ private boolean eink = false; private boolean showZoomOnScroll = false; private boolean volumeUpIsDown = false; private boolean volumeDownIsDown = false; private GestureDetector gestureDetector = null; private Scroller scroller = null; private boolean verticalScrollLock = true; private boolean lockedVertically = false; private float downX = 0; private float downY = 0; private float lastX = 0; private float lastY = 0; private float maxExcursionY = 0; private int doubleTapAction = Options.DOUBLE_TAP_ZOOM_IN_OUT; private int zoomToRestore = 0; private int leftToRestore; private Actions actions = null; private boolean nook2 = false; private LinearLayout zoomLayout = null; public PagesView(Activity activity) { super(activity); this.activity = activity; this.actions = null; this.lastControlsUseMillis = System.currentTimeMillis(); this.findResultsPaint = new Paint(); this.findResultsPaint.setARGB(0xd0, 0xc0, 0, 0); this.findResultsPaint.setStyle(Paint.Style.FILL); this.findResultsPaint.setAntiAlias(true); this.findResultsPaint.setStrokeWidth(3); this.setOnTouchListener(this); this.setOnKeyListener(this); activity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); this.mtZoomActive = false; this.mtDebounce = 0; this.scroller = null; // new Scroller(activity); this.gestureDetector = new GestureDetector(activity, new GestureDetector.OnGestureListener() { public boolean onDown(MotionEvent e) { return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (lockedVertically) velocityX = 0; doFling(velocityX, velocityY); return true; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } public boolean onSingleTapUp(MotionEvent e) { return false; } }); final OpenFileActivity openFileActivity = (OpenFileActivity)activity; final PagesView pagesView = this; gestureDetector.setOnDoubleTapListener(new OnDoubleTapListener() { public boolean onDoubleTap(MotionEvent e) { switch(doubleTapAction) { case Options.DOUBLE_TAP_ZOOM_IN_OUT: if (zoomToRestore != 0) { left = leftToRestore; top = top * zoomToRestore / zoomLevel; zoomLevel = zoomToRestore; invalidate(); zoomToRestore = 0; } else { int oldLeft = left; int oldZoom = zoomLevel; left += e.getX() - width/2; top += e.getY() - height/2; zoom(2f); zoomToRestore = oldZoom; leftToRestore = oldLeft; } return true; case Options.DOUBLE_TAP_ZOOM: left += e.getX() - width/2; top += e.getY() - height/2; zoom(2f); return true; default: return false; } } public boolean onDoubleTapEvent(MotionEvent e) { return false; } public boolean onSingleTapConfirmed(MotionEvent e) { if (mtDebounce + 600 > SystemClock.uptimeMillis()) return false; if (!showZoomOnScroll) { openFileActivity.showZoom(); pagesView.invalidate(); } if (zoomLayout != null) { Rect r = new Rect(); zoomLayout.getDrawingRect(r); r.set(r.left - 5, r.top - 5, r.right + 5, r.bottom + 5); if (r.contains((int)e.getX(), (int)e.getY())) return false; } return doAction(actions.getAction(e.getY() < height / 2 ? Actions.TOP_TAP : Actions.BOTTOM_TAP)); } }); } public void setStartBookmark(Bookmark b, String bookmarkName) { if (b != null) { this.bookmarkToRestore = b.getLast(bookmarkName); if (this.bookmarkToRestore == null) return; if (this.bookmarkToRestore.numberOfPages != this.pageSizes.length) { this.bookmarkToRestore = null; return; } if (0<this.bookmarkToRestore.page) { this.currentPage = this.bookmarkToRestore.page; } } } /** * Handle size change event. * Update base scaling, move zoom controls to correct place etc. * @param w new width * @param h new height * @param oldw old width * @param oldh old height */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.width = w; this.height = h; if (this.scaling0 == 0f) { this.scaling0 = Math.min( ((float)this.height - 2*marginY) / (float)this.pageSizes[0][1], ((float)this.width - 2*marginX) / (float)this.pageSizes[0][0]); } if (oldw == 0 && oldh == 0) { goToBookmark(); } } public void goToBookmark() { if (this.bookmarkToRestore == null || this.bookmarkToRestore.absoluteZoomLevel == 0 || this.bookmarkToRestore.page < 0 || this.bookmarkToRestore.page >= this.pageSizes.length ) { this.top = this.height / 2; this.left = this.width / 2; } else { this.zoomLevel = (int)(this.bookmarkToRestore.absoluteZoomLevel / this.scaling0); this.rotation = this.bookmarkToRestore.rotation; Point pos = getPagePositionInDocumentWithZoom(this.bookmarkToRestore.page); this.currentPage = this.bookmarkToRestore.page; this.top = pos.y + this.height / 2; this.left = this.getCurrentPageWidth(this.currentPage)/2 + marginX + this.bookmarkToRestore.offsetX; this.bookmarkToRestore = null; } } public void setPagesProvider(PagesProvider pagesProvider) { this.pagesProvider = pagesProvider; if (this.pagesProvider != null) { this.pageSizes = this.pagesProvider.getPageSizes(); maxRealPageSize[0] = 0f; maxRealPageSize[1] = 0f; realDocumentSize[0] = 0f; realDocumentSize[1] = 0f; for (int i = 0; i < this.pageSizes.length; i++) for (int j = 0; j<2; j++) { if (pageSizes[i][j] > maxRealPageSize[j]) maxRealPageSize[j] = pageSizes[i][j]; realDocumentSize[j] += pageSizes[i][j]; } if (this.width > 0 && this.height > 0) { this.scaling0 = Math.min( ((float)this.height - 2*marginY) / (float)this.pageSizes[0][1], ((float)this.width - 2*marginX) / (float)this.pageSizes[0][0]); this.left = this.width / 2; this.top = this.height / 2; } } else { this.pageSizes = null; } this.pagesProvider.setOnImageRenderedListener(this); } /** * Draw view. * @param canvas what to draw on */ int prevTop = -1; int prevLeft = -1; public void onDraw(Canvas canvas) { if (this.nook2) { N2EpdController.setGL16Mode(); } this.drawPages(canvas); if (this.findMode) this.drawFindResults(canvas); } /** * Get current maximum page width by page number taking into account zoom and rotation */ private int getCurrentMaxPageWidth() { float realpagewidth = this.maxRealPageSize[this.rotation % 2 == 0 ? 0 : 1]; return (int)scale(realpagewidth); } /** * Get current maximum page height by page number taking into account zoom and rotation */ /* private int getCurrentMaxPageHeight() { float realpageheight = this.maxRealPageSize[this.rotation % 2 == 0 ? 1 : 0]; return (int)(realpageheight * scaling0 * (this.zoomLevel*0.001f)); } */ /** * Get current maximum page width by page number taking into account zoom and rotation */ private int getCurrentDocumentHeight() { float realheight = this.realDocumentSize[this.rotation % 2 == 0 ? 1 : 0]; /* we add pageSizes.length to account for round-off issues */ return (int)(scale(realheight) + (pageSizes.length - 1) * this.getCurrentMarginY()); } /** * Get current page width by page number taking into account zoom and rotation * @param pageno 0-based page number */ private int getCurrentPageWidth(int pageno) { float realpagewidth = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 0 : 1]; float currentpagewidth = scale(realpagewidth); return (int)currentpagewidth; } private float scale(float unscaled) { return unscaled * scaling0 * this.zoomLevel * 0.001f; } /** * Get current page height by page number taking into account zoom and rotation. * @param pageno 0-based page number */ private float getCurrentPageHeight(int pageno) { float realpageheight = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 1 : 0]; float currentpageheight = scale(realpageheight); return currentpageheight; } private float getCurrentMarginX() { return scale((float)marginX); } private float getCurrentMarginY() { return scale((float)marginY); } /** * This takes into account zoom level. */ private Point getPagePositionInDocumentWithZoom(int page) { float marginX = this.getCurrentMarginX(); float marginY = this.getCurrentMarginY(); float left = marginX; float top = 0; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } top += (page+1) * marginY; return new Point((int)left, (int)top); } /** * Calculate screens (viewports) top-left corner position over document. */ private Point getScreenPositionOverDocument() { float top = this.top - this.height / 2; float left = this.left - this.width / 2; return new Point((int)left, (int)top); } /** * Calculate current page position on screen in pixels. * @param page base-0 page number */ private Point getPagePositionOnScreen(int page) { if (page < 0) throw new IllegalArgumentException("page must be >= 0: " + page); if (page >= this.pageSizes.length) throw new IllegalArgumentException("page number too big: " + page); Point pagePositionInDocument = this.getPagePositionInDocumentWithZoom(page); Point screenPositionInDocument = this.getScreenPositionOverDocument(); return new Point( pagePositionInDocument.x - screenPositionInDocument.x, pagePositionInDocument.y - screenPositionInDocument.y ); } @Override public void computeScroll() { if (this.scroller == null) return; if (this.scroller.computeScrollOffset()) { left = this.scroller.getCurrX(); top = this.scroller.getCurrY(); ((cx.hell.android.pdfview.OpenFileActivity)activity).showPageNumber(false); postInvalidate(); } } /** * Draw pages. * Also collect info what's visible and push this info to page renderer. */ private void drawPages(Canvas canvas) { if (this.eink) { canvas.drawColor(Color.WHITE); } Rect src = new Rect(); /* TODO: move out of drawPages */ Rect dst = new Rect(); /* TODO: move out of drawPages */ int pageWidth = 0; int pageHeight = 0; float pagex0, pagey0, pagex1, pagey1; // in doc, counts zoom int x, y; // on screen int viewx0, viewy0; // view over doc LinkedList<Tile> visibleTiles = new LinkedList<Tile>(); float currentMarginX = this.getCurrentMarginX(); float currentMarginY = this.getCurrentMarginY(); if (this.pagesProvider != null) { if (this.zoomLevel < 5) this.zoomLevel = 5; int pageCount = this.pageSizes.length; viewx0 = this.left - this.width/2; viewy0 = this.top - this.height/2; int adjScreenLeft; int adjScreenTop; int adjScreenWidth; int adjScreenHeight; float renderAhead; if (mtZoomActive) { adjScreenWidth = (int)(this.width / mtZoomValue); adjScreenLeft = this.width/2 - adjScreenWidth/2; adjScreenHeight = (int)(this.height / mtZoomValue); adjScreenTop = this.height/2 - adjScreenHeight/2; renderAhead = 1f; Log.v(TAG, "adj:"+ adjScreenLeft+" "+adjScreenTop+" "+adjScreenWidth+" "+adjScreenHeight); } else { /* We now adjust the position to make sure we don't scroll too * far away from the document text. */ int oldviewx0 = viewx0; int oldviewy0 = viewy0; viewx0 = adjustPosition(viewx0, width, (int)currentMarginX, getCurrentMaxPageWidth()); viewy0 = adjustPosition(viewy0, height, (int)currentMarginY, (int)getCurrentDocumentHeight()); this.left += viewx0 - oldviewx0; this.top += viewy0 - oldviewy0; adjScreenWidth = this.width; adjScreenLeft = 0; adjScreenHeight = this.height; adjScreenTop = 0; renderAhead = this.pagesProvider.getRenderAhead(); } float currpageoff = currentMarginY; this.currentPage = -1; pagey0 = 0; int[] tileSizes = new int[2]; for(int i = 0; i < pageCount; ++i) { // is page i visible? pageWidth = this.getCurrentPageWidth(i); pageHeight = (int) this.getCurrentPageHeight(i); pagex0 = currentMarginX; pagex1 = (int)(currentMarginX + pageWidth); pagey0 = currpageoff; pagey1 = (int)(currpageoff + pageHeight); if (rectsintersect( (int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc viewx0 + adjScreenLeft, viewy0 + adjScreenTop, viewx0 + adjScreenLeft + adjScreenWidth, viewy0 + adjScreenTop + (int)(renderAhead*adjScreenHeight) // viewport rect in doc, or close enough to it )) { if (this.currentPage == -1) { // remember the currently displayed page this.currentPage = i; } x = (int)pagex0 - viewx0 - adjScreenLeft; y = (int)pagey0 - viewy0 - adjScreenTop; getGoodTileSizes(tileSizes, pageWidth, pageHeight); for(int tileix = 0; tileix < (pageWidth + tileSizes[0]-1) / tileSizes[0]; ++tileix) for(int tileiy = 0; tileiy < (pageHeight + tileSizes[1]-1) / tileSizes[1]; ++tileiy) { dst.left = (int)(x + tileix*tileSizes[0]); dst.top = (int)(y + tileiy*tileSizes[1]); dst.right = dst.left + tileSizes[0]; dst.bottom = dst.top + tileSizes[1]; if (dst.intersects(0, 0, adjScreenWidth, (int)(renderAhead*adjScreenHeight))) { Tile tile = new Tile(i, (int)(this.zoomLevel * scaling0), tileix*tileSizes[0], tileiy*tileSizes[1], this.rotation, tileSizes[0], tileSizes[1]); if (dst.intersects(0, 0, adjScreenWidth, adjScreenHeight)) { Bitmap b = this.pagesProvider.getPageBitmap(tile); if (b != null) { //Log.d(TAG, " have bitmap: " + b + ", size: " + b.getWidth() + " x " + b.getHeight()); src.left = 0; src.top = 0; src.right = b.getWidth(); src.bottom = b.getHeight(); if (dst.right > x + pageWidth) { src.right = (int)(b.getWidth() * (float)((x+pageWidth)-dst.left) / (float)(dst.right - dst.left)); dst.right = (int)(x + pageWidth); } if (dst.bottom > y + pageHeight) { src.bottom = (int)(b.getHeight() * (float)((y+pageHeight)-dst.top) / (float)(dst.bottom - dst.top)); dst.bottom = (int)(y + pageHeight); } if (mtZoomActive) { dst.left = (int) ((dst.left-adjScreenWidth/2) * mtZoomValue + this.width/2); dst.right = (int) ((dst.right-adjScreenWidth/2) * mtZoomValue + this.width/2); dst.top = (int) ((dst.top-adjScreenHeight/2) * mtZoomValue + this.height/2); dst.bottom = (int) ((dst.bottom-adjScreenHeight/2) * mtZoomValue + this.height/2); } drawBitmap(canvas, b, src, dst); } } if (!mtZoomActive) visibleTiles.add(tile); } } } /* move to next page */ currpageoff += currentMarginY + this.getCurrentPageHeight(i); } this.pagesProvider.setVisibleTiles(visibleTiles); } } private void drawBitmap(Canvas canvas, Bitmap b, Rect src, Rect dst) { if (colorMode != Options.COLOR_MODE_NORMAL) { Paint paint = new Paint(); Bitmap out; if (b.getConfig() == Bitmap.Config.ALPHA_8) { out = b.copy(Bitmap.Config.ARGB_8888, false); } else { out = b; } paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix( Options.getColorModeMatrix(this.colorMode)))); canvas.drawBitmap(out, src, dst, paint); if (b.getConfig() == Bitmap.Config.ALPHA_8) { out.recycle(); } } else { canvas.drawBitmap(b, src, dst, null); } } /** * Draw find results. * TODO prettier icons * TODO message if nothing was found * @param canvas drawing target */ private void drawFindResults(Canvas canvas) { if (!this.findMode) throw new RuntimeException("drawFindResults but not in find results mode"); if (this.findResults == null || this.findResults.isEmpty()) { Log.w(TAG, "nothing found"); return; } for(FindResult findResult: this.findResults) { if (findResult.markers == null || findResult.markers.isEmpty()) throw new RuntimeException("illegal FindResult: find result must have at least one marker"); Iterator<Rect> i = findResult.markers.iterator(); Rect r = null; Point pagePosition = this.getPagePositionOnScreen(findResult.page); float pagex = pagePosition.x; float pagey = pagePosition.y; float z = (this.scaling0 * (float)this.zoomLevel * 0.001f); while(i.hasNext()) { r = i.next(); canvas.drawLine( r.left * z + pagex, r.top * z + pagey, r.left * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.left * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.right * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.top * z + pagey, this.findResultsPaint); // canvas.drawRect( // r.left * z + pagex, // r.top * z + pagey, // r.right * z + pagex, // r.bottom * z + pagey, // this.findResultsPaint); // Log.d(TAG, "marker lands on: " + // (r.left * z + pagex) + ", " + // (r.top * z + pagey) + ", " + // (r.right * z + pagex) + ", " + // (r.bottom * z + pagey) + ", "); } } } private boolean unlocksVerticalLock(MotionEvent e) { float dx; float dy; dx = Math.abs(e.getX()-downX); dy = Math.abs(e.getY()-downY); if (dy > 0.25 * dx || maxExcursionY > 0.8 * dx) return false; return dx > width/5 || dx > height/5; } /** * * @param event * @return distance in multitouch event */ private float distance(MotionEvent event) { double dx = event.getX(0)-event.getX(1); double dy = event.getY(0)-event.getY(1); return (float)Math.sqrt(dx*dx+dy*dy); } /** * Handle touch event coming from Android system. */ public boolean onTouch(View v, MotionEvent event) { this.lastControlsUseMillis = System.currentTimeMillis(); Log.v(TAG, ""+event.getAction()); if (!gestureDetector.onTouchEvent(event)) { // Log.v(TAG, ""+event.getAction()); if (event.getAction() == MotionEvent.ACTION_DOWN) { downX = event.getX(); downY = event.getY(); lastX = downX; lastY = downY; lockedVertically = verticalScrollLock; maxExcursionY = 0; scroller = null; } else if (event.getAction() == MotionEvent.ACTION_POINTER_2_DOWN && event.getPointerCount() >= 2) { float d = distance(event); if (d > 20f) { this.mtZoomActive = true; this.mtZoomValue = 1f; this.mtDistanceStart = distance(event); this.mtLastDistance = this.mtDistanceStart; } } else if (event.getAction() == MotionEvent.ACTION_MOVE){ if (this.mtZoomActive && event.getPointerCount() >= 2) { float d = distance(event); if (d > 20f) { d = .6f * this.mtLastDistance + .4f * d; this.mtLastDistance = d; this.mtZoomValue = d / this.mtDistanceStart; if (this.mtZoomValue < 0.1f) this.mtZoomValue = 0.1f; else if (mtZoomValue > 10f) this.mtZoomValue = 10f; Log.v(TAG, "MT zoom "+this.mtZoomValue); invalidate(); } } else { if (lockedVertically && unlocksVerticalLock(event)) lockedVertically = false; float dx = event.getX() - lastX; float dy = event.getY() - lastY; float excursionY = Math.abs(event.getY() - downY); if (excursionY > maxExcursionY) maxExcursionY = excursionY; if (lockedVertically) dx = 0; doScroll((int)-dx, (int)-dy); lastX = event.getX(); lastY = event.getY(); } } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_POINTER_2_UP) { if (this.mtZoomActive) { this.mtDebounce = SystemClock.uptimeMillis(); this.mtZoomActive = false; zoom(this.mtZoomValue); } } } return true; } /** * Handle keyboard events */ public boolean onKey(View v, int keyCode, KeyEvent event) { if (this.pageWithVolume && event.getAction() == KeyEvent.ACTION_UP) { /* repeat is a little too fast sometimes, so trap these on up */ switch(keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: volumeUpIsDown = false; return true; case KeyEvent.KEYCODE_VOLUME_DOWN: volumeDownIsDown = false; return true; } } if (event.getAction() == KeyEvent.ACTION_DOWN) { int action = actions.getAction(keyCode); switch (keyCode) { case KeyEvent.KEYCODE_SEARCH: ((cx.hell.android.pdfview.OpenFileActivity)activity).showFindDialog(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (action == Actions.ACTION_NONE) return false; if (!volumeDownIsDown) { /* Disable key repeat as on some devices the keys are a little too * sticky for key repeat to work well. TODO: Maybe key repeat disabling * should be an option? */ doAction(action); } volumeDownIsDown = true; return true; case KeyEvent.KEYCODE_VOLUME_UP: if (action == Actions.ACTION_NONE) return false; if (!this.pageWithVolume) return false; if (!volumeUpIsDown) { doAction(action); } volumeUpIsDown = true; return true; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: case 92: case 93: case 94: case 95: doAction(action); return true; case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_K: doAction(Actions.ACTION_SCREEN_UP); return true; case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_J: doAction(Actions.ACTION_SCREEN_DOWN); return true; case KeyEvent.KEYCODE_H: this.left -= this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_L: this.left += this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_O: zoom(1f/1.1f); return true; case KeyEvent.KEYCODE_P: zoom(1.1f); return true; } } return false; } /** * Test if specified rectangles intersect with each other. * Uses Androids standard Rect class. */ private boolean rectsintersect( int r1x0, int r1y0, int r1x1, int r1y1, int r2x0, int r2y0, int r2x1, int r2y1) { r1.set(r1x0, r1y0, r1x1, r1y1); return r1.intersects(r2x0, r2y0, r2x1, r2y1); } /** * Used as a callback from pdf rendering code. * TODO: only invalidate what needs to be painted, not the whole view */ public void onImagesRendered(Map<Tile,Bitmap> renderedTiles) { Rect rect = new Rect(); /* TODO: move out of onImagesRendered */ int viewx0 = left - width/2; int viewy0 = top - height/2; int pageCount = this.pageSizes.length; float currentMarginX = this.getCurrentMarginX(); float currentMarginY = this.getCurrentMarginY(); viewx0 = adjustPosition(viewx0, width, (int)currentMarginX, getCurrentMaxPageWidth()); viewy0 = adjustPosition(viewy0, height, (int)currentMarginY, (int)getCurrentDocumentHeight()); float currpageoff = currentMarginY; float renderAhead = this.pagesProvider.getRenderAhead(); float pagex0; float pagex1; float pagey0 = 0; float pagey1; float x; float y; int pageWidth; int pageHeight; for(int i = 0; i < pageCount; ++i) { // is page i visible? pageWidth = this.getCurrentPageWidth(i); pageHeight = (int) this.getCurrentPageHeight(i); pagex0 = currentMarginX; pagex1 = (int)(currentMarginX + pageWidth); pagey0 = currpageoff; pagey1 = (int)(currpageoff + pageHeight); if (rectsintersect( (int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc viewx0, viewy0, viewx0 + this.width, viewy0 + this.height )) { x = pagex0 - viewx0; y = pagey0 - viewy0; for (Tile tile: renderedTiles.keySet()) { if (tile.getPage() == i) { Bitmap b = renderedTiles.get(tile); rect.left = (int)(x + tile.getX()); rect.top = (int)(y + tile.getY()); rect.right = rect.left + b.getWidth(); rect.bottom = rect.top + b.getHeight(); if (rect.intersects(0, 0, this.width, (int)(renderAhead*this.height))) { Log.v(TAG, "New bitmap forces redraw"); postInvalidate(); return; } } } } currpageoff += currentMarginY + this.getCurrentPageHeight(i); } Log.v(TAG, "New bitmap does not require redraw"); } /** * Handle rendering exception. * Show error message and then quit parent activity. * TODO: find a proper way to finish an activity when something bad happens in view. */ public void onRenderingException(RenderingException reason) { final Activity activity = this.activity; final String message = reason.getMessage(); this.post(new Runnable() { public void run() { AlertDialog errorMessageDialog = new AlertDialog.Builder(activity) .setTitle("Error") .setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { activity.finish(); } }) .create(); errorMessageDialog.show(); } }); } synchronized public void scrollToPage(int page) { scrollToPage(page, true); } public float pagePosition(int page) { float top = 0; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } if (page > 0) top += scale((float)marginY) * (float)(page); return top; } /** * Move current viewport over n-th page. * Page is 0-based. * @param page 0-based page number */ synchronized public void scrollToPage(int page, boolean positionAtTop) { float top; if (page < 0) page = 0; else if (page >= this.getPageCount()) page = this.getPageCount() - 1; if (positionAtTop) { top = this.height/2 + pagePosition(page); } else { top = this.top - pagePosition(currentPage) + pagePosition(page); } this.top = (int)top; this.currentPage = page; this.invalidate(); } // /** // * Compute what's currently visible. // * @return collection of tiles that define what's currently visible // */ // private Collection<Tile> computeVisibleTiles() { // LinkedList<Tile> tiles = new LinkedList<Tile>(); // float viewx = this.left + (this.dragx1 - this.dragx); // float viewy = this.top + (this.dragy1 - this.dragy); // float pagex = MARGIN; // float pagey = MARGIN; // float pageWidth; // float pageHeight; // int tileix; // int tileiy; // int thisPageTileCountX; // int thisPageTileCountY; // float tilex; // float tiley; // for(int page = 0; page < this.pageSizes.length; ++page) { // // pageWidth = this.getCurrentPageWidth(page); // pageHeight = this.getCurrentPageHeight(page); // // thisPageTileCountX = (int)Math.ceil(pageWidth / TILE_SIZE); // thisPageTileCountY = (int)Math.ceil(pageHeight / TILE_SIZE); // // if (viewy + this.height < pagey) continue; /* before first visible page */ // if (viewx > pagey + pageHeight) break; /* after last page */ // // for(tileix = 0; tileix < thisPageTileCountX; ++tileix) { // for(tileiy = 0; tileiy < thisPageTileCountY; ++tileiy) { // tilex = pagex + tileix * TILE_SIZE; // tiley = pagey + tileiy * TILE_SIZE; // if (rectsintersect(viewx, viewy, viewx+this.width, viewy+this.height, // tilex, tiley, tilex+TILE_SIZE, tiley+TILE_SIZE)) { // tiles.add(new Tile(page, this.zoomLevel, (int)tilex, (int)tiley, this.rotation)); // } // } // } // // /* move to next page */ // pagey += this.getCurrentPageHeight(page) + MARGIN; // } // return tiles; // } // synchronized Collection<Tile> getVisibleTiles() { // return this.visibleTiles; // } /** * Rotate pages. * Updates rotation variable, then invalidates view. * @param rotation rotation */ synchronized public void rotate(int rotation) { this.rotation = (this.rotation + rotation) % 4; this.invalidate(); } /** * Set find mode. * @param m true if pages view should display find results and find controls */ synchronized public void setFindMode(boolean m) { if (this.findMode != m) { this.findMode = m; if (!m) { this.findResults = null; } } } /** * Return find mode. * @return find mode - true if view is currently in find mode */ public boolean getFindMode() { return this.findMode; } // /** // * Ask pages provider to focus on next find result. // * @param forward direction of search - true for forward, false for backward // */ // public void findNext(boolean forward) { // this.pagesProvider.findNext(forward); // this.scrollToFindResult(); // this.invalidate(); // } /** * Move viewport position to find result (if any). * Does not call invalidate(). */ public void scrollToFindResult(int n) { if (this.findResults == null || this.findResults.isEmpty()) return; Rect center = new Rect(); FindResult findResult = this.findResults.get(n); for(Rect marker: findResult.markers) { center.union(marker); } float x = scale((center.left + center.right) / 2); float y = pagePosition(findResult.page) + scale((center.top + center.bottom) / 2); this.left = (int)(x + this.getCurrentMarginX()); this.top = (int)(y); } /** * Get the current page number * * @return the current page. 0-based */ public int getCurrentPage() { return currentPage; } /** * Get the current zoom level * * @return the current zoom level */ public int getCurrentAbsoluteZoom() { return zoomLevel; } /** * Get the current rotation * * @return the current rotation */ public int getRotation() { return rotation; } /** * Get page count. */ public int getPageCount() { return this.pageSizes.length; } /** * Set find results. */ public void setFindResults(List<FindResult> results) { this.findResults = results; } /** * Get current find results. */ public List<FindResult> getFindResults() { return this.findResults; } private void doFling(float vx, float vy) { float avx = vx > 0 ? vx : -vx; float avy = vy > 0 ? vy : -vy; if (avx < .25 * avy) { vx = 0; } else if (avy < .25 * avx) { vy = 0; } int marginX = (int)getCurrentMarginX(); int marginY = (int)getCurrentMarginY(); int minx = this.width/2 + getLowerBound(this.width, marginX, getCurrentMaxPageWidth()); int maxx = this.width/2 + getUpperBound(this.width, marginX, getCurrentMaxPageWidth()); int miny = this.height/2 + getLowerBound(this.height, marginY, getCurrentDocumentHeight()); int maxy = this.height/2 + getUpperBound(this.height, marginY, getCurrentDocumentHeight()); this.scroller = new Scroller(activity); this.scroller.fling(this.left, this.top, (int)-vx, (int)-vy, minx, maxx, miny, maxy); invalidate(); } private void doScroll(int dx, int dy) { this.left += dx; this.top += dy; invalidate(); } /** * Zoom down one level */ public void zoom(float value) { this.zoomLevel *= value; this.left *= value; this.top *= value; Log.d(TAG, "zoom level changed to " + this.zoomLevel); zoomToRestore = 0; this.invalidate(); } /* zoom to width */ public void zoomWidth() { int page = currentPage < 0 ? 0 : currentPage; int pageWidth = getCurrentPageWidth(page); this.top = (this.top - this.height / 2) * this.width / pageWidth + this.height / 2; this.zoomLevel = this.zoomLevel * (this.width - 2*marginX) / pageWidth; this.left = (int) (this.width/2); zoomToRestore = 0; this.invalidate(); } /* zoom to fit */ public void zoomFit() { int page = currentPage < 0 ? 0 : currentPage; int z1 = this.zoomLevel * this.width / getCurrentPageWidth(page); int z2 = (int)(this.zoomLevel * this.height / getCurrentPageHeight(page)); this.zoomLevel = z2 < z1 ? z2 : z1; Point pos = getPagePositionInDocumentWithZoom(page); this.left = this.width/2 + pos.x; this.top = this.height/2 + pos.y; zoomToRestore = 0; this.invalidate(); } /** * Set zoom */ public void setZoomLevel(int zoomLevel) { if (this.zoomLevel == zoomLevel) return; this.zoomLevel = zoomLevel; Log.d(TAG, "zoom level changed to " + this.zoomLevel); zoomToRestore = 0; this.invalidate(); } /** * Set rotation */ public void setRotation(int rotation) { if (this.rotation == rotation) return; this.rotation = rotation; Log.d(TAG, "rotation changed to " + this.rotation); this.invalidate(); } public void setVerticalScrollLock(boolean verticalScrollLock) { this.verticalScrollLock = verticalScrollLock; } public void setColorMode(int colorMode) { this.colorMode = colorMode; this.invalidate(); } public void setZoomIncrement(float step) { this.step = step; } public void setPageWithVolume(boolean pageWithVolume) { this.pageWithVolume = pageWithVolume; } private void getGoodTileSizes(int[] sizes, int pageWidth, int pageHeight) { sizes[0] = getGoodTileSize(pageWidth, MIN_TILE_WIDTH, MAX_TILE_WIDTH); sizes[1] = getGoodTileSize(pageHeight, MIN_TILE_HEIGHT, MAX_TILE_PIXELS / sizes[0]); } private int getGoodTileSize(int pageSize, int minSize, int maxSize) { if (pageSize <= 2) return 2; if (pageSize <= maxSize) return pageSize; int numInPageSize = (pageSize + maxSize - 1) / maxSize; int proposedSize = (pageSize + numInPageSize - 1) / numInPageSize; if (proposedSize < minSize) return minSize; else return proposedSize; } /* Get the upper and lower bounds for the viewpoint. The document itself is * drawn from margin to margin+docDim. */ private int getLowerBound(int screenDim, int margin, int docDim) { if (docDim <= screenDim) { /* all pages can and do fit */ return margin + docDim - screenDim; } else { /* document is too wide/tall to fit */ return 0; } } private int getUpperBound(int screenDim, int margin, int docDim) { if (docDim <= screenDim) { /* all pages can and do fit */ return margin; } else { /* document is too wide/tall to fit */ return 2 * margin + docDim - screenDim; } } private int adjustPosition(int pos, int screenDim, int margin, int docDim) { int min = getLowerBound(screenDim, margin, docDim); int max = getUpperBound(screenDim, margin, docDim); if (pos < min) return min; else if (max < pos) return max; else return pos; } public BookmarkEntry toBookmarkEntry() { return new BookmarkEntry(this.pageSizes.length, this.currentPage, scaling0*zoomLevel, rotation, this.left - this.getCurrentPageWidth(this.currentPage)/2 - marginX); } public void setSideMargins(int margin) { this.marginX = margin; } public void setTopMargin(int margin) { int delta = margin - this.marginY; top += this.currentPage * delta; this.marginY = margin; } public void setDoubleTap(int doubleTapAction) { this.doubleTapAction = doubleTapAction; } public boolean doAction(int action) { float zoomValue = Actions.getZoomValue(action); if (0f < zoomValue) { zoom(zoomValue); return true; } switch(action) { case Actions.ACTION_FULL_PAGE_DOWN: scrollToPage(currentPage + 1, false); return true; case Actions.ACTION_FULL_PAGE_UP: scrollToPage(currentPage - 1, false); return true; case Actions.ACTION_PREV_PAGE: scrollToPage(currentPage - 1); return true; case Actions.ACTION_NEXT_PAGE: scrollToPage(currentPage + 1); return true; case Actions.ACTION_SCREEN_DOWN: this.top += this.getHeight() - 16; this.invalidate(); return true; case Actions.ACTION_SCREEN_UP: this.top -= this.getHeight() - 16; this.invalidate(); return true; default: return false; } } public void setActions(Actions actions) { this.actions = actions; } public void setEink(boolean eink) { this.eink = eink; } public void setNook2(boolean nook2) { this.nook2 = nook2; } public void setShowZoomOnScroll(boolean showZoomOnScroll) { this.showZoomOnScroll = showZoomOnScroll; } public void setZoomLayout(LinearLayout zoomLayout) { this.zoomLayout = zoomLayout; } }
Java
package cx.hell.android.lib.pagesview; import java.util.Map; import android.graphics.Bitmap; /** * Allow renderer to notify view that new bitmaps are ready. * Implemented by PagesView. */ public interface OnImageRenderedListener { void onImagesRendered(Map<Tile,Bitmap> renderedImages); void onRenderingException(RenderingException reason); }
Java
package cx.hell.android.lib.pagesview; import java.util.Collection; import android.graphics.Bitmap; /** * Provide content of pages rendered by PagesView. */ public abstract class PagesProvider { /** * Get page image tile for drawing. */ public abstract Bitmap getPageBitmap(Tile tile); /** * Get page count. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int getPageCount(); /** * Get page sizes. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int[][] getPageSizes(); /** * Set notify target. * Usually page rendering takes some time. If image cannot be provided * immediately, provider may return null. * Then it's up to provider to notify view that requested image has arrived * and is ready to be drawn. * This function, if overridden, can be used to inform provider who * should be notifed. * Default implementation does nothing. */ public void setOnImageRenderedListener(OnImageRenderedListener listener) { /* to be overridden when needed */ } public abstract void setVisibleTiles(Collection<Tile> tiles); public abstract float getRenderAhead(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import javax.ws.rs.ClientErrorException; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; /** * Jersey REST client generated for REST resource:RESTfulResource * [restful/item]<br> * USAGE: * <pre> * DeleteItemClient client = new DeleteItemClient(); * Object response = client.XXX(...); * // do whatever with response * client.close(); * </pre> * * @author Ewoud */ public class DeleteItemClient { private WebTarget webTarget; private Client client; private static final String BASE_URI = "http://localhost:8080/BakkerijX_v2-war/webresources"; public DeleteItemClient() { client = javax.ws.rs.client.ClientBuilder.newClient(); webTarget = client.target(BASE_URI).path("restful/item"); } public String getText() throws ClientErrorException { WebTarget resource = webTarget; return resource.request(javax.ws.rs.core.MediaType.TEXT_PLAIN).get(String.class); } public void deleteItem(String id) throws ClientErrorException { webTarget.path(java.text.MessageFormat.format("{0}", new Object[]{id})).request().delete(); } public void putText(Object requestEntity) throws ClientErrorException { webTarget.request(javax.ws.rs.core.MediaType.TEXT_PLAIN).put(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.TEXT_PLAIN)); } public void close() { client.close(); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import javax.json.Json; import javax.json.stream.JsonParser; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author Ewoud */ @WebServlet(name = "FlowersfoodsServlet", urlPatterns = {"/FlowersfoodsServlet"}) public class FlowersfoodsServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>FlowersfoodsServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Flowers Foods, Inc. (NYSE:FLO)</h1>"); out.println("<p><a href=\"http://localhost:8080/Client-war\">Go back</a></p>"); try{ String url = "https://www.google.com/finance/info?q=" + "FLO"; Response quoteResponse = ClientBuilder.newClient().target(url).request(MediaType.APPLICATION_JSON).get(); String jsonString = quoteResponse.readEntity(String.class); jsonString = jsonString.substring(4); //out.println(jsonString + "<br />"); JsonParser parser = Json.createParser(new StringReader(jsonString)); while(parser.hasNext()) { JsonParser.Event event = parser.next(); if(event.equals(JsonParser.Event.KEY_NAME)){ out.println(parser.getString()+ ": "); } else if (event.equals(JsonParser.Event.VALUE_STRING)){ out.println(parser.getString()+ "<br />"); } } } catch ( Exception e ){ out.println("<h2>Couldn't get Quote</h2>"); } out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ewoud */ @WebServlet(name = "DeleteItemServlet", urlPatterns = {"/DeleteItemServlet"}) public class DeleteItemServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>DeleteItemServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<p><a href=\"http://localhost:8080/Client-war\">Go back</a></p>"); out.println("<h1>DeleteItemServlet</h1>"); try{ DeleteItemClient client = new DeleteItemClient(); client.deleteItem(request.getParameter("id")); out.println("<h2>Deleting item succes if the item exsits!</h2>"); } catch (Exception e) { out.println("<h2>Deleting item failed!</h2>"); } out.println("<hr />"); try{ DeleteItemClient client = new DeleteItemClient(); out.println("<h2>"+client.getText()+"</h2>"); } catch (Exception e) { out.println("<h2>Failed to get some text!</h2>"); } out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import javax.ejb.Local; /** * * @author Anneleen */ @Local public interface StatelessBeanLocal { String queryString(String query); void initialize(); void destroy(); String getDate(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Stateless; /** * * @author Anneleen */ @Stateless public class StatelessBean implements StatelessBeanLocal { @Override public String queryString(String query) { return "The following query was executed: " + query + " at " + getDate(); } @PostConstruct @Override public void initialize() { System.out.println("Stateless bean is created: " + getDate()); } @PreDestroy @Override public void destroy() { System.out.println("Stateless bean is destroyed: " + getDate()); } @Override public String getDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import javax.ejb.Local; import javax.servlet.http.HttpSession; /** * * @author Anneleen */ @Local public interface pageCountLocal { void increment(); void reset(); int getCount(); void destroySession(); public void setSession(HttpSession session); void initialize(); String getDate(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.jms.JMSDestinationDefinition; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * * @author Anneleen */ @JMSDestinationDefinition(name = "jms/Bakkerij", interfaceName = "javax.jms.Queue", resourceAdapter = "jmsra", destinationName = "Bakkerij") @MessageDriven(mappedName = "jms/Bakkerij", activationConfig = { // @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/Bakkerij"), @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") }) public class MessageBean implements MessageListener { @Resource private MessageDrivenContext mdc; public MessageBean() { } @Override public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " + msg.getText()); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.getMessage(); mdc.setRollbackOnly(); } catch (Throwable te) { te.getMessage(); } } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Stateful; import javax.interceptor.Interceptors; import javax.servlet.http.HttpSession; /** * * @author Anneleen */ @Stateful public class pageCount implements pageCountLocal { private int count; private HttpSession session; @Override @Interceptors(InterceptorLogger.class) public void increment() { count++; } @Override public int getCount() { return count; } @Override public void reset() { count = 0; } @Override @PreDestroy public void destroySession() { System.out.println("Stateful bean is destroyed: " + getDate()); session.invalidate(); } @Override public void setSession(HttpSession session) { this.session = session; } @PostConstruct @Override public void initialize() { System.out.println("Stateful bean is created: " + getDate()); } @Override public String getDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; /** * * @author Anneleen */ public class InterceptorLogger { @AroundInvoke public Object incrementCounterLog (InvocationContext context) throws Exception { System.out.println("Message from interceptor: Counter is incremented \n"); Object result = context.proceed(); return result; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.ejb.LocalBean; /** * * @author Anneleen */ @Singleton @LocalBean public class TimerBean { private static final Logger logger = Logger.getLogger("beans.TimerBean"); @PostConstruct @Schedule(dayOfWeek = "Mon-Fri", month = "*", hour = "*", dayOfMonth = "*", year = "*", minute = "*", second = "*/30", persistent = false) public void myTimer() { Date date = new Date(); logger.log(Level.INFO, "---> Timer event: " + date.toString()); } // Add business logic below. (Right-click in editor and choose // "Insert Code > Add Business Method") }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.ejb.Local; /** * * @author Ewoud */ @Local public interface PurchaseOrderItemFacadeLocal { void create(PurchaseOrderItem purchaseOrderItem); void edit(PurchaseOrderItem purchaseOrderItem); void remove(PurchaseOrderItem purchaseOrderItem); PurchaseOrderItem find(Object id); List<PurchaseOrderItem> findAll(); List<PurchaseOrderItem> findRange(int[] range); int count(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.ejb.Local; /** * * @author Ewoud */ @Local public interface PurchaseOrderFacadeLocal { void create(PurchaseOrder purchaseOrder); void edit(PurchaseOrder purchaseOrder); void remove(PurchaseOrder purchaseOrder); PurchaseOrder find(Object id); List<PurchaseOrder> findAll(); List<PurchaseOrder> findRange(int[] range); int count(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.ejb.Local; /** * * @author Ewoud */ @Local public interface ItemFacadeLocal { void create(Item item); void edit(Item item); void remove(Item item); Item find(Object id); List<Item> findAll(); List<Item> findRange(int[] range); int count(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; /** * * @author Ewoud */ public enum ItemType { BREAD, PASTRY, PIE, CAKE, PREPARED_SANDWICHE }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.ejb.Local; /** * * @author Ewoud */ @Local public interface CustomerFacadeLocal { void create(Customer customer); void edit(Customer customer); void remove(Customer customer); Customer find(Object id); List<Customer> findAll(); List<Customer> findRange(int[] range); int count(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.ejb.Local; /** * * @author Ewoud */ @Local public interface BakeryFacadeLocal { void create(Bakery bakery); void edit(Bakery bakery); void remove(Bakery bakery); Bakery find(Object id); List<Bakery> findAll(); List<Bakery> findRange(int[] range); int count(); }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Ewoud */ @Stateless public class PurchaseOrderFacade extends AbstractFacade<PurchaseOrder> implements PurchaseOrderFacadeLocal { @PersistenceContext(unitName = "BakkerijX_v2-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public PurchaseOrderFacade() { super(PurchaseOrder.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Ewoud */ @Stateless public class CustomerFacade extends AbstractFacade<Customer> implements CustomerFacadeLocal { @PersistenceContext(unitName = "BakkerijX_v2-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public CustomerFacade() { super(Customer.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; /** * * @author Ewoud */ @Entity @Table(name = "customer") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @OneToMany(mappedBy = "customer") private List<PurchaseOrder> purchase_orders; @Size(max = 64) @Column(name = "name", length = 64) private String name; @Size(max = 128) @Column(name = "address", length = 128) private String address; @ManyToMany @JoinTable(name = "customer_bakery", joinColumns = @JoinColumn(name = "customer_fk"), inverseJoinColumns = @JoinColumn(name = "bakery_fk")) private List<Bakery> customerOfBakeries; //getter and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<PurchaseOrder> getPurchase_orders() { return purchase_orders; } public void setPurchase_orders(List<PurchaseOrder> purchase_orders) { this.purchase_orders = purchase_orders; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<Bakery> getCustomerOfBakeries() { return customerOfBakeries; } public void setCustomerOfBakeries(List<Bakery> customerOfBakeries) { this.customerOfBakeries = customerOfBakeries; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Customer)) { return false; } Customer other = (Customer) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "database.Customer[ id=" + id + " ]"; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.Size; /** * * @author Ewoud */ @Entity @Table(name = "bakery") public class Bakery implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @Size(max = 64) @Column(name = "name", length = 64) private String name; @Size(max = 128) @Column(name = "address", length = 128) private String address; @ManyToMany(mappedBy = "customerOfBakeries") private List<Customer> customers; //getter and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customers) { this.customers = customers; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Bakery)) { return false; } Bakery other = (Bakery) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "database.Bakery[ id=" + id + " ]"; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Size; /** * * @author Ewoud */ @Entity @Table(name = "item") public class Item implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @Size(max = 64) @Column(name = "name", length = 64) private String name; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "price") private float price; @Size(max = 128) @Column(name = "description", length = 128) private String description; @Enumerated(EnumType.STRING) //Represent Enum as a string in DB @Column(name = "type") private ItemType type; @OneToMany(mappedBy = "item") private List<PurchaseOrderItem> orderdByCustomers; //getter and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ItemType getType() { return type; } public void setType(ItemType type) { this.type = type; } public List<PurchaseOrderItem> getOrderdByCustomers() { return orderdByCustomers; } public void setOrderdByCustomers(List<PurchaseOrderItem> orderdByCustomers) { this.orderdByCustomers = orderdByCustomers; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Item)) { return false; } Item other = (Item) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "database.Item[ id=" + id + " ]"; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Ewoud */ @Stateless public class ItemFacade extends AbstractFacade<Item> implements ItemFacadeLocal { @PersistenceContext(unitName = "BakkerijX_v2-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public ItemFacade() { super(Item.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Ewoud */ @Stateless public class PurchaseOrderItemFacade extends AbstractFacade<PurchaseOrderItem> implements PurchaseOrderItemFacadeLocal { @PersistenceContext(unitName = "BakkerijX_v2-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public PurchaseOrderItemFacade() { super(PurchaseOrderItem.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.util.List; import javax.persistence.EntityManager; /** * * @author Anneleen */ public abstract class AbstractFacade<T> { private Class<T> entityClass; public AbstractFacade(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); public void create(T entity) { getEntityManager().persist(entity); } public void edit(T entity) { getEntityManager().merge(entity); } public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } public T find(Object id) { return getEntityManager().find(entityClass, id); } public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0] + 1); q.setFirstResult(range[0]); return q.getResultList(); } public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * * @author Ewoud */ @Entity @Table(name = "purchase_order") public class PurchaseOrder implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; @Column(name = "delivery_date") @Temporal(TemporalType.DATE) private Date delivery_date; @OneToMany(mappedBy = "purchaseOrder") private List<PurchaseOrderItem> itemsOrdered; //getter and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Date getDelivery_date() { return delivery_date; } public void setDelivery_date(Date delivery_date) { this.delivery_date = delivery_date; } public List<PurchaseOrderItem> getItemsOrdered() { return itemsOrdered; } public void setItemsOrdered(List<PurchaseOrderItem> itemsOrdered) { this.itemsOrdered = itemsOrdered; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PurchaseOrder)) { return false; } PurchaseOrder other = (PurchaseOrder) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "database.PurchaseOrder[ id=" + id + " ]"; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Ewoud */ @Stateless public class BakeryFacade extends AbstractFacade<Bakery> implements BakeryFacadeLocal { @PersistenceContext(unitName = "BakkerijX_v2-ejbPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public BakeryFacade() { super(Bakery.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package database; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * * @author Ewoud */ @Entity @Table(name = "purchase_order_item") public class PurchaseOrderItem implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @Column(name = "amount") private Long amount; @ManyToOne @JoinColumn(name = "item_id") private Item item; @ManyToOne @JoinColumn(name = "purchase_order_id") private PurchaseOrder purchaseOrder; //getter and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public PurchaseOrder getPurchaseOrder() { return purchaseOrder; } public void setPurchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PurchaseOrderItem)) { return false; } PurchaseOrderItem other = (PurchaseOrderItem) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "database.PurchaseOrderItem[ id=" + id + " ]"; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package webservice; import database.Item; import database.ItemFacadeLocal; import database.ItemType; import java.util.List; import javax.ejb.EJB; import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * * @author Ewoud */ @WebService(serviceName = "ItemWebService") public class ItemWebService { @EJB private ItemFacadeLocal itemFacade; /** * Web service operation */ @WebMethod(operationName = "create_bread") @Oneway public void create_bread(@WebParam(name = "name") String name, @WebParam(name = "description") String description, @WebParam(name = "price") float price) { Item newItem = new Item(); newItem.setName(name); newItem.setPrice(price); newItem.setDescription(description); newItem.setType(ItemType.BREAD); itemFacade.create(newItem); } /** * Web service operation */ @WebMethod(operationName = "create_pie") @Oneway public void create_pie(@WebParam(name = "name") String name, @WebParam(name = "description") String description, @WebParam(name = "price") float price) { Item newItem = new Item(); newItem.setName(name); newItem.setPrice(price); newItem.setDescription(description); newItem.setType(ItemType.PIE); itemFacade.create(newItem); } /** * Web service operation */ @WebMethod(operationName = "get_items") public String get_items() { String result = ""; List<Item> items = itemFacade.findAll(); for(Item currentItem : items){ result += ( currentItem.getId() +" | "+currentItem.getName() +" | €"+currentItem.getPrice() +" | "+currentItem.getDescription()+" | " +currentItem.getType()+"\n" ); } //TODO write your implementation code here: return result; } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package webservice; import database.Item; import database.ItemFacadeLocal; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; /** * REST Web Service * * @author Ewoud */ @Path("restful/item") public class RESTfulResource { ItemFacadeLocal itemFacade = lookupItemFacadeLocal(); @Context private UriInfo context; /** * Creates a new instance of RESTfulResource */ public RESTfulResource() { } /** * Retrieves representation of an instance of webservice.RESTfulResource * @return an instance of java.lang.String */ @GET @Produces("text/plain") public String getText() { //TODO return proper representation object return "Some text that is send using RESTful"; } /** * PUT method for updating or creating an instance of RESTfulResource * @param content representation for the resource * @return an HTTP response with content of the updated or created resource. */ @PUT @Consumes("text/plain") public void putText(String content) { } /** * HTTP DELETE requests. */ @DELETE @Path("{id}") public void deleteItem(@PathParam("id") String itemId) { Item deletingItem = itemFacade.find(Long.parseLong(itemId)); if(deletingItem != null){ itemFacade.remove(deletingItem); } } private ItemFacadeLocal lookupItemFacadeLocal() { try { javax.naming.Context c = new InitialContext(); return (ItemFacadeLocal) c.lookup("java:global/BakkerijX_v2/BakkerijX_v2-ejb/ItemFacade!database.ItemFacadeLocal"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package webservice; import java.util.Set; import javax.ws.rs.core.Application; /** * * @author Ewoud */ @javax.ws.rs.ApplicationPath("webresources") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); addRestResourceClasses(resources); return resources; } /** * Do not modify addRestResourceClasses() method. * It is automatically populated with * all resources defined in the project. * If required, comment out calling this method in getClasses(). */ private void addRestResourceClasses(Set<Class<?>> resources) { resources.add(webservice.RESTfulResource.class); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package beans; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Singleton; import javax.ejb.LocalBean; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * * @author Anneleen */ @Singleton @LocalBean @WebListener public class SessionBean implements HttpSessionListener{ private static int counter = 0; @Override public void sessionCreated(HttpSessionEvent se) { counter++; } @Override public void sessionDestroyed(HttpSessionEvent se) { counter--; } public int getActiveSessionsCount() { return counter; } @PostConstruct public void initialize() { System.out.println("Singleton bean is created: " + getDate()); } @PreDestroy public void destroy() { System.out.println("Singleton bean is destroyed: " + getDate()); } public String getDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import database.Item; import database.ItemFacadeLocal; import database.ItemType; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ewoud */ @WebServlet(name = "NewItemServlet", urlPatterns = {"/NewItemServlet"}) public class NewItemServlet extends HttpServlet { @EJB private ItemFacadeLocal itemFacade; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ //get parameters String name = request.getParameter("name"); float price = Float.parseFloat(request.getParameter("price")); String description = request.getParameter("description"); String typeString = request.getParameter("type"); ItemType type; switch(typeString){ case "BREAD": type = ItemType.BREAD; break; case "PASTRY": type = ItemType.PASTRY; break; case "PIE": type = ItemType.PIE; break; case "CAKE": type = ItemType.CAKE; break; case "PREPARED_SANDWICHE": type = ItemType.PREPARED_SANDWICHE; break; default: //this case should not happen but anyhow type = ItemType.BREAD; } //show page out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet newItemServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Adding new item to database...</h1>"); out.println("<hr />"); out.println(name+"<br />"); out.println(price+"<br />"); out.println(description+"<br />"); out.println(typeString); out.println("<hr />"); //save in DB Item newItem = new Item(); newItem.setName(name); newItem.setPrice(price); newItem.setDescription(description); newItem.setType(type); itemFacade.create(newItem); out.println("<h1>Succes!</h1>"); out.println("<hr />"); List<Item> items = itemFacade.findAll(); for(Item currentItem : items){ out.println( currentItem.getName()+" "+currentItem.getPrice() +" "+currentItem.getDescription()+" " +currentItem.getType()+"<br />" ); } out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import beans.StatelessBeanLocal; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Anneleen */ @WebServlet(name = "StatelessServlet", urlPatterns = {"/StatelessServlet"}) public class StatelessServlet extends HttpServlet { @EJB private StatelessBeanLocal statelessBean; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String query = request.getParameter("query"); String statelessMessage = statelessBean.queryString(query); request.setAttribute("statelessMessage", statelessMessage); RequestDispatcher rd = request.getRequestDispatcher("testStateless.jsp"); rd.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import beans.pageCountLocal; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Anneleen */ @WebServlet(name = "HomeServlet", urlPatterns = {"/HomeServlet"}) public class HomeServlet extends HttpServlet { pageCountLocal pageCount; public HomeServlet() { pageCount = lookuppageCountLocal(); } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session == null) { // Not created yet. Now do so yourself. pageCount.reset(); pageCount.setSession(session); request.setAttribute("counter", pageCount.getCount()); } else { // Already created. pageCount.increment(); request.setAttribute("counter", pageCount.getCount()); } response.setContentType("text/html;charset=UTF-8"); String user = request.getParameter("name"); RequestDispatcher rd = request.getRequestDispatcher("index.jsp"); request.setAttribute("user", user); rd.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> private pageCountLocal lookuppageCountLocal() { try { Context c = new InitialContext(); return (pageCountLocal) c.lookup("java:global/BakkerijX_v2/BakkerijX_v2-ejb/pageCount"); } catch (NamingException ne) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne); throw new RuntimeException(ne); } } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import beans.SessionBean; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Anneleen */ @WebServlet(name = "SessionServlet", urlPatterns = {"/SessionServlet"}) public class SessionServlet extends HttpServlet { @EJB private SessionBean sessionBean; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ request.getSession(true); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SessionServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("Number of users online: " + sessionBean.getActiveSessionsCount()); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package server; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.inject.Inject; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSConnectionFactory; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.JMSProducer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ewoud */ @WebServlet(name = "MessageServlet", urlPatterns = {"/MessageServlet"}) public class MessageServlet extends HttpServlet { @Resource(mappedName="jms/BakkerijConnectionFactory") private ConnectionFactory connectionFactory; @Resource(mappedName="jms/Bakkerij") private Queue queue; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * @throws javax.jms.JMSException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JMSException { response.setContentType("text/html;charset=UTF-8"); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(queue); int numberOfMessages = Integer.parseInt(request.getParameter("numberOfMessages")); TextMessage message = session.createTextMessage(); for (int i = 0; i < numberOfMessages; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); messageProducer.send(message); } String notify = "Your messages have been sent!"; RequestDispatcher rd = request.getRequestDispatcher("index.jsp"); request.setAttribute("message", notify); request.setAttribute("user", request.getParameter("user")); rd.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (JMSException ex) { Logger.getLogger(MessageServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (JMSException ex) { Logger.getLogger(MessageServlet.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
package data; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import org.encog.ml.data.MLData; import org.encog.ml.data.MLDataPair; import org.encog.ml.data.MLDataSet; import org.encog.ml.data.basic.BasicMLData; import org.encog.neural.data.NeuralData; import org.encog.neural.data.basic.BasicNeuralDataPair; import weka.core.Instance; import weka.core.Instances; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author root */ public class WekaNeuralDataSet extends Instances implements MLDataSet{ public WekaNeuralDataSet(Instances dataset) { super(dataset); } public WekaNeuralDataSet(Reader reader) throws IOException { super(reader); } public int getIdealSize() { if(super.classAttribute()!=null){ return 1; } return 0; } public int getInputSize() { if(super.classAttribute()!=null){ return super.numAttributes()-1; } return super.numAttributes(); } public boolean isSupervised() { return super.classAttribute()!=null; } public long getRecordCount() { long l= super.numInstances(); return l; } public void getRecord(long l, MLDataPair mldp) { int classIndex=super.classIndex(); Instance instance=super.instance((int) l); double[] values=instance.toDoubleArray(); double[] input=mldp.getInputArray(); double[] ideal=mldp.getIdealArray(); int i=0; for(int j=0;i<input.length;j++){ if(j!=classIndex){ input[i]=values[j]; i++; } } ideal[0]=values[classIndex]; } public MLDataSet openAdditional() { return new WekaNeuralDataSet(this); } public void add(MLData mldata) { double[] data=mldata.getData(); Instance inst=new Instance(data.length); for(int i=0;i<data.length;i++){ inst.setValue(i, data[i]); } super.add(inst); } public void add(MLData mldata, MLData mldata1) { this.add(mldata); Instance inst=super.lastInstance(); inst.setClassValue(mldata1.getData(0)); } public void add(MLDataPair mldp) { this.add(mldp.getInput() , mldp.getIdeal()); } public void close() { } public Iterator<MLDataPair> iterator() { throw new UnsupportedOperationException("Not supported yet."); } private class WekaIterator implements Iterator<MLDataPair>{ private int last; private int current; private BasicNeuralDataPair buffer; public WekaIterator(){ last=numInstances(); current=0; //buffer=new BasicNeuralDataPair(new BasicMLData(numAttributes()-1), new BasicMLData(1)); buffer=new BasicNeuralDataPair((NeuralData) new BasicMLData(numAttributes()-1), (NeuralData) new BasicMLData(1)); } public boolean hasNext() { return current<last-1; } public MLDataPair next() { getRecord(current, buffer); current++; return new BasicNeuralDataPair((NeuralData)new BasicMLData(buffer.getInputArray()), (NeuralData)new BasicMLData(buffer.getIdealArray())); } public void remove() { throw new UnsupportedOperationException("Not supported yet."); } } }
Java
package data; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import org.encog.ml.MLProperties; import org.encog.ml.data.MLData; import org.encog.ml.data.MLDataPair; import org.encog.neural.data.NeuralDataPair; import org.encog.neural.data.basic.BasicNeuralData; import weka.core.Instance; /** * * @author root */ public class WekaNeuralDataPair extends Instance implements MLDataPair{ public WekaNeuralDataPair(int numAttributes) { super(numAttributes); } public WekaNeuralDataPair(double weight, double[] attValues) { super(weight,attValues); } public WekaNeuralDataPair(Instance instance) { super(instance); } public double[] getIdealArray() { return this.getIdeal().getData(); } public double[] getInputArray() { return this.getInput().getData(); } public void setIdealArray(double[] doubles) { super.setClassValue(doubles[0]); } public void setInputArray(double[] doubles) { int size=doubles.length; int i=0; int classIndex=super.classIndex(); for(int j=0;i<size;j++){ if(j!=classIndex){ super.setValue(i, doubles[j]); i++; } } } public boolean isSupervised() { return !super.classIsMissing(); } public MLData getIdeal() { double[] value=new double[1]; value[0]=super.classValue(); return new BasicNeuralData(value); } public MLData getInput() { int size=super.numAttributes()-1; double[] values=new double[size]; int i=0; int classIndex=super.classIndex(); for(int j=0;i<size;j++){ if(j!=classIndex){ values[i]=super.value(j); i++; } } return new BasicNeuralData(values); } public double getSignificance() { return super.weight(); } public void setSignificance(double d) { super.setWeight(d); } }
Java
package data; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import org.encog.ml.data.MLData; import org.encog.neural.data.NeuralData; import weka.core.Attribute; import weka.core.Instance; /** * * @author root */ public class WekaNeuralData extends Instance implements MLData{ public WekaNeuralData(int numAttributes) { super(numAttributes); } public WekaNeuralData(Instance instance) { super(instance); } public void add(int i, double d) { super.insertAttributeAt(i); super.setValue(i, d); } public void clear() { int values=super.numAttributes(); for(int i=0;i<values;i++){ super.setValue(i, 0); } } public NeuralData clone() { return null; } public double[] getData() { return super.toDoubleArray(); } public double getData(int i) { return super.value(i); } public void setData(double[] doubles) { for(int i=0;i<super.numAttributes();i++){ setData(i,doubles[i]); } } public void setData(int i, double d) { super.setValue(i, d); } public int size() { return super.numAttributes(); } }
Java
import classifier.WekaClassifier; import data.WekaNeuralDataSet; import java.io.File; import java.io.FileReader; import java.io.Reader; import org.encog.ConsoleStatusReportable; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.pattern.FeedForwardPattern; import org.encog.neural.prune.PruneIncremental; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author root */ public class Test1 { public static void main(String[] args)throws Exception{ WekaNeuralDataSet set=new WekaNeuralDataSet(new FileReader(new File("rilevamenti.arff"))); set.setClassIndex(set.numAttributes()-1); FeedForwardPattern net=new FeedForwardPattern(); net.setInputNeurons(4); net.setOutputNeurons(1); ConsoleStatusReportable report=new ConsoleStatusReportable(); PruneIncremental prune=new PruneIncremental(set, net, 45, 1, 2, report); prune.addHiddenLayer(1, 6); prune.addHiddenLayer(0, 6); prune.addHiddenLayer(0, 6); prune.init(); prune.process(); System.out.print("finish"); System.exit(0); } }
Java
package classifier; import data.WekaNeuralData; import data.WekaNeuralDataSet; import org.encog.ml.data.MLData; import org.encog.ml.train.MLTrain; import org.encog.neural.networks.BasicNetwork; import weka.classifiers.Classifier; import weka.core.Instance; import weka.core.Instances; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author root */ public class WekaClassifier extends Classifier{ private MLTrain training; private BasicNetwork network; public WekaClassifier(){ } public BasicNetwork getNetwork() { return network; } public void setNetwork(BasicNetwork network) { this.network = network; } public MLTrain getTraining() { return training; } public void setTraining(MLTrain training) { this.training = training; } @Override public void buildClassifier(Instances i) throws Exception { WekaNeuralDataSet set=new WekaNeuralDataSet(i); while(this.training.canContinue()){ this.training.iteration(); } } @Override public double classifyInstance(Instance instance) throws Exception { WekaNeuralData data=new WekaNeuralData(instance); MLData result=this.network.compute(data); return result.getData(0); } }
Java
package com.climoilou.modele; public class Livre { private String auteur; private String titre; private int anneePublication; public Livre(String pStrAuteur, String pStrTitre, int pIntAnneePublication) { this.auteur = pStrAuteur; this.titre = pStrTitre; this.anneePublication = pIntAnneePublication; } public String getAuteur() { return auteur; } public void setAuteur(String auteur) { this.auteur = auteur; } public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } public int getAnneePublication() { return anneePublication; } public void setAnneePublication(int anneePublication) { this.anneePublication = anneePublication; } }
Java
package com.anli.sqlexecution.exceptions; public class DatabaseException extends RuntimeException { public DatabaseException(Throwable cause) { super(cause); } public DatabaseException(String message) { super(message); } public DatabaseException(String message, Throwable cause) { super(message, cause); } }
Java
package com.anli.sqlexecution.handling; import com.anli.sqlexecution.transformation.SqlTransformer; import com.anli.sqlexecution.transformation.TransformerFactory; import java.sql.ResultSet; import java.sql.SQLException; public class TransformingResultSet { protected ResultSet resultSet; protected TransformerFactory transformerFactory; public TransformingResultSet(ResultSet resultSet, TransformerFactory transformerFactory) { this.resultSet = resultSet; this.transformerFactory = transformerFactory; } public boolean next() throws SQLException { return resultSet.next(); } public boolean previous() throws SQLException { return resultSet.previous(); } public <T> T getValue(int columnIndex, Class<T> javaClass) throws SQLException { SqlTransformer transformer = transformerFactory != null ? transformerFactory.getTransformer(javaClass) : null; Class<?> sqlClass = transformer != null ? transformer.getSqlClass() : javaClass; Object sqlValue = resultSet.getObject(columnIndex, sqlClass); if (resultSet.wasNull()) { sqlValue = null; } return (T) (transformer != null ? transformer.toJava(sqlValue) : sqlValue); } public <T> T getValue(String columnLabel, Class<T> javaClass) throws SQLException { SqlTransformer transformer = transformerFactory != null ? transformerFactory.getTransformer(javaClass) : null; Class<?> sqlClass = transformer != null ? transformer.getSqlClass() : javaClass; Object sqlValue = resultSet.getObject(columnLabel, sqlClass); if (resultSet.wasNull()) { return null; } return (T) (transformer != null ? transformer.toJava(sqlValue) : sqlValue); } }
Java
package com.anli.sqlexecution.handling; import java.sql.SQLException; public interface ResultSetHandler<T> { T handle(TransformingResultSet resultSet) throws SQLException; }
Java
package com.anli.sqlexecution.execution; import com.anli.sqlexecution.handling.ResultSetHandler; import com.anli.sqlexecution.exceptions.DatabaseException; import com.anli.sqlexecution.handling.TransformingResultSet; import com.anli.sqlexecution.transformation.SqlTransformer; import com.anli.sqlexecution.transformation.TransformerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SqlExecutor { private static final Logger LOG = LoggerFactory.getLogger(SqlExecutor.class); protected final DataSource source; protected final TransformerFactory transformerFactory; public SqlExecutor(DataSource source, TransformerFactory transformerFactory) { this.source = source; this.transformerFactory = transformerFactory; } public <T> T executeSelect(String query, List parameters, ResultSetHandler<T> resultSetHandler) { try { T result; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { setParameters(statement, parameters); try (ResultSet resultSet = statement.executeQuery()) { result = resultSetHandler.handle(wrapResultSet(resultSet)); } } return result; } catch (SQLException sqlException) { LOG.error("Sql exception for query " + query + "and parameters " + parameters, sqlException); throw new DatabaseException(sqlException); } } public int executeUpdate(String query, List parameters) { try { int result; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { setParameters(statement, parameters); result = statement.executeUpdate(); } return result; } catch (SQLException sqlException) { LOG.error("Sql exception for query " + query + "and parameters " + parameters, sqlException); throw new DatabaseException(sqlException); } } protected Connection getConnection() throws SQLException { return source.getConnection(); } protected TransformingResultSet wrapResultSet(ResultSet resultSet) { return new TransformingResultSet(resultSet, transformerFactory); } protected void setParameters(PreparedStatement statement, List parameters) throws SQLException { if (parameters == null) { return; } int index = 1; for (Object parameter : parameters) { statement.setObject(index, transformValue(parameter)); index++; } } protected Object transformValue(Object javaValue) { if (javaValue == null) { return null; } SqlTransformer transformer = transformerFactory != null ? transformerFactory.getTransformer(javaValue.getClass()) : null; return transformer != null ? transformer.toSql(javaValue) : javaValue; } }
Java
package com.anli.sqlexecution.transformation; import java.util.HashMap; import java.util.Map; public class MapBasedTransformerFactory implements TransformerFactory { protected final Map<Class, SqlTransformer> transformerMap; public MapBasedTransformerFactory(Map<Class, SqlTransformer> map) { this.transformerMap = map; } public MapBasedTransformerFactory() { this.transformerMap = new HashMap<>(); } public void add(Class<?> javaClass, SqlTransformer<?, ?> transformer) { transformerMap.put(javaClass, transformer); } @Override public <J> SqlTransformer<J, ?> getTransformer(Class<? extends J> javaClass) { return transformerMap.get(javaClass); } }
Java
package com.anli.sqlexecution.transformation; public interface TransformerFactory { <J> SqlTransformer<J, ?> getTransformer(Class<? extends J> javaClass); }
Java
package com.anli.sqlexecution.transformation; public interface SqlTransformer<J, S> { S toSql(J source); J toJava(S source); Class<? extends J> getJavaClass(); Class<? extends S> getSqlClass(); }
Java
package com.anli.integrationtesting.servlets; import com.anli.integrationtesting.execution.TestExecutor; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TestExecutionServlet extends HttpServlet { protected static final int HTTP_OK = 200; protected static final int HTTP_CONFLICT = 409; protected static final String CLASS_PARAM = "class"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String executorClassName = request.getParameter(CLASS_PARAM); try { TestExecutor executor = getExecutor(executorClassName); executor.test(); response.setStatus(HTTP_OK); out.print("Test success!"); } catch (Exception | Error thr) { response.setStatus(HTTP_CONFLICT); thr.printStackTrace(out); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected TestExecutor getExecutor(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return (TestExecutor) Class.forName(className).newInstance(); } }
Java
package com.anli.integrationtesting.execution; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MultithreadScheduler { protected final ExecutorService executorService; public MultithreadScheduler(ExecutorService service) { executorService = service; } public MultithreadScheduler(int threadCount) { executorService = Executors.newFixedThreadPool(threadCount); } public MultithreadScheduler() { executorService = Executors.newCachedThreadPool(); } public List executeParallel(List<Callable<Object>> callables) { try { List<Future<Object>> futures = executorService.invokeAll(callables); List results = new ArrayList(futures.size()); for (Future future : futures) { results.add(future.get()); } return results; } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } } }
Java
package com.anli.integrationtesting.execution; public interface TestExecutor { void test() throws Exception; }
Java
package com.anli.integrationtesting; public class Test { protected String name; protected String className; public Test(String name, String className) { this.name = name; this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String toJson() { StringBuilder json = new StringBuilder(); json.append("{"); json.append("name : '").append(name).append("'"); json.append(", "); json.append("className : '").append(className).append("'"); json.append("}"); return json.toString(); } }
Java
package com.anli.configuration; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Configurator { private static final Logger LOG = LoggerFactory.getLogger(Configurator.class); private static final String GLASSFISH_INSTANCE_ROOT_PROPERTY = "com.sun.aas.instanceRoot"; private static final String GLASSFISH_CONFIG_FOLDER = "config"; private static final String GLASSFISH_TRANSACTION_MANAGER_JNDI_NAME = "java:appserver/TransactionManager"; private static final String CDI_BEAN_MANAGER_JNDI_NAME = "java:comp/BeanManager"; private static final String MAIN_CFG_FILE = "main.cfg"; private static volatile Map<String, ConfigSnapshot> snapshots = null; private static synchronized void loadConfiguration() { if (snapshots != null) { return; } Map<String, ConfigSnapshot> formedSnapshots = new HashMap<>(); String rootDirectoryPath = getRootDirectory(); LOG.info("Root directory path: {}", rootDirectoryPath); File rootDirectory = new File(rootDirectoryPath); Map<String, String> snapshotPaths = readProperties(rootDirectory, MAIN_CFG_FILE); for (Map.Entry<String, String> path : snapshotPaths.entrySet()) { Map<String, String> snapshotProperties = readProperties(rootDirectory, path.getValue()); String group = path.getKey(); ConfigSnapshot snapshot = new ConfigSnapshot(group, snapshotProperties); formedSnapshots.put(group, snapshot); } snapshots = formedSnapshots; } private static String getRootDirectory() { // TO DO: implement another app servers implementations LOG.info("Defining root directory for GlassFish Application Server..."); return System.getProperty(GLASSFISH_INSTANCE_ROOT_PROPERTY) + File.separator + GLASSFISH_CONFIG_FOLDER; } private static Map<String, String> readProperties(File rootDirectory, String filePath) { File propertyFile = new File(rootDirectory, filePath); Properties properties = new Properties(); try { properties.load(new FileInputStream(propertyFile)); } catch (IOException ioException) { LOG.error("Could not load config file " + propertyFile.getAbsolutePath(), ioException); } HashMap<String, String> propertyMap = new HashMap<>(); for (Map.Entry<Object, Object> property : properties.entrySet()) { propertyMap.put(property.getKey().toString(), property.getValue().toString()); } LOG.info("{} read contents: {}", propertyFile.getAbsolutePath(), propertyMap); return propertyMap; } public static ConfigSnapshot getConfig(String group) { if (snapshots == null) { loadConfiguration(); } return snapshots.get(group); } public static String getTransationManagerJndiName() { // TODO: implement another app servers implementations return GLASSFISH_TRANSACTION_MANAGER_JNDI_NAME; } public static String getCdiBeanManagerJndiName() { return CDI_BEAN_MANAGER_JNDI_NAME; } }
Java
package com.anli.configuration; import java.util.Map; public class ConfigSnapshot { protected String group; protected Map<String, String> properties; public ConfigSnapshot(String group, Map<String, String> properties) { this.properties = properties; } public String getProperty(String id) { return properties.get(id); } public String getGroup() { return group; } }
Java
package com.anli.busstation.dal.sql.test; import com.anli.configuration.Configurator; import com.anli.sqlexecution.execution.SqlExecutor; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DBHelper { private static final Logger LOG = LoggerFactory.getLogger(DBHelper.class); protected static final String DB_GROUP = "db"; protected static final String CONNECTION_POOL_PROPERTY = "connection_pool"; protected static DataSource source = getDataSource(); public static SqlExecutor getExecutor() { return new SqlExecutor(source, null); } protected static DataSource getDataSource() { String poolName = Configurator.getConfig(DB_GROUP).getProperty(CONNECTION_POOL_PROPERTY); try { InitialContext ic = new InitialContext(); return (DataSource) ic.lookup(poolName); } catch (NamingException nex) { LOG.error("Could not resolve datasource " + poolName, nex); throw new RuntimeException(nex); } } }
Java
package com.anli.busstation.dal.sql.test; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.staff.DriverSkill; import com.anli.busstation.dal.interfaces.entities.staff.Employee; import com.anli.busstation.dal.interfaces.entities.vehicles.GasLabel; import com.anli.busstation.dal.interfaces.entities.vehicles.Model; import com.anli.busstation.dal.interfaces.entities.geography.Region; import com.anli.busstation.dal.interfaces.entities.traffic.Ride; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.traffic.RideRoad; import com.anli.busstation.dal.interfaces.entities.geography.Road; import com.anli.busstation.dal.interfaces.entities.traffic.Route; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.interfaces.entities.geography.Station; import com.anli.busstation.dal.interfaces.entities.maintenance.TechnicalAssignment; import com.anli.busstation.dal.interfaces.entities.staff.MechanicSkill; import com.anli.busstation.dal.interfaces.entities.vehicles.TechnicalState; import com.anli.busstation.dal.interfaces.entities.traffic.Ticket; import com.anli.busstation.dal.test.FixtureCreator; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class SqlFixtureCreator extends FixtureCreator { private static final Logger LOG = LoggerFactory.getLogger(SqlFixtureCreator.class); protected abstract void setObjectId(BSEntity entity, BigInteger id); @Override protected void setIdManually(BSEntity entity, BigInteger id) { String table = getTable(entity); String idColumn = getIdColumn(entity); String updateQuery = "update " + table + " set " + idColumn + " = ? where " + idColumn + " = ?"; DBHelper.getExecutor().executeUpdate(updateQuery, Arrays.asList(new BigDecimal(id), new BigDecimal(entity.getId()))); setObjectId(entity, id); } protected String getTable(BSEntity entity) { if (entity instanceof Bus) { return "buses"; } if (entity instanceof Employee) { return "employees"; } if (entity instanceof DriverSkill) { return "driver_skills"; } if (entity instanceof GasLabel) { return "gas_labels"; } if (entity instanceof MechanicSkill) { return "mechanic_skills"; } if (entity instanceof Model) { return "models"; } if (entity instanceof Region) { return "regions"; } if (entity instanceof Ride) { return "rides"; } if (entity instanceof RidePoint) { return "ride_points"; } if (entity instanceof RideRoad) { return "ride_roads"; } if (entity instanceof Road) { return "roads"; } if (entity instanceof Route) { return "routes"; } if (entity instanceof RoutePoint) { return "route_points"; } if (entity instanceof Station) { return "stations"; } if (entity instanceof TechnicalAssignment) { return "technical_assignments"; } if (entity instanceof TechnicalState) { return "technical_states"; } if (entity instanceof Ticket) { return "tickets"; } LOG.error("Could not resolve entity table for {}", entity.getClass()); throw new RuntimeException(entity.getClass().getCanonicalName()); } protected String getIdColumn(BSEntity entity) { if (entity instanceof Bus) { return "bus_id"; } if (entity instanceof DriverSkill) { return "skill_id"; } if (entity instanceof Employee) { return "employee_id"; } if (entity instanceof GasLabel) { return "label_id"; } if (entity instanceof MechanicSkill) { return "skill_id"; } if (entity instanceof Model) { return "model_id"; } if (entity instanceof Region) { return "region_id"; } if (entity instanceof Ride) { return "ride_id"; } if (entity instanceof RidePoint) { return "ride_point_id"; } if (entity instanceof RideRoad) { return "ride_road_id"; } if (entity instanceof Road) { return "road_id"; } if (entity instanceof Route) { return "route_id"; } if (entity instanceof RoutePoint) { return "route_point_id"; } if (entity instanceof Station) { return "station_id"; } if (entity instanceof TechnicalAssignment) { return "assignment_id"; } if (entity instanceof TechnicalState) { return "state_id"; } if (entity instanceof Ticket) { return "ticket_id"; } LOG.error("Could not resolve id column for {}", entity.getClass()); throw new RuntimeException(entity.getClass().getCanonicalName()); } }
Java
package com.anli.busstation.dal.sql.test; import com.anli.sqlexecution.handling.ResultSetHandler; import com.anli.sqlexecution.handling.TransformingResultSet; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class IdSelector implements ResultSetHandler<List<BigInteger>> { @Override public List<BigInteger> handle(TransformingResultSet resultSet) throws SQLException { List<BigInteger> idList = new ArrayList<>(); while (resultSet.next()) { idList.add(resultSet.getValue(1, BigDecimal.class).toBigInteger()); } return idList; } }
Java
package com.anli.busstation.dal.ejb3.test; import com.anli.busstation.dal.test.servlet.AbstractTester; public class Ejb3Tester extends AbstractTester { @Override protected String getBasePackage() { return "com.anli.busstation.dal.ejb3.test"; } @Override protected String getExecutorUrl() { return "/executor"; } @Override protected String getTitle() { return "Bus Station Data Access Integration Tests (JpaEjb3 implementation)"; } }
Java
package com.anli.busstation.dal.ejb3.test; import com.anli.busstation.dal.ejb3.cache.CacheAccessor; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.factories.ProviderFactory; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.test.FixtureCreator; import com.anli.busstation.dal.test.ModuleAccessor; import java.math.BigInteger; import javax.naming.InitialContext; import javax.naming.NamingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Ejb3ModuleAccessor implements ModuleAccessor { private static final Logger LOG = LoggerFactory.getLogger(Ejb3ModuleAccessor.class); @Override public ProviderFactory getProviderFactory() { return new com.anli.busstation.dal.ejb3.factories.ProviderFactory(); } @Override public FixtureCreator getFixtureCreator() { return new Ejb3FixtureCreator(); } @Override public void resetCaches() { CacheAccessor accessor; try { accessor = (CacheAccessor) InitialContext .doLookup(CacheAccessor.class.getCanonicalName()); } catch (NamingException ex) { LOG.error("Could not resolve cache accessor", ex); throw new RuntimeException(ex); } accessor.resetCaches(); } @Override public void setEntityId(BSEntity entity, BigInteger id) { ((BSEntityImpl) entity).setId(id); } }
Java
package com.anli.busstation.dal.ejb3.test; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.factories.ProviderFactory; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.sql.test.SqlFixtureCreator; import java.math.BigInteger; public class Ejb3FixtureCreator extends SqlFixtureCreator { @Override protected void setObjectId(BSEntity entity, BigInteger id) { ((BSEntityImpl) entity).setId(id); } @Override protected ProviderFactory getFactory() { return new com.anli.busstation.dal.ejb3.factories.ProviderFactory(); } }
Java
package com.anli.busstation.dal.ejb2.test; import com.anli.busstation.dal.ejb2.entities.BSEntityImpl; import com.anli.busstation.dal.ejb2.factories.ProviderProxyFactory; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.factories.ProviderFactory; import com.anli.busstation.dal.test.FixtureCreator; import com.anli.busstation.dal.test.ModuleAccessor; import java.math.BigInteger; public class Ejb2ModuleAccessor implements ModuleAccessor { @Override public ProviderFactory getProviderFactory() { return new ProviderProxyFactory(); } @Override public FixtureCreator getFixtureCreator() { return new Ejb2FixtureCreator(); } @Override public void resetCaches() { } @Override public void setEntityId(BSEntity entity, BigInteger id) { ((BSEntityImpl) entity).setId(id); } }
Java
package com.anli.busstation.dal.ejb2.test; import com.anli.busstation.dal.ejb2.entities.BSEntityImpl; import com.anli.busstation.dal.ejb2.factories.ProviderProxyFactory; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.factories.ProviderFactory; import com.anli.busstation.dal.sql.test.SqlFixtureCreator; import java.math.BigInteger; public class Ejb2FixtureCreator extends SqlFixtureCreator { @Override protected void setObjectId(BSEntity entity, BigInteger id) { ((BSEntityImpl) entity).setId(id); } @Override protected ProviderFactory getFactory() { return new ProviderProxyFactory(); } }
Java
package com.anli.busstation.dal.ejb2.test; import com.anli.busstation.dal.test.servlet.AbstractTester; public class Ejb2Tester extends AbstractTester { @Override protected String getBasePackage() { return "com.anli.busstation.dal.ejb2.test"; } @Override protected String getExecutorUrl() { return "/executor"; } @Override protected String getTitle() { return "Bus Station Data Access Integration Tests (SqlEjb2 implementation)"; } }
Java
package com.anli.busstation.dal.jpa.extractors; import com.anli.busstation.dal.jpa.entities.maintenance.BusServiceImpl; import com.anli.busstation.dal.jpa.entities.maintenance.StationServiceImpl; public class TechnicalAssignmentExtractor extends BaseJoinExtractor { @Override protected Class[] getClasses() { return new Class[]{BusServiceImpl.class, StationServiceImpl.class}; } }
Java
package com.anli.busstation.dal.jpa.extractors; import com.anli.busstation.dal.jpa.entities.staff.DriverImpl; import com.anli.busstation.dal.jpa.entities.staff.MechanicImpl; import com.anli.busstation.dal.jpa.entities.staff.SalesmanImpl; public class EmployeeExtractor extends BaseJoinExtractor { @Override protected Class[] getClasses() { return new Class[]{MechanicImpl.class, DriverImpl.class, SalesmanImpl.class}; } }
Java
package com.anli.busstation.dal.jpa.extractors; import com.anli.busstation.dal.jpa.entities.maintenance.BusRefuellingImpl; import com.anli.busstation.dal.jpa.entities.maintenance.BusRepairmentImpl; public class BusServiceExtractor extends BaseJoinExtractor { @Override protected Class[] getClasses() { return new Class[]{BusRepairmentImpl.class, BusRefuellingImpl.class}; } }
Java
package com.anli.busstation.dal.jpa.extractors; import java.util.HashMap; import java.util.Map; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.eclipse.persistence.descriptors.ClassExtractor; import org.eclipse.persistence.sessions.Record; import org.eclipse.persistence.sessions.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class BaseJoinExtractor extends ClassExtractor { private static final Logger LOG = LoggerFactory.getLogger(BaseJoinExtractor.class); protected Map<Class, String> rowNames; protected Map<Class, BaseJoinExtractor> childrenExtractors; public BaseJoinExtractor() { rowNames = null; childrenExtractors = null; } @Override public Class extractClassFromRow(Record databaseRow, Session session) { for (Map.Entry<Class, String> rowName : getRowNames().entrySet()) { if (databaseRow.get(rowName.getValue()) != null) { Class clazz = rowName.getKey(); BaseJoinExtractor extractor = getExtractor(clazz); return extractor != null ? extractor.extractClassFromRow(databaseRow, session) : clazz; } } throw new RuntimeException("Could not determine entity type for record :" + databaseRow.toString()); } protected void addChildrenExtractor(Class clazz) { org.eclipse.persistence.annotations.ClassExtractor extractor = (org.eclipse.persistence.annotations.ClassExtractor) clazz .getAnnotation(org.eclipse.persistence.annotations.ClassExtractor.class); if (extractor == null) { return; } Class extractorClass = extractor.value(); if (!BaseJoinExtractor.class.isAssignableFrom(extractorClass)) { return; } BaseJoinExtractor extractorInstance; try { extractorInstance = (BaseJoinExtractor) extractorClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOG.error("Could not instantiate extractor " + extractorClass, ex); return; } if (childrenExtractors == null) { childrenExtractors = new HashMap<>(); } childrenExtractors.put(clazz, extractorInstance); } protected BaseJoinExtractor getExtractor(Class clazz) { if (childrenExtractors == null) { return null; } return childrenExtractors.get(clazz); } protected Map<Class, String> getRowNames() { if (rowNames == null) { rowNames = buildRowNames(); } return rowNames; } protected Map<Class, String> buildRowNames() { Class[] classes = getClasses(); Map<Class, String> names = new HashMap<>(); for (Class clazz : classes) { Table table = (Table) clazz.getAnnotation(Table.class); PrimaryKeyJoinColumn joinColumn = (PrimaryKeyJoinColumn) clazz.getAnnotation(PrimaryKeyJoinColumn.class); String rowName = table.name() + "." + joinColumn.name(); addChildrenExtractor(clazz); names.put(clazz, rowName); } return names; } protected abstract Class[] getClasses(); }
Java
package com.anli.busstation.dal.jpa.converters; import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class BooleanConverter implements AttributeConverter<Boolean, Integer> { @Override public Integer convertToDatabaseColumn(Boolean x) { return Boolean.TRUE.equals(x) ? 1 : 0; } @Override public Boolean convertToEntityAttribute(Integer y) { return y != null && !y.equals(0); } }
Java
package com.anli.busstation.dal.jpa.converters; import java.sql.Timestamp; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import org.joda.time.DateTime; @Converter public class DateTimeConverter implements AttributeConverter<DateTime, Timestamp> { @Override public Timestamp convertToDatabaseColumn(DateTime x) { return x != null ? new Timestamp(x.getMillis()) : null; } @Override public DateTime convertToEntityAttribute(Timestamp y) { return y != null ? new DateTime(y.getTime()) : null; } }
Java
package com.anli.busstation.dal.jpa.reflective; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import org.eclipse.persistence.indirection.IndirectCollection; @Singleton public class EntityCloner { private final DescriptorHolder descriptorHolder; @Inject public EntityCloner(DescriptorHolder relationHolder) { this.descriptorHolder = relationHolder; } public <E> E clone(E sourceEntity) { if (sourceEntity == null) { return null; } Class<E> entityClass = (Class<E>) sourceEntity.getClass(); E clonedEntity; try { clonedEntity = entityClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new RuntimeException(ex); } populateEntity(sourceEntity, clonedEntity); return clonedEntity; } public <E> List populateEntity(E sourceEntity, E targetEntity) { return populateEntity(sourceEntity, targetEntity, null); } public <E> List populateEntity(E sourceEntity, E targetEntity, EntityManager manager) { LinkedList inconsistent = new LinkedList<>(); EntityDescriptor entityDescriptor = descriptorHolder.getHolder(sourceEntity.getClass()); for (FieldDescriptor fieldDescriptor : entityDescriptor.getFields()) { try { inconsistent.addAll(populateField(fieldDescriptor, sourceEntity, targetEntity, manager)); } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } } return inconsistent; } protected List populateField(FieldDescriptor descriptor, Object sourceEntity, Object targetEntity, EntityManager manager) throws IllegalAccessException, InvocationTargetException { Method getter = descriptor.getGetter(); Method setter = descriptor.getSetter(); Object value = getter.invoke(sourceEntity); if (descriptor.isCollection()) { return populateCollection(getter, setter, targetEntity, (Collection) value, manager); } else if (descriptor.isReference()) { Object inconsistent = populateReference(setter, targetEntity, value, manager); return inconsistent == null ? Collections.emptyList() : Collections.singletonList(inconsistent); } else { populateFieldValue(setter, targetEntity, value); return Collections.emptyList(); } } protected void populateFieldValue(Method setter, Object targetEntity, Object value) throws IllegalAccessException, InvocationTargetException { setter.invoke(targetEntity, value); } protected Object populateReference(Method setter, Object targetEntity, Object value, EntityManager manager) throws IllegalAccessException, InvocationTargetException { Object actualValue; if (manager == null) { actualValue = clone(value); } else { actualValue = getReference(manager, value); if (actualValue == null && value != null) { return value; } } populateFieldValue(setter, targetEntity, actualValue); return null; } protected Object getReference(EntityManager manager, Object detachedEntity) throws IllegalAccessException, InvocationTargetException { if (detachedEntity == null) { return null; } Class entityClass = detachedEntity.getClass(); Method idGetter = descriptorHolder.getHolder(entityClass) .getIdField().getGetter(); return manager.find(entityClass, idGetter.invoke(detachedEntity)); } protected List populateCollection(Method getter, Method setter, Object targetEntity, Collection value, EntityManager manager) throws IllegalAccessException, InvocationTargetException { if (manager == null) { Collection clonedCollection = cloneCollection(value); populateFieldValue(setter, targetEntity, clonedCollection); return Collections.emptyList(); } else { return mergeCollection(getter, targetEntity, value, manager); } } protected List mergeCollection(Method getter, Object targetEntity, Collection value, EntityManager manager) throws IllegalAccessException, InvocationTargetException { if (value == null) { return Collections.emptyList(); } LinkedList inconsistent = new LinkedList(); Collection targetCollection = (Collection) getter.invoke(targetEntity); targetCollection.clear(); for (Object element : value) { Object reference = getReference(manager, element); if (reference == null && element != null) { inconsistent.add(element); } else { targetCollection.add(reference); } } return inconsistent; } public <C extends Collection> C cloneCollection(C sourceCollection) { return cloneCollection(sourceCollection, true); } public <C extends Collection> C cloneCollection(C sourceCollection, boolean nullLazy) { C clonedCollection = getCollectionInstance(sourceCollection, nullLazy); if (clonedCollection == null) { return null; } for (Object sourceElement : sourceCollection) { clonedCollection.add(clone(sourceElement)); } return clonedCollection; } protected <C extends Collection> C getCollectionInstance(C sourceCollection, boolean nullLazy) { if (sourceCollection == null) { return null; } if (sourceCollection instanceof IndirectCollection && nullLazy) { return null; } if (sourceCollection instanceof List) { return (C) new ArrayList<>(sourceCollection.size()); } if (sourceCollection instanceof Set) { return (C) new HashSet<>((int) (sourceCollection.size() / 0.75)); } throw new RuntimeException(); } }
Java
package com.anli.busstation.dal.jpa.reflective; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class DescriptorHolder { protected final Map<Class, EntityDescriptor> relationHolders; protected final EntityDescriptorBuilder relationBuilder; @Inject public DescriptorHolder(EntityDescriptorBuilder relationBuilder) { this.relationBuilder = relationBuilder; this.relationHolders = new HashMap<>(); } public EntityDescriptor getHolder(Class entityClass) { EntityDescriptor holder = relationHolders.get(entityClass); if (holder == null) { holder = relationBuilder.buildRelation(entityClass); relationHolders.put(entityClass, holder); } return holder; } }
Java
package com.anli.busstation.dal.jpa.reflective; import java.util.Collection; public class EntityDescriptor { protected final String entityName; protected final Collection<FieldDescriptor> fields; protected final FieldDescriptor idField; public EntityDescriptor(String entityName, Collection<FieldDescriptor> fields, FieldDescriptor idField) { this.entityName = entityName; this.fields = fields; this.idField = idField; } public String getEntityName() { return entityName; } public Collection<FieldDescriptor> getFields() { return fields; } public FieldDescriptor getIdField() { return idField; } }
Java
package com.anli.busstation.dal.jpa.reflective; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.inject.Singleton; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; @Singleton public class EntityDescriptorBuilder { public EntityDescriptor buildRelation(Class entityClass) { String name = ((Entity) entityClass.getAnnotation(Entity.class)).name(); List<FieldDescriptor> fields = new LinkedList<>(); FieldDescriptor idField = null; while (entityClass != null) { for (Field field : entityClass.getDeclaredFields()) { int fieldModifiers = field.getModifiers(); if (Modifier.isStatic(fieldModifiers) || Modifier.isFinal(fieldModifiers) || Modifier.isTransient(fieldModifiers)) { continue; } FieldDescriptor descriptor; Method getter = getGetterMethod(entityClass, field); Method setter = getSetterMethod(entityClass, field); if (getter == null || setter == null) { continue; } if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) { ParameterizedType genericType = (ParameterizedType) field.getGenericType(); Class elementClass = (Class) genericType.getActualTypeArguments()[0]; descriptor = getDescriptor(getter, setter, (Class) genericType.getRawType(), elementClass); } else { descriptor = getDescriptor(getter, setter, null, field.getType()); } if (field.isAnnotationPresent(Id.class)) { idField = descriptor; } fields.add(descriptor); } entityClass = entityClass.getSuperclass(); } return getHolder(name, fields, idField); } protected Method getGetterMethod(Class clazz, Field field) { String fieldName = field.getName(); String generalGetterName = getPrefixedName("get", fieldName); Method getterMethod = getClassMethod(clazz, generalGetterName); if (getterMethod != null) { return getterMethod; } String booleanGetterName = getPrefixedName("is", fieldName); return getClassMethod(clazz, booleanGetterName); } protected Method getSetterMethod(Class clazz, Field field) { String fieldName = field.getName(); String setterName = getPrefixedName("set", fieldName); return getSetterRecursively(clazz, setterName, field.getType()); } protected Method getSetterRecursively(Class clazz, String setterName, Class parameterClass) { if (parameterClass == null) { return null; } Method setter = getClassMethod(clazz, setterName, parameterClass); if (setter != null) { return setter; } for (Class interfaceClass : parameterClass.getInterfaces()) { setter = getSetterRecursively(clazz, setterName, interfaceClass); if (setter != null) { return setter; } } return getSetterRecursively(clazz, setterName, parameterClass.getSuperclass()); } protected Method getClassMethod(Class clazz, String name, Class... paramTypes) { try { return clazz.getMethod(name, paramTypes); } catch (NoSuchMethodException nsmException) { return null; } } protected String getPrefixedName(String prefix, String name) { char firstCharacter = Character.toUpperCase(name.charAt(0)); return prefix + firstCharacter + name.substring(1); } protected EntityDescriptor getHolder(String name, Collection<FieldDescriptor> fields, FieldDescriptor idField) { return new EntityDescriptor(name, fields, idField); } protected FieldDescriptor getDescriptor(Method getter, Method setter, Class collectionClass, Class elementClass) { return new FieldDescriptor(getter, setter, collectionClass, elementClass); } }
Java
package com.anli.busstation.dal.jpa.reflective; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.persistence.Entity; import javax.persistence.MappedSuperclass; public class FieldDescriptor { protected final Method getter; protected final Method setter; protected final Class collectionClass; protected final Class elementClass; protected final boolean reference; public FieldDescriptor(Method getter, Method setter, Class collectionClass, Class elementClass) { this.getter = getter; this.setter = setter; this.collectionClass = collectionClass; this.elementClass = elementClass; this.reference = elementClass.isAnnotationPresent(Entity.class) || elementClass.isAnnotationPresent(MappedSuperclass.class); } public FieldDescriptor(Method getter, Method setter, Class clazz) { this(getter, setter, null, clazz); } public Method getGetter() { return getter; } public Method getSetter() { return setter; } public boolean isCollection() { return collectionClass != null; } public boolean isReference() { return reference; } public Class getCollectionClass() { return collectionClass; } public Class getElementClass() { return elementClass; } }
Java
package com.anli.busstation.dal.jpa.entities; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigInteger; import java.util.Iterator; import java.util.List; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.MappedSuperclass; import javax.persistence.TableGenerator; import static javax.persistence.GenerationType.TABLE; import static javax.persistence.InheritanceType.TABLE_PER_CLASS; @MappedSuperclass @Inheritance(strategy = TABLE_PER_CLASS) @TableGenerator(name = "id_generator", table = "id_generation_sequences", pkColumnName = "entity", pkColumnValue = "bs_entity", valueColumnName = "last_id", allocationSize = 1) public abstract class BSEntityImpl implements BSEntity { @Id @GeneratedValue(generator = "id_generator", strategy = TABLE) protected BigInteger id; @Override public BigInteger getId() { return id; } public void setId(BigInteger id) { this.id = id; } @Override public boolean equals(Object comparee) { if (this.id == null) { return false; } if (comparee == null) { return false; } if (!this.getClass().equals(comparee.getClass())) { return false; } BSEntityImpl compareeEntity = (BSEntityImpl) comparee; return this.id.equals(compareeEntity.getId()); } @Override public int hashCode() { int hash = 3; hash = 41 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } @Deprecated protected boolean nullableDeepEquals(BSEntityImpl first, BSEntityImpl second) { if (first != null) { return first.deepEquals(second); } else { return (second == null); } } @Deprecated protected boolean nullableEquals(Object first, Object second) { if (first != null) { return first.equals(second); } else { return (second == null); } } @Deprecated protected boolean nullableEquals(Comparable first, Comparable second) { if (first != null) { if (second == null) { return false; } return first.compareTo(second) == 0; } else { return (second == null); } } @Deprecated protected boolean nullableListDeepEquals(List<BSEntityImpl> first, List<BSEntityImpl> second) { if (first == null && second == null) { return true; } if (first != null && second != null) { Iterator<BSEntityImpl> firstIter = first.iterator(); Iterator<BSEntityImpl> secondIter = second.iterator(); while (firstIter.hasNext() && secondIter.hasNext()) { if (!nullableDeepEquals(firstIter.next(), secondIter.next())) { return false; } } return !firstIter.hasNext() && !secondIter.hasNext(); } else { return false; } } @Override public String toString() { return this.getClass().getSimpleName() + " id = " + id; } }
Java
package com.anli.busstation.dal.jpa.entities.maintenance; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.maintenance.BusRefuelling; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity(name = "BusRefuelling") @Table(name = "bus_refuellings") @PrimaryKeyJoinColumn(name = "assignment_id", referencedColumnName = "assignment_id") public class BusRefuellingImpl extends BusServiceImpl implements BusRefuelling { @Column(name = "gas_volume") protected Integer volume; @Override public Integer getVolume() { return volume; } @Override public void setVolume(Integer volume) { this.volume = volume; } @Override public boolean deepEquals(BSEntity comparee) { if (!super.deepEquals(comparee)) { return false; } BusRefuellingImpl brComparee = (BusRefuellingImpl) comparee; return nullableEquals(this.volume, brComparee.volume); } @Override public String toString() { return super.toString() + " volume = " + volume; } }
Java
package com.anli.busstation.dal.jpa.entities.maintenance; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.maintenance.StationService; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity(name = "StationService") @Table(name = "station_services") @PrimaryKeyJoinColumn(name = "assignment_id", referencedColumnName = "assignment_id") public class StationServiceImpl extends TechnicalAssignmentImpl implements StationService { @Column(name = "description") protected String description; @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public boolean deepEquals(BSEntity comparee) { if (!super.deepEquals(comparee)) { return false; } StationServiceImpl ssComparee = (StationServiceImpl) comparee; return nullableEquals(this.description, ssComparee.description); } @Override public String toString() { return super.toString() + " description = " + description; } }
Java
package com.anli.busstation.dal.jpa.entities.maintenance; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.maintenance.BusRepairment; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity(name = "BusRepairment") @Table(name = "bus_repairments") @PrimaryKeyJoinColumn(name = "assignment_id", referencedColumnName = "assignment_id") public class BusRepairmentImpl extends BusServiceImpl implements BusRepairment { @Column(name = "expendables_price") protected BigDecimal expendablesPrice; @Override public BigDecimal getExpendablesPrice() { return expendablesPrice; } @Override public void setExpendablesPrice(BigDecimal expendablesPrice) { this.expendablesPrice = expendablesPrice; } @Override public boolean deepEquals(BSEntity comparee) { if (!super.deepEquals(comparee)) { return false; } BusRepairmentImpl brComparee = (BusRepairmentImpl) comparee; return nullableEquals(this.expendablesPrice, brComparee.expendablesPrice); } @Override public String toString() { return super.toString() + " expendablesPrice = " + expendablesPrice; } }
Java
package com.anli.busstation.dal.jpa.entities.maintenance; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.jpa.entities.staff.MechanicImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.staff.Mechanic; import com.anli.busstation.dal.interfaces.entities.maintenance.TechnicalAssignment; import com.anli.busstation.dal.jpa.converters.DateTimeConverter; import com.anli.busstation.dal.jpa.extractors.TechnicalAssignmentExtractor; import java.math.BigDecimal; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import org.eclipse.persistence.annotations.ClassExtractor; import org.joda.time.DateTime; import static javax.persistence.InheritanceType.JOINED; import static javax.persistence.TemporalType.TIMESTAMP; @Entity(name = "TechnicalAssignment") @Table(name = "technical_assignments") @Inheritance(strategy = JOINED) @ClassExtractor(TechnicalAssignmentExtractor.class) @AttributeOverride(name = "id", column = @Column(name = "assignment_id")) public abstract class TechnicalAssignmentImpl extends BSEntityImpl implements TechnicalAssignment { @OneToOne @JoinColumn(name = "mechanic", referencedColumnName = "employee_id") protected MechanicImpl mechanic; @Temporal(TIMESTAMP) @Column(name = "begin_time") @Convert(converter = DateTimeConverter.class) protected DateTime beginTime; @Temporal(TIMESTAMP) @Column(name = "end_time") @Convert(converter = DateTimeConverter.class) protected DateTime endTime; @Column(name = "service_cost") protected BigDecimal serviceCost; @Override public Mechanic getMechanic() { return mechanic; } @Override public void setMechanic(Mechanic mechanic) { this.mechanic = (MechanicImpl) mechanic; } @Override public DateTime getBeginTime() { return beginTime; } @Override public void setBeginTime(DateTime beginTime) { this.beginTime = beginTime; } @Override public DateTime getEndTime() { return endTime; } @Override public void setEndTime(DateTime endTime) { this.endTime = endTime; } @Override public BigDecimal getServiceCost() { return serviceCost; } @Override public void setServiceCost(BigDecimal serviceCost) { this.serviceCost = serviceCost; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } TechnicalAssignmentImpl taComparee = (TechnicalAssignmentImpl) comparee; return nullableDeepEquals(this.mechanic, taComparee.mechanic) && nullableEquals(this.beginTime, taComparee.beginTime) && nullableEquals(this.endTime, taComparee.endTime) && nullableEquals(this.serviceCost, taComparee.serviceCost); } @Override public String toString() { return super.toString() + " mechanic = {" + mechanic + "} beginTime = " + beginTime + " endTime = " + endTime + " serviceCost = " + serviceCost; } }
Java
package com.anli.busstation.dal.jpa.entities.maintenance; import com.anli.busstation.dal.jpa.entities.vehicles.BusImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.maintenance.BusService; import com.anli.busstation.dal.jpa.extractors.BusServiceExtractor; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.eclipse.persistence.annotations.ClassExtractor; import static javax.persistence.InheritanceType.JOINED; @Entity(name = "BusService") @Table(name = "bus_services") @Inheritance(strategy = JOINED) @ClassExtractor(BusServiceExtractor.class) @PrimaryKeyJoinColumn(name = "assignment_id", referencedColumnName = "assignment_id") public abstract class BusServiceImpl extends TechnicalAssignmentImpl implements BusService { @OneToOne @JoinColumn(name = "bus", referencedColumnName = "bus_id") protected BusImpl bus; @Override public Bus getBus() { return bus; } @Override public void setBus(Bus bus) { this.bus = (BusImpl) bus; } @Override public boolean deepEquals(BSEntity comparee) { if (!super.deepEquals(comparee)) { return false; } BusServiceImpl bsComparee = (BusServiceImpl) comparee; return nullableDeepEquals(this.bus, bsComparee.bus); } @Override public String toString() { return super.toString() + " bus = {" + bus + "}"; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.jpa.converters.DateTimeConverter; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import org.joda.time.DateTime; import static javax.persistence.TemporalType.TIMESTAMP; @Entity(name = "RidePoint") @Table(name = "ride_points") @AttributeOverride(name = "id", column = @Column(name = "ride_point_id")) public class RidePointImpl extends BSEntityImpl implements RidePoint { @OneToOne @JoinColumn(name = "route_point", referencedColumnName = "route_point_id") protected RoutePointImpl routePoint; @Temporal(TIMESTAMP) @Column(name = "arrival_time") @Convert(converter = DateTimeConverter.class) protected DateTime arrivalTime; @Temporal(TIMESTAMP) @Column(name = "departure_time") @Convert(converter = DateTimeConverter.class) protected DateTime departureTime; @Override public RoutePoint getRoutePoint() { return routePoint; } @Override public void setRoutePoint(RoutePoint routePoint) { this.routePoint = (RoutePointImpl) routePoint; } @Override public DateTime getArrivalTime() { return arrivalTime; } @Override public void setArrivalTime(DateTime arrivalTime) { this.arrivalTime = arrivalTime; } @Override public DateTime getDepartureTime() { return departureTime; } @Override public void setDepartureTime(DateTime departureTime) { this.departureTime = departureTime; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } RidePointImpl rpComparee = (RidePointImpl) comparee; return nullableDeepEquals(this.routePoint, rpComparee.routePoint) && nullableEquals(this.arrivalTime, rpComparee.arrivalTime) && nullableEquals(this.departureTime, rpComparee.departureTime); } @Override public String toString() { return super.toString() + " routePoint = {" + routePoint + "} arrivalTime = " + arrivalTime + " departureTime = " + departureTime; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.jpa.entities.staff.SalesmanImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.staff.Salesman; import com.anli.busstation.dal.interfaces.entities.traffic.Ticket; import com.anli.busstation.dal.jpa.converters.BooleanConverter; import com.anli.busstation.dal.jpa.converters.DateTimeConverter; import java.math.BigDecimal; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import org.joda.time.DateTime; import static javax.persistence.TemporalType.TIMESTAMP; @Entity(name = "Ticket") @Table(name = "tickets") @AttributeOverride(name = "id", column = @Column(name = "ticket_id")) public class TicketImpl extends BSEntityImpl implements Ticket { @OneToOne @JoinColumn(name = "departure_point", referencedColumnName = "ride_point_id") protected RidePointImpl departurePoint; @OneToOne @JoinColumn(name = "arrival_point", referencedColumnName = "ride_point_id") protected RidePointImpl arrivalPoint; @Column(name = "seat") protected Integer seat; @OneToOne @JoinColumn(name = "salesman", referencedColumnName = "employee_id") protected SalesmanImpl salesman; @Temporal(TIMESTAMP) @Column(name = "sale_date") @Convert(converter = DateTimeConverter.class) protected DateTime saleDate; @Column(name = "customer_name") protected String customerName; @Column(name = "price") protected BigDecimal price; @Column(name = "is_sold") @Convert(converter = BooleanConverter.class) protected boolean sold; @Override public RidePoint getDeparturePoint() { return departurePoint; } @Override public void setDeparturePoint(RidePoint departurePoint) { this.departurePoint = (RidePointImpl) departurePoint; } @Override public RidePoint getArrivalPoint() { return arrivalPoint; } @Override public void setArrivalPoint(RidePoint arrivalPoint) { this.arrivalPoint = (RidePointImpl) arrivalPoint; } @Override public Integer getSeat() { return seat; } @Override public void setSeat(Integer seat) { this.seat = seat; } @Override public Salesman getSalesman() { return salesman; } @Override public void setSalesman(Salesman salesman) { this.salesman = (SalesmanImpl) salesman; } @Override public DateTime getSaleDate() { return saleDate; } @Override public void setSaleDate(DateTime saleDate) { this.saleDate = saleDate; } @Override public String getCustomerName() { return customerName; } @Override public void setCustomerName(String customerName) { this.customerName = customerName; } @Override public BigDecimal getPrice() { return price; } @Override public void setPrice(BigDecimal price) { this.price = price; } @Override public boolean isSold() { return sold; } @Override public void setSold(boolean sold) { this.sold = sold; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } TicketImpl ticketComparee = (TicketImpl) comparee; return nullableDeepEquals(this.arrivalPoint, ticketComparee.arrivalPoint) && nullableDeepEquals(this.departurePoint, ticketComparee.departurePoint) && nullableDeepEquals(this.salesman, ticketComparee.salesman) && nullableEquals(this.customerName, ticketComparee.customerName) && nullableEquals(this.saleDate, ticketComparee.saleDate) && nullableEquals(this.seat, ticketComparee.seat) && nullableEquals(this.price, ticketComparee.price) && this.sold == ticketComparee.sold; } @Override public String toString() { return super.toString() + " arrivalPoint = {" + arrivalPoint + "} departurePoint = " + departurePoint + "} salesman = {" + salesman + "} customerName = " + customerName + " saleDate = " + saleDate + " seat = " + seat + " price = " + price + " sold = " + sold; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.jpa.entities.vehicles.BusImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.traffic.Ride; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.traffic.RideRoad; import com.anli.busstation.dal.interfaces.entities.traffic.Ticket; import java.util.List; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderColumn; import javax.persistence.Table; import static javax.persistence.FetchType.LAZY; @Entity(name = "Ride") @Table(name = "rides") @AttributeOverride(name = "id", column = @Column(name = "ride_id")) public class RideImpl extends BSEntityImpl implements Ride { @OneToOne @JoinColumn(name = "bus", referencedColumnName = "bus_id") protected BusImpl bus; @OneToMany(fetch = LAZY) @JoinColumn(name = "ride", referencedColumnName = "ride_id") @OrderColumn(name = "ride_order") protected List<RidePointImpl> ridePoints; @OneToMany(fetch = LAZY) @JoinColumn(name = "ride", referencedColumnName = "ride_id") @OrderColumn(name = "ride_order") protected List<RideRoadImpl> rideRoads; @OneToMany(fetch = LAZY) @JoinColumn(name = "ride", referencedColumnName = "ride_id") @OrderColumn(name = "ride_order") protected List<TicketImpl> tickets; @Override public Bus getBus() { return bus; } @Override public void setBus(Bus bus) { this.bus = (BusImpl) bus; } @Override public List<RidePoint> getRidePoints() { return (List) ridePoints; } public void setRidePoints(List<RidePointImpl> ridePoints) { this.ridePoints = ridePoints; } @Override public List<RideRoad> getRideRoads() { return (List) rideRoads; } public void setRideRoads(List<RideRoadImpl> rideRoads) { this.rideRoads = rideRoads; } @Override public List<Ticket> getTickets() { return (List) tickets; } public List<TicketImpl> getLazyTickets() { return tickets; } public void setTickets(List<TicketImpl> tickets) { this.tickets = tickets; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } RideImpl rideComparee = (RideImpl) comparee; return nullableDeepEquals(this.bus, rideComparee.bus) && nullableListDeepEquals((List) this.ridePoints, (List) rideComparee.ridePoints) && nullableListDeepEquals((List) this.rideRoads, (List) rideComparee.rideRoads) && nullableListDeepEquals((List) this.tickets, (List) rideComparee.tickets); } @Override public String toString() { return super.toString() + " bus = {" + bus + "} ridePoints = " + ridePoints + " rideRoads = " + rideRoads + " tickets = " + tickets; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.jpa.entities.geography.StationImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.interfaces.entities.geography.Station; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity(name = "RoutePoint") @Table(name = "route_points") @AttributeOverride(name = "id", column = @Column(name = "route_point_id")) public class RoutePointImpl extends BSEntityImpl implements RoutePoint { @OneToOne @JoinColumn(name = "station", referencedColumnName = "station_id") protected StationImpl station; @Override public Station getStation() { return station; } @Override public void setStation(Station station) { this.station = (StationImpl) station; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } RoutePointImpl rpComparee = (RoutePointImpl) comparee; return nullableDeepEquals(this.station, rpComparee.station); } @Override public String toString() { return super.toString() + " station = {" + station + "}"; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.traffic.Ride; import com.anli.busstation.dal.interfaces.entities.traffic.Route; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import java.math.BigDecimal; import java.util.List; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OrderColumn; import javax.persistence.Table; import static javax.persistence.FetchType.LAZY; @Entity(name = "Route") @Table(name = "routes") @AttributeOverride(name = "id", column = @Column(name = "route_id")) public class RouteImpl extends BSEntityImpl implements Route { @Column(name = "num_code") protected String numCode; @Column(name = "ticket_price") protected BigDecimal ticketPrice; @OneToMany(fetch = LAZY) @JoinColumn(name = "route", referencedColumnName = "route_id") @OrderColumn(name = "route_order") protected List<RoutePointImpl> routePoints; @OneToMany(fetch = LAZY) @JoinColumn(name = "route", referencedColumnName = "route_id") @OrderColumn(name = "route_order") protected List<RideImpl> rides; @Override public String getNumCode() { return numCode; } @Override public void setNumCode(String numCode) { this.numCode = numCode; } @Override public BigDecimal getTicketPrice() { return ticketPrice; } @Override public void setTicketPrice(BigDecimal ticketPrice) { this.ticketPrice = ticketPrice; } @Override public List<RoutePoint> getRoutePoints() { return (List) routePoints; } public void setRoutePoints(List<RoutePointImpl> routePoint) { this.routePoints = routePoint; } @Override public List<Ride> getRides() { return (List) rides; } public void setRides(List<RideImpl> rides) { this.rides = rides; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } RouteImpl routeComparee = (RouteImpl) comparee; return nullableEquals(this.numCode, routeComparee.numCode) && nullableEquals(this.ticketPrice, routeComparee.ticketPrice) && nullableListDeepEquals((List) this.rides, (List) routeComparee.rides) && nullableListDeepEquals((List) this.routePoints, (List) routeComparee.routePoints); } @Override public String toString() { return super.toString() + " numCode = " + numCode + " ticketPrice = " + ticketPrice + " rides = " + rides + " routePoints" + routePoints; } }
Java
package com.anli.busstation.dal.jpa.entities.traffic; import com.anli.busstation.dal.jpa.entities.BSEntityImpl; import com.anli.busstation.dal.jpa.entities.staff.DriverImpl; import com.anli.busstation.dal.jpa.entities.geography.RoadImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.staff.Driver; import com.anli.busstation.dal.interfaces.entities.traffic.RideRoad; import com.anli.busstation.dal.interfaces.entities.geography.Road; import javax.persistence.AttributeOverride; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity(name = "RideRoad") @Table(name = "ride_roads") @AttributeOverride(name = "id", column = @Column(name = "ride_road_id")) public class RideRoadImpl extends BSEntityImpl implements RideRoad { @OneToOne @JoinColumn(name = "road", referencedColumnName = "road_id") protected RoadImpl road; @OneToOne @JoinColumn(name = "driver", referencedColumnName = "employee_id") protected DriverImpl driver; @Override public Road getRoad() { return road; } @Override public void setRoad(Road road) { this.road = (RoadImpl) road; } @Override public Driver getDriver() { return driver; } @Override public void setDriver(Driver driver) { this.driver = (DriverImpl) driver; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } RideRoadImpl rrComparee = (RideRoadImpl) comparee; return nullableDeepEquals(this.driver, rrComparee.driver) && nullableDeepEquals(this.road, rrComparee.road); } @Override public String toString() { return super.toString() + " driver = {" + driver + "} road = {" + road + "}"; } }
Java