code
stringlengths
3
1.18M
language
stringclasses
1 value
/*------------------------------------------------------------------------------ ** Ident: Innovation en Inspiration > Google Android ** Author: rene ** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.tests.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Calendar; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.res.XmlResourceParser; import android.util.Log; /** * Feeder of GPS-location information * * @version $Id$ * @author Maarten van Berkel (maarten.van.berkel@sogeti.nl / +0586) */ public class MockGPSLoggerDriver implements Runnable { private static final String TAG = "MockGPSLoggerDriver"; private boolean running = true; private int mTimeout; private Context mContext; private TelnetPositionSender sender; private ArrayList<SimplePosition> positions; private int mRouteResource; /** * Constructor: create a new MockGPSLoggerDriver. * * @param context context of the test package * @param route resource identifier for the xml route * @param timeout time to idle between waypoints in miliseconds */ public MockGPSLoggerDriver(Context context, int route, int timeout) { this(); this.mTimeout = timeout; this.mRouteResource = route;// R.xml.denhaagdenbosch; this.mContext = context; } public MockGPSLoggerDriver() { this.sender = new TelnetPositionSender(); } public int getPositions() { return this.positions.size(); } private void prepareRun( int xmlResource ) { this.positions = new ArrayList<SimplePosition>(); XmlResourceParser xmlParser = this.mContext.getResources().getXml( xmlResource ); doUglyXMLParsing( this.positions, xmlParser ); xmlParser.close(); } public void run() { prepareRun( this.mRouteResource ); while( this.running && ( this.positions.size() > 0 ) ) { SimplePosition position = this.positions.remove( 0 ); //String nmeaCommand = createGPGGALocationCommand(position.getLongitude(), position.getLatitude(), 0); String nmeaCommand = createGPRMCLocationCommand( position.lng, position.lat, 0, 0 ); String checksum = calulateChecksum( nmeaCommand ); this.sender.sendCommand( "geo nmea $" + nmeaCommand + "*" + checksum + "\r\n" ); try { Thread.sleep( this.mTimeout ); } catch( InterruptedException e ) { Log.w( TAG, "Interrupted" ); } } } public static String calulateChecksum( String nmeaCommand ) { byte[] chars = null; try { chars = nmeaCommand.getBytes( "ASCII" ); } catch( UnsupportedEncodingException e ) { e.printStackTrace(); } byte xor = 0; for( int i = 0; i < chars.length; i++ ) { xor ^= chars[i]; } return Integer.toHexString( (int) xor ).toUpperCase(); } public void stop() { this.running = false; } private void doUglyXMLParsing( ArrayList<SimplePosition> positions, XmlResourceParser xmlParser ) { int eventType; try { eventType = xmlParser.getEventType(); SimplePosition lastPosition = null; boolean speed = false; while( eventType != XmlPullParser.END_DOCUMENT ) { if( eventType == XmlPullParser.START_TAG ) { if( xmlParser.getName().equals( "trkpt" ) || xmlParser.getName().equals( "rtept" ) || xmlParser.getName().equals( "wpt" ) ) { lastPosition = new SimplePosition( xmlParser.getAttributeFloatValue( 0, 12.3456F ), xmlParser.getAttributeFloatValue( 1, 12.3456F ) ); positions.add( lastPosition ); } if( xmlParser.getName().equals( "speed" ) ) { speed = true; } } else if( eventType == XmlPullParser.END_TAG ) { if( xmlParser.getName().equals( "speed" ) ) { speed = false; } } else if( eventType == XmlPullParser.TEXT ) { if( lastPosition != null && speed ) { lastPosition.speed = Float.parseFloat( xmlParser.getText() ); } } eventType = xmlParser.next(); } } catch( XmlPullParserException e ) { /* ignore */ } catch( IOException e ) {/* ignore */ } } /** * Create a NMEA GPRMC sentence * * @param longitude * @param latitude * @param elevation * @param speed in mps * @return */ public static String createGPRMCLocationCommand( double longitude, double latitude, double elevation, double speed ) { speed *= 0.51; // from m/s to knots final String COMMAND_GPS = "GPRMC," + "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY) "%2$02d" + // mm c.get(Calendar.MINUTE) "%3$02d." + // ss. c.get(Calendar.SECOND) "%4$03d,A," + // ss, c.get(Calendar.MILLISECOND) "%5$03d" + // llll latDegree "%6$09.6f," + // latMinute "%7$c," + // latDirection (N or S) "%8$03d" + // longDegree "%9$09.6f," + // longMinutett "%10$c," + // longDirection (E or W) "%14$.2f," + // Speed over ground in knot "0," + // Track made good in degrees True "%11$02d" + // dd "%12$02d" + // mm "%13$02d," + // yy "0," + // Magnetic variation degrees (Easterly var. subtracts from true course) "E," + // East/West "mode"; // Just as workaround.... Calendar c = Calendar.getInstance(); double absLong = Math.abs( longitude ); int longDegree = (int) Math.floor( absLong ); char longDirection = 'E'; if( longitude < 0 ) { longDirection = 'W'; } double longMinute = ( absLong - Math.floor( absLong ) ) * 60; double absLat = Math.abs( latitude ); int latDegree = (int) Math.floor( absLat ); char latDirection = 'N'; if( latitude < 0 ) { latDirection = 'S'; } double latMinute = ( absLat - Math.floor( absLat ) ) * 60; String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute, latDirection, longDegree, longMinute, longDirection, c.get( Calendar.DAY_OF_MONTH ), c.get( Calendar.MONTH ), c.get( Calendar.YEAR ) - 2000 , speed); return command; } public static String createGPGGALocationCommand( double longitude, double latitude, double elevation ) { final String COMMAND_GPS = "GPGGA," + // $--GGA, "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY) "%2$02d" + // mm c.get(Calendar.MINUTE) "%3$02d." + // ss. c.get(Calendar.SECOND) "%4$03d," + // sss, c.get(Calendar.MILLISECOND) "%5$03d" + // llll latDegree "%6$09.6f," + // latMinute "%7$c," + // latDirection "%8$03d" + // longDegree "%9$09.6f," + // longMinutett "%10$c," + // longDirection "1,05,02.1,00545.5,M,-26.0,M,,"; Calendar c = Calendar.getInstance(); double absLong = Math.abs( longitude ); int longDegree = (int) Math.floor( absLong ); char longDirection = 'E'; if( longitude < 0 ) { longDirection = 'W'; } double longMinute = ( absLong - Math.floor( absLong ) ) * 60; double absLat = Math.abs( latitude ); int latDegree = (int) Math.floor( absLat ); char latDirection = 'N'; if( latitude < 0 ) { latDirection = 'S'; } double latMinute = ( absLat - Math.floor( absLat ) ) * 60; String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute, latDirection, longDegree, longMinute, longDirection ); return command; } class SimplePosition { public float speed; public double lat, lng; public SimplePosition(float latitude, float longtitude) { this.lat = latitude; this.lng = longtitude; } } public void sendSMS( String string ) { this.sender.sendCommand( "sms send 31886606607 " + string + "\r\n" ); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Innovation en Inspiration > Google Android ** Author: rene ** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.tests; import junit.framework.TestSuite; import nl.sogeti.android.gpstracker.tests.actions.ExportGPXTest; import nl.sogeti.android.gpstracker.tests.db.GPStrackingProviderTest; import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest; import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest; import nl.sogeti.android.gpstracker.tests.userinterface.LoggerMapTest; import android.test.InstrumentationTestRunner; import android.test.InstrumentationTestSuite; /** * Perform unit tests Run on the adb shell: * * <pre> * am instrument -w nl.sogeti.android.gpstracker.tests/.GPStrackingInstrumentation * </pre> * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class GPStrackingInstrumentation extends InstrumentationTestRunner { /** * (non-Javadoc) * @see android.test.InstrumentationTestRunner#getAllTests() */ @Override public TestSuite getAllTests() { TestSuite suite = new InstrumentationTestSuite( this ); suite.setName( "GPS Tracking Testsuite" ); suite.addTestSuite( GPStrackingProviderTest.class ); suite.addTestSuite( MockGPSLoggerServiceTest.class ); suite.addTestSuite( GPSLoggerServiceTest.class ); suite.addTestSuite( ExportGPXTest.class ); suite.addTestSuite( LoggerMapTest.class ); // suite.addTestSuite( OpenGPSTrackerDemo.class ); // The demo recorded for youtube // suite.addTestSuite( MapStressTest.class ); // The stress test of the map viewer return suite; } /** * (non-Javadoc) * @see android.test.InstrumentationTestRunner#getLoader() */ @Override public ClassLoader getLoader() { return GPStrackingInstrumentation.class.getClassLoader(); } }
Java
/*------------------------------------------------------------------------------ ** Ident: Innovation en Inspiration > Google Android ** Author: rene ** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.tests.demo; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver; import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.SmallTest; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; /** * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<CommonLoggerMap> { private static final int ZOOM_LEVEL = 16; private static final Class<CommonLoggerMap> CLASS = CommonLoggerMap.class; private static final String PACKAGE = "nl.sogeti.android.gpstracker"; private CommonLoggerMap mLoggermap; private GPSLoggerServiceManager mLoggerServiceManager; private MapView mMapView; private MockGPSLoggerDriver mSender; public OpenGPSTrackerDemo() { super( PACKAGE, CLASS ); } @Override protected void setUp() throws Exception { super.setUp(); this.mLoggermap = getActivity(); this.mMapView = (MapView) this.mLoggermap.findViewById( nl.sogeti.android.gpstracker.R.id.myMapView ); this.mSender = new MockGPSLoggerDriver(); } protected void tearDown() throws Exception { this.mLoggerServiceManager.shutdown( getActivity() ); super.tearDown(); } /** * Start tracking and allow it to go on for 30 seconds * * @throws InterruptedException */ @LargeTest public void testTracking() throws InterruptedException { a_introSingelUtrecht30Seconds(); c_startRoute10Seconds(); d_showDrawMethods30seconds(); e_statistics10Seconds(); f_showPrecision30seconds(); g_stopTracking10Seconds(); h_shareTrack30Seconds(); i_finish10Seconds(); } @SmallTest public void a_introSingelUtrecht30Seconds() throws InterruptedException { this.mMapView.getController().setZoom( ZOOM_LEVEL); Thread.sleep( 1 * 1000 ); // Browse the Utrecht map sendMessage( "Selecting a previous recorded track" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "MENU DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "L" ); Thread.sleep( 2 * 1000 ); sendMessage( "The walk around the \"singel\" in Utrecht" ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 2 * 1000 ); Thread.sleep( 2 * 1000 ); sendMessage( "Scrolling about" ); this.mMapView.getController().animateTo( new GeoPoint( 52095829, 5118599 ) ); Thread.sleep( 2 * 1000 ); this.mMapView.getController().animateTo( new GeoPoint( 52096778, 5125090 ) ); Thread.sleep( 2 * 1000 ); this.mMapView.getController().animateTo( new GeoPoint( 52085117, 5128255 ) ); Thread.sleep( 2 * 1000 ); this.mMapView.getController().animateTo( new GeoPoint( 52081517, 5121646 ) ); Thread.sleep( 2 * 1000 ); this.mMapView.getController().animateTo( new GeoPoint( 52093535, 5116711 ) ); Thread.sleep( 2 * 1000 ); this.sendKeys( "G G" ); Thread.sleep( 5 * 1000 ); } @SmallTest public void c_startRoute10Seconds() throws InterruptedException { sendMessage( "Lets start a new route" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "T" );//Toggle start/stop tracker Thread.sleep( 1 * 1000 ); this.mMapView.getController().setZoom( ZOOM_LEVEL); this.sendKeys( "D E M O SPACE R O U T E ENTER" ); Thread.sleep( 5 * 1000 ); sendMessage( "The GPS logger is already running as a background service" ); Thread.sleep( 5 * 1000 ); this.sendKeys( "ENTER" ); this.sendKeys( "T T T T" ); Thread.sleep( 30 * 1000 ); this.sendKeys( "G G" ); } @SmallTest public void d_showDrawMethods30seconds() throws InterruptedException { sendMessage( "Track drawing color has different options" ); this.mMapView.getController().setZoom( ZOOM_LEVEL ); this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "S" ); Thread.sleep( 3 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "BACK" ); sendMessage( "Plain green" ); Thread.sleep( 15 * 1000 ); this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "S" ); Thread.sleep( 3 * 1000 ); this.sendKeys( "MENU" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_DOWN DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_UP"); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "BACK" ); sendMessage( "Average speeds drawn" ); Thread.sleep( 15 * 1000 ); } @SmallTest public void e_statistics10Seconds() throws InterruptedException { // Show of the statistics screen sendMessage( "Lets look at some statistics" ); this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "E" ); Thread.sleep( 2 * 1000 ); sendMessage( "Shows the basics on time, speed and distance" ); Thread.sleep( 10 * 1000 ); this.sendKeys( "BACK" ); } @SmallTest public void f_showPrecision30seconds() throws InterruptedException { this.mMapView.getController().setZoom( ZOOM_LEVEL ); sendMessage( "There are options on the precision of tracking" ); this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "S" ); Thread.sleep( 3 * 1000 ); this.sendKeys( "DPAD_DOWN DPAD_DOWN" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_UP DPAD_UP" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_DOWN DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_UP" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "BACK" ); sendMessage( "Course will drain the battery the least" ); Thread.sleep( 5 * 1000 ); sendMessage( "Fine will store the best track" ); Thread.sleep( 10 * 1000 ); } @SmallTest public void g_stopTracking10Seconds() throws InterruptedException { this.mMapView.getController().setZoom( ZOOM_LEVEL ); Thread.sleep( 5 * 1000 ); // Stop tracking sendMessage( "Stopping tracking" ); this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "T" ); Thread.sleep( 2 * 1000 ); sendMessage( "Is the track stored?" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "MENU DPAD_RIGHT" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "L" ); this.sendKeys( "DPAD_DOWN DPAD_DOWN" ); Thread.sleep( 2 * 1000 ); this.sendKeys( "DPAD_CENTER" ); Thread.sleep( 2 * 1000 ); } private void h_shareTrack30Seconds() { // TODO Auto-generated method stub } @SmallTest public void i_finish10Seconds() throws InterruptedException { this.mMapView.getController().setZoom( ZOOM_LEVEL ); this.sendKeys( "G G" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "G G" ); Thread.sleep( 1 * 1000 ); this.sendKeys( "G G" ); sendMessage( "Thank you for watching this demo." ); Thread.sleep( 10 * 1000 ); Thread.sleep( 5 * 1000 ); } private void sendMessage( String string ) { this.mSender.sendSMS( string ); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; /** * Utility methods for working with a DOM tree. * $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ public class DOMUtil { /** * Clears all childnodes in document */ public static void clearDocument(Document document) { NodeList nodeList = document.getChildNodes(); if (nodeList == null) { return; } int len = nodeList.getLength(); for (int i = 0; i < len; i++) { document.removeChild(nodeList.item(i)); } } /** * Create empty document TO BE DEBUGGED!. */ public static Document createDocument() { DocumentBuilder documentBuilder = null; // System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException pce) { warn("ParserConfigurationException: " + pce); return null; } return documentBuilder.newDocument(); } /** * Copies all attributes from one element to another in the official way. */ public static void copyAttributes(Element elementFrom, Element elementTo) { NamedNodeMap nodeList = elementFrom.getAttributes(); if (nodeList == null) { // No attributes to copy: just return return; } Attr attrFrom = null; Attr attrTo = null; // Needed as factory to create attrs Document documentTo = elementTo.getOwnerDocument(); int len = nodeList.getLength(); // Copy each attr by making/setting a new one and // adding to the target element. for (int i = 0; i < len; i++) { attrFrom = (Attr) nodeList.item(i); // Create an set value attrTo = documentTo.createAttribute(attrFrom.getName()); attrTo.setValue(attrFrom.getValue()); // Set in target element elementTo.setAttributeNode(attrTo); } } public static Element getFirstElementByTagName(Document document, String tag) { // Get all elements matching the tagname NodeList nodeList = document.getElementsByTagName(tag); if (nodeList == null) { p("no list of elements with tag=" + tag); return null; } // Get the first if any. Element element = (Element) nodeList.item(0); if (element == null) { p("no element for tag=" + tag); return null; } return element; } public static Element getElementById(Document document, String id) { return getElementById(document.getDocumentElement(), id); } public static Element getElementById(Element element, String id) { return getElementById(element.getChildNodes(), id); } /** * Get Element that has attribute id="xyz". */ public static Element getElementById(NodeList nodeList, String id) { // Note we should really use the Query here !! Element element = null; int len = nodeList.getLength(); for (int i = 0; i < len; i++) { Node node = (Node) nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { element = (Element) node; if (((Element) node).getAttribute("id").equals(id)) { // found it ! break; } } } // returns found element or null return element; } public static Document parse(InputStream anInputStream) { Document document; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(anInputStream); } catch (Exception e) { throw new RuntimeException(e); } return document; } /** * Prints an XML DOM. */ public static void printAsXML(Document document, PrintWriter printWriter) { new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document); } /** * Prints an XML DOM. */ public static String dom2String(Document document) { StringWriter sw = new StringWriter(); DOMUtil.printAsXML(document, new PrintWriter(sw)); return sw.toString(); } /** * Replaces an element in document. */ public static void replaceElement(Element newElement, Element oldElement) { // Must be 1 Node parent = oldElement.getParentNode(); if (parent == null) { warn("replaceElement: no parent of oldElement found"); return; } // Create a copy owned by the document ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement); Element newElementCopy = ecv.getCopy(); // Replace the old element with the new copy parent.replaceChild(newElementCopy, oldElement); } /** * Write Document structure to XML file. */ static public void document2File(Document document, String fileName) { new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document); } public static void warn(String s) { p("DOMUtil: WARNING " + s); } public static void p(String s) { // System.out.println("DOMUtil: "+s); } } /* * $Log: DOMUtil.java,v $ * Revision 1.18 2004/09/10 14:20:50 just * expandIncludes() tab to 2 spaces * * Revision 1.17 2004/09/10 12:48:11 just * ok * * Revision 1.16 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.15 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.14 2002/06/18 10:30:02 just * no rel change * * Revision 1.13 2001/08/01 15:20:23 kstroke * fix for expand includes (added rootDir) * * Revision 1.12 2001/02/17 14:28:16 just * added comments and changed interface for expandIds() * * Revision 1.11 2000/12/09 14:35:35 just * added parse() method with optional DTD validation * * Revision 1.10 2000/09/21 22:37:20 just * removed print statements * * Revision 1.9 2000/08/28 00:07:46 just * changes for introduction of EntityResolverImpl * * Revision 1.8 2000/08/24 10:11:12 just * added XML file verfication * * Revision 1.7 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * Makes deep copy of an Element for another Document. * $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ public class ElementCopyVisitor extends DefaultVisitor { Document ownerDocument; Element elementOrig; Element elementCopy; Element elementPointer; int level = 0; public ElementCopyVisitor(Document theOwnerDocument, Element theElement) { ownerDocument = theOwnerDocument; elementOrig = theElement; } public Element getCopy() { new TreeWalker(this).traverse(elementOrig); return elementCopy; } public void visitDocumentPre(Document document) { p("visitDocumentPre: level=" + level); } public void visitDocumentPost(Document document) { p("visitDocumentPost: level=" + level); } public void visitElementPre(Element element) { p("visitElementPre: " + element.getTagName() + " level=" + level); // Create the copy; must use target document as factory Element newElement = ownerDocument.createElement(element.getTagName()); // If first time we need to create the copy if (elementCopy == null) { elementCopy = newElement; } else { elementPointer.appendChild(newElement); } // Always point to the last created and appended element elementPointer = newElement; level++; } public void visitElementPost(Element element) { p("visitElementPost: " + element.getTagName() + " level=" + level); DOMUtil.copyAttributes(element, elementPointer); level--; if (level == 0) return; // Always transfer attributes if any if (level > 0) { elementPointer = (Element) elementPointer.getParentNode(); } } public void visitText(Text element) { // Create the copy; must use target document as factory Text newText = ownerDocument.createTextNode(element.getData()); // If first time we need to create the copy if (elementPointer == null) { p("ERROR no element copy"); return; } else { elementPointer.appendChild(newText); } } private void p(String s) { //System.out.println("ElementCopyVisitor: "+s); } } /* * $Log: ElementCopyVisitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; import org.w3c.dom.*; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the * purpose of printing in HTML-like format the various DOM-Nodes. * <p>In HTML-like printing, only the following Nodes are printed: * <DL> * <DT>Document</DT> * <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, &lt;!DOCTYPE&gt;, or internal DTD).</DD> * <DT>Element</DT> * <DD>All element names are uppercased.</DD> * <DD>Empty elements are written as <code>&lt;BR&gt;</code> instead of <code>&lt;BR/&gt;</code>.</DD> * <DT>Attr</DT> * <DD>All attribute names are lowercased.</DD> * <DT>Text</DT> * </DL> * <p/> * <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes: * <pre> * <p/> * PrintWriter printWriter = new PrintWriter(); * Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter); * TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor); * treeWalker.traverse(document); * printWriter.close(); * <p/> * </pre> * <p/> * <P>By default, this doesn't print non-specified attributes.</P> * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; * @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $ * @see Visitor * @see TreeWalker */ public class XMLPrintVisitor implements Visitor { protected Writer writer = null; protected int level = 0; protected String doctype = null; /** * Constructor for customized encoding and doctype. * * @param writer The character output stream to use. * @param encoding Java character encoding in use by <VAR>writer</VAR>. * @param doctype String to be printed at the top of the document. */ public XMLPrintVisitor(Writer writer, String encoding, String doctype) { this.writer = writer; this.doctype = doctype; // this.isPrintNonSpecifiedAttributes = false; } /** * Constructor for customized encoding. * * @param writer The character output stream to use. * @param encoding Java character encoding in use by <VAR>writer</VAR>. */ public XMLPrintVisitor(Writer writer, String encoding) { this(writer, encoding, null); } /** * Constructor for default encoding. * * @param writer The character output stream to use. */ public XMLPrintVisitor(Writer writer) { this(writer, null, null); } /** * Constructor for default encoding. * * @param fileName the filepath to write to */ public XMLPrintVisitor(String fileName) { try { writer = new FileWriter(fileName); } catch (IOException ioe) { } } /** * Writes the <var>doctype</var> from the constructor (if any). * * @param document Node print as HTML. */ public void visitDocumentPre(Document document) { } /** * Flush the writer. * * @param document Node to print as HTML. */ public void visitDocumentPost(Document document) { write("\n"); flush(); } /** * Creates a formatted string representation of the start of the specified <var>element</var> Node * and its associated attributes, and directs it to the print writer. * * @param element Node to print as XML. */ public void visitElementPre(Element element) { this.level++; write("<" + element.getTagName()); NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); visitAttributePre(attr); } write(">\n"); } /** * Creates a formatted string representation of the end of the specified <var>element</var> Node, * and directs it to the print writer. * * @param element Node to print as XML. */ public void visitElementPost(Element element) { String tagName = element.getTagName(); // if (element.hasChildNodes()) { write("</" + tagName + ">\n"); // } level--; } /** * Creates a formatted string representation of the specified <var>attribute</var> Node * and its associated attributes, and directs it to the print writer. * <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the * XML4J parser; attributes exist as part of a Element Node. * * @param attr attr to print. */ public void visitAttributePre(Attr attr) { write(" " + attr.getName() + "=\"" + attr.getValue() + "\""); } /** * Creates a formatted string representation of the specified <var>text</var> Node, * and directs it to the print writer. CDATASections are respected. * * @param text Node to print with format. */ public void visitText(Text text) { if (this.level > 0) { write(text.getData()); } } private void write(String s) { try { writer.write(s); } catch (IOException e) { } } private void flush() { try { writer.flush(); } catch (IOException e) { } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; /** * This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor * interface as it goes. * <p>The numbered nodes in the trees below indicate the order of traversal given * the specified <code>startNode</code> of &quot;1&quot;. * <pre> * * 1 x x * / \ / \ / \ * 2 6 1 x x x * /|\ \ /|\ \ /|\ \ * 3 4 5 7 2 3 4 x x 1 x x * * </pre> * $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class TreeWalker { private Visitor visitor; private Node topNode; /** * Constructor. * * @param */ public TreeWalker(Visitor theVisitor) { visitor = theVisitor; } /** * Disabled default constructor. */ private TreeWalker() { } /** * Perform a pre-order traversal non-recursive style. */ public void traverse(Node node) { // Remember the top node if (topNode == null) { topNode = node; } while (node != null) { visitPre(node); Node nextNode = node.getFirstChild(); while (nextNode == null) { visitPost(node); // We are ready after post-visiting the topnode if (node == topNode) { return; } try { nextNode = node.getNextSibling(); } catch (IndexOutOfBoundsException e) { nextNode = null; } if (nextNode == null) { node = node.getParentNode(); if (node == null) { nextNode = node; break; } } } node = nextNode; } } protected void visitPre(Node node) { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: visitor.visitDocumentPre((Document) node); break; case Node.ELEMENT_NODE: visitor.visitElementPre((Element) node); break; case Node.TEXT_NODE: visitor.visitText((Text) node); break; // Not yet case Node.ENTITY_REFERENCE_NODE: System.out.println("ENTITY_REFERENCE_NODE"); default: break; } } protected void visitPost(Node node) { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: visitor.visitDocumentPost((Document) node); break; case Node.ELEMENT_NODE: visitor.visitElementPost((Element) node); break; case Node.TEXT_NODE: break; default: break; } } } /* * $Log: TreeWalker.java,v $ * Revision 1.5 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.4 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.3 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; /** * This interface specifies the callbacks from the TreeWalker. * $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * Callback methods from the TreeWalker. */ public interface Visitor { public void visitDocumentPre(Document document); public void visitDocumentPost(Document document); public void visitElementPre(Element element); public void visitElementPost(Element element); public void visitText(Text element); } /* * $Log: Visitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.xml; /** * Implements a Visitor that does nothin' * $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; public class DefaultVisitor implements Visitor { public void visitDocumentPre(Document document) { } public void visitDocumentPost(Document document) { } public void visitElementPre(Element element) { } public void visitElementPost(Element element) { } public void visitText(Text element) { } } /* * $Log: DefaultVisitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.logger; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote; import org.opentraces.metatracker.Constants; /** * Class to interact with the service that tracks and logs the locations * * @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke * @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $ */ public class GPSLoggerServiceManager { private static final String TAG = "MT.GPSLoggerServiceManager"; private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION"; private Context mCtx; private IGPSLoggerServiceRemote mGPSLoggerRemote; private final Object mStartLock = new Object(); private boolean mStarted = false; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mServiceConnection = null; public GPSLoggerServiceManager(Context ctx) { this.mCtx = ctx; } public boolean isStarted() { synchronized (mStartLock) { return mStarted; } } public int getLoggingState() { synchronized (mStartLock) { int logging = Constants.UNKNOWN; try { if (this.mGPSLoggerRemote != null) { logging = this.mGPSLoggerRemote.loggingState(); Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging); } else { Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted); } } catch (RemoteException e) { Log.e(TAG, "Could stat GPSLoggerService.", e); } return logging; } } public boolean isMediaPrepared() { synchronized (mStartLock) { boolean prepared = false; try { if (this.mGPSLoggerRemote != null) { prepared = this.mGPSLoggerRemote.isMediaPrepared(); } else { Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted); } } catch (RemoteException e) { Log.e(TAG, "Could stat GPSLoggerService.", e); } return prepared; } } public long startGPSLogging(String name) { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { return this.mGPSLoggerRemote.startLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } return -1; } } public void pauseGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.pauseLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } } } public long resumeGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { return this.mGPSLoggerRemote.resumeLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } return -1; } } public void stopGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.stopLogging(); } } catch (RemoteException e) { Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e); } } else { Log.e(TAG, "No GPSLoggerRemote service connected to this manager"); } } } public void storeMediaUri(Uri mediaUri) { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.storeMediaUri(mediaUri); } } catch (RemoteException e) { Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e); } } else { Log.e(TAG, "No GPSLoggerRemote service connected to this manager"); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void startup(final ServiceConnection observer) { Log.d(TAG, "connectToGPSLoggerService()"); if (!mStarted) { this.mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { synchronized (mStartLock) { Log.d(TAG, "onServiceConnected()"); GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service); mStarted = true; if (observer != null) { observer.onServiceConnected(className, service); } } } public void onServiceDisconnected(ComponentName className) { synchronized (mStartLock) { Log.e(TAG, "onServiceDisconnected()"); GPSLoggerServiceManager.this.mGPSLoggerRemote = null; mStarted = false; if (observer != null) { observer.onServiceDisconnected(className); } } } }; this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE); } else { Log.w(TAG, "Attempting to connect whilst connected"); } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void shutdown() { Log.d(TAG, "disconnectFromGPSLoggerService()"); try { this.mCtx.unbindService(this.mServiceConnection); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e); } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.net; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Constants and utilities for the KW protocol. * * @author $Author: $ * @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $ */ public class Protocol { /** * AMUSE Protocol version. */ public static final String PROTOCOL_VERSION = "4.0"; /** * Postfixes */ public static final String POSTFIX_REQ = "-req"; public static final String POSTFIX_RSP = "-rsp"; public static final String POSTFIX_NRSP = "-nrsp"; public static final String POSTFIX_IND = "-ind"; /** * Service id's */ public static final String SERVICE_SESSION_CREATE = "ses-create"; public static final String SERVICE_LOGIN = "ses-login"; public static final String SERVICE_LOGOUT = "ses-logout"; public static final String SERVICE_SESSION_PING = "ses-ping"; public static final String SERVICE_QUERY_STORE = "query-store"; public static final String SERVICE_MAP_AVAIL = "map-avail"; public static final String SERVICE_MULTI_REQ = "multi-req"; /** * Common Attributes * */ public static final String ATTR_DEVID = "devid"; public static final String ATTR_USER = "user"; public static final String ATTR_AGENT = "agent"; public static final String ATTR_AGENTKEY = "agentkey"; public static final String ATTR_SECTIONS = "sections"; public static final String ATTR_ID = "id"; public static final String ATTR_CMD = "cmd"; public static final String ATTR_ERROR = "error"; public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !! public static final String ATTR_PASSWORD = "password"; public static final String ATTR_PROTOCOLVERSION = "protocolversion"; public static final String ATTR_STOPONERROR = "stoponerror"; public static final String ATTR_T = "t"; public static final String ATTR_TIME = "time"; public static final String ATTR_DETAILS = "details"; public static final String ATTR_NAME = "name"; /** * Error ids returned in -nrsp as attribute ATTR_ERRORID */ public final static int // 4000-4999 are "user-correctable" errors (user sends wrong input) // 5000-5999 are server failures ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003, ERR4004_INVALID_ATTR_VALUE = 4004, ERR4007_AGENT_LEASE_EXPIRED = 4007, //_Portal/Application_error_codes_(4100-4199) ERR4100_INVALID_USERNAME = 4100, ERR4101_INVALID_PASSWORD = 4101, ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102, //_General_Server_Error_Codes ERR5000_INTERNAL_SERVER_ERROR = 5000; /** * Create login protocol request. */ public static Element createLoginRequest(String aName, String aPassword) { Element request = createRequest(SERVICE_LOGIN); request.setAttribute(ATTR_NAME, aName); request.setAttribute(ATTR_PASSWORD, aPassword); request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION); return request; } /** * Create create-session protocol request. */ public static Element createSessionCreateRequest() { return createRequest(SERVICE_SESSION_CREATE); } /** * Create a positive response element. */ public static Element createRequest(String aService) { Element element = null; try { DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance(); DocumentBuilder build = dFact.newDocumentBuilder(); Document doc = build.newDocument(); element = doc.createElement(aService + POSTFIX_REQ); doc.appendChild(element); } catch (Throwable t) { } return element; } /** * Return service name for a message tag. * * @param aMessageTag * @return */ public static String getServiceName(String aMessageTag) { try { return aMessageTag.substring(0, aMessageTag.lastIndexOf('-')); } catch (Throwable t) { throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag); } } /** * Is message a (negative) response.. * * @param message * @return */ public static boolean isResponse(Element message) { String tag = message.getTagName(); return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP); } /** * Is message a positive response.. * * @param message * @return */ public static boolean isPositiveResponse(Element message) { return message.getTagName().endsWith(POSTFIX_RSP); } /** * Is message a negative response.. * * @param message * @return */ public static boolean isNegativeResponse(Element message) { return message.getTagName().endsWith(POSTFIX_NRSP); } public static boolean isPositiveServiceResponse(Element message, String service) { return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName())); } public static boolean isNegativeServiceResponse(Element message, String service) { return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName())); } public static boolean isService(Element message, String service) { return service.equals(getServiceName(message.getTagName())); } protected Protocol() { } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.net; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.opentraces.metatracker.xml.DOMUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Basic OpenTraces client using XML over HTTP. * <p/> * Use this class within Android HTTP clients. * * @author $Author: Just van den Broecke$ * @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $ * @see */ public class OpenTracesClient extends Protocol { private static final String LOG_TAG = "MT.OpenTracesClient"; /** * Default KW session timeout (minutes). */ public static final int DEFAULT_TIMEOUT_MINS = 5; /** * Full KW protocol URL. */ private String protocolURL; /** * Debug flag for verbose output. */ private boolean debug; /** * Key gotten on login ack */ private String agentKey; /** * Keyworx session timeout (minutes). */ private int timeout; /** * Saved login request for session restore on timeout. */ private Element loginRequest; /** * Constructor with full protocol URL e.g. http://www.bla.com/proto.srv. */ public OpenTracesClient(String aProtocolURL) { this(aProtocolURL, DEFAULT_TIMEOUT_MINS); } /** * Constructor with protocol URL and timeout. */ public OpenTracesClient(String aProtocolURL, int aTimeout) { protocolURL = aProtocolURL; if (!protocolURL.endsWith("/proto.srv")) { protocolURL += "/proto.srv"; } timeout = aTimeout; } /** * Create session. */ synchronized public Element createSession() throws ClientException { agentKey = null; // Create XML request Element request = createRequest(SERVICE_SESSION_CREATE); // Execute request Element response = doRequest(request); handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } public String getAgentKey() { return agentKey; } public boolean hasSession() { return agentKey != null; } public boolean isLoggedIn() { return hasSession() && loginRequest != null; } /** * Login on portal. */ synchronized public Element login(String aName, String aPassword) throws ClientException { // Create XML request Element request = createLoginRequest(aName, aPassword); // Execute request Element response = doRequest(request); // Filter session-related attrs handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } /** * Keep alive service. */ synchronized public Element ping() throws ClientException { return service(createRequest(SERVICE_SESSION_PING)); } /** * perform TWorx service request. */ synchronized public Element service(Element request) throws ClientException { throwOnInvalidSession(); // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Positive response: return wrapped handler response return response; } /** * perform TWorx multi-service request. */ synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException { // We don't need a valid session as one of the requests // may be a login or create-session request. // Create multi-req request with individual requests as children Element request = createRequest(SERVICE_MULTI_REQ); request.setAttribute(ATTR_STOPONERROR, stopOnError + ""); for (Element req : requests) { request.appendChild(req); } // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Filter child responses for session-based responses NodeList responseList = response.getChildNodes(); List<Element> responses = new ArrayList(responseList.getLength()); for (int i = 0; i < responseList.getLength(); i++) { handleResponse(requests.get(i), (Element) responseList.item(i)); responses.add((Element) responseList.item(i)); } // Positive multi-req response: return child responses return responses; } /** * Logout from portal. */ synchronized public Element logout() throws ClientException { throwOnInvalidSession(); // Create XML request Element request = createRequest(SERVICE_LOGOUT); // Execute request Element response = doRequest(request); handleResponse(request, response); // Throw exception or return positive response // throwOnNrsp(response); return response; } /* http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/ */ public void uploadFile(String fileName) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(fileName); HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); Log.d(LOG_TAG, "Upload result: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (Throwable ex) { Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); } } public void setDebug(boolean b) { debug = b; } /** * Filter responses for session-related requests. */ private void handleResponse(Element request, Element response) throws ClientException { if (isNegativeResponse(response)) { return; } String service = Protocol.getServiceName(request.getTagName()); if (service.equals(SERVICE_LOGIN)) { // Save for later session restore loginRequest = request; // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // if (response.hasAttribute(ATTR_TIME)) { // DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME)); // } } else if (service.equals(SERVICE_SESSION_CREATE)) { // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); } else if (service.equals(SERVICE_LOGOUT)) { loginRequest = null; agentKey = null; } } /** * Throw exception on negative protocol response. */ private void throwOnNrsp(Element anElement) throws ClientException { if (isNegativeResponse(anElement)) { String details = "no details"; if (anElement.hasAttribute(ATTR_DETAILS)) { details = anElement.getAttribute(ATTR_DETAILS); } throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)), anElement.getAttribute(ATTR_ERROR), details); } } /** * Throw exception when not logged in. */ private void throwOnInvalidSession() throws ClientException { if (agentKey == null) { throw new ClientException("Invalid tworx session"); } } /** * . */ private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException { // Check for session timeout if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED) { p("Reestablishing session..."); // Reset session agentKey = null; // Do login if already logged in if (loginRequest != null) { response = doRequest(loginRequest); throwOnNrsp(response); } else { response = createSession(); throwOnNrsp(response); } // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // Re-issue service request and return new response return doRequest(request); } // No session timeout so same response return response; } /** * Do XML over HTTP request and retun response. */ private Element doRequest(Element anElement) throws ClientException { // Create URL to use String url = protocolURL; if (agentKey != null) { url = url + "?agentkey=" + agentKey; } else { // Must be login url = url + "?timeout=" + timeout; } p("doRequest: " + url + " req=" + anElement.getTagName()); // Perform request/response HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); Element replyElement = null; try { // Make sure the server knows what kind of a response we will accept httpPost.addHeader("Accept", "text/xml"); // Also be sure to tell the server what kind of content we are sending httpPost.addHeader("Content-Type", "application/xml"); String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument()); StringEntity entity = new StringEntity(xmlString, "UTF-8"); entity.setContentType("application/xml"); httpPost.setEntity(entity); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPost); // Parse response Document replyDoc = DOMUtil.parse(response.getEntity().getContent()); replyElement = replyDoc.getDocumentElement(); p("doRequest: rsp=" + replyElement.getTagName()); } catch (Throwable t) { throw new ClientException("Error in doRequest: " + t); } finally { } return replyElement; } /** * Util: print. */ private void p(String s) { if (debug) { Log.d(LOG_TAG, s); } } /** * Util: warn. */ private void warn(String s) { warn(s, null); } /** * Util: warn with exception. */ private void warn(String s, Throwable t) { Log.e(LOG_TAG, s + " ex=" + t, t); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.net; /** * Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $ * * @author $Author: Just van den Broecke$ * @version $Revision: $ */ public class ClientException extends Exception { private int errorId; String error; protected ClientException() { } public ClientException(String aMessage, Throwable t) { super(aMessage + "\n embedded exception=" + t.toString()); } public ClientException(String aMessage) { super(aMessage); } public ClientException(int anErrorId, String anError, String someDetails) { super(someDetails); errorId = anErrorId; error = anError; } public ClientException(Throwable t) { this("ClientException: ", t); } public String toString() { return "ClientException: " + getMessage(); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker; import android.net.Uri; /** * Various application wide constants * * @author Just van den Broecke * @version $Id:$ */ public class Constants { /** * The authority of the track data provider */ public static final String AUTHORITY = "nl.sogeti.android.gpstracker"; /** * The content:// style URL for the track data provider */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); /** * Logging states, slightly adapted from GPSService states */ public static final int DOWN = 0; public static final int LOGGING = 1; public static final int PAUSED = 2; public static final int STOPPED = 3; public static final int UNKNOWN = 4; public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"}; public static final String DISABLEBLANKING = "disableblanking"; public static final String PREF_ENABLE_SOUND = "pref_enablesound"; public static final String PREF_SERVER_URL = "pref_server_url"; public static final String PREF_SERVER_USER = "pref_server_user"; public static final String PREF_SERVER_PASSWORD = "pref_server_password"; public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService"; public static final String EXTERNAL_DIR = "/OpenGPSTracker/"; public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string"); /** * Activity Action: Pick a file through the file manager, or let user * specify a custom file name. * Data is the current file name or file name suggestion. * Returns a new file name as file URI in data. * <p/> * <p>Constant Value: "org.openintents.action.PICK_FILE"</p> */ public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE"; public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1; /** * Activity Action: Show an about dialog to display * information about the application. * <p/> * The application information is retrieved from the * application's manifest. In order to send the package * you have to launch this activity through * startActivityForResult(). * <p/> * Alternatively, you can specify the package name * manually through the extra EXTRA_PACKAGE. * <p/> * All data can be replaced using optional intent extras. * <p/> * <p> * Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG" * </p> */ public static final String OI_ACTION_SHOW_ABOUT_DIALOG = "org.openintents.action.SHOW_ABOUT_DIALOG"; /** * Definitions for tracks. * */ public static final class Tracks implements android.provider.BaseColumns { /** * The name of this table */ static final String TABLE = "tracks"; /** * The end time */ public static final String NAME = "name"; public static final String CREATION_TIME = "creationtime"; /** * The MIME type of a CONTENT_URI subdirectory of a single track. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track"; /** * The content:// style URL for this provider */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for segments. */ public static final class Segments implements android.provider.BaseColumns { /** * The name of this table */ static final String TABLE = "segments"; /** * The track _id to which this segment belongs */ public static final String TRACK = "track"; static final String TRACK_TYPE = "INTEGER NOT NULL"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; /** * The MIME type of a CONTENT_URI subdirectory of a single segment. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment"; /** * The MIME type of CONTENT_URI providing a directory of segments. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for media URI's. * */ public static final class Media implements android.provider.BaseColumns { /** * The track _id to which this segment belongs */ public static final String TRACK = "track"; public static final String SEGMENT = "segment"; public static final String WAYPOINT = "waypoint"; public static final String URI = "uri"; /** * The name of this table */ public static final String TABLE = "media"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for waypoints. * */ public static final class Waypoints implements android.provider.BaseColumns { /** * The name of this table */ public static final String TABLE = "waypoints"; /** * The latitude */ public static final String LATITUDE = "latitude"; /** * The longitude */ public static final String LONGITUDE = "longitude"; /** * The recorded time */ public static final String TIME = "time"; /** * The speed in meters per second */ public static final String SPEED = "speed"; /** * The segment _id to which this segment belongs */ public static final String SEGMENT = "tracksegment"; /** * The accuracy of the fix */ public static final String ACCURACY = "accuracy"; /** * The altitude */ public static final String ALTITUDE = "altitude"; /** * the bearing of the fix */ public static final String BEARING = "bearing"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.activity; import android.content.SharedPreferences; import android.location.Location; import org.opentraces.metatracker.Constants; public class TrackingState { public int loggingState; public boolean newRoadRating; public int roadRating; public float distance; public Track track = new Track(); public Segment segment = new Segment(); public Waypoint waypoint = new Waypoint(); private SharedPreferences sharedPreferences; public TrackingState(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; reset(); } public void load() { distance = sharedPreferences.getFloat("distance", 0.0f); track.load(); waypoint.load(); } public void save() { sharedPreferences.edit().putFloat("distance", distance).commit(); track.save(); waypoint.save(); } public void reset() { loggingState = Constants.DOWN; distance = 0.0f; waypoint.reset(); track.reset(); } public class Track { public int id = -1; public String name = "NO TRACK"; public long creationTime; public void load() { id = sharedPreferences.getInt("track.id", -1); name = sharedPreferences.getString("track.name", "NO TRACK"); } public void save() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("track.id", id); editor.putString("track.name", name); editor.commit(); } public void reset() { name = "NO TRACK"; id = -1; } } public static class Segment { public int id = -1; } public class Waypoint { public int id = -1; public Location location; public float speed; public float accuracy; public int count; public void load() { id = sharedPreferences.getInt("waypoint.id", -1); count = sharedPreferences.getInt("waypoint.count", 0); } public void save() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("waypoint.id", id); editor.putInt("waypoint.count", count); editor.commit(); } public void reset() { count = 0; id = -1; location = null; } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.activity; import org.opentraces.metatracker.R; import android.os.Bundle; import android.preference.PreferenceActivity; /** * Dialog for setting preferences. * * @author Just van den Broecke */ public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); addPreferencesFromResource( R.layout.settings ); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.opentraces.metatracker.Constants; import org.opentraces.metatracker.R; import org.opentraces.metatracker.net.OpenTracesClient; public class UploadTrackActivity extends Activity { protected static final int DIALOG_FILENAME = 11; protected static final int PROGRESS_STEPS = 10; private static final int DIALOG_INSTALL_FILEMANAGER = 34; private static final String TAG = "MT.UploadTrack"; private String filePath; private TextView fileNameView; private SharedPreferences sharedPreferences; private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager"); Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload); try { startActivity(oiFileManagerDownloadIntent); } catch (ActivityNotFoundException e) { oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk"); oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload); startActivity(oiFileManagerDownloadIntent); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.uploaddialog); fileNameView = (TextView) findViewById(R.id.filename); filePath = null; pickFile(); Button okay = (Button) findViewById(R.id.okayupload_button); okay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (filePath == null) { return; } uploadFile(filePath); } }); } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_INSTALL_FILEMANAGER: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_nofilemanager) .setMessage(R.string.dialog_nofilemanager_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); break; default: dialog = super.onCreateDialog(id); break; } return dialog; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // Bundle extras = intent.getExtras(); switch (requestCode) { case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY: if (resultCode == RESULT_OK && intent != null) { // obtain the filename filePath = intent.getDataString(); if (filePath != null) { // Get rid of URI prefix: if (filePath.startsWith("file://")) { filePath = filePath.substring(7); } fileNameView.setText(filePath); } } break; } } /* http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java */ private void pickFile() { Intent intent = new Intent(Constants.ACTION_PICK_FILE); intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR)); try { startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY); } catch (ActivityNotFoundException e) { // No compatible file manager was found: install openintents filemanager. showDialog(DIALOG_INSTALL_FILEMANAGER); } } /* http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java */ private void uploadFile(String aFilePath) { Intent intent = new Intent(Constants.ACTION_PICK_FILE); intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR)); try { ; OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland")); openTracesClient.createSession(); openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd")); openTracesClient.uploadFile(aFilePath); openTracesClient.logout(); } catch (Throwable e) { Log.e(TAG, "Error uploading file : ", e); } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * 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 org.opentraces.metatracker.activity; import android.app.*; import android.content.*; import android.database.ContentObserver; import android.database.Cursor; import android.location.Location; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.opentraces.metatracker.*; import org.opentraces.metatracker.logger.GPSLoggerServiceManager; import java.text.DecimalFormat; public class MainActivity extends Activity { // MENU'S private static final int MENU_SETTINGS = 1; private static final int MENU_TRACKING = 2; private static final int MENU_UPLOAD = 3; private static final int MENU_HELP = 4; private static final int MENU_ABOUT = 5; private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1; private static final int DIALOG_INSTALL_ABOUT = 2; private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#"); private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##"); private static final String TAG = "MetaTracker.Main"; private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView; private GPSLoggerServiceManager loggerServiceManager; private TrackingState trackingState; private MediaPlayer mediaPlayer; // private PowerManager.WakeLock wakeLock = null; private static final int COLOR_WHITE = 0xFFFFFFFF; private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33}; private SharedPreferences sharedPreferences; private Button[] roadRatingButtons = new Button[6]; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); trackingState = new TrackingState(sharedPreferences); trackingState.load(); setContentView(R.layout.main); getLastTrackingState(); getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver); // mUnits = new UnitsI18n(this, mUnitsChangeListener); speedView = (TextView) findViewById(R.id.currentSpeed); timeView = (TextView) findViewById(R.id.currentTime); distanceView = (TextView) findViewById(R.id.totalDist); waypointCountView = (TextView) findViewById(R.id.waypointCount); accuracyView = (TextView) findViewById(R.id.currentAccuracy); roadRatingView = (TextView) findViewById(R.id.currentRoadRating); // Capture our button from layout roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none); roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo); roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad); roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor); roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good); roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best); for (Button button : roadRatingButtons) { button.setOnClickListener(roadRatingButtonListener); } bindGPSLoggingService(); } /** * Called when the activity is started. */ @Override public void onStart() { Log.d(TAG, "onStart()"); super.onStart(); } /** * Called when the activity is started. */ @Override public void onRestart() { Log.d(TAG, "onRestart()"); super.onRestart(); } /** * Called when the activity is resumed. */ @Override public void onResume() { Log.d(TAG, "onResume()"); getLastTrackingState(); // updateBlankingBehavior(); drawScreen(); super.onResume(); } /** * Called when the activity is paused. */ @Override public void onPause() { trackingState.save(); /* if (this.wakeLock != null && this.wakeLock.isHeld()) { this.wakeLock.release(); Log.w(TAG, "onPause(): Released lock to keep screen on!"); } */ Log.d(TAG, "onPause()"); super.onPause(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy()"); trackingState.save(); /* if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.w(TAG, "onDestroy(): Released lock to keep screen on!"); } */ getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver); sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener); unbindGPSLoggingService(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T'); menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I'); menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C'); menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I'); menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A'); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_TRACKING: startOpenGPSTrackerActivity(); break; case MENU_UPLOAD: startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity"); break; case MENU_SETTINGS: startActivity(new Intent(this, SettingsActivity.class)); break; case MENU_ABOUT: try { startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT); } catch (ActivityNotFoundException e) { showDialog(DIALOG_INSTALL_ABOUT); } break; default: showAlert(R.string.menu_message_unsupported); break; } return true; } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; AlertDialog.Builder builder = null; switch (id) { case DIALOG_INSTALL_OPENGPSTRACKER: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_noopengpstracker) .setMessage(R.string.dialog_noopengpstracker_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); break; case DIALOG_INSTALL_ABOUT: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_nooiabout) .setMessage(R.string.dialog_nooiabout_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mOiAboutDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; default: dialog = super.onCreateDialog(id); break; } return dialog; } private void drawTitleBar(String s) { this.setTitle(s); } /** * Called on any update to Tracks table. */ private void onTrackingUpdate() { getLastTrackingState(); if (trackingState.waypoint.count == 1) { sendRoadRating(); } drawScreen(); } /** * Called on any update to Tracks table. */ private synchronized void playPingSound() { if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) { return; } try { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.ping_short); } else { mediaPlayer.stop(); mediaPlayer.prepare(); } mediaPlayer.start(); } catch (Throwable t) { Log.e(TAG, "Error playing sound", t); } } /** * Retrieve the last point of the current track */ private void getLastWaypoint() { Cursor waypoint = null; try { ContentResolver resolver = this.getContentResolver(); waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE), new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT }, null, null, null); if (waypoint != null && waypoint.moveToLast()) { // New point: increase pointcount int waypointId = waypoint.getInt(0); if (waypointId > 0 && trackingState.waypoint.id != waypointId) { trackingState.waypoint.count++; trackingState.waypoint.id = waypoint.getInt(0); // Increase total distance Location newLocation = new Location(this.getClass().getName()); newLocation.setLongitude(waypoint.getDouble(1)); newLocation.setLatitude(waypoint.getDouble(2)); if (trackingState.waypoint.location != null) { float delta = trackingState.waypoint.location.distanceTo(newLocation); // Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2)); trackingState.distance += delta; } trackingState.waypoint.location = newLocation; trackingState.waypoint.speed = waypoint.getFloat(3); trackingState.waypoint.accuracy = waypoint.getFloat(4); trackingState.segment.id = waypoint.getInt(5); playPingSound(); } } } finally { if (waypoint != null) { waypoint.close(); } } } private void getLastTrack() { Cursor cursor = null; try { ContentResolver resolver = this.getApplicationContext().getContentResolver(); cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null); if (cursor != null && cursor.moveToLast()) { int trackId = cursor.getInt(0); // Check if new track created if (trackId != trackingState.track.id) { trackingState.reset(); trackingState.save(); } trackingState.track.id = trackId; trackingState.track.name = cursor.getString(1); trackingState.track.creationTime = cursor.getLong(2); } } finally { if (cursor != null) { cursor.close(); } } } private void getLastTrackingState() { getLastTrack(); getLoggingState(); getLastWaypoint(); } private void sendRoadRating() { if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null) { Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + "")); loggerServiceManager.storeMediaUri(media); trackingState.newRoadRating = false; } } private void startOpenGPSTrackerActivity() { try { startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap"); } catch (ActivityNotFoundException e) { Log.i(TAG, "Cannot find activity for open-gpstracker"); // No compatible file manager was found: install openintents filemanager. showDialog(DIALOG_INSTALL_OPENGPSTRACKER); } sendRoadRating(); } private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException { Intent intent = new Intent(); intent.setClassName(aPackageName, aClassName); startActivity(intent); } private void bindGPSLoggingService() { unbindGPSLoggingService(); ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { getLoggingState(); drawTitleBar(); } public void onServiceDisconnected(ComponentName className) { trackingState.loggingState = Constants.DOWN; } }; loggerServiceManager = new GPSLoggerServiceManager(this); loggerServiceManager.startup(serviceConnection); } private void unbindGPSLoggingService() { if (loggerServiceManager == null) { return; } try { loggerServiceManager.shutdown(); } finally { loggerServiceManager = null; trackingState.loggingState = Constants.DOWN; } } private void getLoggingState() { // Get state from logger if bound trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState(); // protect for values outside array bounds (set to unknown) if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1) { trackingState.loggingState = Constants.UNKNOWN; } } private String getLoggingStateStr() { return Constants.LOGGING_STATES[trackingState.loggingState]; } private void drawTitleBar() { drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr()); } private void drawScreen() { drawTitleBar(); drawTripStats(); drawRoadRating(); } /** * Retrieves the numbers of the measured speed and altitude * from the most recent waypoint and * updates UI components with this latest bit of information. */ private void drawTripStats() { try { waypointCountView.setText(trackingState.waypoint.count + ""); long secsDelta = 0L; long hours = 0L; long mins = 0L; long secs = 0L; if (trackingState.track.creationTime != 0) { secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000; hours = secsDelta / 3600L; mins = (secsDelta % 3600L) / 60L; secs = ((secsDelta % 3600L) % 60); } timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs)); speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed)); accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy)); distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f)); } finally { } } private String formatTimeNum(long n) { return n < 10 ? ("0" + n) : (n + ""); } private void drawRoadRating() { for (int i = 0; i < roadRatingButtons.length; i++) { roadRatingButtons[i].setBackgroundColor(COLOR_WHITE); } if (trackingState.roadRating >= 0) { roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]); } String roadRatingStr = trackingState.roadRating + ""; roadRatingView.setText(roadRatingStr); } private void showAlert(int aMessage) { new AlertDialog.Builder(this) .setMessage(aMessage) .setPositiveButton("Ok", null) .show(); } private void updateBlankingBehavior() { boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false); if (disableblanking) { /* if (wakeLock == null) { PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); } wakeLock.acquire(); Log.w(TAG, "Acquired lock to keep screen on!"); */ } } private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri oiDownload = Uri.parse("market://details?id=org.openintents.about"); Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); try { startActivity(oiAboutIntent); } catch (ActivityNotFoundException e) { oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk"); oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); startActivity(oiAboutIntent); } } }; private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker"); Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri); try { startActivity(downloadIntent); } catch (ActivityNotFoundException e) { showAlert(R.string.dialog_failinstallopengpstracker_message); } } }; // Create an anonymous implementation of OnClickListener private View.OnClickListener roadRatingButtonListener = new View.OnClickListener() { public void onClick(View v) { for (int i = 0; i < roadRatingButtons.length; i++) { if (v.getId() == roadRatingButtons[i].getId()) { trackingState.roadRating = i; } } trackingState.newRoadRating = true; drawRoadRating(); sendRoadRating(); } }; private final ContentObserver trackingObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { onTrackingUpdate(); Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id); } else { Log.w(TAG, "trackingObserver skipping change"); } } }; private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.DISABLEBLANKING)) { updateBlankingBehavior(); } } }; }
Java
package com.irontec.phpforandroid; import android.content.Context; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; public class PhpUninstaller extends InterpreterUninstaller { public PhpUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { super(descriptor, context, listener); } @Override protected boolean cleanup() { return true; } }
Java
package com.irontec.phpforandroid; import java.io.File; import android.content.Context; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; public class PhpInstaller extends InterpreterInstaller { public PhpInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { super(descriptor, context, listener); } @Override protected boolean setup() { File tmp = new File(InterpreterConstants.INTERPRETER_EXTRAS_ROOT, mDescriptor.getName() + "/tmp"); if (!tmp.isDirectory()) { try { tmp.mkdir(); } catch (SecurityException e) { Log.e(mContext, "Setup failed.", e); return false; } } return true; } }
Java
package com.irontec.phpforandroid; import android.content.Context; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.activity.Main; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; public class PhpMain extends Main { @Override protected InterpreterDescriptor getDescriptor() { return new PhpDescriptor(); } @Override protected InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PhpInstaller(descriptor, context, listener); } @Override protected InterpreterUninstaller getInterpreterUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { return new PhpUninstaller(descriptor, context, listener); } }
Java
package com.irontec.phpforandroid; import java.io.File; import java.util.HashMap; import java.util.Map; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterProvider; import com.googlecode.android_scripting.interpreter.InterpreterUtils; public class PhpProvider extends InterpreterProvider { private static final String ENV_HOME = "PHPHOME"; private static final String ENV_PATH = "PHPPATH"; private static final String ENV_TEMP = "TEMP"; private static final String ENV_DATA = "ANDROID_DATA"; // Is it really used somewhere? @Override protected InterpreterDescriptor getDescriptor() { return new PhpDescriptor(); } // // private String getExtrasRoot() { // return InterpreterConstants.SDCARD_ROOT + getClass().getPackage().getName() // + InterpreterConstants.INTERPRETER_EXTRAS_ROOT; // } // // private String getHome() { // File file = InterpreterUtils.getInterpreterRoot(mContext, mDescriptor.getName()); // return file.getAbsolutePath(); // } // // private String getExtras() { // File file = new File(getExtrasRoot(), mDescriptor.getName()); // return file.getAbsolutePath(); // } // // private String getTemp() { // File tmp = new File(getExtrasRoot(), mDescriptor.getName() + "/tmp"); // if (!tmp.isDirectory()) { // tmp.mkdir(); // } // return tmp.getAbsolutePath(); // } // // @Override // protected Map<String, String> getEnvironmentSettings() { // Map<String, String> settings = new HashMap<String, String>(3); // settings.put(ENV_HOME, getHome()); // settings.put(ENV_PATH, getExtras()); // settings.put(ENV_TEMP, getTemp()); // return settings; // } // // private String getHome() { // File parent = mContext.getFilesDir().getParentFile(); // File file = new File(parent, mDescriptor.getName()); // return file.getAbsolutePath(); // } // // private String getExtras() { // File file = new File(InterpreterConstants.INTERPRETER_EXTRAS_ROOT, mDescriptor.getName()); // return file.getAbsolutePath(); // } // // private String getTemp() { // File tmp = // new File(InterpreterConstants.INTERPRETER_EXTRAS_ROOT, mDescriptor.getName() + "/tmp"); // if (!tmp.isDirectory()) { // tmp.mkdir(); // } // return tmp.getAbsolutePath(); // } // // @Override // protected Map<String, String> getEnvironmentSettings() { // Map<String, String> settings = new HashMap<String, String>(3); // settings.put(ENV_HOME, getHome()); // settings.put(ENV_PATH, getExtras()); // settings.put(ENV_TEMP, getTemp()); // return settings; // } @Override protected Map<String, String> getEnvironmentSettings() { Map<String, String> settings = new HashMap<String, String>(1); settings.put(ENV_DATA, InterpreterConstants.SDCARD_ROOT + getClass().getPackage().getName()); return settings; } }
Java
/* * Copyright (C) 2010 Irontec SL * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package com.irontec.phpforandroid; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterUtils; import com.googlecode.android_scripting.interpreter.PfaHostedInterpreter; import com.googlecode.android_scripting.interpreter.Sl4aHostedInterpreter; /** * * @author Ivan Mosquera Paulo (ivan@irontec.com) * */ public class PhpDescriptor extends PfaHostedInterpreter { public static final String PHP_BASE_INSTALL_URL = "http://php-for-android.googlecode.com/files/"; private static final String PHP_BIN = "bin/php"; private final static String PHP_PREFIX = "-c /sdcard/com.irontec.phpforandroid/extras/php/php.ini"; private static final String ENV_HOME = "PHPHOME"; private static final String ENV_PATH = "PHPPATH"; private static final String ENV_TEMP = "TEMP"; //"%s"; public String getExtension() { return ".php"; } public String getName() { return "php"; } public String getNiceName() { return "PHP 5.3.3"; } public boolean hasInterpreterArchive() { return true; } public boolean hasExtrasArchive() { return true; } public boolean hasScriptsArchive() { return true; } public int getVersion() { return 3; } @Override public int getExtrasVersion() { return 3; } @Override public int getScriptsVersion() { return 3; } public String getBinary() { return PHP_BIN; } public String getEmptyParams(Context context) { return ""; } // public String getExecuteParams(Context context) { // //return " -c " + getPath(context) + " %s"; // //return String.format(format, args)" -c /sdcard/com.irontec.phpforandroid/extras/php "; // //return PHP_PREFIX;///, getPath(context), getBinary());//, "load('%s')"); // return " -c /sdcard/com.irontec.phpforandroid/extras/php %s"; // } // public String[] getExecuteArgs(Context context) { // String args[] = { "-c /sdcard/com.irontec.phpforandroid/extras/php %s"}; // //return " -c " + getPath(context) + " %s"; // //return " -c /sdcard/com.irontec.phpforandroid/extras/php %s"; // return args; // } // public String getExecuteCommand(Context context) { // return String.format("%1$s/%2$s", getPath(context), getBinary()); // } // @Override // public String getScriptCommand(Context context) { // //String absolutePathToJar = new File(getExtrasPath(context), JRUBY_JAR).getAbsolutePath(); // //return String.format(JRUBY_PREFIX, absolutePathToJar, "load('%s')"); // return /*getBinary(context) +*/ "-c /sdcard/com.irontec.phpforandroid/extras/php/php.ini %s"; // } @Override public List<String> getArguments(Context context) { //String absolutePathToJar = new File(getExtrasPath(context), JRUBY_JAR).getAbsolutePath(); return Arrays.asList("-c", "/sdcard/com.irontec.phpforandroid/extras/php/php.ini"); } @Override public String getExtrasArchiveUrl() { return PHP_BASE_INSTALL_URL + getExtrasArchiveName(); } @Override public String getInterpreterArchiveUrl() { return PHP_BASE_INSTALL_URL + getInterpreterArchiveName(); } @Override public String getScriptsArchiveUrl() { return PHP_BASE_INSTALL_URL + getScriptsArchiveName(); } @Override public String getInteractiveCommand(Context context) { return /*getBinary(context) +*/ " -a"; } @Override public File getBinary(Context context) { return new File(getExtrasPath(context), PHP_BIN); } @Override public boolean hasInteractiveMode() { // TODO Auto-generated method stub return false; } @Override public Map<String, String> getEnvironmentVariables(Context context) { Map<String, String> values = new HashMap<String, String>(); values.put(ENV_HOME, getHome(context)); values.put(ENV_PATH, getExtras()); values.put(ENV_TEMP, getTemp()); return values; } private String getHome(Context context) { File file = InterpreterUtils.getInterpreterRoot(context, getName()); return file.getAbsolutePath(); } private String getExtras() { File file = new File(getExtrasRoot(), getName()); return file.getAbsolutePath(); } private String getTemp() { File tmp = new File(getExtrasRoot(), getName() + "/tmp"); if (!tmp.isDirectory()) { tmp.mkdir(); } return tmp.getAbsolutePath(); } private String getExtrasRoot() { return InterpreterConstants.SDCARD_ROOT + getClass().getPackage().getName() + InterpreterConstants.INTERPRETER_EXTRAS_ROOT; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.googlecode.android_scripting.AsyncTaskListener; import com.googlecode.android_scripting.InterpreterInstaller; import com.googlecode.android_scripting.InterpreterUninstaller; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; /** * Base activity for distributing interpreters as APK's. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class Main extends Activity { protected final static float MARGIN_DIP = 3.0f; protected final static float SPINNER_DIP = 10.0f; protected final String mId = getClass().getPackage().getName(); protected SharedPreferences mPreferences; protected InterpreterDescriptor mDescriptor; protected Button mButton; protected Button mAboutButton; protected final static String version = "0.2 (sl4a_r0)"; private LinearLayout mProgressLayout; protected abstract InterpreterDescriptor getDescriptor(); protected abstract InterpreterInstaller getInterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException; protected abstract InterpreterUninstaller getInterpreterUninstaller( InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException; protected enum RunningTask { INSTALL, UNINSTALL } protected volatile RunningTask mCurrentTask = null; protected final AsyncTaskListener<Boolean> mTaskListener = new AsyncTaskListener<Boolean>() { @Override public void onTaskFinished(Boolean result, String message) { mProgressLayout.setVisibility(View.INVISIBLE); if (result) { switch (mCurrentTask) { case INSTALL: setInstalled(true); prepareUninstallButton(); break; case UNINSTALL: setInstalled(false); prepareInstallButton(); break; } } Log.v(Main.this, message); mCurrentTask = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mDescriptor = getDescriptor(); initializeViews(); if (checkInstalled()) { prepareUninstallButton(); } else { prepareInstallButton(); } prepareAboutButton(); } @Override protected void onStop() { super.onStop(); finish(); } // TODO(alexey): Pull out to a layout XML? protected void initializeViews() { LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); layout.setGravity(Gravity.CENTER_HORIZONTAL); TextView textview = new TextView(this); textview.setText(" PhpForAndroid " + version); mButton = new Button(this); mAboutButton = new Button(this); MarginLayoutParams marginParams = new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); final float scale = getResources().getDisplayMetrics().density; int marginPixels = (int) (MARGIN_DIP * scale + 0.5f); marginParams.setMargins(marginPixels, marginPixels, marginPixels, marginPixels); mButton.setLayoutParams(marginParams); mAboutButton.setLayoutParams(marginParams); layout.addView(textview); layout.addView(mButton); layout.addView(mAboutButton); mProgressLayout = new LinearLayout(this); mProgressLayout.setOrientation(LinearLayout.HORIZONTAL); mProgressLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mProgressLayout.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); LinearLayout bottom = new LinearLayout(this); bottom.setOrientation(LinearLayout.HORIZONTAL); bottom.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); bottom.setGravity(Gravity.CENTER_VERTICAL); mProgressLayout.addView(bottom); TextView message = new TextView(this); message.setText(" In Progress..."); message.setTextSize(20); message.setTypeface(Typeface.DEFAULT_BOLD); message.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); ProgressBar bar = new ProgressBar(this); bar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); bottom.addView(bar); bottom.addView(message); mProgressLayout.setVisibility(View.INVISIBLE); layout.addView(mProgressLayout); setContentView(layout); } protected void prepareInstallButton() { mButton.setText("Install"); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { install(); } }); } protected void prepareAboutButton() { mAboutButton.setText("About"); mAboutButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { about(); } }); } protected void prepareUninstallButton() { mButton.setText("Uninstall"); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { uninstall(); } }); } protected void broadcastInstallationStateChange(boolean isInterpreterInstalled) { Intent intent = new Intent(); intent.setData(Uri.parse("package:" + mId)); if (isInterpreterInstalled) { intent.setAction(InterpreterConstants.ACTION_INTERPRETER_ADDED); } else { intent.setAction(InterpreterConstants.ACTION_INTERPRETER_REMOVED); } sendBroadcast(intent); } protected synchronized void about() { Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.phpforandroid.net/about")); startActivity(browserIntent); } // protected synchronized void about() { // // Context mContext = getApplicationContext(); // dialog = new Dialog(Main.this); // dialog.setCancelable(true); // LinearLayout layout = new LinearLayout(this); // layout.setOrientation(LinearLayout.VERTICAL); // layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); // // TextView textview = new TextView(this); // textview.setText(" PHP for Android " + Main.version + // "\n\n www.phpforandroid.net\n (c) Copyright Irontec 2010\n\nDevelopment:\n\n Ivan Mosquera Paulo (ivan@irontec.com)\n\n" // + // " Acknowledgements:\n\n Javier Infante (jabi@irontec.com)\n Gorka Rodrigo (gorka@irontec.com)\n Moshe Doron (momo@php.net)\n Damon Kohler (damonkohler@gmail.com)\n Alexey Reznichenko (alexey.reznichenko@googlemail.com)\n"); // Button button = new Button(this); // button.setText("OK"); // button.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // dialog.dismiss(); // } // }); // layout.addView(textview); // layout.addView(button); // dialog.setContentView(layout); // dialog.setTitle("About PHP for Android"); // dialog.show(); // // } protected synchronized void install() { if (mCurrentTask != null) { return; } mProgressLayout.setVisibility(View.VISIBLE); mCurrentTask = RunningTask.INSTALL; InterpreterInstaller installTask; try { installTask = getInterpreterInstaller(mDescriptor, Main.this, mTaskListener); } catch (Sl4aException e) { Log.e(this, e.getMessage(), e); return; } installTask.execute(); } protected synchronized void uninstall() { if (mCurrentTask != null) { return; } mProgressLayout.setVisibility(View.VISIBLE); mCurrentTask = RunningTask.UNINSTALL; InterpreterUninstaller uninstallTask; try { uninstallTask = getInterpreterUninstaller(mDescriptor, Main.this, mTaskListener); } catch (Sl4aException e) { Log.e(this, e.getMessage(), e); return; } uninstallTask.execute(); } protected void setInstalled(boolean isInstalled) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putBoolean(InterpreterConstants.INSTALLED_PREFERENCE_KEY, isInstalled); // editor.putBoolean(InterpreterConstants.INSTALL_PREF, isInstalled); editor.commit(); broadcastInstallationStateChange(isInstalled); } protected boolean checkInstalled() { boolean isInstalled = mPreferences.getBoolean(InterpreterConstants.INSTALLED_PREFERENCE_KEY, false); // mPreferences.getBoolean(InterpreterConstants.INSTALL_PREF, false); broadcastInstallationStateChange(isInstalled); return isInstalled; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import com.googlecode.android_scripting.IoUtils; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.exception.Sl4aException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * AsyncTask for extracting ZIP files. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public class UrlDownloaderTask extends AsyncTask<Void, Integer, Long> { private final URL mUrl; private final File mFile; private final ProgressDialog mDialog; private Throwable mException; private OutputStream mProgressReportingOutputStream; private final class ProgressReportingOutputStream extends FileOutputStream { private int mProgress = 0; private ProgressReportingOutputStream(File f) throws FileNotFoundException { super(f); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { super.write(buffer, offset, count); mProgress += count; publishProgress(mProgress); } } public UrlDownloaderTask(String url, String out, Context context) throws MalformedURLException { super(); if (context != null) { mDialog = new ProgressDialog(context); } else { mDialog = null; } mUrl = new URL(url); String fileName = new File(mUrl.getFile()).getName(); mFile = new File(out, fileName); } @Override protected void onPreExecute() { Log.v("Downloading " + mUrl); if (mDialog != null) { mDialog.setTitle("Downloading"); mDialog.setMessage(mFile.getName()); // mDialog.setIndeterminate(true); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancel(true); } }); mDialog.show(); } } @Override protected Long doInBackground(Void... params) { try { return download(); } catch (Exception e) { if (mFile.exists()) { // Clean up bad downloads. mFile.delete(); } mException = e; return null; } } @Override protected void onProgressUpdate(Integer... progress) { if (mDialog == null) { return; } if (progress.length > 1) { int contentLength = progress[1]; if (contentLength == -1) { mDialog.setIndeterminate(true); } else { mDialog.setMax(contentLength); } } else { mDialog.setProgress(progress[0].intValue()); } } @Override protected void onPostExecute(Long result) { if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } if (isCancelled()) { return; } if (mException != null) { Log.e("Download failed.", mException); } } @Override protected void onCancelled() { if (mDialog != null) { mDialog.setTitle("Download cancelled."); } } private long download() throws Exception { URLConnection connection = null; try { connection = mUrl.openConnection(); } catch (IOException e) { throw new Sl4aException("Cannot open URL: " + mUrl, e); } int contentLength = connection.getContentLength(); if (mFile.exists() && contentLength == mFile.length()) { Log.v("Output file already exists. Skipping download."); return 0l; } try { mProgressReportingOutputStream = new ProgressReportingOutputStream(mFile); } catch (FileNotFoundException e) { throw new Sl4aException(e); } publishProgress(0, contentLength); int bytesCopied = IoUtils.copy(connection.getInputStream(), mProgressReportingOutputStream); if (bytesCopied != contentLength && contentLength != -1) { throw new IOException("Download incomplete: " + bytesCopied + " != " + contentLength); } mProgressReportingOutputStream.close(); Log.v("Download completed successfully."); return bytesCopied; } }
Java
/* Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.interpreter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.preference.PreferenceManager; /** * A provider that can be queried to obtain execution-related interpreter info. * * <p> * To create an interpreter APK, please extend this content provider and implement getDescriptor() * and getEnvironmentSettings().<br> * Please declare the provider in the android manifest xml (the authority values has to be set to * your_package_name.provider_name). * * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class InterpreterProvider extends ContentProvider { // private static final int BASE = 1; // private static final int ENVVARS = 2; // private static final int ARGS = 3; private static final int PROPERTIES = 1; private static final int ENVIRONMENT_VARIABLES = 2; private static final int ARGUMENTS = 3; private UriMatcher mUriMatcher; private SharedPreferences mPreferences; protected InterpreterDescriptor mDescriptor; protected Context mContext; public static final String MIME = "vnd.android.cursor.item/vnd.googlecode.interpreter"; protected InterpreterProvider() { mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); String auth = this.getClass().getName().toLowerCase(); // mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_BASE, BASE); // mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_ENV, ENVVARS); // mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_ARGS, ARGS); mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_PROPERTIES, PROPERTIES); mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_ENVIRONMENT_VARIABLES, ENVIRONMENT_VARIABLES); mUriMatcher.addURI(auth, InterpreterConstants.PROVIDER_ARGUMENTS, ARGUMENTS); } /** * Should return an instance instance of a class that implements interpreter descriptor. */ protected abstract InterpreterDescriptor getDescriptor(); /** * Should return a map of environment variables names and their values (or null if interpreter * does not require any environment variables). */ protected abstract Map<String, String> getEnvironmentSettings(); @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public String getType(Uri uri) { return MIME; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } @Override public boolean onCreate() { mDescriptor = getDescriptor(); mContext = getContext(); mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (!isInterpreterInstalled()) { return null; } Map<String, ? extends Object> map; switch (mUriMatcher.match(uri)) { case PROPERTIES: map = getProperties(); break; case ENVIRONMENT_VARIABLES: map = getEnvironmentSettings(); break; case ARGUMENTS: map = getArguments(); break; default: map = null; } return buildCursorFromMap(map); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } protected boolean isInterpreterInstalled() { return mPreferences.getBoolean(InterpreterConstants.INSTALLED_PREFERENCE_KEY, false); } protected Cursor buildCursorFromMap(Map<String, ? extends Object> map) { if (map == null) { return null; } MatrixCursor cursor = new MatrixCursor(map.keySet().toArray(new String[map.size()])); cursor.addRow(map.values()); return cursor; } // protected Map<String, Object> getSettings() { // Map<String, Object> values = new HashMap<String, Object>(); // values.put(InterpreterStrings.NAME, mDescriptor.getName()); // values.put(InterpreterStrings.NICE_NAME, mDescriptor.getNiceName()); // values.put(InterpreterStrings.EXTENSION, mDescriptor.getExtension()); // values.put(InterpreterStrings.BINARY, mDescriptor.getBinary(mContext).getAbsolutePath()); // values.put(InterpreterStrings.INTERACTIVE_COMMAND, // mDescriptor.getInteractiveCommand(mContext)); // values.put(InterpreterStrings.SCRIPT_COMMAND, mDescriptor.getScriptCommand(mContext)); // return values; // } private Map<String, String> getProperties() { Map<String, String> values = new HashMap<String, String>(); values.put(InterpreterPropertyNames.NAME, mDescriptor.getName()); values.put(InterpreterPropertyNames.NICE_NAME, mDescriptor.getNiceName()); values.put(InterpreterPropertyNames.EXTENSION, mDescriptor.getExtension()); values.put(InterpreterPropertyNames.BINARY, mDescriptor.getBinary(mContext).getAbsolutePath()); values.put(InterpreterPropertyNames.INTERACTIVE_COMMAND, mDescriptor .getInteractiveCommand(mContext)); values.put(InterpreterPropertyNames.SCRIPT_COMMAND, mDescriptor.getScriptCommand(mContext)); values.put(InterpreterPropertyNames.HAS_INTERACTIVE_MODE, Boolean.toString(mDescriptor .hasInteractiveMode())); return values; } protected Map<String, Object> getArguments() { Map<String, Object> values = new LinkedHashMap<String, Object>(); int column = 0; for (String argument : mDescriptor.getArguments(mContext)) { values.put(Integer.toString(column), argument); column++; } return values; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.interpreter; import java.io.File; import java.util.ArrayList; import java.util.List; import android.content.Context; /** * A description of the interpreters hosted by the SL4A project. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class Sl4aHostedInterpreter implements InterpreterDescriptor { public static final String BASE_INSTALL_URL = "http://android-scripting.googlecode.com/files/"; public static final String DALVIKVM = "/system/bin/dalvikvm"; public int getInterpreterVersion() { return getVersion(); } public int getExtrasVersion() { return getVersion(); } public int getScriptsVersion() { return getVersion(); } public String getInterpreterArchiveName() { return String.format("%s_r%s.zip", getName(), getInterpreterVersion()); } public String getExtrasArchiveName() { return String.format("%s_extras_r%s.zip", getName(), getExtrasVersion()); } public String getScriptsArchiveName() { return String.format("%s_scripts_r%s.zip", getName(), getScriptsVersion()); } public String getInterpreterArchiveUrl() { return BASE_INSTALL_URL + getInterpreterArchiveName(); } public String getExtrasArchiveUrl() { return BASE_INSTALL_URL + getExtrasArchiveName(); } public String getScriptsArchiveUrl() { return BASE_INSTALL_URL + getScriptsArchiveName(); } // TODO(damonkohler): This shouldn't be public. public File getExtrasPath(Context context) { if (!hasInterpreterArchive() && hasExtrasArchive()) { return new File(InterpreterConstants.SDCARD_ROOT + this.getClass().getPackage().getName() + InterpreterConstants.INTERPRETER_EXTRAS_ROOT, getName()); } return InterpreterUtils.getInterpreterRoot(context, getName()); } public String getInteractiveCommand(Context context) { return ""; } public String getScriptCommand(Context context) { return "%s"; } @Override public List<String> getArguments(Context context) { return new ArrayList<String>(); } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.interpreter; import java.io.File; import java.util.ArrayList; import java.util.List; import android.content.Context; /** * A description of the interpreters hosted by the SL4A project. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class PfaHostedInterpreter implements InterpreterDescriptor { public static final String BASE_INSTALL_URL = // "http://code.google.com/p/php-for-android/downloads/"; "http://php-for-android.googlecode.com/files/"; public static final String DALVIKVM = "/system/bin/dalvikvm"; public int getInterpreterVersion() { return getVersion(); } public int getExtrasVersion() { return getVersion(); } public int getScriptsVersion() { return getVersion(); } public String getInterpreterArchiveName() { return String.format("%s_r%s.zip", getName(), getInterpreterVersion()); } public String getExtrasArchiveName() { return String.format("%s_extras_r%s.zip", getName(), getExtrasVersion()); } public String getScriptsArchiveName() { return String.format("%s_scripts_r%s.zip", getName(), getScriptsVersion()); } public String getInterpreterArchiveUrl() { return BASE_INSTALL_URL + getInterpreterArchiveName(); } public String getExtrasArchiveUrl() { return BASE_INSTALL_URL + getExtrasArchiveName(); } public String getScriptsArchiveUrl() { return BASE_INSTALL_URL + getScriptsArchiveName(); } // TODO(damonkohler): This shouldn't be public. public File getExtrasPath(Context context) { if (!hasInterpreterArchive() && hasExtrasArchive()) { return new File(InterpreterConstants.SDCARD_ROOT + this.getClass().getPackage().getName() + InterpreterConstants.INTERPRETER_EXTRAS_ROOT, getName()); } return InterpreterUtils.getInterpreterRoot(context, getName()); } public String getInteractiveCommand(Context context) { return ""; } public String getScriptCommand(Context context) { return "%s"; } @Override public List<String> getArguments(Context context) { return new ArrayList<String>(); } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.future.FutureResult; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * AsyncTask for extracting ZIP files. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public class ZipExtractorTask extends AsyncTask<Void, Integer, Long> { private static enum Replace { YES, NO, YESTOALL, SKIPALL } private final File mInput; private final File mOutput; private final ProgressDialog mDialog; private Throwable mException; private int mProgress = 0; private final Context mContext; private boolean mReplaceAll; private final class ProgressReportingOutputStream extends FileOutputStream { private ProgressReportingOutputStream(File f) throws FileNotFoundException { super(f); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { super.write(buffer, offset, count); mProgress += count; publishProgress(mProgress); } } public ZipExtractorTask(String in, String out, Context context, boolean replaceAll) throws Sl4aException { super(); mInput = new File(in); mOutput = new File(out); if (!mOutput.exists()) { if (!mOutput.mkdirs()) { throw new Sl4aException("Failed to make directories: " + mOutput.getAbsolutePath()); } } if (context != null) { mDialog = new ProgressDialog(context); } else { mDialog = null; } mContext = context; mReplaceAll = replaceAll; } @Override protected void onPreExecute() { Log.v("Extracting " + mInput.getAbsolutePath() + " to " + mOutput.getAbsolutePath()); if (mDialog != null) { mDialog.setTitle("Extracting"); mDialog.setMessage(mInput.getName()); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancel(true); } }); mDialog.show(); } } @Override protected Long doInBackground(Void... params) { try { return unzip(); } catch (Exception e) { if (mInput.exists()) { // Clean up bad zip file. mInput.delete(); } mException = e; return null; } } @Override protected void onProgressUpdate(Integer... progress) { if (mDialog == null) { return; } if (progress.length > 1) { int max = progress[1]; mDialog.setMax(max); } else { mDialog.setProgress(progress[0].intValue()); } } @Override protected void onPostExecute(Long result) { if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } if (isCancelled()) { return; } if (mException != null) { Log.e("Zip extraction failed.", mException); } } @Override protected void onCancelled() { if (mDialog != null) { mDialog.setTitle("Extraction cancelled."); } } private long unzip() throws Exception { long extractedSize = 0l; Enumeration<? extends ZipEntry> entries; ZipFile zip = new ZipFile(mInput); long uncompressedSize = getOriginalSize(zip); publishProgress(0, (int) uncompressedSize); entries = zip.entries(); try { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { // Not all zip files actually include separate directory entries. // We'll just ignore them // and create them as necessary for each actual entry. continue; } File destination = new File(mOutput, entry.getName()); if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } if (destination.exists() && mContext != null && !mReplaceAll) { Replace answer = showDialog(entry.getName()); switch (answer) { case YES: break; case NO: continue; case YESTOALL: mReplaceAll = true; break; default: return extractedSize; } } ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination); extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream); outStream.close(); } } finally { try { zip.close(); } catch (Exception e) { // swallow this exception, we are only interested in the original one } } Log.v("Extraction is complete."); return extractedSize; } private long getOriginalSize(ZipFile file) { Enumeration<? extends ZipEntry> entries = file.entries(); long originalSize = 0l; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getSize() >= 0) { originalSize += entry.getSize(); } } return originalSize; } private Replace showDialog(final String name) { final FutureResult<Replace> mResult = new FutureResult<Replace>(); MainThread.run(mContext, new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle(String.format("Script \"%s\" already exist.", name)); builder.setMessage(String.format("Do you want to replace script \"%s\" ?", name)); DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Replace result = Replace.SKIPALL; switch (which) { case DialogInterface.BUTTON_POSITIVE: result = Replace.YES; break; case DialogInterface.BUTTON_NEGATIVE: result = Replace.NO; break; case DialogInterface.BUTTON_NEUTRAL: result = Replace.YESTOALL; break; } mResult.set(result); dialog.dismiss(); } }; builder.setNegativeButton("Skip", buttonListener); builder.setPositiveButton("Replace", buttonListener); builder.setNeutralButton("Replace All", buttonListener); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mResult.set(Replace.SKIPALL); dialog.dismiss(); } }); builder.show(); } }); try { return mResult.get(); } catch (InterruptedException e) { Log.e(e); } return null; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; /** * This listener asynchronously receives a task result whenever it finishes. Should be implemented * to avoid blocking on task's get() method. * * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public interface AsyncTaskListener<T> { public void onTaskFinished(T result, String message); }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; import java.io.File; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterUtils; /** * AsyncTask for installing interpreters. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class InterpreterInstaller extends AsyncTask<Void, Void, Boolean> { protected final InterpreterDescriptor mDescriptor; protected final AsyncTaskListener<Boolean> mTaskListener; protected final Queue<RequestCode> mTaskQueue; protected final Context mContext; protected final Handler mainThreadHandler; protected Handler mBackgroundHandler; protected volatile AsyncTask<Void, Integer, Long> mTaskHolder; protected final String mInterpreterRoot; protected static enum RequestCode { DOWNLOAD_INTERPRETER, DOWNLOAD_INTERPRETER_EXTRAS, DOWNLOAD_SCRIPTS, EXTRACT_INTERPRETER, EXTRACT_INTERPRETER_EXTRAS, EXTRACT_SCRIPTS } // Executed in the UI thread. private final Runnable mTaskStarter = new Runnable() { @Override public void run() { RequestCode task = mTaskQueue.peek(); try { AsyncTask<Void, Integer, Long> newTask = null; switch (task) { case DOWNLOAD_INTERPRETER: newTask = downloadInterpreter(); break; case DOWNLOAD_INTERPRETER_EXTRAS: newTask = downloadInterpreterExtras(); break; case DOWNLOAD_SCRIPTS: newTask = downloadScripts(); break; case EXTRACT_INTERPRETER: newTask = extractInterpreter(); break; case EXTRACT_INTERPRETER_EXTRAS: newTask = extractInterpreterExtras(); break; case EXTRACT_SCRIPTS: newTask = extractScripts(); break; } mTaskHolder = newTask.execute(); } catch (Exception e) { Log.v(e.getMessage(), e); } if (mBackgroundHandler != null) { mBackgroundHandler.post(mTaskWorker); } } }; // Executed in the background. private final Runnable mTaskWorker = new Runnable() { @Override public void run() { RequestCode request = mTaskQueue.peek(); try { if (mTaskHolder != null && mTaskHolder.get() != null) { mTaskQueue.remove(); mTaskHolder = null; // Post processing. if (request == RequestCode.EXTRACT_INTERPRETER && !chmodIntepreter()) { // Chmod returned false. Looper.myLooper().quit(); } else if (mTaskQueue.size() == 0) { // We're done here. Looper.myLooper().quit(); return; } else if (mainThreadHandler != null) { // There's still some work to do. mainThreadHandler.post(mTaskStarter); return; } } } catch (Exception e) { Log.e(e); } // Something went wrong... switch (request) { case DOWNLOAD_INTERPRETER: Log.e("Downloading interpreter failed."); break; case DOWNLOAD_INTERPRETER_EXTRAS: Log.e("Downloading interpreter extras failed."); break; case DOWNLOAD_SCRIPTS: Log.e("Downloading scripts failed."); break; case EXTRACT_INTERPRETER: Log.e("Extracting interpreter failed."); break; case EXTRACT_INTERPRETER_EXTRAS: Log.e("Extracting interpreter extras failed."); break; case EXTRACT_SCRIPTS: Log.e("Extracting scripts failed."); break; } Looper.myLooper().quit(); } }; // TODO(Alexey): Add Javadoc. public InterpreterInstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> taskListener) throws Sl4aException { super(); mDescriptor = descriptor; mContext = context; mTaskListener = taskListener; mainThreadHandler = new Handler(); mTaskQueue = new LinkedList<RequestCode>(); String packageName = mDescriptor.getClass().getPackage().getName(); if (packageName.length() == 0) { throw new Sl4aException("Interpreter package name is empty."); } mInterpreterRoot = InterpreterConstants.SDCARD_ROOT + packageName; if (mDescriptor == null) { throw new Sl4aException("Interpreter description not provided."); } if (mDescriptor.getName() == null) { throw new Sl4aException("Interpreter not specified."); } if (isInstalled()) { throw new Sl4aException("Interpreter is installed."); } if (mDescriptor.hasInterpreterArchive()) { mTaskQueue.offer(RequestCode.DOWNLOAD_INTERPRETER); mTaskQueue.offer(RequestCode.EXTRACT_INTERPRETER); } if (mDescriptor.hasExtrasArchive()) { mTaskQueue.offer(RequestCode.DOWNLOAD_INTERPRETER_EXTRAS); mTaskQueue.offer(RequestCode.EXTRACT_INTERPRETER_EXTRAS); } if (mDescriptor.hasScriptsArchive()) { mTaskQueue.offer(RequestCode.DOWNLOAD_SCRIPTS); mTaskQueue.offer(RequestCode.EXTRACT_SCRIPTS); } } @Override protected Boolean doInBackground(Void... params) { new Thread(new Runnable() { @Override public void run() { executeInBackground(); final boolean result = (mTaskQueue.size() == 0); mainThreadHandler.post(new Runnable() { @Override public void run() { finish(result); } }); } }).start(); return true; } private boolean executeInBackground() { File root = new File(mInterpreterRoot); if (root.exists()) { FileUtils.delete(root); } if (!root.mkdirs()) { Log.e("Failed to make directories: " + root.getAbsolutePath()); return false; } if (Looper.myLooper() == null) { Looper.prepare(); } mBackgroundHandler = new Handler(Looper.myLooper()); mainThreadHandler.post(mTaskStarter); Looper.loop(); // Have we executed all the tasks? return (mTaskQueue.size() == 0); } protected void finish(boolean result) { if (result && setup()) { mTaskListener.onTaskFinished(true, "Installation successful."); } else { if (mTaskHolder != null) { mTaskHolder.cancel(true); } cleanup(); mTaskListener.onTaskFinished(false, "Installation failed."); } } protected AsyncTask<Void, Integer, Long> download(String in) throws MalformedURLException { String out = mInterpreterRoot; return new UrlDownloaderTask(in, out, mContext); } protected AsyncTask<Void, Integer, Long> downloadInterpreter() throws MalformedURLException { return download(mDescriptor.getInterpreterArchiveUrl()); } protected AsyncTask<Void, Integer, Long> downloadInterpreterExtras() throws MalformedURLException { return download(mDescriptor.getExtrasArchiveUrl()); } protected AsyncTask<Void, Integer, Long> downloadScripts() throws MalformedURLException { return download(mDescriptor.getScriptsArchiveUrl()); } protected AsyncTask<Void, Integer, Long> extract(String in, String out, boolean replaceAll) throws Sl4aException { return new ZipExtractorTask(in, out, mContext, replaceAll); } protected AsyncTask<Void, Integer, Long> extractInterpreter() throws Sl4aException { String in = new File(mInterpreterRoot, mDescriptor.getInterpreterArchiveName()).getAbsolutePath(); String out = InterpreterUtils.getInterpreterRoot(mContext).getAbsolutePath(); return extract(in, out, true); } protected AsyncTask<Void, Integer, Long> extractInterpreterExtras() throws Sl4aException { String in = new File(mInterpreterRoot, mDescriptor.getExtrasArchiveName()).getAbsolutePath(); String out = mInterpreterRoot + InterpreterConstants.INTERPRETER_EXTRAS_ROOT; return extract(in, out, true); } protected AsyncTask<Void, Integer, Long> extractScripts() throws Sl4aException { String in = new File(mInterpreterRoot, mDescriptor.getScriptsArchiveName()).getAbsolutePath(); String out = InterpreterConstants.SCRIPTS_ROOT; return extract(in, out, false); } protected boolean chmodIntepreter() { int dataChmodErrno; boolean interpreterChmodSuccess; try { dataChmodErrno = FileUtils.chmod(InterpreterUtils.getInterpreterRoot(mContext), 0755); interpreterChmodSuccess = FileUtils.recursiveChmod(InterpreterUtils.getInterpreterRoot(mContext, mDescriptor .getName()), 0755); } catch (Exception e) { Log.e(e); return false; } return dataChmodErrno == 0 && interpreterChmodSuccess; } protected boolean isInstalled() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); return preferences.getBoolean(InterpreterConstants.INSTALLED_PREFERENCE_KEY, false); // return preferences.getBoolean(InterpreterConstants.INSTALL_PREF, false); } private void cleanup() { List<File> directories = new ArrayList<File>(); directories.add(new File(mInterpreterRoot)); if (mDescriptor.hasInterpreterArchive()) { if (!mTaskQueue.contains(RequestCode.EXTRACT_INTERPRETER)) { directories.add(InterpreterUtils.getInterpreterRoot(mContext, mDescriptor.getName())); } } for (File directory : directories) { FileUtils.delete(directory); } } protected abstract boolean setup(); }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.preference.PreferenceManager; import com.googlecode.android_scripting.exception.Sl4aException; import com.googlecode.android_scripting.interpreter.InterpreterConstants; import com.googlecode.android_scripting.interpreter.InterpreterDescriptor; import com.googlecode.android_scripting.interpreter.InterpreterUtils; /** * AsyncTask for uninstalling interpreters. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public abstract class InterpreterUninstaller extends AsyncTask<Void, Void, Boolean> { protected final InterpreterDescriptor mDescriptor; protected final Context mContext; protected final ProgressDialog mDialog; protected final AsyncTaskListener<Boolean> mListener; protected final String mInterpreterRoot; public InterpreterUninstaller(InterpreterDescriptor descriptor, Context context, AsyncTaskListener<Boolean> listener) throws Sl4aException { super(); mDescriptor = descriptor; mContext = context; mListener = listener; String packageName = mDescriptor.getClass().getPackage().getName(); if (packageName.length() == 0) { throw new Sl4aException("Interpreter package name is empty."); } mInterpreterRoot = InterpreterConstants.SDCARD_ROOT + packageName; if (mDescriptor == null) { throw new Sl4aException("Interpreter description not provided."); } if (mDescriptor.getName() == null) { throw new Sl4aException("Interpreter not specified."); } if (!isInstalled()) { throw new Sl4aException("Interpreter not installed."); } if (context != null) { mDialog = new ProgressDialog(context); } else { mDialog = null; } } public final void execute() { execute(null, null, null); } @Override protected void onPreExecute() { if (mDialog != null) { mDialog.setMessage("Uninstalling " + mDescriptor.getNiceName()); mDialog.setIndeterminate(true); mDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancel(true); } }); mDialog.show(); } } @Override protected void onPostExecute(Boolean result) { if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } if (result) { mListener.onTaskFinished(result, "Uninstallation successful."); } else { mListener.onTaskFinished(result, "Uninstallation failed."); } } @Override protected Boolean doInBackground(Void... params) { List<File> directories = new ArrayList<File>(); directories.add(new File(mInterpreterRoot)); if (mDescriptor.hasInterpreterArchive()) { directories.add(InterpreterUtils.getInterpreterRoot(mContext, mDescriptor.getName())); } for (File directory : directories) { FileUtils.delete(directory); } return cleanup(); } protected boolean isInstalled() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext); return preferences.getBoolean(InterpreterConstants.INSTALLED_PREFERENCE_KEY, false); // return preferences.getBoolean(InterpreterConstants.INSTALL_PREF, false); } protected abstract boolean cleanup(); }
Java
/** * StringCharConverter * * @author Chris Pratt * * 1/5/2012 */ package com.anodyzed.onyx.type; public class StringCharConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Character's * * @param from Either a CharSequence or a Character * @param to The type to convert to * @return Either a Character or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (((CharSequence)from).length() > 0) ? (T)new Character(((CharSequence)from).charAt(0)) : null; } else if(from instanceof Character) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Character",from); } //convert } //*StringCharConverter
Java
/** * StringEnumConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringEnumConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Enum's * * @param from Either a CharSequence or an Enum * @param to The type to convert to * @return Either an Enum or a String */ @Override @SuppressWarnings({"unchecked","rawtypes"}) public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { try { return to.cast(Enum.valueOf((Class<? extends Enum>)to,from.toString())); } catch(IllegalArgumentException x) { throw new ConversionException("Unable to convert ''{0}'' ({0.class.name}) to a {1.name}",from,to,x); } } else if(from instanceof Enum) { return to.cast(((Enum<?>)from).name()); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor an Enum",from); } //convert } //*StringEnumConverter
Java
/** * StringFloatConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringFloatConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Float's * * @param from Either a CharSequence or a Float * @param to The type to convert to * @return Either a Float or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Float(from.toString()); } else if(from instanceof Float) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Float",from); } //convert } //*StringFloatConverter
Java
/** * StringByteConverter * * @author Chris Pratt * * 1/5/2012 */ package com.anodyzed.onyx.type; public class StringByteConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Byte's * * @param from Either a CharSequence or a Byte * @param to The type to convert to * @return Either a Byte or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (((CharSequence)from).length() > 0) ? (T)new Byte((byte)((CharSequence)from).charAt(0)) : null; } else if(from instanceof Byte) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Byte",from); } //convert } //*StringByteConverter
Java
/** * StringIntConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringIntConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Integer's * * @param from Either a CharSequence or an Integer * @param to The type to convert to * @return Either an Integer or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Integer(from.toString()); } else if(from instanceof Integer) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor an Integer",from); } //convert } //*StringIntConverter
Java
/** * StringShortConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringShortConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Short's * * @param from Either a CharSequence or a Short * @param to The type to convert to * @return Either a Short or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Short(from.toString()); } else if(from instanceof Short) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Short",from); } //convert } //*StringShortConverter
Java
/** * StringDateConverter - Converts To/From ISO Date Strings * * @author Chris Pratt * * 2/27/2012 */ package com.anodyzed.onyx.type; import com.anodyzed.onyx.util.Convert; import java.util.Date; public class StringDateConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Date's * * @param from Either a CharSequence or an Date * @param to The type to convert to * @return Either an Date or a String */ @Override public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { return to.cast(Convert.toDate(from.toString())); } else if(from instanceof Date) { return to.cast(Convert.toISOString((Date)from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Date",from); } //convert } //*StringDateConverter
Java
/** * StringDoubleConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringDoubleConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Double's * * @param from Either a CharSequence or a Double * @param to The type to convert to * @return Either a Double or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Double(from.toString()); } else if(from instanceof Double) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Double",from); } //convert } //*StringDoubleConverter
Java
/** * BigDecimalDoubleConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; import java.math.BigDecimal; public class BigDecimalDoubleConverter implements Converter { /** * Convert BigDecimals to/from Double's * * @param from Either a BigDecimal or a Double * @param to The type to convert to * @return Either a Double or a BigDecimal */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof BigDecimal) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Double(((BigDecimal)from).doubleValue()); } else if(from instanceof Double) { return to.cast(BigDecimal.valueOf((Double)from)); } throw new ConversionException("{0.class.name} is neither a BigDecimal nor a Double",from); } //convert } //*BigDecimalDoubleConverter
Java
/** * StringLongConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; public class StringLongConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Long's * * @param from Either a CharSequence or a Long * @param to The type to convert to * @return Either a Long or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)new Long(from.toString()); } else if(from instanceof Long) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Long",from); } //convert } //*StringLongConverter
Java
/** * ConverterFactory * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ConverterFactory { /** * ConverterKey */ private static class ConverterKey { private Class<?> type1; private Class<?> type2; /** * Constructor * * @param t1 One of the Conversion Types * @param t2 The other Conversion Type */ public ConverterKey (Class<?> t1,Class<?> t2) { this.type1 = t1; this.type2 = t2; } //ConverterKey /** * Computer a Hash Bucket Location that allows the types to be in any order * * @return Hash Index */ @Override public int hashCode () { return type1.hashCode() + type2.hashCode(); } //hashCode /** * Consider the Converter Key equal if the types are the same, regardless of their order * * @param o The ConverterKey in question * @return true if equivalent */ @Override public boolean equals (Object o) { return (o instanceof ConverterKey) && ((((ConverterKey)o).type1.isAssignableFrom(type1) && ((ConverterKey)o).type2.isAssignableFrom(type2)) || (((ConverterKey)o).type1.isAssignableFrom(type2) && ((ConverterKey)o).type2.isAssignableFrom(type1))); } //equals } //*ConverterKey private static ConverterFactory defaultFactory = null; protected static Map<ConverterKey,Converter> defaults; static { defaults = new HashMap<>(); Converter converter = new StringBooleanConverter(); defaults.put(new ConverterKey(CharSequence.class,Boolean.class),converter); defaults.put(new ConverterKey(CharSequence.class,Boolean.TYPE),converter); converter = new StringByteConverter(); defaults.put(new ConverterKey(CharSequence.class,Byte.class),converter); defaults.put(new ConverterKey(CharSequence.class,Byte.TYPE),converter); converter = new StringCharConverter(); defaults.put(new ConverterKey(CharSequence.class,Character.class),converter); defaults.put(new ConverterKey(CharSequence.class,Character.TYPE),converter); converter = new StringDoubleConverter(); defaults.put(new ConverterKey(CharSequence.class,Double.class),converter); defaults.put(new ConverterKey(CharSequence.class,Double.TYPE),converter); converter = new StringFloatConverter(); defaults.put(new ConverterKey(CharSequence.class,Float.class),converter); defaults.put(new ConverterKey(CharSequence.class,Float.TYPE),converter); converter = new StringIntConverter(); defaults.put(new ConverterKey(CharSequence.class,Integer.class),converter); defaults.put(new ConverterKey(CharSequence.class,Integer.TYPE),converter); converter = new StringLongConverter(); defaults.put(new ConverterKey(CharSequence.class,Long.class),converter); defaults.put(new ConverterKey(CharSequence.class,Long.TYPE),converter); converter = new StringShortConverter(); defaults.put(new ConverterKey(CharSequence.class,Short.class),converter); defaults.put(new ConverterKey(CharSequence.class,Short.TYPE),converter); defaults.put(new ConverterKey(CharSequence.class,Enum.class),new StringEnumConverter()); defaults.put(new ConverterKey(CharSequence.class,Date.class),new StringDateConverter()); defaults.put(new ConverterKey(Calendar.class,Date.class),new DateCalendarConverter()); converter = new BigDecimalDoubleConverter(); defaults.put(new ConverterKey(BigDecimal.class,Double.class),converter); defaults.put(new ConverterKey(BigDecimal.class,Double.TYPE),converter); } protected Map<ConverterKey,Converter> converters; /** * Constructor */ public ConverterFactory () { converters = new HashMap<>(defaults); } //ConverterFactory /** * Add a new Converter to this Factory instance * * @param t1 One of the conversion types * @param t2 The other conversion type * @param converter The converter implementation */ public void addConverter (Class<?> t1,Class<?> t2,Converter converter) { converters.put(new ConverterKey(t1,t2),converter); } //addConverter /** * Get a Converter for the specified types * * @param t1 One of the conversion types * @param t2 The other conversion types * @return The converter implementation */ public Converter getConverter (Class<?> t1,Class<?> t2) { ConverterKey key = new ConverterKey(t1,t2); Converter converter = converters.get(key); if(converter == null) { for(Map.Entry<ConverterKey,Converter> entry : converters.entrySet()) { if(key.equals(entry.getKey())) { return entry.getValue(); } } } return converter; } //getConverter /** * Add a default Converter to be used when converting between the specified types by any Factories created after this point * * @param t1 One of the conversion types * @param t2 The other conversion type * @param converter The default converter implementation */ public static void addDefaultConverter (Class<?> t1,Class<?> t2,Converter converter) { defaults.put(new ConverterKey(t1,t2),converter); } //addDefaultConverter /** * Retrieve the default converter factory. * * NB: The only way to add converters to the returned instance is to add * additional default converters * * @return The Default Converter Factory */ public static ConverterFactory getDefaultFactory () { if(defaultFactory == null) { defaultFactory = new ConverterFactory() { { converters = defaults; } /** * Add a new Converter to this Factory instance * * @param t1 One of the conversion types * @param t2 The other conversion type * @param converter The converter implementation */ @Override public void addConverter(Class<? > t1, Class<? > t2, Converter converter) { throw new UnsupportedOperationException("The Default Converter does not allow Converters to be added at runtime"); } //addConverter }; //*ConverterFactory } return defaultFactory; } //getDefaultFactory } //*ConverterFactory
Java
/** * StringBooleanConverter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; import com.anodyzed.onyx.util.Convert; public class StringBooleanConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Boolean's * * @param from Either a CharSequence or a Boolean * @param to The type to convert to * @return Either a Boolean or a String */ @Override @SuppressWarnings("unchecked") public <T> T convert (Object from,Class<T> to) { if(from instanceof CharSequence) { // Should use to.cast() to avoid @SuppressWarnings, but it doesn't // properly support primitives return (T)Convert.toBoolean(from.toString(),null); } else if(from instanceof Boolean) { return to.cast(String.valueOf(from)); } throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor a Boolean",from); } //convert } //*StringBooleanConverter
Java
/** * ConversionException * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; import com.anodyzed.onyx.util.FormattedRuntimeException; @SuppressWarnings("serial") public class ConversionException extends FormattedRuntimeException { /** * No-arg Constructor */ public ConversionException () { super(); } //ConversionException /** * Constructor * * @param msg A Descriptive Message Format String about the cause of the Exception * @param args Replacement Arguments for the Format String */ public ConversionException (String msg,Object... args) { super(msg,args); } //ConversionException /** * Constructor * * @param cause The Throwable that initiated this Exception Chain */ public ConversionException (Throwable cause) { super(cause); } //ConversionException } //*ConversionException
Java
/** * DateCalendarConverter * * @author Chris Pratt * * 12/16/2011 */ package com.anodyzed.onyx.type; import java.util.Calendar; import java.util.Date; public class DateCalendarConverter implements Converter { /** * Convert Strings (or CharSequence's) to/from Enum's * * @param from Either a CharSequence or an Enum * @param to The type to convert to * @return Either an Enum or a String */ @Override public <T> T convert (Object from,Class<T> to) { if(from instanceof Date) { Calendar cal = Calendar.getInstance(); cal.setTime((Date)from); return to.cast(cal); } else if(from instanceof Calendar) { return to.cast(((Calendar)from).getTime()); } throw new ConversionException("{0.class.name} is neither a Date nor a Calendar",from); } //convert } //*DateCalendarConverter
Java
/** * Converter * * @author Chris Pratt * * 12/15/2011 */ package com.anodyzed.onyx.type; /** * Implementations of this Interface are registered with the * {@link ConverterFactory} to convert bi-directionally between two types. * * The {@code convert} method should recognize either type as input and return * the opposite time on output. */ public interface Converter { /** * Convert the supplied Object from its initial format to the expected resulting format. * * @param from The Object to convert from * @param to The Class to convert to * @return The converted Object */ <T> T convert(Object from,Class<T> to); } //#Converter
Java
package com.anodyzed.onyx.bean; /** * BeanWrapper * * @author UPRATCH * @since 4/27/12 */ public interface BeanWrapper { /** * Get the Wrapped Bean * * @return The Wrapped Bean */ Object getBean(); } //#BeanWrapper
Java
/** * BeanUtils * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.bean; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.text.TextFormat; import com.anodyzed.onyx.type.Converter; import com.anodyzed.onyx.type.ConverterFactory; import com.anodyzed.onyx.util.Convert; import com.anodyzed.onyx.util.Misc; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class BeanUtils { private static final Log log = LogBuilder.getLogger(); /** * Private Constructor */ private BeanUtils () { } //BeanUtils /** * Get the Property Descriptor of the property in the supplied class * * @param clazz The Class to Introspect * @param property The Name of the Property to locate * @return The Property Descriptor * @throws IntrospectionException if we get lost in introspection */ public static PropertyDescriptor getDescriptor (Class<?> clazz,String property) throws IntrospectionException { for(PropertyDescriptor descriptor : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { if(property.equals(descriptor.getName())) { return descriptor; } } return null; } //getDescriptor /** * Get the Property Accessor for the specified property name * * @param clazz The Bean Class * @param property The Property Name * @return The Property Accessor Method * @throws IntrospectionException if we get lost in introspection */ public static Method getAccessor (Class<?> clazz,String property) throws IntrospectionException { PropertyDescriptor descriptor = getDescriptor(clazz,property); return (descriptor != null) ? descriptor.getReadMethod() : null; } //getAccessor /** * Get the List of Accessors * * @param clazz The Bean Class * @return The List of Accessor Methods * @throws IntrospectionException if we get lost in introspection */ public static List<Method> getAccessors (Class<?> clazz) throws IntrospectionException { Method accessor; List<Method> accessors = new ArrayList<>(); for(PropertyDescriptor descriptor : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { if((accessor = descriptor.getReadMethod()) != null) { accessors.add(accessor); } } return accessors; } //getAccessors /** * Get the List of Properties * * @param clazz The Bean Class * @return The Set of Property Names * @throws IntrospectionException if we get lost in introspection */ public static Set<String> getProperties (Class<?> clazz) throws IntrospectionException { Set<String> properties = new HashSet<>(); for(PropertyDescriptor descriptor : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { if(descriptor.getReadMethod() != null) { properties.add(descriptor.getName()); } } return properties; } //getProperties /** * Get the Property Mutator for the specified property name * * @param clazz The Bean Class * @param property The Property Name * @return The Property Mutator Method * @throws IntrospectionException if we get lost in introspection */ public static Method getMutator (Class<?> clazz,String property) throws IntrospectionException { PropertyDescriptor descriptor = getDescriptor(clazz,property); return (descriptor != null) ? descriptor.getWriteMethod() : null; } //getMutator /** * Get the Type of the Specified Property in the supplied Class * * @param clazz The Bean Class * @param property The Property Name * @return The Property Type Class * @throws IntrospectionException if we get lost in introspection */ public static Class<?> getPropertyType (Class<?> clazz,String property) throws IntrospectionException { PropertyDescriptor descriptor = getDescriptor(clazz,property); return (descriptor != null) ? descriptor.getPropertyType() : null; } //getPropertyType /** * Get the Class for elements in the named Collection or Array * * @param parent The Bean Context * @param property The (possibly dot notated) bean property * @return The element type */ public static Class<?> getElementType (Object parent,String property) throws IntrospectionException { int dot = property.lastIndexOf('.'); Object bean = (dot != -1) ? getValue(parent,property.substring(0,dot)) : parent; String prop = (dot != -1) ? property.substring(dot + 1) : property; Class<?> cls = bean.getClass(); try { Field field = cls.getDeclaredField(prop); if(field.isAnnotationPresent(RTTI.class)) { return field.getAnnotation(RTTI.class).value(); } else { log.trace("No RTTI Annotation Present on {0.declaringClass.name}.{0.name}",field); } } catch(NoSuchFieldException x) { log.trace("Can''t locate the {0} field of {1}",property,parent,x); } Method accessor = getAccessor(cls,prop); if(accessor != null) { Type type = accessor.getGenericReturnType(); if(type instanceof ParameterizedType) { Type[] args = ((ParameterizedType)type).getActualTypeArguments(); if((args != null) && (args.length > 0) && (args[0] instanceof Class<?>)) { return (Class<?>)args[0]; } } } else { log.trace("No Accessor for {0} in {1.name}",prop,cls); } if((bean instanceof Collection<?>) && !((Collection<?>)bean).isEmpty()) { Object testval = ((Collection<?>)bean).iterator().next(); if(testval != null) { return testval.getClass(); } } return null; } //getElementType /** * Turn the Method Name into the Property it manages by removing "get", "set", * or "is" and lowercasing the new first character. * * @param method The Property management method * @return The property name */ public static String toPropertyName (Method method) { String name = method.getName(); if((name.startsWith("get") || name.startsWith("set")) && (name.length() > 3)) { return Character.toLowerCase(name.charAt(3)) + name.substring(4); } else if(name.startsWith("is") && (name.length() > 2)) { return Character.toLowerCase(name.charAt(2)) + name.substring(3); } return name; } //toPropertyName /** * Determine whether the supplied class contains a, possibly dot-notated, * property with the specified name. * * @param clazz The Bean Class * @param property the dot-notated property name * @return true if available * @throws IntrospectionException if we get lost in introspection */ public static boolean containsProperty (Class<?> clazz,String property) throws IntrospectionException { if(property != null) { int pos; String parent = property,child = null; if((pos = property.indexOf('.')) != -1) { child = property.substring(pos + 1); parent = property.substring(0,pos); } if(getProperties(clazz).contains(parent)) { return (child == null) || containsProperty(getAccessor(clazz,parent).getReturnType(),child); } } return false; } //containsProperty /** * Check whether the bean contains the value of the (possibly dot notated) Property * * @param bean The Bean to access * @param property The Property name * @param factory The property value conversion factory * @return The property value from the bean * @throws IntrospectionException if we get lost in introspection */ public static boolean contains (Object bean,String property,ConverterFactory factory) throws IntrospectionException { if(bean != null) { Class<?> cls = bean.getClass(); try { int dot = property.indexOf('.'); if(dot == -1) { if(property.equals("size") || property.equals("length")) { if(bean instanceof Collection<?>) { return true; } else if(bean instanceof Map<?,?>) { return true; } else if(bean instanceof String) { return true; } else if(cls.isArray()) { return true; } else if(getAccessor(cls,property) != null) { return true; } else { try { return cls.getMethod(property) != null; } catch(NoSuchMethodException x) { // Just return false } } } else if(bean instanceof Map<?,?>) { return ((Map<?,?>)bean).containsKey(property); } else { return getAccessor(cls,property) != null; } } else { Object subbean = getBean(bean,property.substring(0,dot),factory); return (subbean != null) && contains(subbean,property.substring(dot + 1)); } } catch(IllegalAccessException x) { Class<?>[] interfaces = cls.getInterfaces(); for(Class<?> i : interfaces) { if(getAccessor(i,property) != null) { return true; } } IntrospectionException y = new IntrospectionException("Unable to locate " + property + " property of " + bean); y.initCause(x); throw y; } catch(InvocationTargetException x) { IntrospectionException y = new IntrospectionException("Unable to locate " + property + " property of " + bean); y.initCause(x); throw y; } } return false; } //contains /** * Check whether the bean contains the value of the (possibly dot notated) Property * * @param bean The Bean to access * @param property The Property name * @return The property value from the bean * @throws IntrospectionException if we get lost in introspection */ public static boolean contains (Object bean,String property) throws IntrospectionException { return contains(bean,property,ConverterFactory.getDefaultFactory()); } //contains /** * Get the Bean property of the supplied bean * * @param bean The parent bean * @param property The bean child name * @param factory The Type Converter Factory * @return The child bean * @throws IntrospectionException if we get lost in introspection * @throws IllegalAccessException if we try to touch something we're not allowed to * @throws InvocationTargetException if something goes wrong within the constructor of the bean */ private static Object getBean (Object bean,String property,ConverterFactory factory) throws IntrospectionException, IllegalAccessException, InvocationTargetException { int l; String index = null; String prop = property; if((l = property.indexOf('[')) != -1) { int r = property.indexOf(']',l); if(r != -1) { index = property.substring(l + 1,r); } prop = property.substring(0,l); } Object ret; Method accessor = null; Class<?> beantype = bean.getClass(); if(bean instanceof Map<?,?>) { ret = ((Map<?,?>)bean).get(prop); } else { accessor = getAccessor(beantype,prop); ret = (accessor != null) ? accessor.invoke(bean) : null; } if((ret != null) && (index != null)) { if(ret instanceof Map<?,?>) { Class<?> keytype = null; try { Field field = beantype.getDeclaredField(prop); if(field.isAnnotationPresent(RTTI.class)) { keytype = field.getAnnotation(RTTI.class).key(); } else { log.trace("No RTTI Annotation Present getting {0.declaringClass.name}.{0.name} map",field); } } catch(NoSuchFieldException x) { log.trace("Can''t locate the {0} field of {1}",prop,bean,x); } if(keytype == null) { if(accessor == null) { accessor = getAccessor(beantype,prop); } if(accessor != null) { Type type = accessor.getGenericReturnType(); if(type instanceof ParameterizedType) { Type[] args = ((ParameterizedType)type).getActualTypeArguments(); if((args != null) && (args.length > 0)) { if(args[0] instanceof Class<?>) { keytype = (Class<?>)args[0]; } } } if(keytype == null) { if(!((Map<?,?>)ret).isEmpty()) { Object testkey = ((Map<?,?>)ret).keySet().iterator().next(); if(testkey != null) { keytype = testkey.getClass(); } } } } } ret = ((Map<?,?>)ret).get(convertArg(index,keytype,factory)); } else if(Misc.isNumeric(index)) { int ndx = Convert.toInt(index,0); if(ret instanceof List<?>) { ret = (((List<?>)ret).size() > ndx) ? ((List<?>)ret).get(ndx) : null; } else if(ret.getClass().isArray()) { ret = (Array.getLength(ret) > ndx) ? Array.get(ret,ndx) : null; } } } return ret; } //getBean /** * Get the value of the (possibly dot notated) Property from the Bean * * @param bean The Bean to access * @param property The Property name * @param factory The Type Converter Factory * @return The property value from the bean * @throws IntrospectionException if we get lost in introspection */ public static Object getValue (Object bean,String property,ConverterFactory factory) throws IntrospectionException { property = property.trim(); char ch = property.charAt(0); if(((ch == '"') || (ch == '\'')) && (property.charAt(property.length() - 1) == ch)) { return property.substring(1,property.length() - 1); } else if(bean != null) { Method accessor; Class<?> cls = bean.getClass(); try { int dot = property.indexOf('.'); if(dot == -1) { if(property.equals("size") || property.equals("length")) { if(bean instanceof Collection<?>) { return ((Collection<?>)bean).size(); } else if(bean instanceof Map<?,?>) { return ((Map<?,?>)bean).size(); } else if(bean instanceof String) { return ((String)bean).length(); } else if(cls.isArray()) { return Array.getLength(bean); } else if((accessor = getAccessor(cls,property)) != null) { return accessor.invoke(bean); } else { try { return cls.getMethod(property).invoke(bean); } catch(NoSuchMethodException x) { // Just return null } } } else { return getBean(bean,property,factory); } } else { Object subbean = getBean(bean,property.substring(0,dot),factory); return (subbean != null) ? getValue(subbean,property.substring(dot + 1)) : null; } } catch(IllegalAccessException x) { Class<?>[] interfaces = cls.getInterfaces(); for(Class<?> i : interfaces) { try { if((accessor = getAccessor(i,property)) != null) { return accessor.invoke(bean); } } catch(IllegalAccessException y) { // Nop } catch(InvocationTargetException y) { IntrospectionException z = new IntrospectionException("Unable to introspect " + property + " property of " + bean); z.initCause(y); throw z; } } IntrospectionException y = new IntrospectionException("Unable to introspect " + property + " property of " + bean); y.initCause(x); throw y; } catch(InvocationTargetException x) { IntrospectionException y = new IntrospectionException("Unable to introspect " + property + " property of " + bean); y.initCause(x); throw y; } } return null; } //getValue /** * Get the value of the (possibly dot notated) Property from the Bean * * @param bean The Bean to access * @param property The Property name * @return The property value from the bean * @throws IntrospectionException if we get lost in introspection */ public static Object getValue (Object bean,String property) throws IntrospectionException { return getValue(bean,property,ConverterFactory.getDefaultFactory()); } //getValue /** * Get the string value of the (possibly dot notated) Property from the * supplied bean * * @param bean The Bean to access * @param property The property name * @return The String property value */ public static String getString (Object bean,String property) { try { return String.valueOf(getValue(bean,property)); } catch(IntrospectionException x) { log.warn("Error Introspecting {1} property of {0}",bean,property,x); return "null"; } } //getString /** * Test if the supplied primitive Type matches the supplied wrapper type * (i.e. int and Integer) * * @param primitive the Class with isPrimitive == true * @param wrapper the Class is isPrimitive == false * @return true if equivalent */ private static boolean primitiveEquivalence (Class<?> primitive,Class<?> wrapper) { if(primitive == Boolean.TYPE) { return wrapper.equals(Boolean.class); } else if(primitive == Byte.TYPE) { return wrapper.equals(Byte.class); } else if(primitive == Character.TYPE) { return wrapper.equals(Character.class); } else if(primitive == Double.TYPE) { return wrapper.equals(Double.class); } else if(primitive == Float.TYPE) { return wrapper.equals(Float.class); } else if(primitive == Integer.TYPE) { return wrapper.equals(Integer.class); } else if(primitive == Long.TYPE) { return wrapper.equals(Long.class); } else if(primitive == Short.TYPE) { return wrapper.equals(Short.class); } return false; } //primitiveEquivalence /** * Test the supplied types for equivalence including equivalence between * primitives and their corresponding wrapper classes. * * @param type1 The first type * @param type2 The other type * @return true if equivalent */ public static boolean equivalent (Class<?> type1,Class<?> type2) { if(!type1.isAssignableFrom(type2)) { if(type1.isPrimitive()) { return primitiveEquivalence(type1,type2); } else if(type2.isPrimitive()) { return primitiveEquivalence(type2,type1); } return false; } return true; } //equivalent /** * Test whether the supplied type is numeric * * @param type The questionable type * @return true if numeric */ public static boolean isNumeric (Class<?> type) { return Number.class.isAssignableFrom(type) || (type.isPrimitive() && (type == Long.TYPE) || (type == Integer.TYPE) || (type == Short.TYPE) || (type == Byte.TYPE) || (type == Double.TYPE) || (type == Float.TYPE)); } //isNumeric /** * Test whether a number of the first type can be assigned to a number of * the second type (i.e. an Int can always be assigned to a long). * * NB: Same type match (e.g. int -> int or even long -> Long) would have * been caught by {@link #equivalent} * * @param type1 The Left Type * @param type2 The Right Type * @return true if numerically assignable */ private static boolean numericallyAssignable (Class<?> type1,Class<?> type2) { if(isNumeric(type1) && isNumeric(type2)) { if((type2 == Long.TYPE) || (type2 == Long.class)) { return (type1 == Integer.TYPE) || (type1 == Integer.class) || (type1 == Short.TYPE) || (type1 == Short.class) || (type1 == Byte.TYPE) || (type1 == Byte.class); } else if((type2 == Integer.TYPE) || (type2 == Integer.class)) { return (type1 == Short.TYPE) || (type1 == Short.class) || (type1 == Byte.TYPE) || (type1 == Byte.class); } else if((type2 == Short.TYPE) || (type2 == Short.class)) { return (type1 == Byte.TYPE) || (type1 == Byte.class); } else if((type2 == Double.TYPE) || (type2 == Double.class)) { return (type1 == Float.TYPE) || (type1 == Float.class) || (type1 == Long.TYPE) || (type1 == Integer.class) || (type1 == Integer.TYPE) || (type1 == Integer.class) || (type1 == Short.TYPE) || (type1 == Short.class) || (type1 == Byte.TYPE) || (type1 == Byte.class); } else if((type2 == Float.TYPE) || (type2 == Float.class)) { return (type1 == Long.TYPE) || (type1 == Integer.class) || (type1 == Integer.TYPE) || (type1 == Integer.class) || (type1 == Short.TYPE) || (type1 == Short.class) || (type1 == Byte.TYPE) || (type1 == Byte.class); } } return false; } //numericallyAssignable /** * Convert the incoming Argument to the expected type, if possible * * @param arg The incoming Argument * @param type The expected Type * @param factory The ConverterFactory to use for Type Conversions * @return The converted Argument */ public static Object convertArg (Object arg,Class<?> type,ConverterFactory factory) { if(arg != null) { if(type != null) { Class<?> argType = arg.getClass(); if(!equivalent(type,argType)) { if(!numericallyAssignable(argType,type)) { Converter converter = factory.getConverter(argType,type); if(converter != null) { return converter.convert(arg,type); } else { log.warn("Argument ({0.name}) is not convertible to {1.name}",argType,type); } } else { log.trace("No Conversion Necessary: {0.name} <=> {1.name}",argType,type); } } else { log.trace("No Conversion Necessary: {0.name} <-> {1.name}",argType,type); } } else { log.trace("Expected Type is null, not converting {0}",arg); } } else { log.trace("Argument is null"); } return arg; } //convertArg /** * Set the property of the bean. Dot notation is not taken into account, * but indexed properties are handled properly. * * @param bean The Bean to access * @param property The Property name * @param value The new Property value * @param factory The property value type conversion factory * @return The previous property value from the bean * @throws IntrospectionException if we get lost in introspection * @throws IllegalAccessException if we try to touch something we're not allowed to * @throws InstantiationException if we can't create the resulting bean * @throws InvocationTargetException if something goes wrong within the constructor of the bean */ @SuppressWarnings("unchecked") private static Object setBean (Object bean,String property,Object value,ConverterFactory factory) throws IllegalAccessException,InstantiationException,IntrospectionException,InvocationTargetException { int l; String index = null; String prop = property; if((l = property.indexOf('[')) != -1) { int r = property.indexOf(']',l); if(r != -1) { index = property.substring(l + 1,r); } prop = property.substring(0,l); } Class<?> beancls = bean.getClass(); if(index == null) { // Not an indexed property, handle it directly if(bean instanceof Map<?,?>) { return ((Map<Object,Object>)bean).put(prop,value); } else { PropertyDescriptor desc = getDescriptor(beancls,prop); if(desc != null) { try { Method mutator = desc.getWriteMethod(); return (mutator != null) ? mutator.invoke(bean,convertArg(value,desc.getPropertyType(),factory)) : null; } catch(IllegalArgumentException x) { IntrospectionException y = new IntrospectionException(TextFormat.format("Unable to Invoke {0.writeMethod.name}({0.propertyType}) with a {1.class.name} parameter",desc,value)); y.initCause(x); throw y; } } } } else { // Indexed property Method accessor; Object subbean = null; if(bean instanceof Map<?,?>) { if((subbean = ((Map<?,?>)bean).get(prop)) == null) { if(!((Map<?,?>)bean).isEmpty()) { Object testval = ((Map<?,?>)bean).values().iterator().next(); if(testval != null) { subbean = testval.getClass().newInstance(); ((Map<String,Object>)bean).put(property,subbean); } } } } else { accessor = getAccessor(beancls,prop); if(accessor != null) { if((subbean = accessor.invoke(bean)) == null) { Method mutator = getMutator(beancls,prop); if(mutator != null) { subbean = accessor.getReturnType().newInstance(); mutator.invoke(bean,subbean); } else { throw new IntrospectionException(TextFormat.format("Unable to initialize the {0} property of the class {1.name} ({2})",prop,beancls,property)); } } } } if(subbean != null) { if(subbean instanceof Map<?,?>) { return ((Map<String,Object>)subbean).put(index,value); } else if(subbean instanceof List<?>) { if(Misc.isNumeric(index)) { int ndx = Integer.parseInt(index); if(((List<?>)subbean).size() > ndx) { return ((List<Object>)subbean).set(ndx,value); } else { ((List<Object>)subbean).add(value); } } } } } return null; } //setBean /** * Set the value of the (possibly dot notated) Property from the Bean * * @param bean The Bean to access * @param property The Property name * @param value The new Property value * @param factory The property value type conversion factory * @return The previous property value from the bean * @throws IntrospectionException if we get lost in introspection */ @SuppressWarnings("unchecked") public static Object setValue (Object bean,String property,Object value,ConverterFactory factory) throws IntrospectionException { property = property.trim(); char ch = property.charAt(0); if(((ch == '"') || (ch == '\'')) && (property.charAt(property.length() - 1) == ch)) { return property.substring(1,property.length() - 1); } else if(bean != null) { try { int dot = property.indexOf('.'); if(dot == -1) { // No Dot, this is the final node we will be setting return setBean(bean,property,value,factory); } else { // Dot indicates just another link in the chain, keep recursing int l; String index = null; String prop = property.substring(0,dot); if((l = prop.indexOf('[')) != -1) { int r = prop.indexOf(']',l); if(r != -1) { index = prop.substring(l + 1,r); } prop = prop.substring(0,l); } Object subbean = null; Method accessor = null; Class<?> cls = bean.getClass(); if(bean instanceof Map<?,?>) { if((subbean = ((Map<?,?>)bean).get(prop)) == null) { if(!((Map<?,?>)bean).isEmpty()) { Object testval = ((Map<?,?>)bean).values().iterator().next(); if(testval != null) { subbean = testval.getClass().newInstance(); ((Map<String,Object>)bean).put(prop,subbean); } } } } else { accessor = getAccessor(cls,prop); if(accessor != null) { if((subbean = accessor.invoke(bean)) == null) { Method mutator = getMutator(cls,prop); if(mutator != null) { subbean = accessor.getReturnType().newInstance(); mutator.invoke(bean,subbean); } else { throw new IntrospectionException(TextFormat.format("Unable to initialize the {0} property of the class {1.name} ({2})",prop,cls,property)); } } } } if(subbean != null) { if(index != null) { int ndx = (Misc.isNumeric(index)) ? Integer.parseInt(index) : -1; if(subbean instanceof Map<?,?>) { Class<?> keytype = null; Class<?> valtype = null; try { Field field = cls.getDeclaredField(prop); if(field.isAnnotationPresent(RTTI.class)) { RTTI rtti = field.getAnnotation(RTTI.class); keytype = rtti.key(); valtype = rtti.value(); } else { log.trace("No RTTI Annotation Present on {0.declaringClass.name}.{0.name} map",field); } } catch(NoSuchFieldException x) { log.trace("Can''t locate the {0} field of {1}",prop,bean,x); } if(keytype == null) { if(accessor == null) { accessor = getAccessor(cls,prop); } Type type = accessor.getGenericReturnType(); if(type instanceof ParameterizedType) { Type[] args = ((ParameterizedType)type).getActualTypeArguments(); if((args != null) && (args.length > 1)) { log.trace("Actual Type Arguments: <{0,array,csv}>",(Object)args); if(args[0] instanceof Class<?>) { keytype = (Class<?>)args[0]; } if(args[1] instanceof Class<?>) { valtype = (Class<?>)args[1]; } } } if(keytype == null) { if(!((Map<?,?>)subbean).isEmpty()) { Object testkey = ((Map<?,?>)subbean).keySet().iterator().next(); if(testkey != null) { keytype = testkey.getClass(); } Object testval = ((Map<?,?>)subbean).values().iterator().next(); if(testval != null) { valtype = testval.getClass(); } } } } Object key = convertArg(index,keytype,factory); Object val = ((Map<?,?>)subbean).get(key); if(val == null) { val = valtype.newInstance(); ((Map<Object,Object>)subbean).put(key,val); } subbean = val; } else if(subbean.getClass().isArray()) { if(ndx != -1) { Object val = (Array.getLength(subbean) > ndx) ? Array.get(subbean,ndx) : null; if(val != null) { subbean = val; } else { if((val = subbean.getClass().getComponentType().newInstance()) != null) { Array.set(subbean,ndx,val); subbean = val; } } } } else if(subbean instanceof List<?>) { if(ndx != -1) { Object val = (((List<?>)subbean).size() > ndx) ? ((List<?>)subbean).get(ndx) : null; if(val != null) { subbean = val; } else { try { Field field = cls.getDeclaredField(prop); if(field.isAnnotationPresent(RTTI.class)) { val = field.getAnnotation(RTTI.class).value().newInstance(); } else { log.trace("No RTTI Annotation Present on {0.declaringClass.name}.{0.name}",field); } } catch(NoSuchFieldException x) { log.trace("Can''t locate the {0} field of {1}",prop,bean,x); } if(val == null) { if(accessor == null) { accessor = getAccessor(cls,prop); } Type type = accessor.getGenericReturnType(); if(type instanceof ParameterizedType) { Type[] args = ((ParameterizedType)type).getActualTypeArguments(); if((args != null) && (args.length > 0) && (args[0] instanceof Class<?>)) { val = ((Class<Object>)args[0]).newInstance(); } } } if((val == null) && !((List<?>)subbean).isEmpty()) { Object testval = ((List<?>)subbean).iterator().next(); if(testval != null) { val = testval.getClass().newInstance(); } } if(val != null) { ((List<Object>)subbean).add(val); subbean = val; } } } } } return setValue(subbean,property.substring(dot + 1),value,factory); } } } catch(IllegalAccessException x) { Method accessor; Class<?>[] interfaces = bean.getClass().getInterfaces(); for(Class<?> i : interfaces) { try { if((accessor = getAccessor(i,property)) != null) { return accessor.invoke(bean); } } catch(IllegalAccessException y) { // Nop } catch(InvocationTargetException y) { IntrospectionException z = new IntrospectionException("Unable to introspect " + property + " property of " + bean); z.initCause(y); throw z; } } IntrospectionException y = new IntrospectionException("Unable to introspect " + property + " property of " + bean); y.initCause(x); throw y; } catch(InstantiationException | InvocationTargetException x) { IntrospectionException y = new IntrospectionException("Unable to introspect " + property + " property of " + bean); y.initCause(x); throw y; } } return null; } //setValue /** * Set the value of the (possibly dot notated) Property from the Bean * * @param bean The Bean to access * @param property The Property name * @param value The new Property value * @return The previous property value from the bean * @throws IntrospectionException if we get lost in introspection */ public static Object setValue (Object bean,String property,Object value) throws IntrospectionException { return setValue(bean,property,value,ConverterFactory.getDefaultFactory()); } //setValue /** * Set the string value of the (possibly dot notated) Property from the * supplied bean * * @param bean The Bean to access * @param property The property name * @param value The property value String * @return The String property value */ public static String setString (Object bean,String property,String value) { try { return String.valueOf(setValue(bean,property,value)); } catch(IntrospectionException x) { log.warn("Error Updating {1} property of {0} to ''{2}''",bean,property,value,x); return "null"; } } //setString } //*BeanUtils
Java
/** * BeanMap * * @author Chris Pratt * * 11/11/2011 */ package com.anodyzed.onyx.bean; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.type.Converter; import com.anodyzed.onyx.type.ConverterFactory; import java.beans.IntrospectionException; import java.io.Serializable; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @SuppressWarnings("serial") public class BeanMap implements BeanWrapper, Map<String,Object>, Serializable { private static final Log log = LogBuilder.getLogger(); private Object bean; private Set<String> keys = null; private ConverterFactory factory; /** * Constructor * * @param bean The Source Data Bean * @param factory The Type Conversion Factory */ public BeanMap (Object bean,ConverterFactory factory) { this.bean = bean; this.factory = factory; } //BeanMap /** * Constructor * * @param bean The Source Data Bean */ public BeanMap (Object bean) { this(bean,new ConverterFactory()); } //BeanMap /** * Get the value of the bean attribute. * * @return The bean value as a Object */ @Override public Object getBean () { return bean; } //getBean /** * Set the value of the bean attribute. * * @param bean The new bean value as a Object */ public void setBean (Object bean) { this.bean = bean; } //setBean /** * Add an additional converter to the Converter Factory * * @param a The first conversion type * @param b The second conversion type * @param converter The Converter */ public void addConverter (Class<?> a,Class<?> b,Converter converter) { factory.addConverter(a,b,converter); } //addConverter /** * Get the Converter Factory used in this Bean Map * * @return Converter Factory */ public ConverterFactory getConverterFactory () { return factory; } //getConverterFactory /** * Set the Converter Factory to use in this Bean Map * * @param factory The new Converter Factory */ public void setConverterFactory (ConverterFactory factory) { this.factory = factory; } //setConverterFactory /** * Returns the number of properties defined by the bean. * * Note: This does not take into account sub-properties of contained beans * that could be reached using dot notation * * @return property count * @see java.util.AbstractMap#size() */ @Override public int size () { return entrySet().size(); } //size /** * Returns true if there are no properties defined by the bean. * * @return false if any properties are defined on the bean * @see java.util.AbstractMap#isEmpty() */ @Override public boolean isEmpty () { return size() == 0; } //isEmpty /** * Determine whether any of the properties of this bean match the supplied * value. * * Note: the search will include any Collections or Maps in the bean, but not * sub-beans. * * @param value The value to search for * @return true if the value is contained in this bean * @see java.util.AbstractMap#containsValue(java.lang.Object) */ @Override public boolean containsValue (Object value) { Object v; for(String key : keySet()) { if((v = get(key)) == null) { if(value == null) { return true; } } else { if(v.equals(value)){ return true; } if(v instanceof Map) { if(((Map<?,?>)v).containsValue(value)) { return true; } } else if(v instanceof Collection) { if(((Collection<?>)v).contains(value)) { return true; } } } } return false; } //containsValue /** * Determine whether the supplied key maps to a property of this bean, or a * sub-bean using dot-notation. * * @param key The bean property key * @return true if the key is contained in the bean hierarchy * @see java.util.AbstractMap#containsKey(java.lang.Object) */ @Override public boolean containsKey (Object key) { try { return (key != null) && BeanUtils.contains(bean,key.toString(),factory); } catch(IntrospectionException x) { log.debug("Unable to locate the value for ''{0}'' in bean {1}",key,bean,x); } return false; } //containsKey /** * Returns the value for the supplied property of this bean, or a sub-bean * using dot-notation. * * @param key The bean property key * @return The bean property value * @see java.util.AbstractMap#get(java.lang.Object) */ @Override public Object get (Object key) { try { return (key != null) ? BeanUtils.getValue(bean,key.toString(),factory) : null; } catch(IntrospectionException x) { log.debug("Unable to retrieve the value for ''{0}'' in bean {1}",key,bean,x); } return null; } //get /** * Set the value of the supplied property of this bean, or a sub-bean using * dot-notation. Any null beans found along the dot-notation path will be * instantiated as needed. * * @param key The bean property key * @param value The updated bean property value * @return The previous bean property value * @see java.util.AbstractMap#put(java.lang.Object, java.lang.Object) */ @Override public Object put (String key,Object value) { try { return (key != null) ? BeanUtils.setValue(bean,key,value,factory) : null; } catch(IntrospectionException x) { log.debug("Unable to update the value for ''{0}'' in bean {1} to {2}",key,bean,value,x); } return null; } //put /** * If the key references a property with an Object type, set that property to * null. Otherwise, attempt to set the property to a neutral value (i.e. * int=0, boolean=false...) * * Note: this does not meet the contract of the Map interface, since it does * not remove the corresponding key. * * @param key The bean property key * @return the removed property value * @see java.util.AbstractMap#remove(java.lang.Object) */ @Override public Object remove (Object key) { try { return (key != null) ? BeanUtils.setValue(bean,key.toString(),null,factory) : null; } catch(IntrospectionException x) { log.debug("Unable to remove the value for ''{0}'' in bean {1}",key,bean,x); } return null; } //remove /** * Put each of the values in the supplied map into this map. * * @param map The source map * @see java.util.AbstractMap#putAll(java.util.Map) */ @Override public void putAll (Map<? extends String,?> map) { for(Entry<? extends String,?> entry : map.entrySet()) { put(entry.getKey(),entry.getValue()); } } //putAll /** * Removes all the values from the map. * * Note: this does not meet the contract of the Map interface, since it does * not remove the corresponding keys. * * @see java.util.AbstractMap#clear() */ @Override public void clear () { for(String key : keySet()) { put(key,null); } } //clear /** * Get the Set of property names in this bean. * * Note: this set does not include properties of sub-beans that could be * referenced using dot-notation * * @return Set of property name Strings * @see java.util.AbstractMap#keySet() */ @Override @SuppressWarnings("unchecked") public Set<String> keySet () { if(bean instanceof Map<?,?>) { return ((Map<String,?>)bean).keySet(); } else { if(keys == null) { try { keys = BeanUtils.getProperties(bean.getClass()); } catch(IntrospectionException x) { log.debug("Failed building the keySet for {0}",bean,x); } } return keys; } } //keySet /** * Get the Collection of property values in this bean. * * @return Collection of property values * @see java.util.AbstractMap#values() */ @Override @SuppressWarnings("unchecked") public Collection<Object> values () { if(bean instanceof List<?>) { return (List<Object>)bean; } else if(bean instanceof Map<?,?>) { return ((Map<?,Object>)bean).values(); } else { List<Object> vals = new ArrayList<Object>(); for(String key : keySet()) { vals.add(get(key)); } return vals; } } //values /** * Get the Set of key/value entry pairs in this map * * @return Set of Map Entry's * @see java.util.AbstractMap#entrySet() */ @Override @SuppressWarnings("unchecked") public Set<Entry<String,Object>> entrySet () { if(bean instanceof Map<?,?>) { return ((Map<String,Object>)bean).entrySet(); } else { Set<Entry<String,Object>> entries = new HashSet<Entry<String,Object>>(); for(String key : keySet()) { entries.add(new AbstractMap.SimpleEntry<String,Object>(key,get(key))); } return entries; } } //entrySet /** * Determine whether the supplied argument is equivalent to this BeanMap * * @param o The Object in question * @return true if <code>o</code> is a BeanMap containing an equivalent Bean * @see java.util.AbstractMap#equals(java.lang.Object) */ @Override public boolean equals (Object o) { return (o instanceof BeanMap) && (bean.equals(((BeanMap)o).getBean())); } //equals /** * Generate a Hash Bucket Index for this BeanMap * * @return bean based hash code * @see java.util.AbstractMap#hashCode() */ @Override public int hashCode () { return bean.hashCode() * 31; } //hashCode /** * Return a String Representation of this bean map * * @return Debug String * @see java.util.AbstractMap#toString() */ @Override public String toString () { return "BeanMap<" + bean + '>'; } //toString } //*BeanMap
Java
/** * RTTI * * @author Chris Pratt * * 12/14/2011 */ package com.anodyzed.onyx.bean; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface RTTI { Class<?> key() default Object.class; Class<?> value(); } //#RTTI
Java
/** * TextFormat * * @author Chris Pratt * * 3/2/1999 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.util.Misc; import com.anodyzed.onyx.util.PrototypeMap; /** * <code>TextFormat</code> provides a means to produce concatenated * messages in language-neutral way. Use this to construct messages * displayed for end users. * * <p> * <code>TextFormat</code> takes a set of objects, formats them, then * inserts the formatted strings into the pattern at the appropriate places. * * <p> * <strong>Note:</strong> * <code>TextFormat</code> differs from the <code>java.text.Format</code> * classes in that you create a <code>TextFormat</code> object with one * of its constructors (not with a <code>getInstance</code> style factory * method). The factory methods aren't necessary because <code>TextFormat</code> * itself doesn't implement locale specific behavior. Any locale specific * behavior is defined by the pattern that you provide as well as the * sub-formats used for inserted arguments. * * <h4><a name="patterns">Patterns and Their Interpretation</a></h4> * * <code>TextFormat</code> uses patterns of the following form: * <blockquote><pre> * <i>TextFormatPattern:</i> * <i>String</i> * <i>TextFormatPattern</i> <i>FormatElement</i> <i>String</i> * * <i>FormatElement:</i> * { <i>BeanReference</i> } * { <i>BeanReference</i> , <i>FormatType</i> } * { <i>BeanReference</i> , <i>FormatType</i> , <i>FormatStyle</i> } * * <i>BeanReference:</i> * { <i>ArgumentIndex</i> } * { <i>ArgumentIndex</i> . <i>BeanProperty</i> } * { <i>ArgumentIndex</i> . <i>BeanProperty</i> [ . <i>BeanProperty</i> ]... } * * <i>FormatType: one of </i> * number date time array list map boolean * * <i>FormatStyle:</i> * csv * short * medium * long * full * integer * currency * percent * duration * <i>SubformatPattern</i> * * <i>String:</i> * <i>StringPart<sub>opt</sub></i> * <i>String</i> <i>StringPart</i> * * <i>StringPart:</i> * '' * ' <i>QuotedString</i> ' * <i>UnquotedString</i> * * <i>SubformatPattern:</i> * <i>SubformatPatternPart<sub>opt</sub></i> * <i>SubformatPattern</i> <i>SubformatPatternPart</i> * <i>true BooleanPatternPart</i> | <i>false BooleanPatternPart</i> * * <i>SubFormatPatternPart:</i> * ' <i>QuotedPattern</i> ' * <i>UnquotedPattern</i> * * <i>BooleanPatternPart:</i> * <i>UnquotedPattern</i> * * </pre></blockquote> * * <p> * Within a <i>String</i>, <code>"''"</code> represents a single * quote. A <i>QuotedString</i> can contain arbitrary characters * except single quotes; the surrounding single quotes are removed. * An <i>UnquotedString</i> can contain arbitrary characters * except single quotes and left curly brackets. Thus, a string that * should result in the formatted message "'{0}'" can be written as * <code>"'''{'0}''"</code> or <code>"'''{0}'''"</code>. * <p> * Within a <i>SubformatPattern</i>, different rules apply. * A <i>QuotedPattern</i> can contain arbitrary characters * except single quotes; but the surrounding single quotes are * <strong>not</strong> removed, so they may be interpreted by the * sub-format. For example, <code>"{1,number,$'#',##}"</code> will * produce a number format with the pound-sign quoted, with a result * such as: "$#31,45". * An <i>UnquotedPattern</i> can contain arbitrary characters * except single quotes, but curly braces within it must be balanced. * For example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> * are valid sub-format patterns, but <code>"ab {0'}' de"</code> and * <code>"ab } de"</code> are not. * <p> * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message * format patterns unfortunately have shown to be somewhat confusing. * In particular, it isn't always obvious to localizers whether single * quotes need to be doubled or not. Make sure to inform localizers about * the rules, and tell them (for example, by using comments in resource * bundle source files) which strings will be processed by TextFormat. * Note that localizers may need to use single quotes in translated * strings where the original version doesn't have them. * </dl> * <p> * The <i>ArgumentIndex</i> value is a non-negative integer written * using the digits '0' through '9', and represents an index into the * <code>arguments</code> array passed to the <code>format</code> methods * or the result array returned by the <code>parse</code> methods. * <p> * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create * a <code>Format</code> instance for the format element. The following * table shows how the values map to Format instances. Combinations not * shown in the table are illegal. A <i>SubformatPattern</i> must * be a valid pattern string for the Format subclass used. * <p> * <table border="1" summary="Shows how FormatType and FormatStyle values map to Format instances"> * <tr> * <th id="ft">Format Type</th> * <th id="fs">Format Style</th> * <th id="sc">Sub-format Created</th> * </tr><tr> * <td headers="ft"><i>(none)</i></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>null</code></td> * </tr><tr> * <td headers="ft" rowspan="3"><code>array</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><code>csv</code></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>Convert.toDelimitedString(value,subformatPattern[0]</code></td> * </tr><tr> * <td headers="ft" rowspan="6"><code>date</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>short</code></td> * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.SHORT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>medium</code></td> * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>long</code></td> * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.LONG,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>full</code></td> * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.FULL,getLocale())</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>new SimpleDateFormat(subformatPattern,getLocale())</td> * </tr><tr> * <td headers="ft" rowspan="3"><code>list</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><code>csv</code></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>Convert.toDelimitedString(value,subformatPattern[0]</code></td> * </tr><tr> * <td headers="ft" rowspan="3"><code>map</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><code>csv</code></td> * <td headers="sc"><code>Convert.toCSVString()</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>Convert.toDelimitedString(value,subformatPattern[0]</code></td> * </tr><tr> * <td headers="ft" rowspan="5"><code>number</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>NumberFormat.getInstance(getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>integer</code></td> * <td headers="sc"><code>NumberFormat.getIntegerInstance(getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>currency</code></td> * <td headers="sc"><code>NumberFormat.getCurrencyInstance(getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>percent</code></td> * <td headers="sc"><code>NumberFormat.getPercentInstance(getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>duration</code></td> * <td headers="sc"><code>Misc.duration()</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>new DecimalFormat(subformatPattern,new DecimalFormatSymbols(getLocale()))</code></td> * </tr><tr> * <td headers="ft" rowspan="6"><code>time</code></td> * <td headers="fs"><i>(none)</i></td> * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>short</code></td> * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.SHORT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>medium</code></td> * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>long</code></td> * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.LONG,getLocale())</code></td> * </tr><tr> * <td headers="fs"><code>full</code></td> * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.FULL,getLocale())</code></td> * </tr><tr> * <td headers="fs"><i>SubformatPattern</i></td> * <td headers="sc"><code>new SimpleDateFormat(subformatPattern,getLocale())</td> * </tr> * </table> * <p> * * <h4>Usage Information</h4> * * <p> * Here are some examples of usage: * <blockquote> * <pre> * String result = TextFormat.format( * "{3,fname} did you notice that at {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", * 7,new Date(System.currentTimeMillis()),"a disturbance in the Force"); * * <em>output</em>: Luke did you notice that at 12:30 PM on Jul 3, 2053, there was a disturbance * in the Force on planet 7. * * </pre> * </blockquote> * Typically, the message format will come from resources, and the * arguments will be dynamically set at runtime. * * <p> * Example 2: * <blockquote> * <pre> * TextFormat form = new TextFormat( * "The disk \"{1}\" contains {0} file(s)."); * * System.out.println(form.format(3,"MyDisk")); * * // output, with different Arguments * <em>output</em>: The disk "MyDisk" contains 3 file(s). * <em>output</em>: The disk "MyDisk" contains 1 file(s). * <em>output</em>: The disk "MyDisk" contains 1,273 file(s). * </pre> * </blockquote> * * <p> * When a single argument is parsed more than once in the string, the last match * will be the final result of the parsing. For example, * <pre> * TextFormat mf = new TextFormat("{0,number,#.##}, {0,number,#.#}"); * Object[] objs = {new Double(3.1415)}; * String result = mf.format( objs ); * // result now equals "3.14, 3.1" * objs = null; * objs = mf.parse(result, new ParsePosition(0)); * // objs now equals {new Double(3.1)} * </pre> * <p> * Likewise, parsing with a TextFormat object using patterns containing * multiple occurrences of the same argument would return the last match. For * example, * <pre> * TextFormat mf = new TextFormat("{0}, {0}, {0}"); * String forParsing = "x, y, z"; * Object[] objs = mf.parse(forParsing, new ParsePosition(0)); * // result now equals {new String("z")} * </pre> * * <h4><a name="synchronization">Synchronization</a></h4> * * <p> * Text formats are not synchronized. * Creating separate format instances for each thread is recommended. * If multiple threads access a format concurrently, it must be synchronized * externally. * * @see java.util.Locale * @see java.text.Format * @see java.text.NumberFormat * @see java.text.DecimalFormat * @author Chris Pratt */ public class TextFormat { /** * TextNode */ static class TextNode extends TextFormatter { private String text; /** * Constructor * * @param text The Static Text for this node */ public TextNode (CharSequence text) { super(null,null,null); this.text = text.toString(); } //TextNode /** * Return the static String * * @param args The Formatting Arguments (ignored) * @return The Static Text */ @Override public String toString (Object... args) { return text; } //toString } //*TextNode /** * StringNode */ static class StringNode extends TextFormatter { /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public StringNode (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); } //StringNode /** * Return the String representation of the Argument * * @param args The Formatting Arguments * @return The String Representation of the proper argument */ @Override public String toString (Object... args) { Object o = getValue(args); return (o != null) ? o.toString() : null; } //toString } //*StringNode private static final PrototypeMap<String,TextFormatter> DEF_FORMATTERS; static { DEF_FORMATTERS = new PrototypeMap<>(); DEF_FORMATTERS.put("array",CollectionFormatter.class); DEF_FORMATTERS.put("binary",BinaryFormatter.class); DEF_FORMATTERS.put("boolean",BooleanFormatter.class); DEF_FORMATTERS.put("choice",ChoiceFormatter.class); DEF_FORMATTERS.put("date",DateFormatter.class); DEF_FORMATTERS.put("list",CollectionFormatter.class); DEF_FORMATTERS.put("map",CollectionFormatter.class); DEF_FORMATTERS.put("number",NumberFormatter.class); DEF_FORMATTERS.put("string",StringFormatter.class); DEF_FORMATTERS.put("substring",SubstringFormatter.class); DEF_FORMATTERS.put("time",TimeFormatter.class); } private static final Class<?>[] ARGS3 = {TextFormat.class,CharSequence.class,CharSequence.class}; private static final Class<?>[] ARGS4 = {TextFormat.class,CharSequence.class,CharSequence.class,CharSequence.class}; private String text; private TextFormatter base = null; private PrototypeMap<String,TextFormatter> formatters; /** * Constructor * * @param text The Text to be Formatted */ public TextFormat (String text) { if(text != null) { this.text = text; formatters = new PrototypeMap<>(DEF_FORMATTERS); } else { throw new NullPointerException("Text Format Pattern cannot be null"); } } //TextFormat /** * Constructor * * @param text The Text Format Pattern * @param formatters The Prototype Map of Text Formatters */ private TextFormat (String text,PrototypeMap<String,TextFormatter> formatters) { if(text != null) { this.text = text; this.formatters = formatters; } else { throw new NullPointerException("Text Format Pattern cannot be null"); } } //TextFormat /** * Compile the supplied format string into an executable stack */ private void compile () { int nd,pos,slf4jndx = 0; TextFormatter curr,prev = null; StringBuilder buf = new StringBuilder(); char[] ch = text.toCharArray(); for(int i = 0;i < ch.length;i++) { switch(ch[i]) { case '\'': if(ch[++i] == '\'') { buf.append('\''); } else { while((i < ch.length) && (ch[i] != '\'')) { buf.append(ch[i++]); } } break; case '{': if(buf.length() > 0) { curr = new TextNode(buf); if(base == null) { base = prev = curr; } else { prev.setNext(curr); prev = curr; } buf.setLength(0); } if(ch[i + 1] != '}') { StringBuilder key = new StringBuilder(); while((ch[++i] != '.') && (ch[i] != ',') && (ch[i] != '}')) { key.append(ch[i]); } StringBuilder bean = null; if(ch[i] == '.') { bean = new StringBuilder(); if(Character.isJavaIdentifierStart(ch[++i])) { do { bean.append(ch[i]); } while(Character.isJavaIdentifierPart(ch[++i]) || (ch[i] == '.') || (ch[i] == ':')); } } if(ch[i] == ',') { nd = Misc.arrayIndexOf(ch,'}',++i); if(((pos = Misc.arrayIndexOf(ch,',',i)) != -1) && (pos < nd)) { int nest = 0; boolean literal = false; nd = pos + 1; while((ch[nd] != '}') || literal || (nest > 0)) { switch(ch[nd]) { case '\'': literal = !literal; break; case '{': if(!literal) { ++nest; } break; case '}': if(!literal) { --nest; } break; } ++nd; } curr = formatters.newInstance(new String(ch,i,pos - i),ARGS4,new Object[] {this,key,bean,new String(ch,++pos,nd - pos)}); } else { curr = formatters.newInstance(new String(ch,i,nd - i),ARGS3,new Object[] {this,key,bean}); } if(curr == null) { curr = new StringNode(this,key,bean); } i = nd; } else { curr = new StringNode(this,key,bean); } key.setLength(0); } else { // Emulate SLF4j {} style behavior curr = new StringNode(this,String.valueOf(slf4jndx++),null); } if(base == null) { base = prev = curr; } else { prev.setNext(curr); prev = curr; } while((i < ch.length) && (ch[i] != '}')) { ++i; } break; default: buf.append(ch[i]); break; } } if(buf.length() > 0) { curr = new TextNode(buf); if(base == null) { base = curr; } else { prev.setNext(curr); } } } //compile /** * Format the String using the supplied Arguments * * @param args The Format Arguments * @return The Formatted String */ public String format (Object... args) { if(base == null) { compile(); } StringBuilder buf = new StringBuilder(); TextFormatter curr = base; while(curr != null) { buf.append(curr.toString(args)); curr = curr.getNext(); } return buf.toString(); } //format /** * Return a new Text Formatter using the same set of Formatters as this * instance. * * @param text The new Text to be formatted * @return The new Text Format */ public TextFormat subformat (String text) { return new TextFormat(text,formatters); } //subformat /** * Add a new Formatter to this TextFormat instance * * @param key The key to recognize this TextFormatter by * @param formatter The Class of the TextFormatter to register */ public void addFormatter (String key,Class<? extends TextFormatter> formatter) { formatters.put(key,formatter); base = null; } //addFormatter /** * Convenience Static Formatter * * @param text The Format Pattern * @param args The Format Arguments * @return The Formatted String */ public static String format (String text,Object... args) { return new TextFormat(text).format(args); } //format /** * Send the formatted output to the System.out Standard Output Stream * * @param text The Format Pattern * @param args The Format Arguments */ public static void stdout (String text,Object... args) { System.out.println(new TextFormat(text).format(args)); } //stdout /** * Send the formatted output to the System.err Standard Error Stream * * @param text The Format Pattern * @param args The Format Arguments */ public static void stderr (String text,Object... args) { System.err.println(new TextFormat(text).format(args)); } //stderr /** * Add a new Formatter to all future instances of TextFormat * * @param key The key to recognize this TextFormatter by * @param formatter The Class of the TextFormatter to register */ public static void addDefaultFormatter (String key,Class<? extends TextFormatter> formatter) { DEF_FORMATTERS.put(key,formatter); } //addDefaultFormatter } //*TextFormat
Java
/** * StringFormatter * * @author Chris Pratt * * 4/1/2012 */ package com.anodyzed.onyx.text; public class StringFormatter extends TextFormatter { private CharSequence format; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String * @param format The String Format request */ public StringFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence format) { super(parent,key,bean); this.format = format; } //StringFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String */ public StringFormatter (TextFormat parent, CharSequence key, CharSequence bean) { super(parent,key,bean); this.format = "string"; } //StringFormatter /** * Return a modified string value * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o != null) { String s = o.toString(); if(format.equals("lower")) { return s.toLowerCase(); } else if(format.equals("upper")) { return s.toUpperCase(); } else if(format.equals("trim")) { return s.trim(); } return s; } return null; } //toString } //*StringFormatter
Java
/** * BinaryFormatter * * @author Chris Pratt * * 5/8/2010 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.util.Base64; import com.anodyzed.onyx.util.Hex; public class BinaryFormatter extends TextFormatter { private String style; /** * Constructor * * @param parent The Parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public BinaryFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); style = "dump"; } //BinaryFormatter /** * Constructor * * @param parent The Parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param style The Date Style */ public BinaryFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean); this.style = style.toString(); } //BinaryFormatter /** * Return a string representation of a date object * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o instanceof byte[]) { if(style.equals("dump")) { return Hex.dump((byte[])o); } else if(style.equals("base64")) { return Base64.encode((byte[])o); } } else if(o instanceof String) { if(style.equals("dump")) { return Hex.dump((String)o); } } return null; } //toString } //*BinaryFormatter
Java
/** * SubstringFormatter * * @author Chris Pratt * * 2/24/2010 */ package com.anodyzed.onyx.text; public class SubstringFormatter extends TextFormatter { private int st; private int nd; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String * @param range The Substring Range */ public SubstringFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence range) { super(parent,key,bean); int sep; int step = 1; String rng = range.toString(); if((sep = rng.indexOf('-')) == -1) { if((sep = rng.indexOf(',')) == -1) { if((sep = rng.indexOf("...")) == -1) { sep = rng.indexOf(".."); step = 2; } else { step = 3; } } } if(sep != -1) { st = Integer.parseInt(rng.substring(0,sep)); nd = Integer.parseInt(rng.substring(sep + step)); } else { st = Integer.parseInt(rng); nd = -1; } } //SubstringFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String */ public SubstringFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); throw new IllegalArgumentException("Substring Formatter requires a range string"); } //SubstringFormatter /** * Return a substring of the string value * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o != null) { String s = o.toString(); int l = s.length(); if(st < l) { return (nd == -1) ? s.substring(st) : s.substring(st,Math.min(nd,l)); } return ""; } return null; } //toString } //*SubstringFormatter
Java
/** * BooleanFormatter * * @author Chris Pratt * * 11/26/2009 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.util.Convert; public class BooleanFormatter extends TextFormatter { private String positive; private String negative; /** * Constructor * * @param parent The Parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The Additional Bean reference String * @param style The Format String */ public BooleanFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean); String fmt = style.toString(); int pos = fmt.indexOf('|'); if(pos != -1) { positive = fmt.substring(0,pos); negative = fmt.substring(pos + 1); } } //BooleanFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The Additional Bean reference String */ public BooleanFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); positive = "true"; negative = "false"; } //BooleanFormatter /** * Return a string representation of a boolean * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o instanceof Boolean) { return ((Boolean)o) ? positive : negative; } else if(o instanceof String) { return (Convert.toBoolean((String)o)) ? positive : negative; } return null; } //toString } //*BooleanFormatter
Java
/** * DateFormatter * * @author Chris Pratt * * 11/26/2009 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.util.Convert; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateFormatter extends TextFormatter { protected DateFormat fmt; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public DateFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); fmt = DateFormat.getInstance(); } //DateFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param style The Date Style */ public DateFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean); if(style.equals("short")) { fmt = DateFormat.getDateInstance(DateFormat.SHORT); } else if(style.equals("medium")) { fmt = DateFormat.getDateInstance(DateFormat.MEDIUM); } else if(style.equals("long")) { fmt = DateFormat.getDateInstance(DateFormat.LONG); } else if(style.equals("full")) { fmt = DateFormat.getDateInstance(DateFormat.FULL); } else { fmt = new SimpleDateFormat(style.toString()); } } //DateFormatter /** * Return a string representation of a date object * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o instanceof Date) { return fmt.format((Date)o); } else if(o instanceof Calendar) { return fmt.format(((Calendar)o).getTime()); } else if(o instanceof String) { return fmt.format(Convert.toDate((String)o)); } else if(o instanceof Number) { return fmt.format(new Date(((Number)o).longValue())); } return null; } //toString } //*DateFormatter
Java
/** * CollectionFormatter * * @author Chris Pratt * * 11/26/2009 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.util.Convert; import java.util.Map; public class CollectionFormatter extends TextFormatter { private char delim; private int[] fixed; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public CollectionFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); delim = ','; } //CollectionFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param fmt The Format String */ public CollectionFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence fmt) { super(parent,key,bean); if(fmt.length() > 0) { String str; if(fmt.equals("csv")) { delim = ','; } else if(fmt.equals("tsv")) { delim = '\t'; } else if(Character.isDigit(fmt.charAt(0)) && ((str = fmt.toString()).indexOf(',') != -1)) { int i = 0; String[] lens = Convert.toStringArray(str,','); fixed = new int[lens.length]; for(String len : lens) { fixed[i++] = Integer.parseInt(len); } } else { delim = fmt.charAt(0); } } } //CollectionFormatter /** * Return a string representation of an array * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object o = getValue(args); if(o != null) { if(fixed == null) { if(o.getClass().isArray()) { return Convert.toDelimitedString((Object[])o,delim); } else if(o instanceof Map<?,?>) { return Convert.toDelimitedString((Map<?,?>)o,delim); } else if(o instanceof Iterable<?>) { return Convert.toDelimitedString((Iterable<?>)o,delim); } else if(o instanceof String) { return (String)o; } } else { if(o.getClass().isArray()) { return Convert.toFixedString((Object[])o,fixed); } else if(o instanceof Iterable<?>) { return Convert.toFixedString((Iterable<?>)o,fixed); } } } return null; } //toString } //*CollectionFormatter
Java
/** * ChoiceFormatter * * @author Chris Pratt * * 11/17/2009 */ package com.anodyzed.onyx.text; import java.text.ChoiceFormat; import java.util.ArrayList; import java.util.List; public class ChoiceFormatter extends TextFormatter { private double[] choiceLimits; private TextFormat[] choiceFormats; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String * @param format The Format String */ public ChoiceFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence format) { super(parent,key,bean); StringBuilder buffer = new StringBuilder(); List<Double> newChoiceLimits = new ArrayList<>(); List<TextFormat> newChoiceFormats = new ArrayList<>(); int part = 0; char ch; double startValue = 0; double oldStartValue = Double.NaN; boolean inQuote = false; String temp; for(int i = 0;i < format.length();++i) { ch = format.charAt(i); if(ch == '\'') { // Check for "''" indicating a literal quote if(((i + 1) < format.length()) && (format.charAt(i + 1) == ch)) { buffer.append(ch); ++i; } else { inQuote = !inQuote; } } else if(inQuote) { buffer.append(ch); } else if((ch == '<') || (ch == '#') || (ch == '\u2264')) { temp = buffer.toString().trim(); if(temp.length() == 0) { throw new IllegalArgumentException("Segment must begin with a start value"); } try { switch(temp) { case "\u221E": startValue = Double.POSITIVE_INFINITY; break; case "-\u221E": startValue = Double.NEGATIVE_INFINITY; break; default: startValue = Double.valueOf(temp); if(ch == '<') { startValue = ChoiceFormat.nextDouble(startValue); } break; } } catch(Exception x) { throw new IllegalArgumentException("Unable to determine start value from " + temp,x); } if(startValue <= oldStartValue) { throw new IllegalArgumentException("Segments must be in ascending order"); } buffer.setLength(0); part = 1; } else if(ch == '|') { newChoiceLimits.add(startValue); newChoiceFormats.add(parent.subformat(buffer.toString())); oldStartValue = startValue; buffer.setLength(0); part = 0; } else { buffer.append(ch); } } // clean up last one if(part == 1) { newChoiceLimits.add(startValue); newChoiceFormats.add(parent.subformat(buffer.toString())); } int i = 0; choiceLimits = new double[newChoiceLimits.size()]; for(double d : newChoiceLimits) { choiceLimits[i++] = d; } choiceFormats = newChoiceFormats.toArray(new TextFormat[newChoiceFormats.size()]); } //ChoiceFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index of Map Key for this node * @param bean The Additional Bean Reference String */ public ChoiceFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); throw new IllegalArgumentException("Choice Formatter requires a format string"); } //ChoiceFormatter /** * Return a string representation of the choice * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Number n = -1.0; Object o = getValue(args); if(o != null) { if(o instanceof Number) { n = (Number)o; } else { try { n = Long.valueOf(o.toString()); } catch(NumberFormatException x) { try { n = Double.valueOf(o.toString()); } catch(NumberFormatException y) { return null; } } } } int i; double number = n.doubleValue(); for(i = 0;i < choiceLimits.length;++i) { if(!(number >= choiceLimits[i])) { // same as number < choiceLimits, except catches NaN break; } } if(--i < 0) { i = 0; } // return either a formatted number, or a string return choiceFormats[i].format(args); } //toString } //*ChoiceFormatter
Java
/** * TextFormatter * * @author Chris Pratt * * 9/25/2009 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.bean.BeanUtils; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.util.Misc; import java.beans.IntrospectionException; import java.util.Map; public abstract class TextFormatter { private static final Log log = LogBuilder.getLogger(); protected TextFormat parent; private TextFormatter next; private String key; private String bean; /** * Constructor * * @param parent The Parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference string */ public TextFormatter (TextFormat parent,CharSequence key,CharSequence bean) { this.parent = parent; this.key = (key != null) ? key.toString() : null; this.bean = (bean != null) ? bean.toString() : null; } //TextFormatter /** * Convert the Node to a String * * @param args The Formatting Arguments * @return The Formatted String */ public abstract String toString(Object... args); /** * Get the Value for the Node * * @param args The Array of Arguments * @return The Node Value */ public Object getValue (Object... args) { if(Misc.isNumeric(key)) { int ndx = Integer.parseInt(key); if(args[ndx] != null) { if(bean != null) { try { return BeanUtils.getValue(args[ndx],bean); } catch(IntrospectionException x) { if(log.isTraceEnabled()) { log.trace("Failed Introspecting " + args[ndx] + " for '" + bean + '\'',x); } return null; } } else { return args[ndx]; } } } else if(args[0] instanceof Map<?,?>) { if(bean != null) { try { return BeanUtils.getValue(((Map<?,?>)args[0]).get(key),bean); } catch(IntrospectionException x) { if(log.isTraceEnabled()) { log.trace("Failed Introspecting " + args[0] + " for '" + bean + '\'',x); } } } else { return ((Map<?,?>)args[0]).get(key); } } else { if(bean != null) { try { return BeanUtils.getValue(args[0],key + '.' + bean); } catch(IntrospectionException x) { if(log.isTraceEnabled()) { log.trace("Failed Introspecting " + args[0] + " for '" + key + '.' + bean + '\'',x); } } } else { try { return BeanUtils.getValue(args[0],key); } catch(IntrospectionException x) { if(log.isTraceEnabled()) { log.trace("Failed Introspecting " + args[0] + " for '" + key + '\'',x); } } } } return null; } //getValue /** * Get the value of the next attribute. * * @return The next value as a TextFormatter */ public TextFormatter getNext () { return next; } //getNext /** * Set the value of the next attribute. * * @param next The new next value as a TextFormatter */ public void setNext (TextFormatter next) { this.next = next; } //setNext } //*TextFormatter
Java
/** * TimeFormatter * * @author Chris Pratt * * 11/26/2009 */ package com.anodyzed.onyx.text; import java.text.DateFormat; import java.text.SimpleDateFormat; public class TimeFormatter extends DateFormatter { /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public TimeFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); fmt = DateFormat.getTimeInstance(); } //TimeFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param style The Date Style */ public TimeFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean); if(style.equals("short")) { fmt = DateFormat.getTimeInstance(DateFormat.SHORT); } else if(style.equals("medium")) { fmt = DateFormat.getTimeInstance(DateFormat.MEDIUM); } else if(style.equals("long")) { fmt = DateFormat.getTimeInstance(DateFormat.LONG); } else if(style.equals("full")) { fmt = DateFormat.getTimeInstance(DateFormat.FULL); } else { fmt = new SimpleDateFormat(style.toString()); } } //TimeFormatter } //*TimeFormatter
Java
/** * NumberFormatter * * @author Chris Pratt * * 11/26/2009 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.util.Calc; import com.anodyzed.onyx.util.FPCalc; import com.anodyzed.onyx.util.Fraction; import com.anodyzed.onyx.util.Misc; import java.text.DecimalFormat; import java.text.NumberFormat; public class NumberFormatter extends TextFormatter { private static final Log log = LogBuilder.getLogger(); protected NumberFormat fmt; protected boolean fraction = false; protected boolean duration = false; protected TextFormat equation = null; /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public NumberFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); fmt = NumberFormat.getInstance(); } //NumberFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param style The Numeric Style */ public NumberFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean); String format = style.toString(); switch(format) { case "currency": fmt = NumberFormat.getCurrencyInstance(); break; case "percent": fmt = NumberFormat.getPercentInstance(); break; case "integer": fmt = NumberFormat.getIntegerInstance(); break; case "fraction": fraction = true; break; case "duration": duration = true; break; default: if(format.startsWith("calc,")) { equation = parent.subformat(format.substring(5)); } else if(format.startsWith("integer,")) { fmt = NumberFormat.getIntegerInstance(); equation = parent.subformat(format.substring(8)); } else if(format.startsWith("duration,")) { duration = true; equation = parent.subformat(format.substring(9)); } else { fmt = new DecimalFormat(format); } break; } } //NumberFormatter /** * Return a string representation of a numeric object * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object arg = getValue(args); if(arg != null) { if(fraction) { if(arg instanceof Number) { return Fraction.toString(((Number)arg).doubleValue()); } else if(arg instanceof String) { return Fraction.toString((String)arg); } } else if(duration) { if(equation != null) { return Misc.duration(Calc.eval(equation.format(args))); } else if(arg instanceof Number) { return Misc.duration(((Number)arg).longValue()); } else if(arg instanceof String) { return Misc.duration(Long.parseLong((String)arg)); } } else if(equation != null) { String eq = equation.format(args); if(fmt != null) { return (eq.indexOf('.') != -1) ? fmt.format(FPCalc.eval(eq)) : fmt.format(Calc.eval(eq)); } else { return (eq.indexOf('.') != -1) ? FPCalc.toString(eq) : Calc.toString(eq); } } else { try { return fmt.format(arg); } catch(IllegalArgumentException x) { log.debug("Unable to format {0} ({0.class.name}) as a Number using ({1})",arg,fmt); } } } return null; } //toString } //*NumberFormatter
Java
/** * ZeroNullNumberFormatter * * @author Chris Pratt * * 1/24/2012 */ package com.anodyzed.onyx.text; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; public class ZeroNullNumberFormatter extends NumberFormatter { private static final Log log = LogBuilder.getLogger(); /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String */ public ZeroNullNumberFormatter (TextFormat parent,CharSequence key,CharSequence bean) { super(parent,key,bean); } //ZeroNullNumberFormatter /** * Constructor * * @param parent The parent TextFormat * @param key The Argument Index or Map Key for this node * @param bean The additional Bean reference String * @param style The Date Style */ public ZeroNullNumberFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence style) { super(parent,key,bean,style); } //ZeroNullNumberFormatter /** * Return a string representation of a numeric object * * @param args The Formatting Arguments * @return The Formatted String */ @Override public String toString (Object... args) { Object arg = getValue(args); if(arg == null) { if(fraction || duration) { return "0"; } else { try { return fmt.format(0); } catch(IllegalArgumentException x) { log.debug("Unable to format {0} ({0.class.name}) as a Number using ({1})",arg,fmt); } } } return super.toString(args); } //toString } //*ZeroNullNumberFormatter
Java
/** * LogFactory * * @author Chris Pratt * * 10/20/2011 */ package com.anodyzed.onyx.log; public interface LogFactory { /** * Get the Logger defined for the category named for the calling class * * @return Logger */ Log getLogger(); /** * Get the Logger defined for the category named for the supplied class * * @param clazz The class whose name should be used as the category * @return Logger */ Log getLogger(Class<?> clazz); /** * Get the Logger defined for the specified category * * @param category The category name * @return Logger */ Log getLogger(String category); /** * Set the Mapped Diagnostic Context Identifier * * @param id The MDC Identifier */ void setId(String id); /** * Set a Mapped Diagnostic Context Key/Value pair * * @param key The MDC Key * @param val The MDC Value */ void set(String key,String val); } //#LogFactory
Java
/** * SLF4jLogContextInitializer * * @author Chris Pratt * * 7/29/2012 */ package com.anodyzed.onyx.log.slf4j; import com.anodyzed.onyx.log.LogBuilder; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class SLF4jLogContextInitializer implements ServletContextListener { /** * The Servlet Context is being constructed, initialize the LogBuilder to use * this Factory * * @param event The Servlet Context Event */ @Override public void contextInitialized (ServletContextEvent event) { LogBuilder.setLogFactory(new SLF4jLogFactory()); } //contextInitialized /** * The Servlet Context is being destroyed, clean up * * @param event The Servlet Context Event */ @Override public void contextDestroyed (ServletContextEvent event) { } //contextDestroyed } //*SLF4jLogContextInitializer
Java
/** * SLF4jBridgeContextInitializer * * @author Chris Pratt * * 7/13/2011 */ package com.anodyzed.onyx.log.slf4j; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.slf4j.bridge.SLF4JBridgeHandler; public class SLF4jBridgeContextInitializer implements ServletContextListener { /** * The Servlet Context is being constructed, initialize the java.util.logging * -> SLF4j Bridge * * @param event The Servlet Context Event */ @Override public void contextInitialized (ServletContextEvent event) { SLF4JBridgeHandler.install(); } //contextInitialized /** * The Servlet Context is being destroyed, clean up * * @param event The Servlet Context Event */ @Override public void contextDestroyed (ServletContextEvent event) { } //contextDestroyed } //*SLF4jBridgeContextInitializer
Java
/** * SLF4jLogFactory * * @author Chris Pratt * * 7/29/2012 */ package com.anodyzed.onyx.log.slf4j; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.LogFactory; import org.slf4j.LoggerFactory; import org.slf4j.MDC; public class SLF4jLogFactory implements LogFactory { @Override public Log getLogger () { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for(int i = 0;i < trace.length;i++) { if(trace[i].getClassName().equals(LogBuilder.FQBN)) { return new SLF4jLog(LoggerFactory.getLogger(trace[i + 1].getClassName())); } } return null; } //getLogger @Override public Log getLogger (Class<?> clazz) { return new SLF4jLog(LoggerFactory.getLogger(clazz)); } //getLogger @Override public Log getLogger (String category) { return new SLF4jLog(LoggerFactory.getLogger(category)); } //getLogger @Override public void setId (String id) { MDC.put("id",id); } //getId @Override public void set (String key,String val) { MDC.put(key,val); } //set } //*SLF4jLogFactory
Java
/** * SLF4jLog * * @author Chris Pratt * * 7/29/2012 */ package com.anodyzed.onyx.log.slf4j; import com.anodyzed.onyx.bean.BeanUtils; import com.anodyzed.onyx.cache.Cache; import com.anodyzed.onyx.cache.CacheLoader; import com.anodyzed.onyx.cache.MRUCache; import com.anodyzed.onyx.cache.SimpleCache; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogException; import com.anodyzed.onyx.log.LogLevel; import com.anodyzed.onyx.text.TextFormat; import com.anodyzed.onyx.util.SplayTreeMap; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.slf4j.Logger; import org.slf4j.spi.LocationAwareLogger; /** * Java 5+ SLF4j Facade - Allows using format strings and variable argument * lists to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to SLF4j's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public class SLF4jLog implements Log { private static final String FQCN = SLF4jLog.class.getName(); private static final TextFormat BEAN_PROPERTY = new TextFormat(" {0}: {1}"); private static final Cache<String,TextFormat> formatCache = new MRUCache<>(new SimpleCache<>("formatCache",null,new CacheLoader<String,TextFormat>() { @Override public TextFormat load (Object arg,String key) { return new TextFormat(key); } //load },new SplayTreeMap<String,TextFormat>()),100); private LocationAwareLogger log; /** * Constructor * * @param log The Logger to Delegate to */ protected SLF4jLog (LocationAwareLogger log) { this.log = log; } //SLF4jLog /** * Constructor * * @param log Casting Constructor that tests the log to ensure it implements * the LocationAwareLogger interface. * @throws LogException If <code>log</code> does not implement * <code>LocationAwareLogger</code> */ protected SLF4jLog (Logger log) { if(log instanceof LocationAwareLogger) { this.log = (LocationAwareLogger)log; } else { throw new LogException("SLF4j Loggers must implement the LocationAwareLogger interface to be used with ELF4j, " + log.getClass().getName() + " does not"); } } //SLF4jLog /** * Get the Wrapped Logger * * @return Wrapped Logger instance */ public Logger getWrappedLogger () { return log; } //getWrappedLogger /** * Convert the ELF4j LogLevel to an SLF4j Location Aware Logger Level Integer * * @param level The ELF4j Logging Level * @return The SLF4j Logging Integer */ private static int toIntLevel (LogLevel level) { switch(level) { case All: case Trace: return LocationAwareLogger.TRACE_INT; case Debug: return LocationAwareLogger.DEBUG_INT; case Info: return LocationAwareLogger.INFO_INT; case Warn: return LocationAwareLogger.WARN_INT; case Error: return LocationAwareLogger.ERROR_INT; } return -1; } //toIntLevel /** * Write the formatted message (and possible Throwable) to the log * * @param fqcn The Fully Qualified Class Name of the Log class being used * @param level The Message Priority * @param fmt The <code>TextFormat</code> * @param args Replacement Arguments */ public void write (String fqcn,LogLevel level,TextFormat fmt,Object... args) { try { String msg = fmt.format(args); Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; log.log(null,fqcn,toIntLevel(level),msg,null,t); } catch(IndexOutOfBoundsException x) { log.log(null,fqcn,LocationAwareLogger.ERROR_INT,"Invalid Index in Log Statement \"{}\" - {}",new Object[] {fmt,x.getMessage()},null); } } //write /** * Test whether the logger is enabled for the supplied Level * * @param level The Logging Priority Level * @return true if enabled */ @Override public boolean isEnabledFor (LogLevel level) { switch(level) { case All: return true; case Trace: return log.isTraceEnabled(); case Debug: return log.isDebugEnabled(); case Info: return log.isInfoEnabled(); case Warn: return log.isWarnEnabled(); case Error: return log.isWarnEnabled(); } // None return false; } //isEnabledFor /** * Write a Log Message at the supplied Logback Priority * * @param level The Logging Priority Level * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void log (LogLevel level,String fmt,Object... args) { if(isEnabledFor(level)) { write(FQCN,level,formatCache.get(fmt),args); } } //log /** * Write a Log Message at the supplied Logback Priority * * @param level The Logging Priority Level * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void log (LogLevel level,TextFormat fmt,Object... args) { if(isEnabledFor(level)) { write(FQCN,level,fmt,args); } } //log /** * Log all the Readable Properties in a Bean * * @param level The Logging Priority Level integer * @param msg The lead in Message * @param bean The Bean to Log */ @Override public void bean (LogLevel level,String msg,Object bean) { if(isEnabledFor(level)) { if(msg != null) { log.log(null,FQCN,toIntLevel(level),formatCache.get(msg).format(bean),null,null); } if(bean != null) { try { for(Method method : BeanUtils.getAccessors(bean.getClass())) { try { log.log(null,FQCN,toIntLevel(level),BEAN_PROPERTY.format((Object)method.getName(),method.invoke(bean)),null,null); } catch(IllegalAccessException | InvocationTargetException ignore) { } } } catch(IntrospectionException ignore) { } } else { log.log(null,FQCN,toIntLevel(level),"<null>",null,null); } } } //bean /** * Check whether Trace Logging is Enabled * * @return true if trace logging is enabled */ @Override public boolean isTraceEnabled () { return log.isTraceEnabled(); } //isTraceEnabled /** * Write out a trace level message * * @param fmt The Log Message Format String * @param args The replacement arguments */ @Override public void trace (String fmt,Object... args) { if(log.isTraceEnabled()) { write(FQCN,LogLevel.Trace,formatCache.get(fmt),args); } } //trace /** * Write out a trace level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void trace (TextFormat fmt,Object... args) { if(log.isTraceEnabled()) { write(FQCN,LogLevel.Trace,fmt,args); } } //trace /** * Write out the bean properties at the trace level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void traceBean (String msg,Object bean) { if(log.isTraceEnabled()) { bean(LogLevel.Trace,msg,bean); } } //traceBean /** * Check whether Debug Logging is enabled * * @return true if debug logging is enabled */ @Override public boolean isDebugEnabled () { return log.isDebugEnabled(); } //isDebugEnabled /** * Write out a debug level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void debug (String fmt,Object... args) { if(log.isDebugEnabled()) { write(FQCN,LogLevel.Debug,formatCache.get(fmt),args); } } //debug /** * Write out a debug level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void debug (TextFormat fmt,Object... args) { if(log.isDebugEnabled()) { write(FQCN,LogLevel.Debug,fmt,args); } } //debug /** * Write out the bean properties at the debug level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void debugBean (String msg,Object bean) { if(log.isDebugEnabled()) { bean(LogLevel.Debug,msg,bean); } } //debugBean /** * Check whether informational logging is enabled * * @return true if enabled */ @Override public boolean isInfoEnabled () { return log.isInfoEnabled(); } //isInfoEnabled /** * Write out an informational level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void info (String fmt,Object... args) { if(log.isInfoEnabled()) { write(FQCN,LogLevel.Info,formatCache.get(fmt),args); } } //info /** * Write out an informational level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void info (TextFormat fmt,Object... args) { if(log.isInfoEnabled()) { write(FQCN,LogLevel.Info,fmt,args); } } //info /** * Check whether warning logging is enabled * * @return true if enabled */ @Override public boolean isWarnEnabled () { return log.isWarnEnabled(); } //isWarnEnabled /** * Write out a warning level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void warn (String fmt,Object... args) { if(log.isWarnEnabled()) { write(FQCN,LogLevel.Warn,formatCache.get(fmt),args); } } //warn /** * Write out a warning level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void warn (TextFormat fmt,Object... args) { if(log.isWarnEnabled()) { write(FQCN,LogLevel.Warn,fmt,args); } } //warn /** * Write out an error level message * * @param fmt The log message format string * @param args The replacement arguments */ @Override public void error (String fmt,Object... args) { if(log.isErrorEnabled()) { write(FQCN,LogLevel.Error,formatCache.get(fmt),args); } } //error /** * Write out an error level message * * @param fmt The log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void error (TextFormat fmt,Object... args) { if(log.isErrorEnabled()) { write(FQCN,LogLevel.Error,fmt,args); } } //error /** * Get the Effective Level for this Logger * * @return Logging Level */ @Override public LogLevel getEffectiveLevel () { if(log.isTraceEnabled()) { return LogLevel.Trace; } else if(log.isDebugEnabled()) { return LogLevel.Debug; } else if(log.isInfoEnabled()) { return LogLevel.Info; } else if(log.isWarnEnabled()) { return LogLevel.Warn; } else if(log.isErrorEnabled()) { return LogLevel.Error; } return LogLevel.None; } //getEffectiveLevel } //*SLF4jLog
Java
/** * Log4jLogFactory * * @author Chris Pratt * * 10/20/2011 */ package com.anodyzed.onyx.log.log4j; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.LogFactory; import org.apache.log4j.Logger; import org.apache.log4j.MDC; public class Log4jLogFactory implements LogFactory { @Override public Log getLogger () { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for(int i = 0;i < trace.length;i++) { if(trace[i].getClassName().equals(LogBuilder.FQBN)) { return new Log4jLog(Logger.getLogger(trace[i + 1].getClassName())); } } return null; } //getLogger @Override public Log getLogger (Class<?> clazz) { return new Log4jLog(Logger.getLogger(clazz)); } //getLogger @Override public Log getLogger (String category) { return new Log4jLog(Logger.getLogger(category)); } //getLogger /** * Set the Mapped Diagnostic Context Identifier for the current thread * * @param id The Identifier String */ @Override public void setId (String id) { MDC.put("id",id); } //setId /** * Set the value of a Mapped Diagnostic Context key for the current thread * * @param key The MDC Key * @param val The MDC Value */ @Override public void set (String key,String val) { MDC.put(key,val); } //set } //*Log4jLogFactory
Java
/** * Log4jLog * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.log.log4j; import com.anodyzed.onyx.bean.BeanUtils; import com.anodyzed.onyx.cache.Cache; import com.anodyzed.onyx.cache.CacheLoader; import com.anodyzed.onyx.cache.MRUCache; import com.anodyzed.onyx.cache.SimpleCache; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogLevel; import com.anodyzed.onyx.text.TextFormat; import com.anodyzed.onyx.util.SplayTreeMap; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.log4j.Level; import org.apache.log4j.Logger; /** * Java 5 Log4j Facade - Allows using format strings and variable argument lists * to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to Log4j's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public class Log4jLog implements Log { private static final String FQCN = Log4jLog.class.getName(); private static final TextFormat BEAN_PROPERTY = new TextFormat(" {0}: {1}"); private static final Cache<String,TextFormat> formatCache = new MRUCache<>(new SimpleCache<>("formatCache",null,new CacheLoader<String,TextFormat>() { @Override public TextFormat load (Object arg,String key) { return new TextFormat(key); } //load },new SplayTreeMap<String,TextFormat>()),100); private Logger log; /** * Constructor * * @param log The Log4j Logger */ public Log4jLog (Logger log) { this.log = log; } //Log4jLog /** * Get the wrapped Log4j Logger * * @return Log4j Logger */ public Logger getWrappedLogger () { return log; } //getWrappedLogger /** * Convert the LogLevel to the Log4j Level * * @param lvl The ELF4j LogLevel * @return The Log4j Log Level */ private Level level (LogLevel lvl) { switch(lvl) { case Debug: return Level.DEBUG; case Trace: return Level.TRACE; case Info: return Level.INFO; case Warn: return Level.WARN; case Error: return Level.ERROR; case None: return Level.OFF; case All: return Level.ALL; } return null; } //level /** * Write the formatted message (and possible Throwable) to the log * * @param lvl The Message Priority * @param fmt The <code>TextFormat</code> * @param args Replacement Arguments */ private void write (Level lvl,TextFormat fmt,Object... args) { try { Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; log.log(FQCN,lvl,fmt.format(args),t); } catch(IndexOutOfBoundsException x) { log.log(FQCN,Level.ERROR,"Invalid Index in Log Statement \"" + fmt + '\"',x); } catch(IllegalArgumentException x) { log.log(FQCN,Level.ERROR,"Invalid Argument in Log Statement \"" + fmt + '\"',x); } } //write /** * Log all the Readable Properties in a Bean * * @param lvl The Log4j Logging Priority Level * @param msg The lead-in message [optional] * @param bean The Bean to Log */ private void writeBean (Level lvl,String msg,Object bean) { if(log.isEnabledFor(lvl)) { if(msg != null) { log.log(FQCN,lvl,formatCache.get(msg).format(bean),null); } if(bean != null) { try { for(Method method : BeanUtils.getAccessors(bean.getClass())) { try { log.log(FQCN,lvl,BEAN_PROPERTY.format((Object)method.getName(),method.invoke(bean)),null); } catch(IllegalAccessException | InvocationTargetException ignore) { // fallthru } } } catch(IntrospectionException ignore) { } } else { log.log(FQCN,lvl,"<null>",null); } } } //writeBean /** * Test whether the logger is enabled for the supplied Logging Priority Level * * @param lvl The Logging Priority Level in question * @return true if enabled */ @Override public boolean isEnabledFor (LogLevel lvl) { return log.isEnabledFor(level(lvl)); } //isEnabledFor /** * Write a Log Message at the supplied Log4j Priority * * @param lvl The Logging Priority Level * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void log (LogLevel lvl,String fmt,Object... args) { Level pri = level(lvl); if(log.isEnabledFor(pri)) { write(pri,formatCache.get(fmt),args); } } //log /** * Write a Log Message at the supplied Log4j Priority * * @param lvl The Logging Priority Level * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void log (LogLevel lvl,TextFormat fmt,Object... args) { Level pri = level(lvl); if(log.isEnabledFor(pri)) { write(pri,fmt,args); } } //log /** * Log all the Readable Properties in a Bean * * @param lvl The Logging Priority Level * @param msg The lead in Message * @param bean The Bean to Log */ @Override public void bean (LogLevel lvl,String msg,Object bean) { writeBean(level(lvl),msg,bean); } //bean /** * Check whether Trace Logging is Enabled * * @return true if trace logging is enabled */ @Override public boolean isTraceEnabled () { return log.isTraceEnabled(); } //isTraceEnabled /** * Write out a trace level message * * @param fmt The Log Message Format String * @param args The replacement arguments */ @Override public void trace (String fmt,Object... args) { if(log.isTraceEnabled()) { write(Level.TRACE,formatCache.get(fmt),args); } } //trace /** * Write out a trace level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void trace (TextFormat fmt,Object... args) { if(log.isTraceEnabled()) { write(Level.TRACE,fmt,args); } } //trace /** * Write out the bean properties at the trace level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void traceBean (String msg,Object bean) { if(log.isTraceEnabled()) { writeBean(Level.TRACE,msg,bean); } } //traceBean /** * Check whether Debug Logging is enabled * * @return true if debug logging is enabled */ @Override public boolean isDebugEnabled () { return log.isDebugEnabled(); } //isDebugEnabled /** * Write out a debug level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void debug (String fmt,Object... args) { if(log.isDebugEnabled()) { write(Level.DEBUG,formatCache.get(fmt),args); } } //debug /** * Write out a debug level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void debug (TextFormat fmt,Object... args) { if(log.isDebugEnabled()) { write(Level.DEBUG,fmt,args); } } //debug /** * Write out the bean properties at the debug level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void debugBean (String msg,Object bean) { if(log.isDebugEnabled()) { writeBean(Level.DEBUG,msg,bean); } } //debugBean /** * Check whether informational logging is enabled * * @return true if enabled */ @Override public boolean isInfoEnabled () { return log.isInfoEnabled(); } //isInfoEnabled /** * Write out an informational level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void info (String fmt,Object... args) { if(log.isInfoEnabled()) { write(Level.INFO,formatCache.get(fmt),args); } } //info /** * Write out an informational level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void info (TextFormat fmt,Object... args) { if(log.isInfoEnabled()) { write(Level.INFO,fmt,args); } } //info /** * Check whether warning logging is enabled * * @return true if enabled */ @Override public boolean isWarnEnabled () { return log.isEnabledFor(Level.WARN); } //isWarnEnabled /** * Write out a warning level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void warn (String fmt,Object... args) { if(log.isEnabledFor(Level.WARN)) { write(Level.WARN,formatCache.get(fmt),args); } } //warn /** * Write out a warning level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void warn (TextFormat fmt,Object... args) { if(log.isEnabledFor(Level.WARN)) { write(Level.WARN,fmt,args); } } //warn /** * Write out an error level message * * @param fmt The log message format string * @param args The replacement arguments */ @Override public void error (String fmt,Object... args) { if(log.isEnabledFor(Level.ERROR)) { write(Level.ERROR,formatCache.get(fmt),args); } } //error /** * Write out an error level message * * @param fmt The log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void error (TextFormat fmt,Object... args) { if(log.isEnabledFor(Level.ERROR)) { write(Level.ERROR,fmt,args); } } //error /** * Get the Effective Level for this Logger * * @return Logging Level */ @Override public LogLevel getEffectiveLevel () { switch(log.getEffectiveLevel().toInt()) { case Level.DEBUG_INT: return LogLevel.Debug; case Level.TRACE_INT: return LogLevel.Trace; case Level.INFO_INT: return LogLevel.Info; case Level.WARN_INT: return LogLevel.Warn; case Level.ERROR_INT: case Level.FATAL_INT: return LogLevel.Error; case Level.ALL_INT: return LogLevel.All; case Level.OFF_INT: return LogLevel.None; } return null; } //getEffectiveLevel } //*Log4jLogger
Java
/** * Log4jLogContextInitializer * * @author Chris Pratt * * 11/11/2011 */ package com.anodyzed.onyx.log.log4j; import com.anodyzed.onyx.log.LogBuilder; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Log4jLogContextInitializer implements ServletContextListener { /** * The Servlet Context is being constructed, initialize the LogBuilder to use * this Factory * * @param event The Servlet Context Event */ @Override public void contextInitialized (ServletContextEvent event) { LogBuilder.setLogFactory(new Log4jLogFactory()); } //contextInitialized /** * The Servlet Context is being destroyed, clean up * * @param event The Servlet Context Event */ @Override public void contextDestroyed (ServletContextEvent event) { } //contextDestroyed } //*Log4jLogContextInitializer
Java
/** * LogBuilder * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.log; import com.anodyzed.onyx.log.sysout.SysOutLogFactory; /** * Java 5 Log4j Facade - Allows using format strings and variable argument lists * to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to Log4j's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public class LogBuilder { public static final String FQBN = LogBuilder.class.getName(); private static LogFactory factory; private static String tempId = null; /** * Set the Log Factory * * @param factory The Log Factory */ public static void setLogFactory (LogFactory factory) { LogBuilder.factory = factory; if(tempId != null) { factory.setId(tempId); tempId = null; } } //setLogFactory /** * Set the Mapped Diagnostic Context Identifier for the current thread * * @param id The Identifier String */ public static void setId (String id) { if(factory != null) { factory.setId(id); } else { tempId = id; } } //setId /** * Set the value of a Mapped Diagnostic Context key for the current thread * * @param key The MDC Key * @param val The MDC Value */ public static void set (String key,String val) { factory.set(key,val); } //set /** * Get the Log Object using the Call Stack to determine the appropriate Logger * * @return The Log Object */ public static Log getLogger () { if(factory == null) { factory = new SysOutLogFactory(); System.out.println("LogBuilder.setLoggerFactory not called, defaulting to SysOutLogFactory"); } return factory.getLogger(); } //getLogger /** * Get the Log Object for the supplied class * * @param clazz The Logger Class * @return The Log Object */ public static Log getLogger (Class<?> clazz) { if(factory == null) { factory = new SysOutLogFactory(); System.out.println("LogBuilder.setLoggerFactory not called, defaulting to SysOutLogFactory"); } return factory.getLogger(clazz); } //getLogger /** * Get the Log Object for the supplied category name * * @param category The Category Name * @return The Log Object */ public static Log getLogger (String category) { if(factory == null) { factory = new SysOutLogFactory(); System.out.println("LogBuilder.setLoggerFactory not called, defaulting to SysOutLogFactory"); } return factory.getLogger(category); } //getLogger } //*LogBuilder
Java
/** * LogInitializerBean * * @author Chris Pratt * * 2/13/2012 */ package com.anodyzed.onyx.log; import org.slf4j.bridge.SLF4JBridgeHandler; public class LogInitializerBean { /** * Constructor * * @param factory The Log Factory to install */ public LogInitializerBean (LogFactory factory) { LogBuilder.setLogFactory(factory); } //LogInitializerBean /** * Initialize the java.util.logging Bridge * * @param on true to initialize */ public void setBridgeJavaLogging (boolean on) { if(on) { SLF4JBridgeHandler.install(); } } //setBridgeJavaLogging } //*LogInitializerBean
Java
/** * LoggingMap * * @author Chris Pratt * * 11/10/2011 */ package com.anodyzed.onyx.log; import java.util.Collection; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingMap<K,V> implements Map<K,V> { private static final Logger log = LoggerFactory.getLogger(LoggingMap.class); private String name; private Map<K,V> map; /** * Constructor * * @param name The Map Name * @param map The Map Access to be Logged */ public LoggingMap (String name,Map<K,V> map) { this.name = name; this.map = map; } //LoggingMap /** * Get the Unwrapped Map * * @return The wrapped Map */ public Map<K,V> unwrap () { return map; } //unwrap /** * Get the Logging Map Name * * @return Map Name */ public String getName () { return name; } //getName /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ @Override public int size () { int size = map.size(); log.debug("{}.size() = {}",name,size); return size; } //size /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ @Override public boolean isEmpty () { boolean empty = map.isEmpty(); log.debug("{}.isEmpty() = {}",name,empty); return empty; } //isEmpty /** * Returns true if this map contains a mapping for the specified key. More * formally, returns true if and only if this map contains a mapping for a key * k such that (key==null ? k==null : key.equals(k)). (There can be at most * one such mapping.) * * @param key key whose presence in this map is to be tested * @return true if this map contains a mapping for the specified key */ @Override public boolean containsKey (Object key) { boolean contained = map.containsKey(key); log.debug("{}.containsKey({}) = {}",new Object[] {name,key,contained}); return contained; } //containsKey /** * Returns true if this map maps one or more keys to the specified value. More * formally, returns true if and only if this map contains at least one * mapping to a value v such that (value==null ? v==null : value.equals(v)). * This operation will probably require time linear in the map size for most * implementations of the Map interface. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the specified value */ @Override public boolean containsValue (Object value) { boolean contained = map.containsValue(value); log.debug("{}.containsValue({}) = {}",new Object[] {name,value,contained}); return contained; } //containsValue /** * Returns the value to which the specified key is mapped, or null if this map * contains no mapping for the key. * <p> * More formally, if this map contains a mapping from a key k to a value v * such that (key==null ? k==null : key.equals(k)), then this method returns * v; otherwise it returns null. (There can be at most one such mapping.) * <p> * If this map permits null values, then a return value of null does not * necessarily indicate that the map contains no mapping for the key; it's * also possible that the map explicitly maps the key to null. The containsKey * operation may be used to distinguish these two cases. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or null if this map * contains no mapping for the key */ @Override public V get (Object key) { V got = map.get(key); log.debug("{}.get({}) = {}",new Object[] {name,key,got}); return got; } //get /** * Associates the specified value with the specified key in this map (optional * operation). If the map previously contained a mapping for the key, the old * value is replaced by the specified value. (A map m is said to contain a * mapping for a key k if and only if m.containsKey(k) would return true.) * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or null if there was no * mapping for key. (A null return can also indicate that the map * previously associated null with key, if the implementation supports * null values.) */ @Override public V put (K key,V value) { V putted = map.put(key,value); log.debug("{}.put({},{}) = {}",new Object[] {name,key,value,putted}); return putted; } //put /** * Removes the mapping for a key from this map if it is present (optional * operation). More formally, if this map contains a mapping from key k to * value v such that (key==null ? k==null : key.equals(k)), that mapping is * removed. (The map can contain at most one such mapping.) * <p> * Returns the value to which this map previously associated the key, or null * if the map contained no mapping for the key. * <p> * If this map permits null values, then a return value of null does not * necessarily indicate that the map contained no mapping for the key; it's * also possible that the map explicitly mapped the key to null. * <p> * The map will not contain a mapping for the specified key once the call * returns. * * @param key key whose mapping is to be removed from the map * @return the previous value associated with key, or null if there was no * mapping for key. */ @Override public V remove (Object key) { V removed = map.remove(key); log.debug("{}.remove({}) = {}",new Object[] {name,key,removed}); return removed; } //remove /** * Copies all of the mappings from the specified map to this map (optional * operation). The effect of this call is equivalent to that of calling put(k, * v) on this map once for each mapping from key k to value v in the specified * map. The behavior of this operation is undefined if the specified map is * modified while the operation is in progress. * * @param m mappings to be stored in this map */ @Override public void putAll (Map<? extends K,? extends V> m) { log.debug("{}.putAll([{} values])",name,m.size()); map.putAll(m); } //putAll /** * Removes all of the mappings from this map (optional operation). The map * will be empty after this call returns. */ @Override public void clear () { log.debug("{}.clear() = {} values",name,map.size()); map.clear(); } //clear /** * Returns a Set view of the keys contained in this map. The set is backed by * the map, so changes to the map are reflected in the set, and vice-versa. If * the map is modified while an iteration over the set is in progress (except * through the iterator's own remove operation), the results of the iteration * are undefined. The set supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, Set.remove, * removeAll, retainAll, and clear operations. It does not support the add or * addAll operations. * * @return a set view of the keys contained in this map */ @Override public Set<K> keySet () { Set<K> keys = map.keySet(); log.debug("{}.keySet() = {} keys",name,keys.size()); return keys; } //keySet /** * Returns a Collection view of the values contained in this map. The * collection is backed by the map, so changes to the map are reflected in the * collection, and vice-versa. If the map is modified while an iteration over * the collection is in progress (except through the iterator's own remove * operation), the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding mapping from the * map, via the Iterator.remove, Collection.remove, removeAll, retainAll and * clear operations. It does not support the add or addAll operations. * * @return a collection view of the values contained in this map */ @Override public Collection<V> values () { Collection<V> values = map.values(); log.debug("{}.values() = {} values",name,values.size()); return values; } //values /** * Returns a Set view of the mappings contained in this map. The set is backed * by the map, so changes to the map are reflected in the set, and vice-versa. * If the map is modified while an iteration over the set is in progress * (except through the iterator's own remove operation, or through the * setValue operation on a map entry returned by the iterator) the results of * the iteration are undefined. The set supports element removal, which * removes the corresponding mapping from the map, via the Iterator.remove, * Set.remove, removeAll, retainAll and clear operations. It does not support * the add or addAll operations. * * @return a set view of the mappings contained in this map */ @Override public Set<Map.Entry<K,V>> entrySet () { Set<Map.Entry<K,V>> entries = map.entrySet(); log.debug("{}.entrySet() = {} entries",name,entries.size()); return entries; } //entrySet /** * Wrap the supplied Map in a Logging Map <b>IF</b> the current logging level * of the calling class is Debug or above. * * NB: The logging level is checked against the name of the calling class. * If some other log criteria is being used it will have to be checked * manually. * * NB: The debug log level is evaluated only once, when wrap is called. If * the logging level changes after the map has been wrapped, no change will be * observed by the Map returned from this call. * * @param name The Map Name * @param map The Map to be wrapped * @return The wrapped Map or the original map if debug is not enabled */ public static <K,V> Map<K,V> wrap (String name,Map<K,V> map) { Log log = LogBuilder.getLogger(Thread.currentThread().getStackTrace()[2].getClassName()); if(log.isDebugEnabled()) { return new LoggingMap<K,V>(name,map); } return map; } //wrap } //*LoggingMap
Java
/** * LogbackUtils * * @author Chris Pratt * * 7/28/2011 */ package com.anodyzed.onyx.log.logback; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.StackTraceElementProxy; public class LogbackUtils { /** * Private Constructor */ private LogbackUtils () { } //LogbackUtils /** * Turn the Throwable Proxy back into a Throwable for the Data Collection * Service * * @param proxy The Logback Throwable Proxy * @return The Java Throwable */ public static Throwable toThrowable (IThrowableProxy proxy) { if(proxy != null) { Throwable t = new Exception(proxy.getClassName() + ": " + proxy.getMessage()); int i = 0; StackTraceElementProxy[] proxies = proxy.getStackTraceElementProxyArray(); StackTraceElement[] stack = new StackTraceElement[proxies.length]; for(StackTraceElementProxy element : proxies) { stack[i] = element.getStackTraceElement(); } t.setStackTrace(stack); t.initCause(toThrowable(proxy.getCause())); return t; } return null; } //toThrowable } //*LogbackUtils
Java
/** * SLF4jLogContextInitializer * * @author Chris Pratt * * 11/11/2011 */ package com.anodyzed.onyx.log.logback; import com.anodyzed.onyx.log.LogBuilder; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class LogbackLogContextInitializer implements ServletContextListener { /** * The Servlet Context is being constructed, initialize the LogBuilder to use * this Factory * * @param event The Servlet Context Event */ @Override public void contextInitialized (ServletContextEvent event) { LogBuilder.setLogFactory(new LogbackLogFactory()); } //contextInitialized /** * The Servlet Context is being destroyed, clean up * * @param event The Servlet Context Event */ @Override public void contextDestroyed (ServletContextEvent event) { } //contextDestroyed } //*SLF4jLogContextInitializer
Java
/** * SLF4jLogFactory * * @author Chris Pratt * * 10/20/2011 */ package com.anodyzed.onyx.log.logback; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.LogFactory; import org.slf4j.LoggerFactory; import org.slf4j.MDC; public class LogbackLogFactory implements LogFactory { @Override public Log getLogger () { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for(int i = 0;i < trace.length;i++) { if(trace[i].getClassName().equals(LogBuilder.FQBN)) { return new LogbackLog(LoggerFactory.getLogger(trace[i + 1].getClassName())); } } return null; } //getLogger @Override public Log getLogger (Class<?> clazz) { return new LogbackLog(LoggerFactory.getLogger(clazz)); } //getLogger @Override public Log getLogger (String category) { return new LogbackLog(LoggerFactory.getLogger(category)); } //getLogger @Override public void setId (String id) { MDC.put("id",id); } //getId @Override public void set (String key,String val) { MDC.put(key,val); } //set } //*SLF4jLogFactory
Java
/** * SLF4jLog * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.log.logback; import ch.qos.logback.classic.Level; import com.anodyzed.onyx.bean.BeanUtils; import com.anodyzed.onyx.cache.Cache; import com.anodyzed.onyx.cache.CacheLoader; import com.anodyzed.onyx.cache.MRUCache; import com.anodyzed.onyx.cache.SimpleCache; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogLevel; import com.anodyzed.onyx.text.TextFormat; import com.anodyzed.onyx.util.SplayTreeMap; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.slf4j.Logger; import org.slf4j.spi.LocationAwareLogger; /** * Java 5+ Logback Facade - Allows using format strings and variable argument * lists to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to Logback's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public class LogbackLog implements Log { private static final String FQCN = LogbackLog.class.getName(); private static final TextFormat BEAN_PROPERTY = new TextFormat(" {0}: {1}"); private static final Cache<String,TextFormat> formatCache = new MRUCache<>(new SimpleCache<>("formatCache",null,new CacheLoader<String,TextFormat>() { @Override public TextFormat load (Object arg,String key) { return new TextFormat(key); } //load },new SplayTreeMap<String,TextFormat>()),100); private Logger log; /** * Constructor * * @param log The Logger to Delegate to */ protected LogbackLog (Logger log) { this.log = log; } //Log /** * Get the Wrapped Logger * * @return Wrapped Logger instance */ public Logger getWrappedLogger () { return log; } //getWrappedLogger /** * Convert the Logback Level integers to the Location Aware Logger Level * integers * * @param original Logging Level * @return Adjusted Logging Level */ // private int toLevel (int lvl) { // if(lvl > 100) { // switch(lvl) { // case Level.TRACE_INT: // return LocationAwareLogger.TRACE_INT; // case Level.DEBUG_INT: // return LocationAwareLogger.DEBUG_INT; // case Level.INFO_INT: // return LocationAwareLogger.INFO_INT; // case Level.WARN_INT: // return LocationAwareLogger.WARN_INT; // case Level.ERROR_INT: // return LocationAwareLogger.ERROR_INT; // } // } // return lvl; // } //toLevel /** * Convert the Log Level to a Logback Level * * @param level The Log Level * @return The Logback Level */ private Level toLevel (LogLevel level) { switch(level) { case All: return Level.ALL; case Trace: return Level.TRACE; case Debug: return Level.DEBUG; case Info: return Level.INFO; case Warn: return Level.WARN; case Error: return Level.ERROR; case None: return Level.OFF; } return null; } //toLevel /** * Write the formatted message (and possible Throwable) to the log * * @param fqcn The Fully Qualified Class Name of the Log class being used * @param level The Message Priority integer * @param fmt The <code>TextFormat</code> * @param args Replacement Arguments */ public void write (String fqcn,int level,TextFormat fmt,Object... args) { try { String msg = fmt.format(args); Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; ((ch.qos.logback.classic.Logger)log).log(null,fqcn,level,msg,null,t); } catch(IndexOutOfBoundsException x) { ((ch.qos.logback.classic.Logger)log).log(null,fqcn,LocationAwareLogger.ERROR_INT,"Invalid Index in Log Statement \"{}\" - {}",new Object[] {fmt,x.getMessage()},null); } } //write /** * Test whether the logger is enabled for the supplied Logback Priority * * @param level The Logging Priority Level * @return true if enabled */ @Override public boolean isEnabledFor (LogLevel level) { return ((ch.qos.logback.classic.Logger)log).isEnabledFor(toLevel(level)); } //isEnabledFor /** * Write a Log Message at the supplied Logback Priority * * @param level The Logging Priority Level * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void log (LogLevel level,String fmt,Object... args) { if(isEnabledFor(level)) { write(FQCN,toLevel(level).toInt(),formatCache.get(fmt),args); } } //log /** * Write a Log Message at the supplied Logback Priority * * @param level The Logging Priority Level * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void log (LogLevel level,TextFormat fmt,Object... args) { if(isEnabledFor(level)) { write(FQCN,toLevel(level).toInt(),fmt,args); } } //log /** * Log all the Readable Properties in a Bean * * @param level The Logging Priority Level integer * @param msg The lead in Message * @param bean The Bean to Log */ @Override public void bean (LogLevel level,String msg,Object bean) { Level lvl = toLevel(level); if(((ch.qos.logback.classic.Logger)log).isEnabledFor(toLevel(level))) { int ilvl = lvl.toInt(); if(msg != null) { ((LocationAwareLogger)log).log(null,FQCN,ilvl,formatCache.get(msg).format(bean),null,null); } if(bean != null) { try { for(Method method : BeanUtils.getAccessors(bean.getClass())) { try { ((LocationAwareLogger)log).log(null,FQCN,ilvl,BEAN_PROPERTY.format((Object)method.getName(),method.invoke(bean)),null,null); } catch(IllegalAccessException | InvocationTargetException ignore) { // fallthru } } } catch(IntrospectionException ignore) { } } else { ((LocationAwareLogger)log).log(null,FQCN,ilvl,"<null>",null,null); } } } //bean /** * Check whether Trace Logging is Enabled * * @return true if trace logging is enabled */ @Override public boolean isTraceEnabled () { return log.isTraceEnabled(); } //isTraceEnabled /** * Write out a trace level message * * @param fmt The Log Message Format String * @param args The replacement arguments */ @Override public void trace (String fmt,Object... args) { if(log.isTraceEnabled()) { write(FQCN,LocationAwareLogger.TRACE_INT,formatCache.get(fmt),args); } } //trace /** * Write out a trace level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void trace (TextFormat fmt,Object... args) { if(log.isTraceEnabled()) { write(FQCN,LocationAwareLogger.TRACE_INT,fmt,args); } } //trace /** * Write out the bean properties at the trace level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void traceBean (String msg,Object bean) { if(log.isTraceEnabled()) { bean(LogLevel.Trace,msg,bean); } } //traceBean /** * Check whether Debug Logging is enabled * * @return true if debug logging is enabled */ @Override public boolean isDebugEnabled () { return log.isDebugEnabled(); } //isDebugEnabled /** * Write out a debug level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void debug (String fmt,Object... args) { if(log.isDebugEnabled()) { write(FQCN,LocationAwareLogger.DEBUG_INT,formatCache.get(fmt),args); } } //debug /** * Write out a debug level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void debug (TextFormat fmt,Object... args) { if(log.isDebugEnabled()) { write(FQCN,LocationAwareLogger.DEBUG_INT,fmt,args); } } //debug /** * Write out the bean properties at the debug level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void debugBean (String msg,Object bean) { if(log.isDebugEnabled()) { bean(LogLevel.Debug,msg,bean); } } //debugBean /** * Check whether informational logging is enabled * * @return true if enabled */ @Override public boolean isInfoEnabled () { return log.isInfoEnabled(); } //isInfoEnabled /** * Write out an informational level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void info (String fmt,Object... args) { if(log.isInfoEnabled()) { write(FQCN,LocationAwareLogger.INFO_INT,formatCache.get(fmt),args); } } //info /** * Write out an informational level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void info (TextFormat fmt,Object... args) { if(log.isInfoEnabled()) { write(FQCN,LocationAwareLogger.INFO_INT,fmt,args); } } //info /** * Check whether warning logging is enabled * * @return true if enabled */ @Override public boolean isWarnEnabled () { return log.isWarnEnabled(); } //isWarnEnabled /** * Write out a warning level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void warn (String fmt,Object... args) { if(log.isWarnEnabled()) { write(FQCN,LocationAwareLogger.WARN_INT,formatCache.get(fmt),args); } } //warn /** * Write out a warning level message * * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void warn (TextFormat fmt,Object... args) { if(log.isWarnEnabled()) { write(FQCN,LocationAwareLogger.WARN_INT,fmt,args); } } //warn /** * Write out an error level message * * @param fmt The log message format string * @param args The replacement arguments */ @Override public void error (String fmt,Object... args) { if(log.isErrorEnabled()) { write(FQCN,LocationAwareLogger.ERROR_INT,formatCache.get(fmt),args); } } //error /** * Write out an error level message * * @param fmt The log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void error (TextFormat fmt,Object... args) { if(log.isErrorEnabled()) { write(FQCN,LocationAwareLogger.ERROR_INT,fmt,args); } } //error /** * Get the Effective Level for this Logger * * @return Logging Level */ @Override public LogLevel getEffectiveLevel () { switch(((ch.qos.logback.classic.Logger)log).getEffectiveLevel().toInt()) { case Level.DEBUG_INT: return LogLevel.Debug; case Level.TRACE_INT: return LogLevel.Trace; case Level.INFO_INT: return LogLevel.Info; case Level.WARN_INT: return LogLevel.Warn; case Level.ERROR_INT: return LogLevel.Error; case Level.ALL_INT: return LogLevel.All; case Level.OFF_INT: return LogLevel.None; } return null; } //getEffectiveLevel } //*SLF4jLog
Java
/** * LogException * * @author Chris Pratt * * 7/23/2011 */ package com.anodyzed.onyx.log; @SuppressWarnings("serial") public class LogException extends RuntimeException { /** * No-arg Constructor */ public LogException () { super(); } //LogException /** * Constructor * * @param msg A Descriptive Message about the cause of the Exception */ public LogException (String msg) { super(msg); } //LogException /** * Constructor * * @param cause The Throwable that initiated this Exception Chain */ public LogException (Throwable cause) { super(cause); } //LogException /** * Constructor * * @param msg A Descriptive Message about the cause of the Exception * @param cause The Throwable that initiated this Exception Chain */ public LogException (String msg,Throwable cause) { super(msg,cause); } //LogException } //*LogException
Java
/** * Log * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.log; import com.anodyzed.onyx.text.TextFormat; /** * Java 5 Log Facade - Allows using format strings and variable argument lists * to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to Log4j's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public interface Log { /** * Test whether the logger is enabled for the supplied Logging Priority * * @param lvl The Log Priority Level * @return true if enabled */ boolean isEnabledFor (LogLevel lvl); /** * Write a Log Message at the supplied Logging Priority * * @param lvl The Log Priority Level * @param fmt The Log message format string * @param args The replacement arguments */ void log(LogLevel lvl,String fmt,Object... args); /** * Write a Log Message at the supplied Logging Priority using the pre-parsed * <code>TextFormat</code> * * @param lvl The Log Priority Level * @param fmt The <code>TextFormat</code> for the message * @param args The replacement arguments */ void log(LogLevel lvl,TextFormat fmt,Object... args); /** * Log all the Readable Properties in a Bean * * @param lvl The Log Priority Level * @param msg The lead in Message * @param bean The Bean to Log */ void bean(LogLevel lvl,String msg,Object bean); /** * Check whether Trace Logging is Enabled * * @return true if trace logging is enabled */ boolean isTraceEnabled(); /** * Write out a trace level message * * @param fmt The Log Message Format String * @param args The replacement arguments */ void trace(String fmt,Object... args); /** * Write out a trace level message formatted with the pre-parsed * <code>TextFormat</code> * * @param fmt The <code>TextFormat</code> for the message * @param args The replacement parameters */ void trace(TextFormat fmt,Object... args); /** * Write out the bean properties at the trace level * * @param msg A descriptive message * @param bean The Bean being debugged */ void traceBean(String msg,Object bean); /** * Check whether Debug Logging is enabled * * @return true if debug logging is enabled */ boolean isDebugEnabled(); /** * Write out a debug level message * * @param fmt The Log message format string * @param args The replacement arguments */ void debug(String fmt,Object... args); /** * Write out a debug level message formatted with the pre-parsed * <code>TextFormat</code> * * @param fmt The <code>TextFormat</code> for the message * @param args The replacement parameters */ void debug(TextFormat fmt,Object... args); /** * Write out the bean properties at the debug level * * @param msg A descriptive message * @param bean The Bean being debugged */ void debugBean(String msg,Object bean); /** * Check whether informational logging is enabled * * @return true if enabled */ boolean isInfoEnabled(); /** * Write out an informational level message * * @param fmt The Log message format string * @param args The replacement arguments */ void info(String fmt,Object... args); /** * Write out an informational level message formatted with the pre-parsed * <code>TextFormat</code> * * @param fmt The <code>TextFormat</code> for the message * @param args The replacement parameters */ void info(TextFormat fmt,Object... args); /** * Check whether warning logging is enabled * * @return true if enabled */ boolean isWarnEnabled(); /** * Write out a warning level message * * @param fmt The Log message format string * @param args The replacement arguments */ void warn(String fmt,Object... args); /** * Write out a warning level message formatted with the pre-parsed * <code>TextFormat</code> * * @param fmt The <code>TextFormat</code> for the message * @param args The replacement parameters */ void warn(TextFormat fmt,Object... args); /** * Write out an error level message * * @param fmt The log message format string * @param args The replacement arguments */ void error(String fmt,Object... args); /** * Write out an error level message formatted with the pre-parsed * <code>TextFormat</code> * * @param fmt The <code>TextFormat</code> for the message * @param args The replacement parameters */ void error(TextFormat fmt,Object... args); /** * Get the Effective Level for this Logger * * @return Logging Level */ LogLevel getEffectiveLevel(); } //*Log
Java
/** * LogLevel * * @author Chris Pratt * * 7/23/2011 */ package com.anodyzed.onyx.log; import com.anodyzed.onyx.util.Misc; public enum LogLevel { None, Error, Warn, Info, Debug, Trace, All; /** * Determine whether the current level is Greater Than or Equal To the * supplied level. * * @param level The suspect Log Level * @return true if greater or equal */ public boolean isGreaterOrEqual (LogLevel level) { return ordinal() <= level.ordinal(); } //isGreaterOrEqual /** * Convert the String Level Name to the Log Level. Return the default Level * if level is null or doesn't match any level names. * * @param level The Level Name * @param def The Default Level * @return The corresponding or default LogLevel */ public static LogLevel toLevel (String level,LogLevel def) { if(!Misc.isEmpty(level)) { for(LogLevel lvl : values()) { if(level.equalsIgnoreCase(lvl.name())) { return lvl; } } } return def; } //toLevel /** * Convert the String Level Name to the Log Level * * @param level The Level Name * @return The corresponding LogLevel (or null) */ public static LogLevel toLevel (String level) { return toLevel(level,null); } //toLevel } //*LogLevel
Java
/** * JULLogContextInitializer * * @author Chris Pratt * * 11/11/2011 */ package com.anodyzed.onyx.log.jul; import com.anodyzed.onyx.log.LogBuilder; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class JULLogContextInitializer implements ServletContextListener { /** * ServletContextListener: The Servlet Context is being constructed, * initialize the LogBuilder to use this Factory. * * @param event The Servlet Context Event */ @Override public void contextInitialized (ServletContextEvent event) { LogBuilder.setLogFactory(new JULLogFactory()); } //contextInitialized /** * ServletContextListener: The Servlet Context is being destroyed, clean up. * * @param event The Servlet Context Event */ @Override public void contextDestroyed (ServletContextEvent event) { } //contextDestroyed } //*JULLogContextInitializer
Java
/** * JULLogFactory * * @author Chris Pratt * * 10/20/2011 */ package com.anodyzed.onyx.log.jul; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.LogFactory; import java.util.logging.Logger; public class JULLogFactory implements LogFactory { @Override public Log getLogger () { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for(int i = 0;i < trace.length;i++) { if(trace[i].getClassName().equals(LogBuilder.FQBN)) { return new JULLog(Logger.getLogger(trace[i + 1].getClassName())); } } return null; } //getLogger @Override public Log getLogger (Class<?> clazz) { return new JULLog(Logger.getLogger(clazz.getName())); } //getLogger @Override public Log getLogger (String category) { return new JULLog(Logger.getLogger(category)); } //getLogger /** * Set the Mapped Diagnostic Context Identifier for the current thread * * @param id The Identifier String */ @Override public void setId (String id) { } //setId /** * Set the value of a Mapped Diagnostic Context key for the current thread * * @param key The MDC Key * @param val The MDC Value */ @Override public void set (String key,String val) { } //set } //*JULLogFactory
Java
/** * Log4jLog * * @author Chris Pratt * * 10/23/2007 */ package com.anodyzed.onyx.log.jul; import com.anodyzed.onyx.bean.BeanUtils; import com.anodyzed.onyx.cache.Cache; import com.anodyzed.onyx.cache.CacheLoader; import com.anodyzed.onyx.cache.MRUCache; import com.anodyzed.onyx.cache.SimpleCache; import com.anodyzed.onyx.log.Log; import com.anodyzed.onyx.log.LogLevel; import com.anodyzed.onyx.text.TextFormat; import com.anodyzed.onyx.util.SplayTreeMap; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** * Java 5 java.util.logging Facade - Allows using format strings and variable * argument lists to build log messages efficiently. * * Since there is no up-front string processing used to construct the log * message, if the logger is set above the level of the log method called, it is * quickly and quietly ignored, with no processing. * * If, on the other hand, the log level is below the level of the log method * called, the format string is processed and the supplied arguments are used to * build the log message. * * The Log message format string is comprised of static text with interspersed * replacement argument placeholders. The placeholders begin with '{' and end * with '}'. * * Example: * <code>"Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}"</code> * * The simplest is just the (zero based) index of the argument used to replace * the placeholder. Additionally you can add a dot separated string of bean * property names to access from the indexed argument. Lastly, you can use the * java.text.MessageFormat style comma separated format descriptors to format * each replacement element. * * Example: * <code>log.debug("Simple {0}, More Complex {1.lastname}, Even More Complex * {2.address.city}, Most Complex {1.birthDate,date,yyyyMMdd}", * 5, user, company);</code> * * Might write out: * <code>Simple 5, More Complex Chris, Even More Complex Sacramento, * Most Complex 19640123</code> * * Oh, one last thing, if the last argument is an instance of Throwable, it will * be passed on to java.util.logging's Throwable support * * @see com.anodyzed.onyx.text.TextFormat */ public class JULLog implements Log { private static final String FQCN = JULLog.class.getName(); private static final TextFormat BEAN_PROPERTY = new TextFormat(" {0}: {1}"); private static final Cache<String,TextFormat> formatCache = new MRUCache<>(new SimpleCache<>("formatCache",null,new CacheLoader<String,TextFormat>() { @Override public TextFormat load (Object arg,String key) { return new TextFormat(key); } //load },new SplayTreeMap<String,TextFormat>()),100); private Logger log; /** * Constructor * * @param log The Log4j Logger */ public JULLog (Logger log) { this.log = log; } //Log4jLog /** * Get the wrapped Log4j Logger * * @return Log4j Logger */ public Logger getWrappedLogger () { return log; } //getWrappedLogger /** * Convert the LogLevel to the Log4j Level * * @param lvl The ELF4j LogLevel * @return The Log4j Log Level */ private Level level (LogLevel lvl) { switch(lvl) { case Debug: return Level.CONFIG; case Trace: return Level.FINE; case Info: return Level.INFO; case Warn: return Level.WARNING; case Error: return Level.SEVERE; case None: return Level.OFF; case All: return Level.ALL; } return null; } //level /** * Find the Stack Trace Element of the caller of the log statement * * @return The current Class & Method Names */ private String[] getCaller () { int i = 0; StackTraceElement[] elements = Thread.currentThread().getStackTrace(); while(i < elements.length) { if(elements[i++].getClassName().equals(FQCN)) { while(i < elements.length) { if(!elements[i].getClassName().equals(FQCN)) { String[] caller = new String[2]; caller[0] = elements[i].getClassName(); caller[1] = elements[i].getMethodName(); return caller; } ++i; } } } return null; } //getCaller /** * Write the formatted message (and possible Throwable) to the log using the * pre-parsed <code>TextFormat</code> * * @param lvl The Message Priority Level * @param fmt The <code>TextFormat</code> of the message * @param args Replacement Arguments */ private void write (Level lvl,TextFormat fmt,Object... args) { String[] caller = getCaller(); try { String msg = fmt.format(args); Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; if(t != null) { log.logp(lvl,caller[0],caller[1],msg,t); } else { log.logp(lvl,caller[0],caller[1],msg); } } catch(IndexOutOfBoundsException x) { log.logp(Level.SEVERE,caller[0],caller[1],"Invalid Index in Log Statement \"" + fmt + '\"',x); } catch(IllegalArgumentException x) { log.logp(Level.SEVERE,caller[0],caller[1],"Invalid Argument in Log Statement \"" + fmt + '\"',x); } } //write /** * Log all the Readable Properties in a Bean * * @param lvl The Logging Level * @param msg The lead-in message [optional] * @param bean The Bean to Log */ private void writeBean (Level lvl,String msg,Object bean) { if(isEnabledFor(lvl)) { String[] caller = getCaller(); if(msg != null) { log.logp(lvl,caller[0],caller[1],formatCache.get(msg).format(bean)); } if(bean != null) { try { for(Method method : BeanUtils.getAccessors(bean.getClass())) { try { log.logp(lvl,caller[0],caller[1],BEAN_PROPERTY.format((Object)method.getName(),method.invoke(bean))); } catch(IllegalAccessException | InvocationTargetException x) { // fallthru } } } catch(IntrospectionException x) { // fallthru } } else { log.logp(lvl,caller[0],caller[1],"<null>"); } } } //writeBean /** * Test whether the logger is enabled for the suppled Logging Level * * @param lvl The java.util.logging.Level in question * @return true if enabled */ private boolean isEnabledFor (Level lvl) { return log.isLoggable(lvl); } //isEnabledFor /** * Test whether the logger is enabled for the supplied Logging Priority Level * * @param lvl The Logging Priority Level in question * @return true if enabled */ @Override public boolean isEnabledFor (LogLevel lvl) { return log.isLoggable(level(lvl)); } //isEnabledFor /** * Write a Log Message at the supplied Log4j Priority * * @param lvl The Logging Priority Level * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void log (LogLevel lvl,String fmt,Object... args) { if(isEnabledFor(lvl)) { write(level(lvl),formatCache.get(fmt),args); } } //log /** * Write a Log Message at the supplied Log4j Priority * * @param lvl The Logging Priority Level * @param fmt The Log message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void log (LogLevel lvl,TextFormat fmt,Object... args) { if(isEnabledFor(lvl)) { write(level(lvl),fmt,args); } } //log /** * Log all the Readable Properties in a Bean * * @param lvl The Logging Priority Level * @param msg The lead in Message * @param bean The Bean to Log */ @Override public void bean (LogLevel lvl,String msg,Object bean) { writeBean(level(lvl),msg,bean); } //bean /** * Check whether Trace Logging is Enabled * * @return true if trace logging is enabled */ @Override public boolean isTraceEnabled () { return log.isLoggable(Level.FINE); } //isTraceEnabled /** * Write out a trace level message * * @param fmt The Log Message Format String * @param args The replacement arguments */ @Override public void trace (String fmt,Object... args) { if(log.isLoggable(Level.FINE)) { write(Level.FINE,formatCache.get(fmt),args); } } //trace /** * Write out a trace level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void trace (TextFormat fmt,Object... args) { if(log.isLoggable(Level.FINE)) { write(Level.FINE,fmt,args); } } //trace /** * Write out the bean properties at the trace level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void traceBean (String msg,Object bean) { if(log.isLoggable(Level.FINE)) { writeBean(Level.FINE,msg,bean); } } //traceBean /** * Check whether Debug Logging is enabled * * @return true if debug logging is enabled */ @Override public boolean isDebugEnabled () { return log.isLoggable(Level.CONFIG); } //isDebugEnabled /** * Write out a debug level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void debug (String fmt,Object... args) { if(log.isLoggable(Level.CONFIG)) { write(Level.CONFIG,formatCache.get(fmt),args); } } //debug /** * Write out a debug level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void debug (TextFormat fmt,Object... args) { if(log.isLoggable(Level.CONFIG)) { write(Level.CONFIG,fmt,args); } } //debug /** * Write out the bean properties at the debug level * * @param msg A descriptive message * @param bean The Bean being debugged */ @Override public void debugBean (String msg,Object bean) { if(log.isLoggable(Level.CONFIG)) { writeBean(Level.CONFIG,msg,bean); } } //debugBean /** * Check whether informational logging is enabled * * @return true if enabled */ @Override public boolean isInfoEnabled () { return log.isLoggable(Level.INFO); } //isInfoEnabled /** * Write out an informational level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void info (String fmt,Object... args) { if(log.isLoggable(Level.INFO)) { write(Level.INFO,formatCache.get(fmt),args); } } //info /** * Write out an informational level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void info (TextFormat fmt,Object... args) { if(log.isLoggable(Level.INFO)) { write(Level.INFO,fmt,args); } } //info /** * Check whether warning logging is enabled * * @return true if enabled */ @Override public boolean isWarnEnabled () { return log.isLoggable(Level.WARNING); } //isWarnEnabled /** * Write out a warning level message * * @param fmt The Log message format string * @param args The replacement arguments */ @Override public void warn (String fmt,Object... args) { if(log.isLoggable(Level.WARNING)) { write(Level.WARNING,formatCache.get(fmt),args); } } //warn /** * Write out a warning level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void warn (TextFormat fmt,Object... args) { if(log.isLoggable(Level.WARNING)) { write(Level.WARNING,fmt,args); } } //warn /** * Write out an error level message * * @param fmt The log message format string * @param args The replacement arguments */ @Override public void error (String fmt,Object... args) { if(log.isLoggable(Level.SEVERE)) { write(Level.SEVERE,formatCache.get(fmt),args); } } //error /** * Write out an error level message * * @param fmt The Log Message <code>TextFormat</code> * @param args The replacement arguments */ @Override public void error (TextFormat fmt,Object... args) { if(log.isLoggable(Level.SEVERE)) { write(Level.SEVERE,fmt,args); } } //error /** * Get the Effective Level for this Logger * * @return Logging Level */ @Override public LogLevel getEffectiveLevel () { switch(log.getLevel().intValue()) { case 700: // Level.CONFIG: return LogLevel.Debug; case 500: // Level.FINE: return LogLevel.Trace; case 800: // Level.INFO: return LogLevel.Info; case 900: // Level.WARNING: return LogLevel.Warn; case 1000: // Level.SEVERE: return LogLevel.Error; case Integer.MIN_VALUE: // Level.ALL: return LogLevel.All; case Integer.MAX_VALUE: // Level.OFF: return LogLevel.None; } return null; } //getEffectiveLevel } //*Log4jLogger
Java
/** * Period * * @author Chris Pratt * * 12/2/2010 */ package com.anodyzed.onyx.util; import com.anodyzed.onyx.text.TextFormat; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Iterator; @SuppressWarnings("serial") public class Period implements Iterable<Date>, Serializable { private static final TextFormat toStr = new TextFormat("{0.start,date,yyyy-MM-dd HH:mm} - {0.end,date,yyyy-MM-dd HH:mm}"); private Date start; private Date end; private Date inc = null; private int resolution = Calendar.MILLISECOND; /** * No-arg Bean Constructor */ public Period () { } //Period /** * Constructor * * @param start The Beginning Date of the Period * @param end The Final Date of the Period */ public Period (Date start,Date end) { this.start = start; this.end = end; } //Period /** * Constructor * * @param start The Starting Calendar * @param end The Ending Calendar */ public Period (Calendar start,Calendar end) { this(start.getTime(),end.getTime()); } //Period /** * Constructor * * @param start The Starting Date * @param duration The duration of the Period * @param unit The unit of the duration */ public Period (Date start,int duration,int unit) { this(Convert.toCalendar(start),duration,unit); } //Period /** * Constructor * * @param start The Starting Calendar * @param duration The duration of the Period * @param unit The unit of the duration */ public Period (Calendar start,int duration,int unit) { this.start = start.getTime(); start.add(unit,duration); this.end = start.getTime(); } //Period /** * Get the value of the start attribute. * * @return The start value as a Date */ public Date getStart () { return start; } //getStart /** * Set the value of the start attribute. * * @param start The new start value as a Date * @return this Period */ public Period setStart (Date start) { this.start = start; return this; } //setStart /** * Set the value of the start attribute. * * @param cal The new start value as a Calendar * @return this Period */ public Period setStart (Calendar cal) { return setStart(cal.getTime()); } //setStart /** * Get the Duration of the Period. * * @return duration */ public int getDuration () { return Chrono.change(end,start,resolution); } //getDuration /** * Set the value of the end attribute by specifying the duration of the period * * @param duration The length of the Period * @param unit The duration unit (i.e. Calendar.DATE) * @return this Period */ public Period setDuration (int duration,int unit) { end = Chrono.add(start,duration - 1,unit); inc = null; resolution = unit; return this; } //setDuration /** * Calculate the duration (in milliseconds) between the two dates * * @return period duration (in ms) */ public long getDurationInMillis () { if((getStart() != null) && (getEnd() != null)) { return end.getTime() - start.getTime(); } throw new NullPointerException("start and end dates cannot be null"); } //getDurationInMillis /** * Get the duration between steps when using the iterator defined by this * Period. * * @return Iteration Resolution */ public int getResolution () { return resolution; } //getResolution /** * Set the duration between steps when using the iterator defined by this * Period. * * @param resolution The Iteration Resolution * @return this Period */ public Period setResolution (int resolution) { this.resolution = resolution; return this; } //setResolution /** * Get the value of the end attribute. * * @return The end value as a Date */ public Date getEnd () { return end; } //getEnd /** * Set the value of the end attribute. * * @param end The new end value as a Date * @return this Period */ public Period setEnd (Date end) { this.end = end; return this; } //setEnd /** * Set the value of the end attribute. * * @param cal The new end value as a Calendar * @return this Period */ public Period setEnd (Calendar cal) { return setEnd(cal.getTime()); } //setEnd /** * Get the End Date that includes the last unit * * @return Inclusive End Date */ private Date getEndInclusive () { if(inc == null) { inc = Chrono.add(end,1,resolution); } return inc; } //getEndInclusive /** * Create a Period from Midnight on the morning of the start date to midnight * the night of the end date (i.e. midnight of the next morning). * * @param start The Starting Date of the Unit * @param end The Ending Date of the Unit * @param unit The Calendar Unit * @return The Period */ public static Period getPeriod (Date start,Date end,int unit) { return new Period().setStart(Chrono.clearTo(start,unit)).setEnd(Chrono.clearTo(end,unit)).setResolution(unit); } //getPeriod /** * Create a Period from Midnight on the morning of the start calendar to * midnight the night of the end calendar (i.e. midnight of the next morning). * * @param start The Starting Calendar of the Unit * @param end The Ending Calendar of the Unit * @param unit The Calendar Unit * @return The Period */ public static Period getPeriod (Calendar start,Calendar end,int unit) { return new Period().setStart(Chrono.clearTo(start,unit)).setEnd(Chrono.clearTo(end,unit)).setResolution(unit); } //getPeriod /** * Create a Period from the Beginning <code>unit</code> of the * <code>start</code> time, going to the end of the time unit * <code>duration</code> units later. * * For example a Period from <code>2012/11/19 22:09:30</code> with a * <code>duration</code> of <code>7</code> and a <code>unit</code> of * <code>Calendar.DATE</code> would yield a Period stretching from * <code>2012/11/19 00:00:00</code> through <code>2012/11/27 00:00:00</code> * * @param start The Starting Date * @param duration The number of units in the Period * @param unit The Calendar Units for the duration * @return The Period */ public static Period getPeriod (Date start,int duration,int unit) { return new Period().setStart(Chrono.clearTo(start,unit)).setEnd(Chrono.clearTo(Chrono.add(start,duration - 1,unit),unit)).setResolution(unit); } //getPeriod /** * Create a Period from the Beginning <code>unit</code> of the * <code>start</code> time, going to the end of the time unit * <code>duration</code> units later. * * For example a Period from <code>2012/11/19 22:09:30</code> with a * <code>duration</code> of <code>7</code> and a <code>unit</code> of * <code>Calendar.DATE</code> would yield a Period stretching from * <code>2012/11/19 00:00:00</code> through <code>2012/11/27 00:00:00</code> * * @param start The Starting Date * @param duration The number of units in the Period * @param unit The Calendar Units for the duration * @return The Period */ public static Period getPeriod (Calendar start,int duration,int unit) { return new Period().setStart(Chrono.clearTo(start,unit)).setEnd(Chrono.clearTo(Chrono.add(start,duration - 1,unit),unit)).setResolution(unit); } //getPeriod /** * Test whether the supplied Date is contained within the Period. * * @param date The Date to check * @return true if <code>date</code> is within the Period */ public boolean contains (Date date) { return !date.before(getStart()) && !date.after(getEndInclusive()); } //contains /** * Test whether the supplied Calendar is contained within the Period. * * @param cal The Calendar to check * @return true if <code>cal</code> is within the Period */ public boolean contains (Calendar cal) { return contains(cal.getTime()); } //contains /** * Iterable: Iterate over the Period * * @return Date Iterator */ @Override public Iterator<Date> iterator () { return new Iterator<Date>() { Calendar cal = null; Calendar next = Convert.toCalendar(getStart()); /** * Check if there's another unit in the Period * * @return true if more unit's available */ @Override public boolean hasNext () { boolean ret = true; if(cal != null) { next.add(resolution,1); ret = !Chrono.after(next,getEnd(),resolution); } return ret; } //hasNext /** * Get the Date of the Next Unit * * @return Next unit's Date */ @Override public Date next () { cal = next; return next.getTime(); } //next /** * Remove the underlying Date from the Period? This operation is not * supported! * * @exception UnsupportedOperationException Always! Because this Operation * is not supported */ @Override public void remove () { throw new UnsupportedOperationException("It is not possible to remove a Date from a Period"); } //remove }; } //iterator /** * Return a String representation of the Period. * * @return String Period description */ @Override public String toString () { return toStr.format(this); } //toString } //*Period
Java
/** * Hex * * @author Chris Pratt * @version 1.0 * * 11/30/1998 */ package com.anodyzed.onyx.util; import java.io.PrintWriter; import java.io.StringWriter; public class Hex { private static final char[] DECIMAL = {'0','1','2','3','4','5','6','7','8','9'}; private static final char[] DIGITS = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; /** * Constructor - Private to prevent instantiation */ private Hex () { } //Hex /** * Return the decimal character for the integer value * * @param c The integer value * @return the character */ public static char chr (int c) { return DECIMAL[c & 0xF]; } //chr /** * Return the hexadecimal character for the integer value * * @param c The integer value * @return the character (upper-case) */ public static char hex (int c) { return DIGITS[c & 0xF]; } //hex /** * Return the ordinal number of the character provided * * @param c One of (0 - 9, A - F, a - f) * @return An integer between 0 and 15 */ public static int ord (char c) { if(c <= '9') { return (c) - ('0'); } else if(c <= 'F') { return (c) - ('A') + 10; } else { return (c) - ('a') + 10; } } //ord /** * Convert an array of bytes to an (upper-case) string of hexadecimal characters * * @param bytes The array of bytes * @return the printable string */ public static String toString (byte[] bytes) { StringBuilder buf = new StringBuilder(bytes.length * 2); for(byte b : bytes) { buf.append(DIGITS[(b & 0xF0) >> 4]).append(DIGITS[b & 0x0F]); } return buf.toString(); } //toString /** * Parse a string of hexadecimal characters into an array of bytes * * @param str The string to be parsed * @return an array of bytes */ public static byte[] parseBytes (String str) { int pos = 0,count = str.length() / 2; byte[] bytes = new byte[count]; for(int i = 0;i < count;i++) { bytes[i] = (byte)Integer.parseInt(str.substring(pos++,pos++),16); } return bytes; } //parseBytes /** * Return a string representation of the offset right padded with 0's * suitable for printing * * @param num the Offset Index * @return The Offset String */ private static String offset (int num) { char[] buf = new char[6]; buf[0] = chr(num / 100000); num %= 100000; buf[1] = chr(num / 10000); num %= 10000; buf[2] = chr(num / 1000); num %= 1000; buf[3] = chr(num / 100); num %= 100; buf[4] = chr(num / 10); buf[5] = chr(num % 10); return new String(buf); } //offset /** * Create a Hex dump * * @param buf The Buffer of Bytes to be output * @param off The Offset from the beginning of the buffer * @param len The Number of bytes to be written * @return A String containing the Hex Dump */ public static String dump (byte[] buf,int off,int len) { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); int i; int pos = off; int count,size = len; while(size > 0) { out.print(offset(pos) + ": "); count = (size >= 16) ? 16 : size; for(i = 0;i < count;i++) { if(i == 8) { out.print(' '); } out.print(hex(buf[i + pos] >>> 4)); out.print(hex(buf[i + pos])); out.print(' '); } if(i < 16) { if(i <= 8) { out.print(' '); } while(i++ < 16) { out.print(" "); } } out.print(' '); for(i = 0;i < count;i++) { if(i == 8) { out.print(' '); } if((buf[i + pos] >= 32) && (buf[i] < 128)) { out.print((char)buf[i + pos]); } else { out.print('.'); } } out.println(); pos += count; size -= count; } return str.toString(); } //dump /** * Create a hex dump * * @param buf The buffer of bytes to be output * @return A String containing the Hex Dump */ public static String dump (byte[] buf) { return dump(buf,0,buf.length); } //dump /** * Create a hex dump * * @param buf The string of bytes to be output * @return A String containing the Hex Dump */ public static String dump (String buf) { return dump(buf.getBytes()); } //dump /** * Create a hex dump * * @param buf an array of characters * @return a string containing the Hex Dump */ public static String dump (char[] buf) { return dump(new String(buf)); } //dump /** * Create a hex dump * * @param buf an array of characters * @param ofs the starting offset in the array * @param len the number of characters to dump * @return a string containing the Hex Dump */ public static String dump (char[] buf,int ofs,int len) { return dump(new String(buf,ofs,len)); } //dump /** * Hex Dump an Object * * @param obj The object to be dumped * @return The Hex Dump of the object */ public static String dump (Object obj) { return dump(obj.toString()); } //dump } //*Hex
Java
/** * LinkedStack * * @author Chris Pratt * * 1/24/2006 */ package com.anodyzed.onyx.util; import java.io.Serializable; import java.util.ConcurrentModificationException; import java.util.EmptyStackException; import java.util.Iterator; import java.util.NoSuchElementException; @SuppressWarnings("serial") public class LinkedStack<E> implements Stack<E>, Serializable { /** * Node */ private class Node { Node up; E data; /** * Constructor * * @param up The Node One up the Stack * @param data The Node Payload */ public Node (Node up,E data) { this.up = up; this.data = data; } //Node /** * Get the Data from the Node * * @return The Payload Data */ E get () { return data; } //get /** * Get the Next Node up the Stack * * @return Next Node up the Stack */ Node up () { return up; } //up } //*Node /** * Itr */ private class Itr implements Iterator<E> { private int mod; private Node curr,prev; /** * Constructor */ public Itr () { mod = modCount; curr = top; prev = null; } //Itr /** * Returns <tt>true</tt> if the iteration has more elements. (In other * words, returns <tt>true</tt> if <tt>next</tt> would return an element * rather than throwing an exception.) * * @return <tt>true</tt> if the iterator has more elements. */ @Override public boolean hasNext () { if(mod == modCount) { return curr != null; } throw new ConcurrentModificationException(); } //hasNext /** * Returns the next element in the iteration. Calling this method * repeatedly until the {@link #hasNext()} method returns false will * return each element in the underlying collection exactly once. * * @return the next element in the iteration. * @exception NoSuchElementException iteration has no more elements. */ @Override public E next () { if(mod == modCount) { if(curr != null) { prev = curr; curr = curr.up(); return prev.get(); } throw new NoSuchElementException(); } throw new ConcurrentModificationException(); } //next /** * Removes from the underlying collection the last element returned by the * iterator. This method can be called only once per call to <tt>next</tt>. * The behavior of an iterator is unspecified if the underlying collection * is modified while the iteration is in progress in any way other than by * calling this method. * * @exception IllegalStateException if the <tt>next</tt> method has not * yet been called, or the <tt>remove</tt> method has already * been called after the last call to the <tt>next</tt> * method. */ @Override public void remove () { if(mod == modCount) { if(prev != null) { Node p = null,n = top; while(n != prev) { p = n; n = n.up(); } if(p == null) { top = prev.up(); } else { p.up = prev.up(); } } else { throw new IllegalStateException(); } } else { throw new ConcurrentModificationException(); } } //remove } //*Itr private transient int modCount; private int size; private Node top; /** * Constructor */ public LinkedStack () { modCount = 0; size = 0; top = null; } //LinkedStack /** * Copy Constructor * * @param stack The stack to copy */ public LinkedStack (Stack<E> stack) { if(!stack.isEmpty()) { for(int i = stack.size() - 1;i >= 0;i--) { push(stack.peek(i)); } } } //LinkedStack /** * Add an Element to the Top of the Stack * * @param e The Element to Push onto the Stack * @return true if successful */ @Override public boolean push (E e) { top = new Node(top,e); ++size; ++modCount; return true; } //push /** * Retrieve the Element <code>n</code> from the Top without modifying the * Stack * * @param n The distance from the top of the stack to peek * @return The <code>n</code><small>th</small> Element from the Top of the Stack */ @Override public E peek (int n) { Node node = top; for(int i = 0;i < n;i++) { if(node != null) { node = node.up(); } else { throw new EmptyStackException(); } } if(node != null) { return node.get(); } throw new EmptyStackException(); } //peek /** * Retrieve the Top Element on the Stack without modifying the Stack * * @return The Top Element on the Stack */ @Override public E peek () { if(top != null) { return top.get(); } throw new EmptyStackException(); } //peek /** * Retrieve and Remove the Top Element from the Stack * * @return The Top Element on the Stack */ @Override public E pop () { if(top != null) { Node node = top; top = node.up(); --size; modCount++; return node.get(); } throw new EmptyStackException(); } //pop /** * Remove all the Elements from the Stack */ @Override public void clear () { top = null; size = 0; modCount++; } //clear /** * Return the number of elements on the Stack * * @return element count */ @Override public int size () { return size; } //size /** * Test whether the stack is empty * * @return true if there are no elements in the stack */ @Override public boolean isEmpty () { return top == null; } //isEmpty /** * Returns an iterator over a set of elements of type E to walk the stack * from Top to Bottom. * * @return an Iterator. */ @Override public Iterator<E> iterator () { return new Itr(); } //iterator } //*LinkedStack
Java
package com.anodyzed.onyx.util; import java.io.Serializable; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * Implements the {@link java.util.Map} contract using a top-down splay tree. * The map is sorted according to the {@linkplain Comparable natural * ordering} of its keys, or by a {@link Comparator} provided at map * creation time, depending on which constructor is used. * * <p>Note that the ordering maintained by a sorted map (whether or not an * explicit comparator is provided) must be <i>consistent with equals</i> if * this sorted map is to correctly implement the <tt>Map</tt> interface. (See * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of * <i>consistent with equals</i>.) This is so because the <tt>Map</tt> * interface is defined in terms of the equals operation, but a map performs * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>) * method, so two keys that are deemed equal by this method are, from the * standpoint of the sorted map, equal. The behavior of a sorted map * <i>is</i> well-defined even if its ordering is inconsistent with equals; it * just fails to obey the general contract of the <tt>Map</tt> interface. * * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a map concurrently, and at least one of the * threads modifies the map structurally, it <i>must</i> be synchronized * externally. (Due to the self-optimizing nature of a Splay Tree, even * <tt>get</tt>ting a value from the map during iteration will cause a * structural modification.) This is typically accomplished by synchronizing * on some object that naturally encapsulates the map. If no such object * exists, the map should be "wrapped" using the * {@link java.util.Collections#synchronizedSortedMap Collections.synchronizedSortedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map: <pre> * SortedMap m = Collections.synchronizedSortedMap(new SplayTreeMap(...));</pre> * * <p>The iterators returned by the <tt>iterator</tt> method of the collections * returned by all of this class's "collection view methods" are * <i>fail-fast</i>: if the map is structurally modified at any time after the * iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a {@link * java.util.ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>java.util.ConcurrentModificationException</tt> on a best-effort * basis. Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class * and its views represent snapshots of mappings at the time they were * produced. They do <em>not</em> support the <tt>Entry.setValue</tt> * method. (Note however that it is possible to change mappings in the * associated map using <tt>put</tt>.) * * Based on code available at http://www.link.cs.cmu.edu/splay/ * This code is in the public domain. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Chris Pratt and Danny Sleator <sleator@cs.cmu.edu> * @version 2011/12/15 * @see java.util.Map * @see java.util.TreeMap * @see java.lang.Comparable * @see java.util.Comparator * @see java.util.Collection */ @SuppressWarnings("serial") public class SplayTreeMap<K,V> extends AbstractMap<K,V> implements Serializable { static final class Entry<K,V> implements Map.Entry<K,V> { K key; // The data in the node V value; // The data Payload Entry<K,V> parent; // Parent Entry<K,V> left; // Left child Entry<K,V> right; // Right child Entry (K key,V value,Entry<K,V> parent) { this.key = key; this.value = value; this.parent = parent; left = right = null; } //Entry /** * Returns the key. * * @return the key */ @Override public K getKey () { return key; } //getKey /** * Returns the value associated with the key. * * @return the value associated with the key */ @Override public V getValue () { return value; } //getValue /** * Replaces the value currently associated with the key with the given * value. * * @return the value associated with the key before this method was * called */ @Override public V setValue (V value) { V oldValue = this.value; this.value = value; return oldValue; } //setValue @Override public boolean equals (Object o) { if(!(o instanceof Map.Entry)) { return false; } Map.Entry<?,?> e = (Map.Entry<?,?>)o; return Misc.equals(key,e.getKey()) && Misc.equals(value,e.getValue()); } //equals @Override public int hashCode () { int keyHash = ((key == null) ? 0 : key.hashCode()); int valHash = ((value == null) ? 0 : value.hashCode()); return keyHash ^ valHash; } //hashCode @Override public String toString () { return key + "=" + value; } //toString } //Entry private final Entry<K,V> header = new Entry<K,V>(null,null,null); // For splay private transient Entry<K,V> root; private final Comparator<? super K> comparator,assignedComparator; private transient int size; private Set<Map.Entry<K,V>> entrySet = null; /** * The number of structural modifications to the tree. */ private transient int modCount = 0; public SplayTreeMap () { this.root = null; this.size = 0; this.comparator = new Comparator<K>() { /** * Perform a Natural Order Comparison */ @Override @SuppressWarnings("unchecked") public int compare (K k1,K k2) { return ((Comparable<? super K>)k1).compareTo(k2); } //compare }; this.assignedComparator = null; } //SplayTreeMap /** * Constructor * * @param comparator The Comparator used to order the tree */ public SplayTreeMap (Comparator<? super K> comparator) { this.root = null; this.size = 0; this.comparator = this.assignedComparator = comparator; } //SplayTreeMap /** * Return the Comparator assigned during the construction of this Splay Tree Map * * @return Assigned Comparator */ public Comparator<? super K> comparator () { return assignedComparator; } //comparator /** * Return the Set of Map Entries * * @return Set of Map Entries */ @Override public Set<Map.Entry<K,V>> entrySet () { if(entrySet == null) { entrySet = new EntrySet(); } return entrySet; } //entrySet /** * Find an item in the tree. * * @param key The entry key * @return The matching entry */ public Entry<K,V> find (K key) { if(root != null) { splay(key); return (comparator.compare(root.key,key) == 0) ? root : null; } return null; } //find /** * Get the Value associated with the specified Key * * @param key The Entry Key * @return The Entry Value */ @Override @SuppressWarnings("unchecked") public V get (Object key) { Entry<K,V> entry = find((K)key); return (entry != null) ? entry.value : null; } //get /** * Associate the supplied value with the provided key * * @param key The Entry Key * @param value The Entry Value * @return The replaced Entry Value (or null) */ @Override public V put (K key,V value) { if(root == null) { root = new Entry<K,V>(key,value,null); ++modCount; ++size; } else { int c; splay(key); if((c = comparator.compare(key,root.key)) != 0) { Entry<K,V> n = new Entry<K,V>(key,value,root); if(c < 0) { n.left = root.left; n.right = root; root.left = null; } else { n.right = root.right; n.left = root; root.right = null; } root = n; ++size; } else { V ret = root.value; root.value = value; return ret; } } return null; } //put /** * Check whether the Map contains the supplied Key * * @param key The Entry Key * @return {@code true} if an entry == {@code key} exists in the map */ @Override @SuppressWarnings("unchecked") public boolean containsKey (Object key) { return find((K)key) != null; } //containsKey /** * Return the number of entries in the map * * @return Map entry count */ @Override public int size () { return size; } //size /** * Test if the tree is logically empty. * * @return true if empty, false otherwise. */ @Override public boolean isEmpty () { return root == null; } //isEmpty /** * Clear all the entries from the Map */ @Override public void clear () { modCount++; size = 0; root = null; } //clear /** * Remove from the tree. * * @param key the item to remove. */ @Override @SuppressWarnings("unchecked") public V remove (Object key) { splay((K)key); if(comparator.compare((K)key,root.key) == 0) { // Now delete the root if(root.left == null) { root = root.right; } else { Entry<K,V> x = root.right; root = root.left; splay((K)key); root.right = x; setParent(x,root); } setParent(root,null); } return null; } //remove /** * Find the leftmost Entry (the smallest key) * * @return The Leftmost entry */ private Entry<K,V> leftmost () { Entry<K,V> entry = root; if(root != null) { while(entry.left != null) { entry = entry.left; } } return entry; } //leftmost /** * Find the smallest key in the tree. * * @return the First Map Key */ public K firstKey () { Entry<K,V> min = leftmost(); if(min != null) { splay(min.key); return min.key; } throw new NoSuchElementException(); } //findMin /** * Find the rightmost Entry (the largest key) * * @return The Rightmost entry */ public Entry<K,V> rightmost () { Entry<K,V> entry = root; if(root != null) { while(entry.right != null) { entry = entry.right; } } return entry; } //rightmost /** * Find the largest key in the tree. * * @return The Last Map Key */ public K lastKey () { Entry<K,V> max = rightmost(); if(max != null) { splay(max.key); return max.key; } throw new NoSuchElementException(); } //findMax /** * Returns the successor of the specified Entry, or null if no such. * * @param t The entry before the requested entry * @return The entry after the specified entry */ static <K,V> Entry<K,V> successor (Entry<K,V> t) { if(t != null) { Entry<K,V> p; if(t.right != null) { p = t.right; while(p.left != null) { p = p.left; } } else { p = t.parent; Entry<K,V> ch = t; while((p != null) && (ch == p.right)) { ch = p; p = p.parent; } } return p; } return null; } //successor /** * Returns the predecessor of the specified Entry, or null if no such. * * @param t The entry after the requested entry * @return The entry before the specified entry */ static <K,V> Entry<K,V> predecessor (Entry<K,V> t) { if(t != null) { Entry<K,V> p; if(t.left != null) { p = t.left; while(p.right != null) { p = p.right; } } else { p = t.parent; Entry<K,V> ch = t; while((p != null) && (ch == p.left)) { ch = p; p = p.parent; } } return p; } return null; } //predecessor /** * Utility function to safely set the parent * * @param child The proposed Child * @param parent The possible Parent */ private static <K,V> void setParent (Entry<K,V> child,Entry<K,V> parent) { if(child != null) { child.parent = parent; } } //setParent /** * Internal method to perform a top-down splay. * * splay(key) does the splay operation on the given key. If key is in the * tree, then the Entry containing that key becomes the root. If key is not * in the tree, then after the splay, key.root is either the greatest key < * key in the tree, or the least key > key in the tree. * * This means, among other things, that if you splay with a key that's larger * than any in the tree, the rightmost node of the tree becomes the root. This * property is used in the delete() method. * * @param key The Key to Splay on */ private void splay (K key) { int c; if((c = comparator.compare(key,root.key)) != 0) { Entry<K,V> l, r, t, y; l = r = header; t = root; header.left = header.right = null; do { if(c < 0) { if(t.left == null) { break; } if(comparator.compare(key,t.left.key) < 0) { y = t.left; /* rotate right */ t.left = y.right; setParent(y.right,t); y.right = t; setParent(t,y); t = y; if(t.left == null) { break; } } r.left = t; /* link right */ setParent(t,r); r = t; t = t.left; } else { if(t.right == null) { break; } if(comparator.compare(key,t.right.key) > 0) { y = t.right; /* rotate left */ t.right = y.left; setParent(y.left,t); y.left = t; setParent(t,y); t = y; if(t.right == null) { break; } } l.right = t; /* link left */ setParent(t,l); l = t; t = t.right; } } while((c = comparator.compare(key,t.key)) != 0); l.right = t.left; /* assemble */ setParent(t.left,l); r.left = t.right; setParent(t.right,r); t.left = header.right; setParent(header.right,t); t.right = header.left; setParent(header.left,t); root = t; root.parent = null; ++modCount; } } //splay abstract class AbstractEntryIterator<T> implements Iterator<T> { Entry<K,V> next; Entry<K,V> lastReturned; int expectedModCount; AbstractEntryIterator (Entry<K,V> first) { expectedModCount = modCount; lastReturned = null; next = first; } //AbstractEntryIterator @Override public final boolean hasNext () { return next != null; } //hasNext final Entry<K,V> nextEntry () { Entry<K,V> e = next; if(e != null) { if(modCount == expectedModCount) { next = successor(e); lastReturned = e; return e; } throw new ConcurrentModificationException(); } throw new NoSuchElementException(); } //nextEntry final Entry<K,V> prevEntry () { Entry<K,V> e = next; if(e != null) { if(modCount == expectedModCount) { next = predecessor(e); lastReturned = e; return e; } throw new ConcurrentModificationException(); } throw new NoSuchElementException(); } //prevEntry @Override public void remove () { if(lastReturned != null) { if(modCount == expectedModCount) { // deleted entries are replaced by their successors if((lastReturned.left != null) && (lastReturned.right != null)) { next = lastReturned; } SplayTreeMap.this.remove(lastReturned.key); expectedModCount = modCount; lastReturned = null; return; } throw new ConcurrentModificationException(); } throw new IllegalStateException(); } //remove } //*AbstractEntryIterator final class EntryIterator extends AbstractEntryIterator<Map.Entry<K,V>> { EntryIterator (Entry<K,V> first) { super(first); } //EntryIterator @Override public Map.Entry<K,V> next () { return nextEntry(); } //next } //*EntryIterator // final class ValueIterator extends AbstractEntryIterator<V> { // ValueIterator (Entry<K,V> first) { // super(first); // } //ValueIterator // // @Override // public V next () { // return nextEntry().value; // } //next // } //*ValueIterator // // final class KeyIterator extends AbstractEntryIterator<K> { // KeyIterator (Entry<K,V> first) { // super(first); // } //KeyIterator // // @Override // public K next () { // return nextEntry().key; // } //next // } //*KeyIterator // // final class DescendingKeyIterator extends AbstractEntryIterator<K> { // DescendingKeyIterator (Entry<K,V> first) { // super(first); // } //DescendingKeyIterator // // @Override // public K next () { // return prevEntry().key; // } //next // } //*DescendingKeyIterator /** * EntrySet */ final class EntrySet extends AbstractSet<Map.Entry<K,V>> { /** * Iterate over the Map Entries * * @return Map Entry Iterator */ @Override public Iterator<Map.Entry<K,V>> iterator () { return new EntryIterator(leftmost()); } //iterator /** * Get the matching Entry from the map * * @param entry The Map Entry to find * @return The matching entry, or null */ private Entry<K,V> getEntry (Map.Entry<K,V> entry) { Entry<K,V> e = find(entry.getKey()); return (e != null) ? (Misc.equals(e.getValue(),entry.getValue()) ? e : null) : null; } //getEntry /** * Check whether the Entry Set contains a matching Entry * * @param o The Map Entry to test * @return true if a matching Map Entry exists */ @Override @SuppressWarnings("unchecked") public boolean contains (Object o) { return (o instanceof Map.Entry) && (getEntry((Map.Entry<K,V>)o) != null); } //contains /** * Return the Size of the Map Data * * @return Map Entry Count */ @Override public int size () { return SplayTreeMap.this.size(); } //size /** * Clear all Entries from the Set and Map */ @Override public void clear () { SplayTreeMap.this.clear(); } //clear /** * Remove the specified Entry from the Set and Map * * @param o The Map Entry to remove * @return true if successfully removed */ @Override @SuppressWarnings("unchecked") public boolean remove (Object o) { if(o instanceof Map.Entry) { Entry<K,V> e = getEntry((Map.Entry<K,V>)o); if(e != null) { SplayTreeMap.this.remove(e.key); return true; } } return false; } //remove } //*EntrySet } //*SplayTreeMap
Java
/** * Misc - Miscellaneous and Sundry Utility Functions * * @author Chris Pratt * * 3/5/1999 */ package com.anodyzed.onyx.util; import java.util.Collection; import java.util.Date; import java.util.Map; public class Misc { public static final long MS = 1; public static final long SEC = 1000 * MS; public static final long MIN = 60 * SEC; public static final long HR = 60 * MIN; public static final long DAY = 24 * HR; public static final long WK = 7 * DAY; public static final long YR = 365 * DAY; public static final long LYR = 4 * YR; /** * Protected Constructor */ protected Misc () { } //Misc ////////// Numeric Identification ////////// /** * Test whether a character is a numeric digit in the specified base * * @param c The Character in Question * @param base The Numeric Base * @return true if the character is a numeric digit in base */ public static boolean isNumeric (char c,int base) { if(base > 10) { char C; return ((c >= '0') && (c <= '9')) || (((C = Character.toUpperCase(c)) >= 'A') && (C <= (((char)base - 10) + 'A'))); } else { return (c >= '0') && (c <= (((char)base - 1) + '0')); } } //isNumeric /** * Test whether a String is Numeric * * @param str The Test String * @return true if all the characters are numeric */ public static boolean isNumeric (String str) { if((str != null) && (str.length() > 0)) { char[] ch = str.toCharArray(); for(char c : ch) { if(!Character.isDigit(c)) { return false; } } return true; } return false; } //isNumeric ////////// Object Management ////////// /** * Test whether the supplied String contains any non-whitespace characters * * @param str The String to test * @return true if the supplied string is null, or contains <b>only</b> * whitespace characters */ public static boolean isEmpty (String str) { return (str == null) || (str.trim().length() <= 0); } //isEmpty /** * Test whether the supplied Array contains any elements * * @param ary The Array to test * @return true if the supplied Array is null or contains no elements */ public static <T> boolean isEmpty (T[] ary) { return (ary == null) || (ary.length == 0); } //isEmpty /** * Test whether the supplied Collection contains any elements * * @param col The Collection to test * @return true if the supplied Collection is null or empty */ public static boolean isEmpty (Collection<?> col) { return (col == null) || col.isEmpty(); } //isEmpty /** * Test whether the supplied Map contains any elements * * @param map The Map to test * @return true if the supplied Map is null or empty */ public static boolean isEmpty (Map<?,?> map) { return (map == null) || map.isEmpty(); } //isEmpty /** * Test two values for equality. Differs from o1.equals(o2) only in * that it copes with <tt>null</tt> o1 properly. * * @param o1 The first Object to test * @param o2 The second Object to test * @return true if the objects are equivalent */ public static boolean equals (Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } //equals ////////// Array Manipulation ////////// /** * Find the Index of an element of an Array * * @param ary The Object Array * @param item The Object to search for * @param start The index to start searching from * @return The index of <code>item</code> in <code>ary</code> (or -1 if not * found) */ public static int arrayIndexOf (Object[] ary,Object item,int start) { if(item != null) { for(int i = start;i < ary.length;i++) { if(item.equals(ary[i])) { return i; } } } else { for(int i = start;i < ary.length;i++) { if(ary[i] == null) { return i; } } } return -1; } //arrayIndexOf /** * Find the Index of an element of an Array * * @param ary The Object Array * @param item The Object to search for * @return The index of <code>item</code> in <code>ary</code> (or -1 if not * found) */ public static int arrayIndexOf (Object[] ary,Object item) { return arrayIndexOf(ary,item,0); } //arrayIndexOf /** * Find the Index of an element of an Array * * @param ary The byte Array * @param b The byte to search for * @param start The index to start searching from * @return The index of <code>b</code> in <code>ary</code> (or * -1 if not found) */ public static int arrayIndexOf (byte[] ary,byte b,int start) { for(int i = start;i < ary.length;i++) { if(b == ary[i]) { return i; } } return -1; } //arrayIndexOf /** * Find the Index of an element of an Array * * @param ary The byte Array * @param b The byte to search for * @return The index of <code>b</code> in <code>ary</code> (or * -1 if not found) */ public static int arrayIndexOf (byte[] ary,byte b) { return arrayIndexOf(ary,b,0); } //arrayIndexOf /** * Find the Index of an element of an Array * * @param ary The character Array * @param ch The character to search for * @param start The index to start searching from * @return The index of <code>ch</code> in <code>ary</code> (or * -1 if not found) */ public static int arrayIndexOf (char[] ary,char ch,int start) { for(int i = start;i < ary.length;i++) { if(ch == ary[i]) { return i; } } return -1; } //arrayIndexOf /** * Find the Index of an element of an Array * * @param ary The character Array * @param ch The character to search for * @return The index of <code>ch</code> in <code>ary</code> (or * -1 if not found) */ public static int arrayIndexOf (char[] ary,char ch) { return arrayIndexOf(ary,ch,0); } //arrayIndexOf ////////// Chronographic Utilities ////////// /** * Append the next division to the duration string * * @param buf The String Buffer * @param dur The division duration * @param div The division name * @param spc if true, prepend a space * @return the new space value */ private static boolean append (StringBuilder buf,long dur,String div,boolean spc) { if(spc) { buf.append(' '); } buf.append(dur).append(' ').append(div); if(dur != 1) { buf.append('s'); } return true; } //append /** * Return the duration as a string description of a length of time * * @param time The duration length (in ms) * @return The duration description String */ public static String duration (long time) { StringBuilder buf = new StringBuilder(); if(time < 0) { time *= -1; } if(time > 0) { long dur; boolean space = false; if(time >= YR) { dur = time / LYR; time %= LYR; space = append(buf,(dur * 4) + (time / YR),"year",space); time %= YR; } if(time >= WK) { space = append(buf,time / WK,"week",space); time %= WK; } if(time >= DAY) { space = append(buf,time / DAY,"day",space); time %= DAY; } if(time >= HR) { space = append(buf,time / HR,"hour",space); time %= HR; } if(time >= MIN) { space = append(buf,time / MIN,"minute",space); time %= MIN; } if(time >= SEC) { space = append(buf,time / SEC,"second",space); time %= SEC; } if(time >= MS) { append(buf,time,"millisecond",space); } } else { buf.append("0 milliseconds"); } return buf.toString(); } //duration /** * Return the length of time between two points as a string description * * @param start The starting time (in ms) * @param stop The ending time (in ms) * @return The duration description String */ public static String duration (long start,long stop) { return duration(stop - start); } //duration /** * Return the length of time between two Dates as a string description * * @param start The starting Date * @param stop The ending Date * @return The duration description String */ public static String duration (Date start,Date stop) { return duration(stop.getTime() - start.getTime()); } //duration /** * Return the Period Duration string * * @param period The Time Period * @return The duration description String */ public static String duration (Period period) { return duration(period.getDurationInMillis()); } //duration } //*Misc
Java
/** * Fraction * * @author Chris Pratt * * 2/14/2005 */ package com.anodyzed.onyx.util; import java.text.ParseException; @SuppressWarnings("serial") public class Fraction extends Number { private double dec; private long w; private long n; private long d; /** * No-arg Bean Constructor */ public Fraction () { w = n = d = 0; dec = 0.0; } //Fraction /** * Constructor - Algorithm adapted from * http://www.ozgrid.com/forum/archive/index.php/t-22530.html * * @param dec The Double to represent as a Fraction */ public Fraction (double dec) { setDecimal(dec); } //Fraction /** * Constructor * * @param n The Numerator of the Fraction * @param d The Denominator of the Fraction */ public Fraction (long n,long d) { this(0,n,d); } //Fraction /** * Constructor * * @param w The Whole Portion of the Fraction * @param n The Numerator of the Fraction * @param d The Denominator of the Fraction */ public Fraction (long w,long n,long d) { this.w = w; this.n = n; this.d = d; this.dec = w + ((double)n / (double)d); } //Fraction /** * Constructor * * @param frac The Fraction String * @throws ParseException If the fraction can't be parsed */ public Fraction (String frac) throws ParseException { if(frac.indexOf('/') == -1) { setDecimal(Double.parseDouble(frac)); } else { long x = 0; w = 0; n = -1; d = -1; char[] ch = frac.toCharArray(); boolean neg = (ch[0] == '-'); int i = (neg | (ch[0] == '+')) ? 1 : 0; for(;i < ch.length;i++) { switch(ch[i]) { case ' ': w = x; x = 0; break; case '/': n = x; x = 0; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': x = (x * 10) + Character.digit(ch[i],10); break; default: throw new ParseException("\'" + ch[i] + "\' is not a valid character in a Fraction - " + frac,i); } } d = x; if((n != -1) && (d != -1) && (d != 0)) { dec = w + ((double)n / (double)d); if(neg) { dec = -dec; if(w != 0) { w = -w; } else { n = -n; } } } else { throw new ParseException("Malformed Fraction - " + frac,i); } reduce(); } } //Fraction /** * Return the Whole Number portion of the Fraction * * @return The Non-fractional part */ public long getWhole () { return w; } //getWhole /** * Set the Whole part of the Fraction * * @param w The Whole Number */ public void setWhole (long w) { this.w = w; } //setWhole /** * Get the Numerator of the Reduced Fraction * * @return The Fraction's Numerator */ public long getNumerator () { return n; } //getNumerator /** * Set the Numerator of the Fraction * * @param n The fraction numerator */ public void setNumerator (long n) { this.n = n; if(d != 0) { dec = w + ((double)n / (double)d); } else { dec = Double.NaN; } } //setNumerator /** * Get the Denominator of the Reduced Fraction * * @return The Fraction's Denominator */ public long getDenominator () { return d; } //getDenominator /** * Set the Denominator of the Fraction * * @param d The fraction denominator */ public void setDenominator (long d) { this.d = d; if(d != 0) { dec = w + ((double)n / (double)d); } else { dec = Double.NaN; } } //setDenominator /** * Number: Returns the value of the specified number as a <code>double</code>. * This may involve rounding. * * @return the numeric value represented by this Object after conversion to * type <code>double</code> */ @Override public double doubleValue () { return dec; } //doubleValue /** * Number: Returns the value of the specified number as a <code>float</code>. * This may involve rounding. * * @return the numeric value represented by this Object after conversion to * type <code>float</code> */ @Override public float floatValue () { return (float)dec; } //floatValue /** * Number: Returns the value of the specified number as a <code>int</code>. * This may involve rounding. * * @return the numeric value represented by this Object after conversion to * type <code>int</code> */ @Override public int intValue () { return (int)dec; } //intValue /** * Number: Returns the value of the specified number as a <code>long</code>. * This may involve rounding. * * @return the numeric value represented by this Object after conversion to * type <code>long</code> */ @Override public long longValue () { return (long)dec; } //longValue /** * Set the Fraction amount using a Double Precision Floating Point value * * Algorithm adapted from * http://www.ozgrid.com/forum/archive/index.php/t-22530.html * * @param dec The new value to represent as a Fraction */ public void setDecimal (double dec) { this.dec = dec; if(dec >= 1.0) { w = (long)Math.floor(dec); dec -= w; } else { w = 0; } if(dec > 0.0) { double z = dec; double fd = 1.0; double fn; double pd = 0.0; double temp; do { z = (1.0 / (z - Math.floor(z))); temp = fd; fd = Math.floor(z) * fd + pd; pd = temp; fn = Math.floor(dec * fd + 0.5); } while((Math.abs(dec - (fn / fd)) >= 1.0e-14) && (z != Math.floor(z))); n = (long)Math.floor(fn); d = (long)Math.floor(fd); if(n > d) { w += n / d; n = n % d; } reduce(); } else { n = d = 0; } } //setDecimal /** * Reduce the Fraction */ private void reduce () { if(n == 0) { d = 1; } else { long gcd = gcd(n,d); n /= gcd; d /= gcd; if(d < 0) { n = -n; d = -d; } } } //reduce /** * Compute the Greatest Common Divisor between two numbers * * @param left The First Parameter * @param rite The Second Parameter * @return The Greatest Common Divisor of the given parameters */ public static long gcd (long left,long rite) { left = Math.abs(left); rite = Math.abs(rite); if((left > 2) && (rite > 2)) { long temp; do { if(left < rite) { temp = left; left = rite; rite = temp; } left %= rite; } while(left != 0); return rite; } else { // If either argument is 0 or 1, the GCD is 1 return 1; } } //gcd /** * Return the String Representation of the Fraction * * @return The String Representation of the Fraction */ @Override public String toString () { StringBuilder buf = new StringBuilder(); if(w != 0) { buf.append(w); } if((n != d)) { if(buf.length() > 0) { buf.append(' '); } buf.append(n).append('/').append(d); } return buf.toString(); } //toString /** * Convenience Method to Format a double precision real value to a * Fractional String * * @param dec The double to Convert * @return The Fractional String representing the double */ public static String toString (double dec) { return new Fraction(dec).toString(); } //toString /** * Convenience Method to Normalize a numeric string as a Fractional String * * @param frac The String to Convert * @return The Fractional String */ public static String toString (String frac) { try { return new Fraction(frac).toString(); } catch(ParseException x) { return null; } } //toString /** * Convenience Method to convert a Fraction String to a double-precision * floating-point value. * * @param frac The String to Convert * @return double value */ public static double toDouble (String frac) { try { return new Fraction(frac).doubleValue(); } catch(ParseException x) { return Double.NaN; } } //toDouble /** * Determine if the supplied character could be part of a number. Supports * Whole, Decimal & Fractional notation (Currently does not support Scientific * or Hexidecimal) * * Supports: * <ul> * <li>12</li> * <li>13.57</li> * <li>.5</li> * <li>1/2</li> * <li>1 7/8</li> * </ul> * * @param ch The character in question * @return true if a digit, '.', '/' or ' ' */ public static boolean isNumeric (char ch) { return Character.isDigit(ch) || (ch == '.') || (ch == '/') || (ch == ' '); } //isNumeric /** * Program Entry-point * * @param args Command Line Arguments * @throws ParseException if the String can't be parsed */ public static void main (String[] args) throws ParseException { StringBuilder buf = new StringBuilder(); for(int i = 0;i < args.length;i++) { if(i > 0) { buf.append(' '); } buf.append(args[i]); } Fraction f = new Fraction(buf.toString()); System.out.println(f.toString()); System.out.println(f.doubleValue()); // System.out.println(new Fraction(Misc.getIntArg("-w",args,0),Misc.getIntArg("-n",args,0),Misc.getIntArg("-d",args,1)).toString()); } //main } //*Fraction
Java
/** * Base64 - Base 64 Transfer Encoding * * @author Chris Pratt * * 3/15/1999 */ package com.anodyzed.onyx.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; public class Base64 { public static final char[] STD_DIGIT = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'}; public static final char[] URL_DIGIT = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','-','_'}; private static final long[] ORD = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,62, 0,62, 0,63,52,53,54,55,56,57,58,59,60,61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25, 0, 0, 0, 0,63, 0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51, 0, 0, 0, 0, 0}; private static final byte[] CRLFb = {(byte)0x0D,(byte)0x0A}; private static final char[] CRLFc = {(char)0x0D,(char)0x0A}; /** * Constructor */ private Base64 () { } //Base64 /** * Encode a character array in base64 mode * * @param buf the bytes to be encoded * @param digits the array of encoding digits * @return the encoded string */ private static char[] encode (char[] buf,char[] digits) { int b = 0,i = 0,j,s; long n; int extra = buf.length % 3; int top = buf.length - extra; int size = ((buf.length / 3) + ((extra == 0) ? 0 : 1)) * 4; int pad = 3 - ((buf.length * 4) % 3); char[] bytes = new char[size]; while(i < top) { n = ((((long)buf[i++]) & 0xFF) << 16) | ((((long)buf[i++]) & 0xFF) << 8) | (((long)buf[i++]) & 0xFF); bytes[b++] = digits[(int)((n >>> 18) & 0x3F)]; bytes[b++] = digits[(int)((n >>> 12) & 0x3F)]; bytes[b++] = digits[(int)((n >>> 6) & 0x3F)]; bytes[b++] = digits[(int)(n & 0x3F)]; } if(extra > 0) { n = 0; s = 16; for(j = 0;j < extra;j++) { n |= (((long)buf[i++]) & 0xFF) << s; s >>= 1; } s = 18; for(j = 0;j < 4 - pad;j++) { bytes[b++] = digits[(int)((n >>> s) & 0x3F)]; s -= 6; } for(j = 0;j < pad;j++) { bytes[b++] = '='; } } return bytes; } //encode /** * Encode a character array in base64 mode * * @param bytes the bytes to be encoded * @return the encoded string */ public static char[] encode (char[] bytes) { return encode(bytes,STD_DIGIT); } //encode /** * Encode a character array in modified base64 mode. * * This mode replaces the '+' and '/' characters that are problematic in * URLs with '-' and '_', respectively. * * @param bytes the bytes to be encoded * @return the encoded string */ public static char[] encodeURLSafe (char[] bytes) { return encode(bytes,URL_DIGIT); } //encodeURLSafe /** * Encode an array of bytes * * @param buf the bytes to be encoded * @param ofs The Offset to start encoding * @param len The Number of characters to encode * @param digits the array of encoding digits * @return the encoded string */ private static String encode (byte[] buf,int ofs,int len,char[] digits) { int b = 0,i = ofs,j,s; long n; int extra = len % 3; int top = len - extra; int size = ((len / 3) + ((extra == 0) ? 0 : 1)) * 4; int pad = 3 - ((len * 4) % 3); char[] bytes = new char[size]; while(i < top) { n = ((((long)buf[i++]) & 0xFF) << 16) | ((((long)buf[i++]) & 0xFF) << 8) | (((long)buf[i++]) & 0xFF); bytes[b++] = digits[(int)((n >>> 18) & 0x3F)]; bytes[b++] = digits[(int)((n >>> 12) & 0x3F)]; bytes[b++] = digits[(int)((n >>> 6) & 0x3F)]; bytes[b++] = digits[(int)(n & 0x3F)]; } if(extra > 0) { n = 0; s = 16; for(j = 0;j < extra;j++) { n |= (((long)buf[i++]) & 0xFF) << s; s >>= 1; } s = 18; for(j = 0;j < 4 - pad;j++) { bytes[b++] = digits[(int)((n >>> s) & 0x3F)]; s -= 6; } for(j = 0;j < pad;j++) { bytes[b++] = '='; } } return new String(bytes); } //encode /** * Encode an array of bytes * * @param buf the bytes to be encoded * @param ofs The Offset to start encoding * @param len The Number of characters to encode * @return the encoded string */ public static String encode (byte[] buf,int ofs,int len) { return encode(buf,ofs,len,STD_DIGIT); } //encode /** * Encode an array of bytes using modified Base64 encoding. * * This mode replaces the '+' and '/' characters that are problematic in * URLs with '-' and '_', respectively. * * @param buf the bytes to be encoded * @param ofs The Offset to start encoding * @param len The Number of characters to encode * @return the encoded string */ public static String encodeURLSafe (byte[] buf,int ofs,int len) { return encode(buf,ofs,len,URL_DIGIT); } //encodeURLSafe /** * Encode an array of bytes * * @param buf the bytes to be encoded * @param ofs the offset to start encoding * @return the encoded string */ public static String encode (byte[] buf,int ofs) { return encode(buf,ofs,buf.length - ofs,STD_DIGIT); } //encode /** * Encode an array of bytes using modified Base64 encoding. * * This mode replaces the '+' and '/' characters that are problematic in * URLs with '-' and '_', respectively. * * @param buf the bytes to be encoded * @param ofs the offset to start encoding * @return the encoded string */ public static String encodeURLSafe (byte[] buf,int ofs) { return encode(buf,ofs,buf.length - ofs,URL_DIGIT); } //encodeURLSafe /** * Encode an array of bytes base64 mode * * @param buf the bytes to be encoded * @return the encoded string */ public static String encode (byte[] buf) { return encode(buf,0,buf.length,STD_DIGIT); } //encode /** * Encode an array of bytes using modified Base64 encoding. * * This mode replaces the '+' and '/' characters that are problematic in * URLs with '-' and '_', respectively. * * @param buf the bytes to be encoded * @return the encoded string */ public static String encodeURLSafe (byte[] buf) { return encode(buf,0,buf.length,URL_DIGIT); } //encodeURLSafe /** * Push the bytes in the buffer to the output stream * * @param out The Output Stream to write to * @param buf The Bytes to write * @param line The Maximum Line Length * @param pos The Array of Position Information * @throws IOException If the streams get crossed */ private static void push (OutputStream out,byte[] buf,int line,int[] pos) throws IOException { if((line > 0) && ((pos[1] + buf.length) > line)) { out.write(CRLFb); pos[1] = 0; } out.write(buf); pos[0] += buf.length; pos[1] += buf.length; } //push /** * Encode the input stream and write it to the output stream, breaking each * line every <tt>line</tt> characters * * @param in The Input Stream * @param out The Output Stream * @param line The maximum number of bytes per line * @param digit The array of encoding digits * @return number of bytes written to <tt>out</tt> * @throws IOException If the streams get crossed */ public static int encode (InputStream in,OutputStream out,int line,char[] digit) throws IOException { long n; int read; int[] pos = {0,0}; byte[] ibuf = new byte[3]; byte[] obuf = new byte[4]; if(!(in instanceof BufferedInputStream)) { in = new BufferedInputStream(in); } if(!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } while((read = in.read(ibuf)) == 3) { n = ((((long)ibuf[0]) & 0xFF) << 16) | ((((long)ibuf[1]) & 0xFF) << 8) | (((long)ibuf[2]) & 0xFF); obuf[0] = (byte)digit[(int)((n >>> 18) & 0x3F)]; obuf[1] = (byte)digit[(int)((n >>> 12) & 0x3F)]; obuf[2] = (byte)digit[(int)((n >>> 6) & 0x3F)]; obuf[3] = (byte)digit[(int)(n & 0x3F)]; push(out,obuf,line,pos); } if(read > 0) { n = (((long)ibuf[0]) & 0xFF) << 16; if(read == 2) { n |= (((long)ibuf[1]) & 0xFF) << 8; } obuf[0] = (byte)digit[(int)((n >>> 18) & 0x3F)]; obuf[1] = (byte)digit[(int)((n >>> 12) & 0x3F)]; obuf[2] = (byte)((read == 2) ? digit[(int)((n >>> 6) & 0x3F)] : '='); obuf[3] = '='; push(out,obuf,line,pos); } out.flush(); return pos[0]; } //encode /** * Encode the input stream and write it to the output stream, breaking each * line every <tt>line</tt> characters * * @param in The Input Stream * @param out The Output Stream * @param line The maximum number of bytes per line * @return number of bytes written to <tt>out</tt> * @throws IOException If the streams get crossed */ public static int encode (InputStream in,OutputStream out,int line) throws IOException { return encode(in,out,line,STD_DIGIT); } //encode /** * Encode the input stream and write it to the output stream, breaking each * line every <tt>line</tt> characters * * @param in The Input Stream * @param out The Output Stream * @param line The maximum number of bytes per line * @return number of bytes written to <tt>out</tt> * @throws IOException If the streams get crossed */ public static int encodeURLSafe (InputStream in,OutputStream out,int line) throws IOException { return encode(in,out,line,URL_DIGIT); } //encodeURLSafe /** * Encode the input stream and write it to the output stream, breaking each * line at 76 characters * * @param in The Input Stream * @param out The Output Stream * @return the number of bytes written * @throws IOException if the streams get crossed */ public static int encode (InputStream in,OutputStream out) throws IOException { return encode(in,out,76,STD_DIGIT); } //encode /** * Encode the input stream and write it to the output stream, breaking each * line at 76 characters * * @param in The Input Stream * @param out The Output Stream * @return the number of bytes written * @throws IOException if the streams get crossed */ public static int encodeURLSafe (InputStream in,OutputStream out) throws IOException { return encode(in,out,76,URL_DIGIT); } //encodeURLSafe /** * Push the bytes in the buffer to the writer * * @param out The Writer to write to * @param buf The Chars to write * @param line The Maximum Line Length * @param pos The Array of Position Information * @throws IOException if the streams get crossed */ private static void push (Writer out,char[] buf,int line,int[] pos) throws IOException { if((line > 0) && ((pos[1] + buf.length) > line)) { out.write(CRLFc); pos[1] = 0; } out.write(buf); pos[0] += buf.length; pos[0] += buf.length; } //push /** * Encode the input stream and write it to the writer, breaking each line * every <tt>line</tt> characters * * @param in The Input Stream * @param out The Writer * @param line The maximum number of bytes per line * @param digit The array of encoding digits * @return number of bytes written to <tt>out</tt> * @throws IOException if the streams get crossed */ public static int encode (InputStream in,Writer out,int line,char[] digit) throws IOException { long n; int read; int[] pos = {0,0}; byte[] ibuf = new byte[3]; char[] obuf = new char[4]; if(!(in instanceof BufferedInputStream)) { in = new BufferedInputStream(in); } if(!(out instanceof BufferedWriter)) { out = new BufferedWriter(out); } while((read = in.read(ibuf)) == 3) { n = ((((long)ibuf[0]) & 0xFF) << 16) | ((((long)ibuf[1]) & 0xFF) << 8) | (((long)ibuf[2]) & 0xFF); obuf[0] = digit[(int)((n >>> 18) & 0x3F)]; obuf[1] = digit[(int)((n >>> 12) & 0x3F)]; obuf[2] = digit[(int)((n >>> 6) & 0x3F)]; obuf[3] = digit[(int)(n & 0x3F)]; push(out,obuf,line,pos); } if(read > 0) { n = (((long)ibuf[0]) & 0xFF) << 16; if(read == 2) { n |= (((long)ibuf[1]) & 0xFF) << 8; } obuf[0] = digit[(int)((n >>> 18) & 0x3F)]; obuf[1] = digit[(int)((n >>> 12) & 0x3F)]; obuf[2] = (read == 2) ? digit[(int)((n >>> 6) & 0x3F)] : '='; obuf[3] = '='; push(out,obuf,line,pos); } out.flush(); return pos[0]; } //encode /** * Encode the input stream and write it to the writer, breaking each line * every <tt>line</tt> characters * * @param in The Input Stream * @param out The Writer * @param line The maximum number of bytes per line * @return number of bytes written to <tt>out</tt> * @throws IOException if the streams get crossed */ public static int encode (InputStream in,Writer out,int line) throws IOException { return encode(in,out,line,STD_DIGIT); } //encode /** * Encode the input stream and write it to the output stream, breaking each * line at 76 characters * * @param in The Input Stream * @param out The Output Stream Writer * @return the number of bytes written * @throws IOException If the streams get crossed */ public static int encode (InputStream in,Writer out) throws IOException { return encode(in,out,76); } //encode /** * Decode the character array from base64 * * @param data The Base64 array to be decoded * @return Decoded character array */ public static char[] decode (char[] data) { long n; int i = 0,j = 0; int len = (data.length * 3) / 4; if((data[data.length - 1]) == '=') { if((data[data.length - 2]) == '=') { --len; } --len; } char[] buf = new char[len]; while(i < data.length) { n = (ORD[data[i++]] << 18) | (ORD[data[i++]] << 12) | (ORD[data[i++]] << 6) | ORD[data[i++]]; buf[j++] = (char)((n >>> 16) & 0xFF); if(--len > 0) { buf[j++] = (char)((n >>> 8) & 0xFF); if(--len > 0) { buf[j++] = (char)(n & 0xFF); --len; } } } return buf; } //decode /** * Decode the Reader to the Output Stream, allows interspersed carriage * returns and line-feeds. * * @param in The Input Stream Reader * @param out The Output Stream * @return The number of bytes written to the Output Stream * @throws IOException If the streams get crossed */ public static int decode (Reader in,OutputStream out) throws IOException { long n; int i,j,len,count = 0; String line; byte[] buf; char[] data; BufferedReader reader = (in instanceof BufferedReader) ? (BufferedReader)in : new BufferedReader(in); while((line = reader.readLine()) != null) { data = line.toCharArray(); i = 0; j = 0; len = (data.length * 3) / 4; if((data[data.length - 1]) == '=') { if((data[data.length - 2]) == '=') { --len; } --len; } buf = new byte[len]; while(i < data.length) { n = (ORD[data[i++]] << 18) | (ORD[data[i++]] << 12) | (ORD[data[i++]] << 6) | ORD[data[i++]]; buf[j++] = (byte)((n >>> 16) & 0xFF); if(--len > 0) { buf[j++] = (byte)((n >>> 8) & 0xFF); if(--len > 0) { buf[j++] = (byte)(n & 0xFF); --len; } } } out.write(buf); count += len; } return count; } //decode /** * Decode the Input Stream to the Output Stream, allows interspersed carriage * returns and line-feeds. * * @param in The Input Stream * @param out The Output Stream * @return The number of bytes written to the Output Stream * @throws IOException if the streams get crossed */ public static int decode (InputStream in,OutputStream out) throws IOException { return decode(new InputStreamReader(in),out); } //decode /** * Decode the String from base64, allows interspersed carriage returns and * line-feeds. * * @param str The Base64 String to be decoded * @return Decoded byte array */ public static byte[] decode (String str) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); decode(new BufferedReader(new StringReader(str)),out); return out.toByteArray(); } catch(IOException x) { return null; } } //decode /** * Print the Usage Message */ private static void usage () { System.err.println("Usage: java Base64 <encode | encodeURLSafe | decode | file> <data> [<data> ...]"); } //usage /** * Program Entry-point * * @param args Command Line Arguments * @throws IOException if the streams get crossed */ public static void main (String[] args) throws IOException { if(args.length >= 2) { if(args[0].equalsIgnoreCase("encode")) { int i; StringBuilder buf = new StringBuilder(); for(i = 1;i < args.length - 1;i++) { buf.append(args[i]).append(' '); } buf.append(args[i]); System.err.println(new String(encode(buf.toString().toCharArray()))); } else if(args[0].equalsIgnoreCase("encodeURLSafe")) { int i; StringBuilder buf = new StringBuilder(); for(i = 1;i < args.length - 1;i++) { buf.append(args[i]).append(' '); } buf.append(args[i]); System.err.println(new String(encodeURLSafe(buf.toString().toCharArray()))); } else if(args[0].equalsIgnoreCase("decode")) { System.err.println(Hex.dump(new String(decode(args[1])))); } else if(args[0].equalsIgnoreCase("file")) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); int cnt = encode(new FileInputStream(args[1]),bytes); String encoded = new String(bytes.toByteArray()); System.err.println("Encoded: (" + cnt + ')'); System.err.println(encoded); System.err.println("Decoded:"); System.err.println(new String(decode(encoded))); } else { usage(); } } else { usage(); } } //main } //*Base64
Java
/** * FormattedRuntimeException * * @author Chris Pratt * * 12/12/2011 */ package com.anodyzed.onyx.util; import com.anodyzed.onyx.text.TextFormat; @SuppressWarnings("serial") public class FormattedRuntimeException extends RuntimeException { /** * No-arg Constructor */ public FormattedRuntimeException () { super(); } //FormattedRuntimeException /** * Constructor * * @param msg A Descriptive Message Format String about the cause of the Exception * @param args Replacement Arguments for the Format String */ public FormattedRuntimeException (String msg,Object... args) { super(TextFormat.format(msg,args)); Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; if(t != null) { initCause(t); } } //FormattedRuntimeException /** * Constructor * * @param cause The Throwable that initiated this Exception Chain */ public FormattedRuntimeException (Throwable cause) { super(cause); } //FormattedRuntimeException } //*FormattedRuntimeException
Java
/** * Chrono - Date/Time Utilities * * @author Chris Pratt * * 11/26/2001 */ package com.anodyzed.onyx.util; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; public class Chrono { protected static final DateFormatSymbols symbols = new DateFormatSymbols(); /** * Constructor */ public Chrono () { } //Chrono /** * Returns a copy of the supplied calendar with the fields up to the specified * field cleared, exclusive. So to clear out the time and leave the date use * <code>clearTo(cal,Calendar.DAY_OF_MONTH)</code> or to clear away the * seconds to leave the Hours and Minutes, use * <code>clearTo(cal,Calendar.MINUTE)</code> * * @param cal The Calendar to be cleared * @param field The Field to be cleared to * @return The Cleared Calendar */ @SuppressWarnings("fallthrough") public static Calendar clearTo (Calendar cal,int field) { Calendar c = (Calendar)cal.clone(); switch(field) { case Calendar.ERA: c.clear(); c.set(Calendar.YEAR,0); break; case Calendar.YEAR: c.clear(Calendar.MONTH); case Calendar.MONTH: c.set(Calendar.DAY_OF_MONTH,1); case Calendar.DAY_OF_MONTH: c.set(Calendar.HOUR_OF_DAY,0); case Calendar.HOUR: case Calendar.HOUR_OF_DAY: c.set(Calendar.MINUTE,0); case Calendar.MINUTE: c.set(Calendar.SECOND,0); case Calendar.SECOND: c.set(Calendar.MILLISECOND,0); } return c; } //clearTo /** * Clear the fields of the Date up to the specified field, exclusive * * @param date The Date to be cleared * @param field The Field to be cleared to * @return The Cleared Date * @see #clearTo(Calendar,int) */ public static Date clearTo (Date date,int field) { return clearTo(Convert.toCalendar(date),field).getTime(); } //clearTo /** * Test if Calendar A represents a timestamp that is after Calendar B down to * the specified field * * @param a The first Calendar * @param b The second Calendar * @param field The Calendar Field * @return true if Calendar A is after Calendar B */ public static boolean after (Calendar a,Calendar b,int field) { return clearTo(a,field).after(clearTo(b,field)); } //after /** * Test if Calendar/Date A is after Calendar/Date B down to the specified * field * * @param a The first Calendar/Date * @param b The second Calendar/Date * @param field The Calendar Field * @return true if Calendar/Date A is after Calendar/Date B */ public static boolean after (Object a,Object b,int field) { Calendar A = (a instanceof Calendar) ? (Calendar)a : ((a instanceof Date) ? Convert.toCalendar((Date)a) : null); Calendar B = (b instanceof Calendar) ? (Calendar)b : ((b instanceof Date) ? Convert.toCalendar((Date)b) : null); return (A != null) && (B != null) && after(A,B,field); } //after /** * Test if Calendar A represents a timestamp that is before Calendar B down to * the specified field * * @param a The first Calendar * @param b The second Calendar * @param field The Calendar Field * @return true if Calendar A is before Calendar B */ public static boolean before (Calendar a,Calendar b,int field) { return clearTo(a,field).before(clearTo(b,field)); } //before /** * Test if Calendar/Date A is before Calendar/Date B down to the specified * field * * @param a The first Calendar/Date * @param b The second Calendar/Date * @param field The Calendar Field * @return true if Calendar/Date A is before Calendar/Date B */ public static boolean before (Object a,Object b,int field) { Calendar A = (a instanceof Calendar) ? (Calendar)a : ((a instanceof Date) ? Convert.toCalendar((Date)a) : null); Calendar B = (b instanceof Calendar) ? (Calendar)b : ((b instanceof Date) ? Convert.toCalendar((Date)b) : null); return (A != null) && (B != null) && before(A,B,field); } //before /** * Convenience method to perform Calendar arithmetic * * @param cal The starting Calendar * @param duration The number of units to add (can be negative) * @param unit The Calendar units to add * @return The sum Calendar */ public static Calendar add (Calendar cal,int duration,int unit) { cal.add(unit,duration); return cal; } //add /** * Convenience method to perform Date arithmetic * * @param date The starting date * @param duration The number of units to add (can be negative) * @param unit The Calendar units to add * @return The sum Date */ public static Date add (Date date,int duration,int unit) { return add(Convert.toCalendar(date),duration,unit).getTime(); } //add /** * Calculate the Unit Change in Time between the two Calendars * for the specified field * * Unit Change represents the number of times the value has changed or, put * another way, the Library time. Example: When you check out a book from * the library at 5:00pm, If you check it in at 9:00am the next morning you * have kept if for 1 day as far as the library is concerned, even though * you have only had it for 16 hours. It's also true that if you turned it * in at 7:00pm that day, you would still only be charged for 1 day even * though you had the book for 26 hours. Because the Unit Change in days * was only 1. * * @param a The first Calendar * @param b The second Calendar * @param field The Calendar Field * @return The Unit Change */ public static int change (Calendar a,Calendar b,int field) { Calendar A,B; int change = 0; if(b.after(a)) { A = clearTo(a,field); B = clearTo(b,field); } else { A = clearTo(b,field); B = clearTo(a,field); } while(A.before(B)) { A.add(field,1); ++change; } return change; } //change /** * Calculate the Unit Change in Time between two Calendars and/or Dates * for the specified field * * @param a The First Calendar/Date * @param b The Second Calendar/Date * @param field The Calendar Field * @return The Unit Change */ public static int change (Object a,Object b,int field) { Calendar A = (a instanceof Calendar) ? (Calendar)a : ((a instanceof Date) ? Convert.toCalendar((Date)a) : null); Calendar B = (b instanceof Calendar) ? (Calendar)b : ((b instanceof Date) ? Convert.toCalendar((Date)b) : null); if((A != null) && (B != null)) { return change(A,B,field); } return -1; } //change /** * Calculate the Unit Change in Time between the supplied Calendar or Date * and Now * * @param a The Calendar/Date * @param field The Calendar Field * @return The Unit Change */ public static int change (Object a,int field) { return change(a,Calendar.getInstance(),field); } //change /** * Get the Abbreviations for the Months of the Year * * @return 3 Letter Month Abbreviations String Array */ public static String[] getMonthAbbreviations () { return symbols.getShortMonths(); } //getMonthAbbreviations /** * Get the Names of the Months of the Year * * @return Month Name String Array */ public static String[] getMonthNames () { return symbols.getMonths(); } //getMonthNames } //*Chrono
Java
/** * FormattedException * * @author Chris Pratt * * 12/12/2011 */ package com.anodyzed.onyx.util; import com.anodyzed.onyx.text.TextFormat; @SuppressWarnings("serial") public class FormattedException extends Exception { /** * No-arg Constructor */ public FormattedException () { super(); } //FormattedException /** * Constructor * * @param msg A Descriptive Message Format String about the cause of the Exception * @param args Replacement Arguments for the Format String */ public FormattedException (String msg,Object... args) { super(TextFormat.format(msg,args)); Throwable t = ((args != null) && (args.length > 0) && (args[args.length - 1] instanceof Throwable)) ? (Throwable)args[args.length - 1] : null; if(t != null) { initCause(t); } } //FormattedException /** * Constructor * * @param cause The Throwable that initiated this Exception Chain */ public FormattedException (Throwable cause) { super(cause); } //FormattedException } //*FormattedException
Java
/** * Calc * * @author Chris Pratt * * 2/26/2003 */ package com.anodyzed.onyx.util; public class Calc { private static final char NONE = (char)-1; private static final char SPC = ' '; private static final char LEFT = '('; private static final char RITE = ')'; private static final char ADD = '+'; private static final char SUB = '-'; private static final char MUL = '*'; private static final char DIV = '/'; private static final char MOD = '%'; private static final char NOT = '~'; private static final char BANG = '!'; private static final char SHL = '<'; private static final char SHR = '>'; private static final char AND = '&'; private static final char OR = '|'; private static final char XOR = '^'; /** * Constructor */ private Calc () { } //Calc /** * Parse the Number from the Equation * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The Numeric Value */ private static long getNum (char[] equation,int[] pos) { boolean not = false; boolean neg = false; int base = 10; long val = 0; while((pos[0] < equation.length) && (equation[pos[0]] == SPC)) { pos[0]++; } if((pos[0] < equation.length) && (equation[pos[0]] == LEFT)) { pos[0]++; return eval(equation,pos); } else { if((pos[0] < equation.length) && ((equation[pos[0]] == NOT) || (equation[pos[0]] == BANG))) { not = true; pos[0]++; } if((pos[0] < equation.length) && ((equation[pos[0]] == SUB) || (equation[pos[0]] == ADD))) { neg = equation[pos[0]++] == SUB; } if((pos[0] < equation.length) && (equation[pos[0]] == '0')) { if((++(pos[0]) < equation.length) && (equation[pos[0]] == 'x')) { base = 16; pos[0]++; } else if((pos[0] < equation.length) && (equation[pos[0]] == 'b')) { base = 2; pos[0]++; } else { base = 8; } } while((pos[0] < equation.length) && Misc.isNumeric(equation[pos[0]],base)) { val = (val * base) + Character.digit(equation[pos[0]++],base); } if(pos[0] < equation.length) { if(Character.toUpperCase(equation[pos[0]]) == 'K') { val *= 1024; pos[0]++; } else if(Character.toUpperCase(equation[pos[0]]) == 'M') { val *= 1048576; pos[0]++; } else if(Character.toUpperCase(equation[pos[0]]) == 'G') { val *= 1073741824; pos[0]++; } } if(not) { val = ~val; } if(neg) { val *= -1; } return val; } } //getNum /** * Get a single Equation Term * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The term value */ private static long getTerm (char[] equation,int[] pos) { long val = getNum(equation,pos); while(pos[0] < equation.length) { switch(getOperator(equation,pos)) { case LEFT: pos[0]++; return eval(equation,pos); case MUL: pos[0]++; val *= getNum(equation,pos); break; case MOD: pos[0]++; val %= getNum(equation,pos); case DIV: pos[0]++; val /= getNum(equation,pos); break; default: return val; } } return val; } //getTerm /** * Locate the next Operator * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The Operator Character */ private static char getOperator (char[] equation,int[] pos) { while(pos[0] < equation.length) { switch(equation[pos[0]]) { case SPC: // Skip it pos[0]++; break; case '{': case '[': return LEFT; case '}': case ']': return RITE; case LEFT: case RITE: case ADD: case SUB: case MUL: case DIV: case NOT: case BANG: return equation[pos[0]]; case AND: if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == AND)) { pos[0]++; } return AND; case OR: if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == OR)) { pos[0]++; } return OR; case XOR: if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == XOR)) { pos[0]++; } return XOR; case SHL: if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == SHL)) { pos[0]++; } return SHL; case SHR: if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == SHR)) { pos[0]++; if((pos[0] + 1 < equation.length) && (equation[pos[0] + 1] == SHR)) { pos[0]++; } } return SHR; default: throw new IllegalArgumentException("Parse Error at position " + pos[0] + " (" + equation[pos[0]] + ')'); } } return NONE; } //getOperator /** * Evaluate the specified equation from the specified position and with the * given starting value * * @param val The Initial value * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The result of the evaluation */ private static long eval (long val,char[] equation,int[] pos) { char op; while(pos[0] < equation.length) { switch(op = getOperator(equation,pos)) { case NONE: case RITE: pos[0]++; return val; case ADD: pos[0]++; val += getTerm(equation,pos); break; case SUB: pos[0]++; val -= getTerm(equation,pos); break; case SHL: pos[0]++; val <<= getTerm(equation,pos); break; case SHR: pos[0]++; val >>= getTerm(equation,pos); break; case AND: pos[0]++; val &= getTerm(equation,pos); break; case OR: pos[0]++; val |= getTerm(equation,pos); break; case XOR: pos[0]++; val ^= getTerm(equation,pos); break; default: throw new IllegalArgumentException("Unrecognized Operation (" + op + ") at position " + pos[0]); } } return val; } //eval /** * Evaluate the specified equation from the specified position * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The result of the evaluation */ private static long eval (char[] equation,int[] pos) { return eval(getTerm(equation,pos),equation,pos); } //eval /** * Evaluate the specified equation * * @param equation The Equation String * @return The result of the Evaluation */ public static long eval (String equation) { return eval(equation.toCharArray(),new int[] {0}); } //eval /** * Evaluate the specified equation * * @param val The Initial value of the equation * @param equation The Equation String * @return The result of the Evaluation */ public static long eval (long val,String equation) { return eval(val,equation.toCharArray(),new int[] {0}); } //eval /** * Evaluate the specified equation and return the answer as a string * * @param equation The Equation String * @return The Result of the Evaluation String */ public static String toString (String equation) { return String.valueOf(eval(equation.toCharArray(),new int[] {0})); } //toString /** * Evaluate the specified equation and return the answer as a String * * @param val The Initial value of the equation * @param equation The Equation String * @return The Result of the Evaluation as a String */ public static String toString (long val,String equation) { return String.valueOf(eval(val,equation.toCharArray(),new int[] {0})); } //toString /** * Round the number <code>d</code> to the nearest <code>t</code>. * * @param d The Number to be Rounded * @param t The target increment * @return <code>d</code> rounded to the nearest <code>t</code> */ public static double roundToNearest (double d,double t) { return Math.round(d / t) * t; } //roundToNearest /** * Return the next value of <code>d</code> away from zero by an increment of * <code>t</code>. * * @param d The Number to be Ceiling'd * @param t The target increment * @return <code>d</code> ceilinged to the nearest <code>t</code> */ public static double ceilToNearest (double d,double t) { return Math.ceil(d / t) * t; } //ceilToNearest /** * Return the next value of <code>d</code> closer to zero by an increment of * <code>t</code>. * * @param d The Number to be Floored * @param t The target increment * @return <code>d</code> floored to the nearest <code>t</code> */ public static double floorToNearest (double d,double t) { return Math.floor(d / t) * t; } //floorToNearest /** * Add the supplied integers, substituting 0 for any possible null values * * @param a The first Integer * @param b The second Integer * @return Their sum */ public static Integer add (Integer a,Integer b) { return (a != null) ? ((b != null) ? new Integer(a + b) : a) : ((b != null) ? b : null); } //add /** * Add the supplied double-precision floating-point numbers, substituting 0.0 * for any possible null values * * @param a The first number * @param b The second number * @return Their sum */ public static Double add (Double a,Double b) { return (a != null) ? ((b != null) ? new Double(a + b) : a) : ((b != null) ? b : null); } //add } //*Calc
Java
/** * FPCalc - Floating Point Calculator * * @author Chris Pratt * * 12/26/2012 */ package com.anodyzed.onyx.util; public class FPCalc { private static final char NONE = (char)-1; private static final char SPC = ' '; private static final char LEFT = '('; private static final char RITE = ')'; private static final char ADD = '+'; private static final char SUB = '-'; private static final char MUL = '*'; private static final char DIV = '/'; private static final char MOD = '%'; private static final char DOT = '.'; /** * Constructor */ private FPCalc () { } //FPCalc /** * Parse the Number from the Equation * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The Numeric Value */ private static double getNum (char[] equation,int[] pos) { boolean neg = false; double val = 0.0; while((pos[0] < equation.length) && (equation[pos[0]] == SPC)) { pos[0]++; } if((pos[0] < equation.length) && (equation[pos[0]] == LEFT)) { pos[0]++; return eval(equation,pos); } else { if((pos[0] < equation.length) && ((equation[pos[0]] == SUB) || (equation[pos[0]] == ADD))) { neg = equation[pos[0]++] == SUB; } while((pos[0] < equation.length) && Character.isDigit(equation[pos[0]])) { val = (val * 10) + Character.digit(equation[pos[0]++],10); } if((pos[0] < equation.length) && (equation[pos[0]] == DOT)) { pos[0]++; double fraction = 0.1; while((pos[0] < equation.length) && Character.isDigit(equation[pos[0]])) { val = val + (Character.digit(equation[pos[0]++],10) * fraction); fraction = fraction / 10; } } if(neg) { val *= -1; } return val; } } //getNum /** * Get a single Equation Term * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The term value */ private static double getTerm (char[] equation,int[] pos) { double val = getNum(equation,pos); while(pos[0] < equation.length) { switch(getOperator(equation,pos)) { case LEFT: pos[0]++; return eval(equation,pos); case MUL: pos[0]++; val *= getNum(equation,pos); break; case MOD: pos[0]++; val %= getNum(equation,pos); case DIV: pos[0]++; val /= getNum(equation,pos); break; default: return val; } } return val; } //getTerm /** * Locate the next Operator * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The Operator Character */ private static char getOperator (char[] equation,int[] pos) { while(pos[0] < equation.length) { switch(equation[pos[0]]) { case SPC: // Skip it pos[0]++; break; case '{': case '[': return LEFT; case '}': case ']': return RITE; case LEFT: case RITE: case ADD: case SUB: case MUL: case DIV: return equation[pos[0]]; default: throw new IllegalArgumentException("Parse Error at position " + pos[0] + " (" + equation[pos[0]] + ')'); } } return NONE; } //getOperator /** * Evaluate the specified equation from the specified position and with the * given starting value * * @param val The Initial value * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The result of the evaluation */ private static double eval (double val,char[] equation,int[] pos) { char op; while(pos[0] < equation.length) { switch(op = getOperator(equation,pos)) { case NONE: case RITE: pos[0]++; return val; case ADD: pos[0]++; val += getTerm(equation,pos); break; case SUB: pos[0]++; val -= getTerm(equation,pos); break; default: throw new IllegalArgumentException("Unrecognized Operation (" + op + ") at position " + pos[0]); } } return val; } //eval /** * Evaluate the specified equation from the specified position * * @param equation The Equation Character Array * @param pos The Current Position Pointer in the Array * @return The result of the evaluation */ private static double eval (char[] equation,int[] pos) { return eval(getTerm(equation,pos),equation,pos); } //eval /** * Evaluate the specified equation * * @param equation The Equation String * @return The result of the Evaluation */ public static double eval (String equation) { return eval(equation.toCharArray(),new int[] {0}); } //eval /** * Evaluate the specified equation * * @param val The Initial value of the equation * @param equation The Equation String * @return The result of the Evaluation */ public static double eval (double val,String equation) { return eval(val,equation.toCharArray(),new int[] {0}); } //eval /** * Evaluate the specified equation and return the answer as a string * * @param equation The Equation String * @return The Result of the Evaluation String */ public static String toString (String equation) { return String.valueOf(eval(equation.toCharArray(),new int[] {0})); } //toString /** * Evaluate the specified equation and return the answer as a String * * @param val The Initial value of the equation * @param equation The Equation String * @return The Result of the Evaluation as a String */ public static String toString (double val,String equation) { return String.valueOf(eval(val,equation.toCharArray(),new int[] {0})); } //toString } //*FPCalc
Java
/** * Stack - A LIFO (Last-in First-out) Queue, or Stack * * @author Chris Pratt * * 1/24/2006 */ package com.anodyzed.onyx.util; public interface Stack<E> extends Iterable<E> { /** * Add an Element to the Top of the Stack * * @param e The Element to Push onto the Stack * @return true if successful */ public boolean push(E e); /** * Retrieve the Top Element on the Stack without modifying the Stack * * @return The Top Element on the Stack */ public E peek(); /** * Retrieve the Element <code>n</code> from the Top without modifying the * Stack * * @param n The distance from the top of the stack to peek * @return The <code>n</code><small>th</small> Element from the Top of the Stack */ public E peek(int n); /** * Retrieve and Remove the Top Element from the Stack * * @return The Top Element on the Stack */ public E pop(); /** * Remove all the Elements from the Stack */ public void clear(); /** * Test whether the stack is empty * * @return true if there are no elements in the stack */ public boolean isEmpty(); /** * Return the number of elements on the Stack * * @return element count */ public int size(); } //#Stack
Java
/** * PrototypeMap * * @author Chris Pratt * * 9/24/2009 */ package com.anodyzed.onyx.util; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; @SuppressWarnings("serial") public class PrototypeMap<K,V> extends HashMap<K,Class<? extends V>> implements Serializable { /** * Constructs an empty map with the default initial capacity (16) and the * default load factor (0.75). */ public PrototypeMap () { super(); } //PrototypeMap /** * Constructor * * @param initialSize The Initial Size of the Map */ public PrototypeMap (int initialSize) { super(initialSize); } //PrototypeMap /** * Constructor * * @param initialSize The Initial Size of the Map * @param loadFactor The percent full before expanding the map */ public PrototypeMap (int initialSize,float loadFactor) { super(initialSize,loadFactor); } //PrototypeMap /** * Copy Constructor * * @param map The Map to Copy */ public PrototypeMap (Map<? extends K,? extends Class<? extends V>> map) { super(map); } //PrototypeMap /** * Create a new Instance of the Class for the specified key * * @param key The Key * @return The new Instance of the Value */ public V newInstance (K key) { try { Class<? extends V> klass = get(key); return (klass != null) ? klass.newInstance() : null; } catch(InstantiationException x) { throw new RuntimeException("Unable to create instance of " + key,x); } catch(IllegalAccessException x) { throw new RuntimeException("Unable to access " + key,x); } } //newInstance /** * Create a new Instance of the Class for the specified key using the * constructor for the supplied types and passing the arguments into the * constructor. * * @param key The Key * @param types The Constructor Type Array * @param args The Constructor Arguments * @return The new Instance of the Value */ public V newInstance (K key,Class<?>[] types,Object[] args) { try { Class<? extends V> klass = get(key); return (klass != null) ? klass.getConstructor(types).newInstance(args) : null; } catch(InstantiationException x) { throw new RuntimeException("Unable to create instance of " + key,x); } catch(IllegalAccessException x) { throw new RuntimeException("Unable to access " + key,x); } catch(NoSuchMethodException x) { throw new RuntimeException("Unable to get constructor for " + key,x); } catch(InvocationTargetException x) { Throwable cause = x.getCause(); if(cause instanceof RuntimeException) { throw (RuntimeException)cause; } else { throw new RuntimeException("Unable to instantiate " + key,cause); } } } //newInstance /** * Create a new Instance of the Class for the specified key passing in the * supplied arguments to the constructor. * * @param key The Key * @param args The Constructor Arguments * @return The new Instance of the Value */ public V newInstance (K key,Object... args) { try { Class<? extends V> klass = get(key); if(klass != null) { Class<?>[] types = new Class<?>[args.length]; for(int i = 0;i < args.length;i++) { types[i] = (args[i] != null) ? args[i].getClass() : null; } return klass.getConstructor(types).newInstance(args); } } catch(InstantiationException x) { throw new RuntimeException("Unable to create instance of " + key,x); } catch(IllegalAccessException x) { throw new RuntimeException("Unable to access " + key,x); } catch(NoSuchMethodException x) { throw new RuntimeException("Unable to get constructor for " + key,x); } catch(InvocationTargetException x) { throw new RuntimeException("Unable to instantiate " + key,x.getTargetException()); } return null; } //newInstance } //*PrototypeMap
Java
/** * Convert - Type Conversion Routines * * @author Chris Pratt * * 7/23/1999 */ package com.anodyzed.onyx.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Convert { private static final String DATE_REGEX = "^((?:[01]?\\d)|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(?:January|February|March|April|June|July|August|September|October|November|December))(?:[ \\-/.]((?:(?:[0-2]?\\d)|(?:3[01]))),?)?[ \\-/]((?:[12]\\d)?\\d\\d)$"; private static final String ISO_REGEX = "^([12]\\d\\d\\d)[ \\-/.](\\d\\d)[ \\-/.](\\d\\d)$"; private static final Set<String> TRUISMS = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); private static final Set<String> FALSEHOODS = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); static { TRUISMS.add("true"); TRUISMS.add("yes"); TRUISMS.add("on"); TRUISMS.add("t"); TRUISMS.add("y"); TRUISMS.add("1"); FALSEHOODS.add("false"); FALSEHOODS.add("no"); FALSEHOODS.add("off"); FALSEHOODS.add("f"); FALSEHOODS.add("n"); FALSEHOODS.add("0"); } /** * Protected Constructor - Prevent Instantiation of this Utility Singleton */ protected Convert () { } //Convert ////////// Simple Type Conversion ////////// /** * Convert the String to a boolean * * @param str the string * @return true if the string was "true" | "yes" | "on" | "y" | "1" */ public static boolean toBoolean (String str) { return (str != null) && TRUISMS.contains(str); } //toBoolean /** * Convert the String to a boolean, return a boolean if the value can't be * determined. * * @param str the String * @param def The default value * @return true if str was "true" | "yes" | "on" | "t" | "y" | "1" * false if str was "false" | "no" | "off" | "f" | "n" | "0" * otherwise {@code def} */ public static boolean toBoolean (String str,boolean def) { if(str != null) { if(TRUISMS.contains(str)) { return true; } else if(FALSEHOODS.contains(str)) { return false; } } return def; } //toBoolean /** * Convert the String to a Boolean, return the supplied default Boolean * value if the value can't be determined from the supplied string. * * @param str the String * @param def The default value * @return TRUE if str was "true" | "yes" | "on" | "t" | "y" | "1" * FALSE if str was "false" | "no" | "off" | "f" | "n" | "0" * otherwise {@code def} */ public static Boolean toBoolean (String str,Boolean def) { if(str != null) { if(TRUISMS.contains(str)) { return Boolean.TRUE; } else if(FALSEHOODS.contains(str)) { return Boolean.FALSE; } } return def; } //toBoolean /** * Convert the String to an Integer or return the default value if it can't * be converted. * * @param str The String to be converted * @param def The default value * @return The Converted Integer */ public static int toInt (String str,int def) { if(str != null) { try { return Integer.parseInt(str); } catch(NumberFormatException x) { // Just return the default value } } return def; } //toInt /** * Convert the String to a Long Integer or return the default value if it * can't be converted. * * @param str The String to be converted * @param def The default value * @return The Converted Long Integer */ public static long toLong (String str,long def) { if(str != null) { try { return Long.parseLong(str); } catch(NumberFormatException x) { // Just return the default value } } return def; } //toLong /** * Convert the String to a float or return the default value if it can't * be converted. * * @param str The String to be converted * @param def The default value * @return The Converted float */ public static float toFloat (String str,float def) { if(str != null) { try { return Float.parseFloat(str); } catch(NumberFormatException x) { // Just return the default value } } return def; } //toFloat /** * Convert the String to a double or return the default value if it can't * be converted. * * @param str The String to be converted * @param def The default value * @return The Converted double */ public static double toDouble (String str,double def) { if(str != null) { try { return Double.parseDouble(str); } catch(NumberFormatException x) { // Just return the default value } } return def; } //toDouble /** * Convert an int to a String using the specified base and the minimum * number of digits. * * @param i The Integer to Convert * @param dig The Number of digits (-1 = any) * @param base The base numbering system * @return The String */ public static String toString (int i,int dig,int base) { StringBuilder buf = new StringBuilder(); boolean neg = i < 0; if(neg) { i *= -1; } while(i > 0) { buf.append(Hex.hex(i % base)); i /= base; --dig; } while(dig-- > 0) { buf.append('0'); } if(neg) { buf.append('-'); } return buf.reverse().toString(); } //toString /** * Convert an int to a String of Decimal Character with a minimum number * of digits. * * @param i The Integer to Convert * @param dig The Minimum number of digits * @return The String */ public static String toString (int i,int dig) { return toString(i,dig,10); } //toString /** * Convert an int to String of Decimal Characters * * @param i The Integer to Convert * @return The String */ public static String toString (int i) { return toString(i,-1,10); } //toString ////////// Collection Conversion ////////// /** * Add the elements of a delimited string to a Collection. * * @param str The delimited String * @param delim The delimiter Character * @param col The Collection to add the elements to * @return The Collection object */ public static <T extends Collection<String>> T toCollection (String str,char delim,T col) { if((str != null) && (str.length() > 0)) { int i = 0; char[] buf = str.toCharArray(); StringBuilder cell = new StringBuilder(); do { while((i < buf.length) && (buf[i] <= ' ')) { ++i; } if((i < buf.length) && (buf[i] == '\"')) { i++; while(true) { if((i < buf.length) && (buf[i] != '\"')) { cell.append(buf[i++]); } else if((buf.length > i + 1) && (buf[i + 1] == '\"')) { cell.append(buf[i++]); ++i; } else { break; } } while((i < buf.length) && (buf[i] != delim)) { ++i; } col.add(cell.toString()); } else { while((i < buf.length) && (buf[i] != delim)) { cell.append(buf[i++]); } col.add(cell.toString().trim()); } cell.setLength(0); } while(++i < buf.length); // Handle the empty cell at the end of the string if(buf[buf.length - 1] == delim) { col.add(""); } } return col; } //toCollection /** * Convert a delimited String to a List Object. * * @param str The delimited String * @param delim The Delimiter character * @return The List Object */ public static List<String> toList (String str,char delim) { return toCollection(str,delim,new ArrayList<String>()); } //toList ////////// Array Conversion ////////// /** * Convert a (Possibly Quoted) delimited string of arguments to an array of * strings. * * @param str The Input string * @param delim The delimiter character * @return The Array of Strings */ public static String[] toStringArray (String str,char delim) { if(str != null) { return toList(str,delim).toArray(new String[0]); } return new String[0]; } //toStringArray ////////// Delimited String Conversion ////////// /** * Convert an Object to be a delimited cell String. * * @param o Object to be Converted * @return The cell String */ protected static String toCell (Object o) { boolean quote = false; String str = String.valueOf(o); StringBuilder cell = new StringBuilder(); if((str.indexOf(',') != -1) || (str.indexOf('\"') != -1)) { quote = true; cell.append('\"'); } int prev = 0,pos = 0; while((pos = str.indexOf('\"',pos)) != -1) { cell.append(str.substring(prev,pos)).append('\"'); prev = pos++; } if(prev < str.length()) { cell.append(str.substring(prev)); } if(quote) { cell.append('\"'); } return cell.toString(); } //toCell /** * Convert an Iterable Collection to a delimited String. * * @param i The Iterable Collection to be Converted * @param delim The delimiter character * @return The delimited string */ public static String toDelimitedString (Iterable<?> i,char delim) { boolean comma = false; StringBuilder buf = new StringBuilder(); for(Object o : i) { if(comma) { buf.append(delim); } else { comma = true; } buf.append(toCell(o)); } return buf.toString(); } //toDelimitedString /** * Return a delimited string of key=value pairs for each entry in the map. * * @param map The map to be converted * @param delim The delimiter character * @return the delimited key=value string */ public static String toDelimitedString (Map<?,?> map,char delim) { StringBuilder buf = new StringBuilder(); if((map != null) && !map.isEmpty()) { boolean comma = false; for(Object key : map.keySet()) { if(comma) { buf.append(delim); } else { comma = true; } buf.append(toCell(String.valueOf(key) + '=' + String.valueOf(map.get(key)))); } } return buf.toString(); } //toDelimitedString /** * Convert an Array of Objects to a single delimited String. * * @param array The Array of Objects * @param delim The delimiter character * @return The delimited string */ public static String toDelimitedString (Object[] array,char delim) { if(array != null) { boolean comma = false; StringBuilder buf = new StringBuilder(); for(Object o : array) { if(comma) { buf.append(delim); } else { comma = true; } buf.append(toCell(o)); } return buf.toString(); } return null; } //toDelimitedString ////////// Fixed-Format String Conversion ////////// /** * Convert a List of Objects to a fixed width String. * * Each entry in the {@code len} array determines the width of the * corresponding column. If the length of the data for the specified * column is greater then the absolute value of the width in {@code len} it * will be truncated to fit. If the data is shorter and the width is * positive (i.e. > 0) the data will be Left Justified and padded on the * right end with spaces. If the width is negative (i.e. < 0) the column * will be Right Justified and padded on the Left with zeroes. * * @param list The List of Objects * @param len The Array of Column Widths * @return The Fixed Width String */ public static String toFixedString (Iterable<?> list,int[] len) { int n,l,i = 0; char ch; String str; StringBuilder buf = new StringBuilder(); for(Object o : list) { n = 0; l = Math.abs(len[i]); if(o != null) { str = String.valueOf(o); if((n = str.length()) > l) { buf.append(str.substring(0,l)); } else { if(len[i] < 0) { while(n++ < l) { buf.append('0'); } } buf.append(str); while(n++ < l) { buf.append(' '); } } } else { ch = (len[i] < 0) ? '0' : ' '; while(n++ < l) { buf.append(ch); } } ++i; } while(i++ < len.length) { l = Math.abs(len[i]); ch = (len[i] < 0) ? '0' : ' '; for(n = 0;n < l;n++) { buf.append(ch); } } return buf.toString(); } //toFixedString /** * Convert an Array of Objects to a fixed width String. Each entry in the * <code>len</code> array determines the width of the corresponding column. * If the length of the data for the specified column is greater than the * absolute value of the width in <code>len</code> it will be truncated to * fit. If the data is shorter and the width is positive (i.e. > 0) the * data will be Left Justified and padded on the right end with spaces. If * the width is negative (i.e. < 0) the column will be Right Justified and * padded on the Left with zeroes. * * @param array The Array of Objects * @param len The Array of Column Widths * @return The Fixed Width String */ public static String toFixedString (Object[] array,int[] len) { int n,l; char ch; String str; StringBuilder buf = new StringBuilder(); for(int i = 0;i < array.length;i++) { n = 0; l = Math.abs(len[i]); if((str = String.valueOf(array[i])) != null) { if((n = str.length()) > l) { buf.append(str.substring(0,l)); } else { if(len[i] < 0) { while(n++ < l) { buf.append('0'); } } buf.append(str); while(n++ < l) { buf.append(' '); } } } else { ch = (len[i] < 0) ? '0' : ' '; while(n++ < l) { buf.append(ch); } } } for(int i = array.length;i < len.length;i++) { l = Math.abs(len[i]); ch = (len[i] < 0) ? '0' : ' '; for(n = 0;n < l;n++) { buf.append(ch); } } return buf.toString(); } //toFixedString ////////// Date Conversion ////////// /** * Convert a Date to a Calendar * * @param date The Date Object * @return The equivalent Calendar Object */ public static Calendar toCalendar (Date date) { Calendar cal = Calendar.getInstance(); if(date != null) { cal.setTime(date); } return cal; } //toCalendar /** * Convert a Date String to a Calendar * * @param date The Date String * @return The Calendar Object */ public static Calendar toCalendar (String date) { Pattern pattern = Pattern.compile(DATE_REGEX); Matcher matcher = pattern.matcher(date); if(matcher.find()) { int y = 1,m = Calendar.JANUARY,d = 1; String data; if((data = matcher.group(3)) != null) { y = Integer.parseInt(data); if(y < 100) { if(y < 25) { // Range = 1925 - 2024 y += 2000; } else { y += 1900; } } } if((data = matcher.group(1)) != null) { if(Misc.isNumeric(data)) { m = Integer.parseInt(data) - 1; } else if(data.length() == 3) { m = Misc.arrayIndexOf(Chrono.getMonthAbbreviations(),data); } else { m = Misc.arrayIndexOf(Chrono.getMonthNames(),data); } } if((data = matcher.group(2)) != null) { d = Integer.parseInt(data); } return new GregorianCalendar(y,m,d); } else { pattern = Pattern.compile(ISO_REGEX); matcher = pattern.matcher(date); if(matcher.find()) { int y = Integer.parseInt(matcher.group(1)); int m = Integer.parseInt(matcher.group(2)); int d = Integer.parseInt(matcher.group(3)); return new GregorianCalendar(y,m - 1,d); } } return null; } //toCalendar /** * Parse a Date String into a Date Object * * @param date The Date String * @return The Date Object */ public static Date toDate (String date) { Calendar cal = toCalendar(date); return (cal != null) ? cal.getTime() : null; } //toDate /** * Parse a Date String into a Date Object using a specific Format String * * @param date The Date String * @param format The Date Format String * @return The Date Object */ public static Date toDate (String date,String format) { if(date != null) { if(format != null) { try { return new SimpleDateFormat(format).parse(date); } catch(ParseException x) { // That didn't work, try using the unformatted method } } return toDate(date); } return null; } //toDate /** * Format a Java Date Object as an ISO Date/Time String * * @param date The Date to Format * @return The ISO Date String */ public static String toISOString (Date date) { if(date != null) { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date); } return null; } //toISOString } //*Convert
Java
/** * BeanUtilsTests * * @author Chris Pratt * * 4/13/2010 */ package com.anodyzed.onyx.bean; import com.anodyzed.onyx.log.LogBuilder; import com.anodyzed.onyx.log.sysout.SysOutLogFactory; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; public class BeanUtilsTests { public static class TestData { class Inner { public String getText () { return "inner"; } //getText } //*Inner public String getText () { return "outer"; } //getText public Object getInner () { return new Inner(); } //getInner public Date getDate () { return new GregorianCalendar(1965,Calendar.JUNE,18).getTime(); } //getDate public int getNum () { return 42; } //getNum public String getStr () { return "Test"; } //getStr /** * @param str unused */ public void setStr (String str) { } //setStr } //*TestData /** * Setup the Test Harness */ @BeforeClass public static void setup () { LogBuilder.setLogFactory(new SysOutLogFactory()); } //setup /** * Perform a jUnit Test on the BeanUtils getDescriptor capability */ @Test public void testDescriptor () throws IntrospectionException { PropertyDescriptor desc = BeanUtils.getDescriptor(TestData.class,"date"); assertNotNull("BeanUtils.getDescriptor(TestData.class,\"date\") returned null",desc); assertNotNull("PropertyDescriptor.getReadMethod() returned null",desc.getReadMethod()); } //testDescriptor /** * Perform a jUnit Test on the BeanUtils getAccessor capability */ @Test public void testAccessor () throws IntrospectionException { assertNotNull("BeanUtils.getAccessor(TestData.class,\"date\") returned null",BeanUtils.getAccessor(TestData.class,"date")); } //testAccessor /** * Perform a jUnit Test on the BeanUtils getAccessors capability */ @Test public void testAccessors () throws IntrospectionException { List<Method> accessors = BeanUtils.getAccessors(TestData.class); assertEquals("BeanUtils.getAccessors(TestData.class) return the wrong number of accessors",6,accessors.size()); } //testAccessors /** * Perform a jUnit Test on the BeanUtils getMutator capability */ @Test public void testMutator () throws IntrospectionException { assertNotNull("BeanUtils.getMutator(TestData.class,\"str\") returned null",BeanUtils.getMutator(TestData.class,"str")); } //testMutator /** * Perform a jUnit Test on the BeanUtils getPropertyType capability */ @Test public void testPropertyType () throws IntrospectionException { Class<?> cls = BeanUtils.getPropertyType(TestData.class,"date"); assertNotNull("BeanUtils.getPropertyType(TestData.class,\"date\") returned null",cls); assertEquals("BeanUtils.getPropertyType(TestData.class,\"date\") doesn't equal java.util.Date",Date.class,cls); } //testPropertyType /** * Perform a jUnit Test on the BeanUtils getValue capability */ @Test public void testValue () throws IntrospectionException { TestData data = new TestData(); assertEquals("BeanUtils.getValue(data,\"text\") != \"outer\"","outer",BeanUtils.getValue(data,"text")); assertEquals("BeanUtils.getValue(data,\"num\") != 42",42,BeanUtils.getValue(data,"num")); assertEquals("BeanUtils.getValue(data,\"str\") != \"Test\"","Test",BeanUtils.getValue(data,"str")); assertEquals("BeanUtils.getValue(data,\"inner.text\") != \"inner\"","inner",BeanUtils.getValue(data,"inner.text")); } //testValue /** * Perform a jUnit Test on the BeanUtils getString capability */ @Test public void testString () { TestData data = new TestData(); assertEquals("BeanUtils.getString(data,\"text\") != \"outer\"","outer",BeanUtils.getString(data,"text")); assertEquals("BeanUtils.getString(data,\"num\") != 42","42",BeanUtils.getString(data,"num")); assertEquals("BeanUtils.getString(data,\"str\") != \"Test\"","Test",BeanUtils.getString(data,"str")); assertEquals("BeanUtils.getString(data,\"inner.text\") != \"inner\"","inner",BeanUtils.getString(data,"inner.text")); } //testString /** * jUnit 3.x Test Suite * * @return Adapted Test Suite */ public static junit.framework.Test suite () { return new junit.framework.JUnit4TestAdapter(BeanUtilsTests.class); } //suite } //*BeanUtilsTests
Java