code
stringlengths
3
1.18M
language
stringclasses
1 value
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.jws.WebService; import org.rapla.components.util.Cancelable; import org.rapla.components.util.Command; import org.rapla.components.util.CommandScheduler; import org.rapla.framework.Configuration; import org.rapla.framework.ConfigurationException; import org.rapla.framework.Container; import org.rapla.framework.Disposable; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.RaplaDefaultContext; import org.rapla.framework.RaplaException; import org.rapla.framework.StartupEnvironment; import org.rapla.framework.TypedComponentRole; import org.rapla.framework.logger.Logger; import org.rapla.storage.dbrm.RemoteServiceCaller; /** Base class for the ComponentContainers in Rapla. * Containers are the RaplaMainContainer, the Client- and the Server-Service */ public class ContainerImpl implements Container { protected Container m_parent; protected RaplaDefaultContext m_context; protected Configuration m_config; protected List<ComponentHandler> m_componentHandler = Collections.synchronizedList(new ArrayList<ComponentHandler>()); protected Map<String,RoleEntry> m_roleMap = Collections.synchronizedMap(new LinkedHashMap<String,RoleEntry>()); Logger logger; public ContainerImpl(RaplaContext parentContext, Configuration config, Logger logger) throws RaplaException { m_config = config; // if ( parentContext.has(Logger.class ) ) // { // logger = parentContext.lookup( Logger.class); // } // else // { // logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO); // } this.logger = logger; if ( parentContext.has(Container.class )) { m_parent = parentContext.lookup( Container.class); } m_context = new RaplaDefaultContext(parentContext) { @Override protected Object lookup(String role) throws RaplaContextException { ComponentHandler handler = getHandler( role ); if ( handler != null ) { return handler.get(); } return null; } @Override protected boolean has(String role) { if (getHandler( role ) != null) return true; return false; } }; addContainerProvidedComponentInstance(Logger.class,logger); init( ); } @SuppressWarnings("unchecked") public <T> T lookup(Class<T> componentRole, String hint) throws RaplaContextException { String key = componentRole.getName()+ "/" + hint; ComponentHandler handler = getHandler( key ); if ( handler != null ) { return (T) handler.get(); } if ( m_parent != null) { return m_parent.lookup(componentRole, hint); } throw new RaplaContextException( key ); } public Logger getLogger() { return logger; } protected void init() throws RaplaException { configure( m_config ); addContainerProvidedComponentInstance( Container.class, this ); addContainerProvidedComponentInstance( Logger.class, getLogger()); } public StartupEnvironment getStartupEnvironment() { try { return getContext().lookup( StartupEnvironment.class); } catch ( RaplaContextException e ) { throw new IllegalStateException(" Container not initialized with a startup environment"); } } protected void configure( final Configuration config ) throws RaplaException { Map<String,ComponentInfo> m_componentInfos = getComponentInfos(); final Configuration[] elements = config.getChildren(); for ( int i = 0; i < elements.length; i++ ) { final Configuration element = elements[i]; final String id = element.getAttribute( "id", null ); if ( null == id ) { // Only components with an id attribute are treated as components. getLogger().debug( "Ignoring configuration for component, " + element.getName() + ", because the id attribute is missing." ); } else { final String className; final String[] roles; if ( "component".equals( element.getName() ) ) { try { className = element.getAttribute( "class" ); Configuration[] roleConfigs = element.getChildren("roles"); roles = new String[ roleConfigs.length ]; for ( int j=0;j< roles.length;j++) { roles[j] = roleConfigs[j].getValue(); } } catch ( ConfigurationException ex) { throw new RaplaException( ex); } } else { String configName = element.getName(); final ComponentInfo roleEntry = m_componentInfos.get( configName ); if ( null == roleEntry ) { final String message = "No class found matching configuration name " + "[name: " + element.getName() + "]"; getLogger().error( message ); continue; } roles = roleEntry.getRoles(); className = roleEntry.getClassname(); } if ( getLogger().isDebugEnabled() ) { getLogger().debug( "Configuration processed for: " + className ); } Logger logger = this.logger.getChildLogger( id ); ComponentHandler handler =new ComponentHandler( element, className, logger); for ( int j=0;j< roles.length;j++) { String roleName = (roles[j]); addHandler( roleName, id, handler ); } } } } protected Map<String,ComponentInfo> getComponentInfos() { return Collections.emptyMap(); } public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass) { addContainerProvidedComponent(roleInterface, implementingClass, null, (Configuration)null); } public <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, Configuration config) { addContainerProvidedComponent(roleInterface, implementingClass, null,config); } public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass) { addContainerProvidedComponent(roleInterface, implementingClass, (Configuration) null); } public <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, Configuration config) { addContainerProvidedComponent( roleInterface, implementingClass, null, config); } public <T, I extends T> void addContainerProvidedComponentInstance(TypedComponentRole<T> roleInterface, I implementingInstance) { addContainerProvidedComponentInstance(roleInterface.getId(), implementingInstance, null); } public <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance) { addContainerProvidedComponentInstance(roleInterface, implementingInstance, implementingInstance.toString()); } public <T> Collection< T> lookupServicesFor(TypedComponentRole<T> role) throws RaplaContextException { Collection<T> list = new LinkedHashSet<T>(); for (T service: getAllServicesForThisContainer(role)) { list.add(service); } if ( m_parent != null) { for (T service:m_parent.lookupServicesFor(role)) { list.add( service); } } return list; } public <T> Collection<T> lookupServicesFor(Class<T> role) throws RaplaContextException { Collection<T> list = new LinkedHashSet<T>(); for (T service:getAllServicesForThisContainer(role)) { list.add( service); } if ( m_parent != null) { for (T service:m_parent.lookupServicesFor(role)) { list.add( service); } } return list; } protected <T, I extends T> void addContainerProvidedComponentInstance(Class<T> roleInterface, I implementingInstance, String hint) { addContainerProvidedComponentInstance(roleInterface.getName(), implementingInstance, hint); } protected <T, I extends T> void addContainerProvidedComponent(Class<T> roleInterface, Class<I> implementingClass, String hint, Configuration config) { addContainerProvidedComponent( roleInterface.getName(), implementingClass.getName(), hint, config); } private <T, I extends T> void addContainerProvidedComponent(TypedComponentRole<T> roleInterface, Class<I> implementingClass, String hint, Configuration config) { addContainerProvidedComponent( roleInterface.getId(), implementingClass.getName(), hint, config); } synchronized private void addContainerProvidedComponent(String role,String classname, String hint,Configuration config) { addContainerProvidedComponent( new String[] {role}, classname, hint, config); } synchronized private void addContainerProvidedComponentInstance(String role,Object componentInstance,String hint) { addHandler( role, hint, new ComponentHandler(componentInstance)); } synchronized private void addContainerProvidedComponent(String[] roles,String classname,String hint, Configuration config) { ComponentHandler handler = new ComponentHandler( config, classname, getLogger() ); for ( int i=0;i<roles.length;i++) { addHandler( roles[i], hint, handler); } } protected <T> Collection<T> getAllServicesForThisContainer(TypedComponentRole<T> role) { RoleEntry entry = m_roleMap.get( role.getId() ); return getAllServicesForThisContainer( entry); } protected <T> Collection<T> getAllServicesForThisContainer(Class<T> role) { RoleEntry entry = m_roleMap.get( role.getName() ); return getAllServicesForThisContainer( entry); } private <T> Collection<T> getAllServicesForThisContainer(RoleEntry entry) { if ( entry == null) { return Collections.emptyList(); } List<T> result = new ArrayList<T>(); Set<String> hintSet = entry.getHintSet(); for (String hint: hintSet) { ComponentHandler handler = entry.getHandler(hint); try { Object service = handler.get(); // we can safely cast here because the method is only called from checked methods @SuppressWarnings("unchecked") T casted = (T)service; result.add(casted); } catch (Exception e) { Throwable ex = e; while( ex.getCause() != null) { ex = ex.getCause(); } getLogger().error("Could not initialize component " + handler + " due to " + ex.getMessage() + " removing from service list" , e); entry.remove(hint); } } return result; } /** * @param roleName * @param hint * @param handler */ private void addHandler(String roleName, String hint, ComponentHandler handler) { m_componentHandler.add( handler); RoleEntry entry = m_roleMap.get( roleName ); if ( entry == null) entry = new RoleEntry(roleName); entry.put( hint , handler); m_roleMap.put( roleName, entry); } ComponentHandler getHandler( String role) { int hintSeperator = role.indexOf('/'); String roleName = role; String hint = null; if ( hintSeperator > 0 ) { roleName = role.substring( 0, hintSeperator ); hint = role.substring( hintSeperator + 1 ); } return getHandler( roleName, hint ); } ComponentHandler getHandler( String role,Object hint) { RoleEntry entry = m_roleMap.get( role ); if ( entry == null) { return null; } ComponentHandler handler = entry.getHandler( hint ); if ( handler != null) { return handler; } if ( hint == null || hint.equals("*" ) ) return entry.getFirstHandler(); // Try the first accessible handler return null; } protected final class DefaultScheduler implements CommandScheduler { private final ScheduledExecutorService executor; private DefaultScheduler() { final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5,new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); String name = thread.getName(); if ( name == null) { name = ""; } thread.setName("raplascheduler-" + name.toLowerCase().replaceAll("thread", "").replaceAll("-|\\[|\\]", "")); thread.setDaemon(true); return thread; } }); this.executor = executor; } public Cancelable schedule(Command command, long delay) { Runnable task = createTask(command); return schedule(task, delay); } public Cancelable schedule(Runnable task, long delay) { if (executor.isShutdown()) { RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString()); getLogger().error(ex.getMessage(), ex); return createCancable( null); } TimeUnit unit = TimeUnit.MILLISECONDS; ScheduledFuture<?> schedule = executor.schedule(task, delay, unit); return createCancable( schedule); } private Cancelable createCancable(final ScheduledFuture<?> schedule) { return new Cancelable() { public void cancel() { if ( schedule != null) { schedule.cancel(true); } } }; } public Cancelable schedule(Runnable task, long delay, long period) { if (executor.isShutdown()) { RaplaException ex = new RaplaException("Can't schedule command because executer is already shutdown " + task.toString()); getLogger().error(ex.getMessage(), ex); return createCancable( null); } TimeUnit unit = TimeUnit.MILLISECONDS; ScheduledFuture<?> schedule = executor.scheduleAtFixedRate(task, delay, period, unit); return createCancable( schedule); } public Cancelable schedule(Command command, long delay, long period) { Runnable task = createTask(command); return schedule(task, delay, period); } public void cancel() { try{ getLogger().info("Stopping scheduler thread."); List<Runnable> shutdownNow = executor.shutdownNow(); for ( Runnable task: shutdownNow) { long delay = -1; if ( task instanceof ScheduledFuture) { ScheduledFuture scheduledFuture = (ScheduledFuture) task; delay = scheduledFuture.getDelay( TimeUnit.SECONDS); } if ( delay <=0) { getLogger().warn("Interrupted active task " + task ); } } getLogger().info("Stopped scheduler thread."); } catch ( Throwable ex) { getLogger().warn(ex.getMessage()); } // we give the update threads some time to execute try { Thread.sleep( 50); } catch (InterruptedException e) { } } } class RoleEntry { Map<String,ComponentHandler> componentMap = Collections.synchronizedMap(new LinkedHashMap<String,ComponentHandler>()); ComponentHandler firstEntry; int generatedHintCounter = 0; String roleName; RoleEntry(String roleName) { this.roleName = roleName; } String generateHint() { return roleName + "_" +generatedHintCounter++; } void put( String hint, ComponentHandler handler ){ if ( hint == null) { hint = generateHint(); } synchronized (this) { componentMap.put( hint, handler); } if (firstEntry == null) firstEntry = handler; } void remove(String hint) { componentMap.remove( hint); } Set<String> getHintSet() { // we return a clone to avoid concurrent modification exception synchronized (this) { LinkedHashSet<String> result = new LinkedHashSet<String>(componentMap.keySet()); return result; } } ComponentHandler getHandler(Object hint) { return componentMap.get( hint ); } ComponentHandler getFirstHandler() { return firstEntry; } public String toString() { return componentMap.toString(); } } public RaplaContext getContext() { return m_context; } boolean disposing; public void dispose() { // prevent reentrence in dispose synchronized ( this) { if ( disposing) { getLogger().warn("Disposing is called twice",new RaplaException("")); return; } disposing = true; } try { removeAllComponents(); } finally { disposing = false; } } protected void removeAllComponents() { Iterator<ComponentHandler> it = new ArrayList<ComponentHandler>(m_componentHandler).iterator(); while ( it.hasNext() ) { it.next().dispose(); } m_componentHandler.clear(); m_roleMap.clear(); } @SuppressWarnings({ "unchecked", "rawtypes" }) Constructor findDependantConstructor(Class componentClass) { Constructor[] constructors= componentClass.getConstructors(); TreeMap<Integer,Constructor> constructorMap = new TreeMap<Integer, Constructor>(); for (Constructor constructor:constructors) { Class[] types = constructor.getParameterTypes(); boolean compatibleParameters = true; for (int j=0; j< types.length; j++ ) { Class type = types[j]; if (!( type.isAssignableFrom( RaplaContext.class) || type.isAssignableFrom( Configuration.class) || type.isAssignableFrom(Logger.class) || type.isAnnotationPresent(WebService.class) || getContext().has( type))) { compatibleParameters = false; } } if ( compatibleParameters ) { //return constructor; constructorMap.put( types.length, constructor); } } // return the constructor with the most paramters if (!constructorMap.isEmpty()) { return constructorMap.lastEntry().getValue(); } return null; } /** Instantiates a class and passes the config, logger and the parent context to the object if needed by the constructor. * This concept is taken form pico container.*/ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Object instanciate( String componentClassName, Configuration config, Logger logger ) throws RaplaContextException { RaplaContext context = m_context; Class componentClass; try { componentClass = Class.forName( componentClassName ); } catch (ClassNotFoundException e1) { throw new RaplaContextException("Component class " + componentClassName + " not found." , e1); } Constructor c = findDependantConstructor( componentClass ); Object[] params = null; if ( c != null) { Class[] types = c.getParameterTypes(); params = new Object[ types.length ]; for (int i=0; i< types.length; i++ ) { Class type = types[i]; Object p; if ( type.isAssignableFrom( RaplaContext.class)) { p = context; } else if ( type.isAssignableFrom( Configuration.class)) { p = config; } else if ( type.isAssignableFrom( Logger.class)) { p = logger; } else if ( type.isAnnotationPresent(WebService.class)) { RemoteServiceCaller lookup = context.lookup(RemoteServiceCaller.class); p = lookup.getRemoteMethod( type); } else { Class guessedRole = type; if ( context.has( guessedRole )) { p = context.lookup( guessedRole ); } else { throw new RaplaContextException(componentClass, "Can't statisfy constructor dependency " + type.getName() ); } } params[i] = p; } } try { final Object component; if ( c!= null) { component = c.newInstance( params); } else { component = componentClass.newInstance(); } return component; } catch (Exception e) { throw new RaplaContextException(componentClassName + " could not be initialized due to " + e.getMessage(), e); } } protected class ComponentHandler implements Disposable { protected Configuration config; protected Logger logger; protected Object component; protected String componentClassName; boolean dispose = true; protected ComponentHandler( Object component) { this.component = component; this.dispose = false; } protected ComponentHandler( Configuration config, String componentClass, Logger logger) { this.config = config; this.componentClassName = componentClass; this.logger = logger; } Semaphore instanciating = new Semaphore(1); Object get() throws RaplaContextException { if ( component != null) { return component; } boolean acquired; try { acquired = instanciating.tryAcquire(60,TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RaplaContextException("Timeout while waiting for instanciation of " + componentClassName ); } if ( !acquired) { throw new RaplaContextException("Instanciating component " + componentClassName + " twice. Possible a cyclic dependency.",new RaplaException("")); } else { try { // test again, maybe instanciated by another thread if ( component != null) { return component; } component = instanciate( componentClassName, config, logger ); return component; } finally { instanciating.release(); } } } boolean disposing; public void dispose() { // prevent reentrence in dispose synchronized ( this) { if ( disposing) { getLogger().warn("Disposing is called twice",new RaplaException("")); return; } disposing = true; } try { if (component instanceof Disposable) { if ( component == ContainerImpl.this) { return; } ((Disposable) component).dispose(); } } catch ( Exception ex) { getLogger().error("Error disposing component ", ex ); } finally { disposing = false; } } public String toString() { if ( component != null) { return component.toString(); } if ( componentClassName != null) { return componentClassName.toString(); } return super.toString(); } } protected Runnable createTask(final Command command) { Runnable timerTask = new Runnable() { public void run() { try { command.execute(); } catch (Exception e) { getLogger().error( e.getMessage(), e); } } public String toString() { return command.toString(); } }; return timerTask; } protected CommandScheduler createCommandQueue() { CommandScheduler commandQueue = new DefaultScheduler(); return commandQueue; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; public class ComponentInfo { String className; String[] roles; public ComponentInfo(String className) { this( className, className ); } public ComponentInfo(String className, String roleName) { this( className, new String[] {roleName} ); } public ComponentInfo(String className, String[] roleNames) { this.className = className; this.roles = roleNames; } public String[] getRoles() { return roles; } public String getClassname() { return className; } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import org.rapla.components.util.Assert; import org.rapla.components.util.JNLPUtil; import org.rapla.components.util.xml.RaplaContentHandler; import org.rapla.components.util.xml.RaplaErrorHandler; import org.rapla.components.util.xml.RaplaNonValidatedInput; import org.rapla.components.util.xml.RaplaSAXHandler; import org.rapla.components.util.xml.XMLReaderAdapter; import org.rapla.framework.Configuration; import org.rapla.framework.RaplaException; import org.rapla.framework.logger.Logger; import org.rapla.framework.logger.NullLogger; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** Tools for configuring the rapla-system. */ public abstract class ConfigTools { /** parse startup parameters. The parse format: <pre> [-?|-c PATH_TO_CONFIG_FILE] [ACTION] </pre> Possible map entries: <ul> <li>config: the config-file</li> <li>action: the start action</li> </ul> @return a map with the parameter-entries or null if format is invalid or -? is used */ public static Map<String,String> parseParams( String[] args ) { boolean bInvalid = false; Map<String,String> map = new HashMap<String,String>(); String config = null; String action = null; // Investigate the passed arguments for ( int i = 0; i < args.length; i++ ) { if ( args[i].toLowerCase().equals( "-c" ) ) { if ( i + 1 == args.length ) { bInvalid = true; break; } config = args[++i]; continue; } if ( args[i].toLowerCase().equals( "-?" ) ) { bInvalid = true; break; } if ( args[i].toLowerCase().substring( 0, 1 ).equals( "-" ) ) { bInvalid = true; break; } action = args[i].toLowerCase(); } if ( bInvalid ) { return null; } if ( config != null ) map.put( "config", config ); if ( action != null ) map.put( "action", action ); return map; } /** Creates a configuration from a URL.*/ public static Configuration createConfig( String configURL ) throws RaplaException { try { URLConnection conn = new URL( configURL).openConnection(); InputStreamReader stream = new InputStreamReader(conn.getInputStream()); StringBuilder builder = new StringBuilder(); //System.out.println( "File Content:"); int s= -1; do { s = stream.read(); // System.out.print( (char)s ); if ( s != -1) { builder.append( (char) s ); } } while ( s != -1); stream.close(); Assert.notNull( stream ); Logger logger = new NullLogger(); RaplaNonValidatedInput parser = new RaplaReaderImpl(); final SAXConfigurationHandler handler = new SAXConfigurationHandler(); String xml = builder.toString(); parser.read(xml, handler, logger); Configuration config = handler.getConfiguration(); Assert.notNull( config ); return config; } catch ( EOFException ex ) { throw new RaplaException( "Can't load configuration-file at " + configURL ); } catch ( Exception ex ) { throw new RaplaException( ex ); } } static public class RaplaReaderImpl implements RaplaNonValidatedInput { public void read(String xml, RaplaSAXHandler handler, Logger logger) throws RaplaException { InputSource source = new InputSource( new StringReader(xml)); try { XMLReader reader = XMLReaderAdapter.createXMLReader(false); reader.setContentHandler( new RaplaContentHandler(handler)); reader.parse(source ); reader.setErrorHandler( new RaplaErrorHandler( logger)); } catch (SAXException ex) { Throwable cause = ex.getException(); if (cause instanceof SAXParseException) { ex = (SAXParseException) cause; cause = ex.getException(); } if (ex instanceof SAXParseException) { throw new RaplaException("Line: " + ((SAXParseException)ex).getLineNumber() + " Column: "+ ((SAXParseException)ex).getColumnNumber() + " " + ((cause != null) ? cause.getMessage() : ex.getMessage()) ,(cause != null) ? cause : ex ); } if (cause == null) { throw new RaplaException( ex); } if (cause instanceof RaplaException) throw (RaplaException) cause; else throw new RaplaException( cause); } catch (IOException ex) { throw new RaplaException( ex.getMessage(), ex); } } } /** Creates an configuration URL from a configuration path. If path is null the URL of the defaultPropertiesFile will be returned. */ public static URL configFileToURL( String path, String defaultPropertiesFile ) throws RaplaException { URL configURL = null; try { if ( path != null ) { File file = new File( path ); if ( file.exists() ) { configURL = ( file.getCanonicalFile() ).toURI().toURL(); } } if ( configURL == null ) { configURL = ConfigTools.class.getClassLoader().getResource( defaultPropertiesFile ); if ( configURL == null ) { File file = new File( defaultPropertiesFile ); if ( !file.exists() ) { file = new File( "war/WEB-INF/" + defaultPropertiesFile ); } if ( !file.exists() ) { file = new File( "war/webclient/" + defaultPropertiesFile ); } if ( file.exists() ) { configURL = file.getCanonicalFile().toURI().toURL(); } } } } catch ( MalformedURLException ex ) { throw new RaplaException( "malformed config path" + path ); } catch ( IOException ex ) { throw new RaplaException( "Can't resolve config path" + path ); } if ( configURL == null ) { throw new RaplaException( defaultPropertiesFile + " not found on classpath and in working folder " + " Path config file with -c argument. " + " For more information start rapla -? or read the api-docs." ); } return configURL; } /** Creates an configuration URL from a configuration filename and the webstart codebae. If filename is null the URL of the defaultPropertiesFile will be returned. */ public static URL webstartConfigToURL( String defaultPropertiesFilename ) throws RaplaException { try { URL base = JNLPUtil.getCodeBase(); URL configURL = new URL( base, defaultPropertiesFilename ); return configURL; } catch ( Exception ex ) { throw new RaplaException( "Can't get configuration file in webstart mode." ); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; import org.rapla.framework.Provider; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; import org.slf4j.spi.LocationAwareLogger; @SuppressWarnings("restriction") public class Slf4jAdapter implements Provider<org.rapla.framework.logger.Logger> { static ILoggerFactory logManager = LoggerFactory.getILoggerFactory(); static public org.rapla.framework.logger.Logger getLoggerForCategory(String categoryName) { LocationAwareLogger loggerForCategory = (LocationAwareLogger)logManager.getLogger(categoryName); return new Wrapper(loggerForCategory, categoryName); } public org.rapla.framework.logger.Logger get() { return getLoggerForCategory( "rapla"); } static class Wrapper implements org.rapla.framework.logger.Logger{ LocationAwareLogger logger; String id; public Wrapper( LocationAwareLogger loggerForCategory, String id) { this.logger = loggerForCategory; this.id = id; } public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public void debug(String message) { log(LocationAwareLogger.DEBUG_INT, message); } public void info(String message) { log( LocationAwareLogger.INFO_INT, message); } private void log(int infoInt, String message) { log( infoInt, message, null); } private void log( int level, String message,Throwable t) { Object[] argArray = null; String fqcn = Wrapper.class.getName(); logger.log(null, fqcn, level,message,argArray, t); } public void warn(String message) { log( LocationAwareLogger.WARN_INT, message); } public void warn(String message, Throwable cause) { log( LocationAwareLogger.WARN_INT, message, cause); } public void error(String message) { log( LocationAwareLogger.ERROR_INT, message); } public void error(String message, Throwable cause) { log( LocationAwareLogger.ERROR_INT, message, cause); } public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName) { String childId = id + "." + childLoggerName; return getLoggerForCategory( childId); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2013 Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; import java.util.logging.Level; import java.util.logging.Logger; import org.rapla.framework.Provider; public class RaplaJDKLoggingAdapter implements Provider<org.rapla.framework.logger.Logger> { public org.rapla.framework.logger.Logger get() { final Logger logger = getLogger( "rapla"); return new Wrapper(logger, "rapla"); } static private java.util.logging.Logger getLogger(String categoryName) { Logger logger = Logger.getLogger(categoryName); return logger; } static String WRAPPER_NAME = RaplaJDKLoggingAdapter.class.getName(); class Wrapper implements org.rapla.framework.logger.Logger{ java.util.logging.Logger logger; String id; public Wrapper( java.util.logging.Logger logger, String id) { this.logger = logger; this.id = id; } public boolean isDebugEnabled() { return logger.isLoggable(Level.CONFIG); } public void debug(String message) { log(Level.CONFIG, message); } public void info(String message) { log(Level.INFO, message); } public void warn(String message) { log(Level.WARNING,message); } public void warn(String message, Throwable cause) { log(Level.WARNING,message, cause); } public void error(String message) { log(Level.SEVERE, message); } public void error(String message, Throwable cause) { log(Level.SEVERE, message, cause); } private void log(Level level,String message) { log(level, message, null); } private void log(Level level,String message, Throwable cause) { StackTraceElement[] stackTrace = new Throwable().getStackTrace(); String sourceClass = null; String sourceMethod =null; for (StackTraceElement element:stackTrace) { String classname = element.getClassName(); if ( !classname.startsWith(WRAPPER_NAME)) { sourceClass=classname; sourceMethod =element.getMethodName(); break; } } logger.logp(level,sourceClass, sourceMethod,message, cause); } public org.rapla.framework.logger.Logger getChildLogger(String childLoggerName) { String childId = id+ "." + childLoggerName; Logger childLogger = getLogger( childId); return new Wrapper( childLogger, childId); } } }
Java
package org.rapla.framework.internal; import org.rapla.framework.ConfigurationException; import org.rapla.framework.RaplaContext; import org.rapla.framework.RaplaContextException; import org.rapla.framework.TypedComponentRole; public class ContextTools { /** resolves a context value in the passed string. If the string begins with <code>${</code> the method will lookup the String-Object in the context and returns it. If it doesn't, the method returns the unmodified string. Example: <code>resolveContext("${download-server}")</code> returns the same as context.get("download-server").toString(); @throws ConfigurationException when no contex-object was found for the given variable. */ public static String resolveContext( String s, RaplaContext context ) throws RaplaContextException { return ContextTools.resolveContextObject(s, context).toString(); } public static Object resolveContextObject( String s, RaplaContext context ) throws RaplaContextException { StringBuffer value = new StringBuffer(); s = s.trim(); int startToken = s.indexOf( "${" ); if ( startToken < 0 ) return s; int endToken = s.indexOf( "}", startToken ); String token = s.substring( startToken + 2, endToken ); String preToken = s.substring( 0, startToken ); String unresolvedRest = s.substring( endToken + 1 ); TypedComponentRole<Object> untypedIdentifier = new TypedComponentRole<Object>(token); Object lookup = context.lookup( untypedIdentifier ); if ( preToken.length() == 0 && unresolvedRest.length() == 0 ) { return lookup; } String contextObject = lookup.toString(); value.append( preToken ); String stringRep = contextObject.toString(); value.append( stringRep ); Object resolvedRest = resolveContext(unresolvedRest, context ); value.append( resolvedRest.toString()); return value.toString(); } }
Java
package org.rapla.framework.internal; import java.util.Date; import java.util.TimeZone; import org.rapla.components.util.DateTools; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.framework.RaplaLocale; public abstract class AbstractRaplaLocale implements RaplaLocale { public String formatTimestamp( Date date ) { Date raplaDate = fromUTCTimestamp(date); StringBuffer buf = new StringBuffer(); { String formatDate= formatDate( raplaDate ); buf.append( formatDate); } buf.append(" "); { String formatTime = formatTime( raplaDate ); buf.append( formatTime); } return buf.toString(); } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, boolean) */ public Date toDate( Date date, boolean fillDate ) { Date result = DateTools.cutDate(DateTools.addDay(date)); return result; // // Calendar cal1 = createCalendar(); // cal1.setTime( date ); // if ( fillDate ) { // cal1.add( Calendar.DATE, 1); // } // cal1.set( Calendar.HOUR_OF_DAY, 0 ); // cal1.set( Calendar.MINUTE, 0 ); // cal1.set( Calendar.SECOND, 0 ); // cal1.set( Calendar.MILLISECOND, 0 ); // return cal1.getTime(); } @Deprecated public Date toDate( int year,int month, int day ) { Date result = toRaplaDate(year, month+1, day); return result; } public Date toRaplaDate( int year,int month, int day ) { Date result = new Date(DateTools.toDate(year, month, day)); return result; } public Date toTime( int hour,int minute, int second ) { Date result = new Date(DateTools.toTime(hour, minute, second)); return result; } /* (non-Javadoc) * @see org.rapla.common.IRaplaLocale#toDate(java.util.Date, java.util.Date) */ public Date toDate( Date date, Date time ) { long millisTime = time.getTime() - DateTools.cutDate( time.getTime()); Date result = new Date( DateTools.cutDate(date.getTime()) + millisTime); return result; // Calendar cal1 = createCalendar(); // Calendar cal2 = createCalendar(); // cal1.setTime( date ); // cal2.setTime( time ); // cal1.set( Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY) ); // cal1.set( Calendar.MINUTE, cal2.get(Calendar.MINUTE) ); // cal1.set( Calendar.SECOND, cal2.get(Calendar.SECOND) ); // cal1.set( Calendar.MILLISECOND, cal2.get(Calendar.MILLISECOND) ); // return cal1.getTime(); } public long fromRaplaTime(TimeZone timeZone,long raplaTime) { long offset = getOffset(timeZone, raplaTime); return raplaTime - offset; } public long toRaplaTime(TimeZone timeZone,long time) { long offset = getOffset(timeZone,time); return time + offset; } public Date fromRaplaTime(TimeZone timeZone,Date raplaTime) { return new Date( fromRaplaTime(timeZone, raplaTime.getTime())); } public Date toRaplaTime(TimeZone timeZone,Date time) { return new Date( toRaplaTime(timeZone, time.getTime())); } private long getOffset(TimeZone timeZone,long time) { long offsetSystem; long offsetRapla; { // Calendar cal =Calendar.getInstance( timeZone); // cal.setTimeInMillis( time ); // int zoneOffset = cal.get(Calendar.ZONE_OFFSET); // int dstOffset = cal.get(Calendar.DST_OFFSET); offsetSystem = timeZone.getOffset(time); } { TimeZone utc = getTimeZone(); // Calendar cal =Calendar.getInstance( utc); // cal.setTimeInMillis( time ); // offsetRapla = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); offsetRapla = utc.getOffset(time); } return offsetSystem - offsetRapla; } public SerializableDateTimeFormat getSerializableFormat() { return new SerializableDateTimeFormat(); } }
Java
package org.rapla.framework.internal; import java.util.Map; import java.util.Stack; import org.rapla.components.util.xml.RaplaSAXAttributes; import org.rapla.components.util.xml.RaplaSAXHandler; import org.rapla.components.util.xml.RaplaSAXParseException; import org.rapla.framework.Configuration; import org.rapla.framework.DefaultConfiguration; public class SAXConfigurationHandler implements RaplaSAXHandler { final Stack<DefaultConfiguration> configStack = new Stack<DefaultConfiguration>(); Configuration parsedConfiguration; public Configuration getConfiguration() { return parsedConfiguration; } public void startElement(String namespaceURI, String localName, RaplaSAXAttributes atts) throws RaplaSAXParseException { DefaultConfiguration defaultConfiguration = new DefaultConfiguration(localName); for ( Map.Entry<String,String> entry :atts.getMap().entrySet()) { String name = entry.getKey(); String value = entry.getValue(); defaultConfiguration.setAttribute( name, value); } configStack.push( defaultConfiguration); } public void endElement( String namespaceURI, String localName ) throws RaplaSAXParseException { DefaultConfiguration current =configStack.pop(); if ( configStack.isEmpty()) { parsedConfiguration = current; } else { DefaultConfiguration parent = configStack.peek(); parent.addChild( current); } } public void characters(char[] ch, int start, int length) { DefaultConfiguration peek = configStack.peek(); String value = peek.getValue(null); StringBuffer buf = new StringBuffer(); if ( value != null) { buf.append( value); } buf.append( ch, start, length); String string = buf.toString(); if ( string.trim().length() > 0) { peek.setValue( string); } } }
Java
/*--------------------------------------------------------------------------* | Copyright (C) 2014 Christopher Kohlhaas | | | | 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. A copy of the license has been included with | | these distribution in the COPYING file, if not go to www.fsf.org | | | | As a special exception, you are granted the permissions to link this | | program with every library, which license fulfills the Open Source | | Definition as published by the Open Source Initiative (OSI). | *--------------------------------------------------------------------------*/ package org.rapla.framework.internal; import java.util.HashMap; import org.rapla.client.ClientServiceContainer; import org.rapla.client.internal.RaplaClientServiceImpl; import org.rapla.components.xmlbundle.I18nBundle; import org.rapla.components.xmlbundle.impl.I18nBundleImpl; import org.rapla.facade.ClientFacade; import org.rapla.facade.internal.FacadeImpl; import org.rapla.storage.CachableStorageOperator; import org.rapla.storage.ImportExportManager; import org.rapla.storage.StorageOperator; import org.rapla.storage.dbrm.RemoteOperator; public class RaplaMetaConfigInfo extends HashMap<String,ComponentInfo> { private static final long serialVersionUID = 1L; public RaplaMetaConfigInfo() { put( "rapla-client", new ComponentInfo(RaplaClientServiceImpl.class.getName(),ClientServiceContainer.class.getName())); put( "resource-bundle",new ComponentInfo(I18nBundleImpl.class.getName(),I18nBundle.class.getName())); put( "facade",new ComponentInfo(FacadeImpl.class.getName(),ClientFacade.class.getName())); put( "remote-storage",new ComponentInfo(RemoteOperator.class.getName(),new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()})); // now the server configurations put( "rapla-server", new ComponentInfo("org.rapla.server.internal.ServerServiceImpl",new String[]{"org.rapla.server.ServerServiceContainer"})); put( "file-storage",new ComponentInfo("org.rapla.storage.dbfile.FileOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()})); put( "db-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()})); put( "sql-storage",new ComponentInfo("org.rapla.storage.dbsql.DBOperator",new String[] {StorageOperator.class.getName(), CachableStorageOperator.class.getName()})); put( "importexport", new ComponentInfo("org.rapla.storage.impl.server.ImportExportManagerImpl",ImportExportManager.class.getName())); } }
Java
package org.rapla.framework; public class RaplaContextException extends RaplaException { private static final long serialVersionUID = 1L; public RaplaContextException( final String key ) { super( "Unable to provide implementation for " + key + " " ); } public RaplaContextException( final Class<?> clazz, final String message ) { super("Unable to provide implementation for " + clazz.getName() + " " + message); } public RaplaContextException( final String message, final Throwable throwable ) { super( message, throwable ); } }
Java
package org.rapla.framework; public interface Provider<T> { T get(); }
Java
/* * Ta klasa ma za zadanie rozwiązać pojedynczą formułę, tj. wskazać podstawienie * lub powiedzieć, że nie ma takiego */ package sat; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.Vector; import sat.convenience.Population; import sat.convenience.Solution; import sat.exceptions.ParseException; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; public class Solver { private static Solver instance; private Vector<FormulaCNF> formulae; private Vector<Vector<Solution>> solutions; private Vector<Vector<Float>> times; private Vector<Solution> emptySolutions = new Vector<Solution>(); public boolean verbose = false; public static void main(String[] args) { { String filename = "formulae"; boolean proceed = false; boolean algoritm = false; int epochs = 1; Solver solver = Solver.getInstance(); for (int i = 0; i < args.length; ++i) { if (args[i].equals("-f") && args.length > i) { filename = args[++i]; } else if (args[i].equals("-v")) { solver.verbose = true; System.out.println("verbose mode enabled"); } } try { solver.decorate(null);solver.decorate("SAT problem");solver.decorate(null); solver.loadFile(filename); solver.mapVariables(); solver.printRaw(); InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(inputStreamReader); while (proceed != true) { try { System.out.println("Please specify the number of repetitions: "); epochs = Integer.parseInt(reader.readLine()); proceed = true; } catch (Exception e) { } } while(algoritm != true) { solver.decorate(null); System.out.println("press g - to run gsat algoritm"); System.out.println("press s - to run sasat algoritm"); System.out.println("press e - to run evosat algoritm"); solver.decorate(null); System.out.println("or q to quit"); solver.decorate(null); System.out.println("or a: auto"); solver.decorate(null); String str = reader.readLine(); if (str.charAt(0) == 'q') { System.out.println("bye!"); return; } if (str.charAt(0) == 'g') { int maxtries = 0, maxflips = 0; proceed = false; while (proceed != true) { try { System.out.println("maxtries: "); maxtries = Integer.parseInt(reader.readLine()); if (maxtries > 0) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("maxflips: "); maxflips = Integer.parseInt(reader.readLine()); if (maxflips > 0) proceed = true; } catch (Exception e) { } } for (int i = 0; i < epochs; ++i) { solver.gsatBatch(maxtries, maxflips, 1, false); } solver.printAll(); //algoritm = true; //jezeli nie ma tej linijki to program sie zapetla } else if (str.charAt(0) == 's') { int maxtries = 0; float decayRate = 0f, tMax = 0f, tMin = 0f; proceed = false; while (proceed != true) { try { System.out.println("enter the number of max tries (i): "); maxtries = Integer.parseInt(reader.readLine()); if (maxtries > 0) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("define the decay rate (f): "); decayRate = Float.parseFloat(reader.readLine()); if (decayRate > 0) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("define max temperature (f): "); tMax = Float.parseFloat(reader.readLine()); if (tMax >= 1) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("define min temperature (f): "); tMin = Float.parseFloat(reader.readLine()); if (tMin >= 0 && tMin <= tMax) proceed = true; } catch (Exception e) { } } for (int i = 0; i < epochs; ++i) { solver.sasatBatch(maxtries, decayRate, tMax, tMin, false);//(1, 2f, 30f, 0f, true); } solver.printAll(); //algoritm = true; //jezeli nie ma tej linijki to program sie zapetla } else if (str.charAt(0) == 'e') { int maxGenerations = 0, populationSize = 0; float localSearchThreshold = 0f; proceed = false; while (proceed != true) { try { System.out.println("maxGenerations: "); maxGenerations = Integer.parseInt(reader.readLine()); if (maxGenerations > 0) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("populationSize: "); populationSize = Integer.parseInt(reader.readLine()); if (populationSize > 0) proceed = true; } catch (Exception e) { } } proceed = false; while (proceed != true) { try { System.out.println("localSearchThreshold: "); localSearchThreshold = Float.parseFloat(reader.readLine()); if (localSearchThreshold > 0) proceed = true; } catch (Exception e) { } } for (int i = 0; i < epochs; ++i) { solver.evosatBatch(maxGenerations, populationSize, localSearchThreshold, 1.0f, false, 1);//140, 1, 0.4f } solver.printAll(); //algoritm = true; //jezeli nie ma tej linijki to program sie zapetla } else if (str.charAt(0) == 'a') { for (int i = 0; i < epochs; ++i) { //solver.gsatBatch(5, 50, 1, false); //solver.evosatBatch(140, 10, 0.4f, 1.0f, false, 1); solver.sasatBatch(1, 2f, 30f, 0f, false); long stop_time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); } solver.printAll(); //algoritm = true; //jezeli nie ma tej linijki to program sie zapetla } } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } } } public void startEpoch() { this.solutions.add(new Vector<Solution>()); this.times.add(new Vector<Float>()); } //returns an instane of solver public static Solver getInstance() { if (instance == null) { instance = new Solver(); } return instance; } private Solver() { formulae = new Vector<FormulaCNF>(); solutions = new Vector<Vector<Solution>>(); times = new Vector<Vector<Float>>(); } public void mapVariables() { for (int i = 0; i < formulae.size(); ++i) { emptySolutions.add(formulae.get(i).getUniqueLiterals()); } } public void loadFile(String path) throws IOException, ParseException { File f = new File(path); BufferedReader br = new BufferedReader(new FileReader(f)); String line; while ((line = br.readLine()) != null) { if (line.length() > 0) { formulae.add(new FormulaCNF(line)); } } br.close(); } public void decorate(String text){ System.out.println("= = = = = "+(text!=null?text:"= = = = = = = =")+" = = = = = "); } public void printRaw() { decorate("Loaded problems:"); for (int i = 0; i < formulae.size(); ++i) { System.out.println("P" + i + ": " + formulae.get(i)); } } public void printAll() { decorate("Obtained solutions:"); for (Vector<Solution> s : solutions) { for (Solution solution : s) { System.out.println(solution); } } decorate("Execution statistics:"); for (int i = 0; i < formulae.size(); ++i) { Vector<Float> mam = getMinAvgMaxCorrect(i); System.out.println("P" + i + "(" + mam.get(3) + "%): t min: " + mam.get(0) + "ms, t avg: " + mam.get(1) + "ms, t max: " + mam.get(2) + "ms"); } } /** * GSAT batch function, attempts to solve all the Solver.formulae * @param maxtries - self-explanatory * @param maxflips - self-explanatory * @param distance - neighborhood radius, currently supports only 1 * @param noRandomStart - if true, the algorithm will attempt to find a solution * by means of exploring the neighborhood of current solution (Solver.solutions[i]) */ private void gsatBatch(int maxtries, int maxflips, int distance, boolean noRandomStart) { startEpoch(); for (int i = 0; i < formulae.size(); ++i) { if (verbose) { System.out.println("Gsat epoch: " + times.size() + " Problem: " + i); } long time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); Solution solution = gsat(formulae.get(i), maxtries, maxflips, distance, noRandomStart ? formulae.get(i).getUniqueLiterals() : null); time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()) - time; float executionTime = (solution != null ? time / 10e6f : Float.NEGATIVE_INFINITY); if (verbose) { System.out.println("Final solution: " + solution); } times.get(times.size() - 1).add(executionTime); solutions.get(solutions.size() - 1).add(solution); try { Thread.sleep(20); } catch (Exception e) { } } } /** * Simulated annealing batch function, attempts to solve all the Solver.formulae * @param maxtries - self-explanatory * @param decayRate - self-explanatory * @param tMax - self-explanatory * @param tMin - self-explanatory * @param noRandom - if true, the algorithm will attempt to find a solution * by means of exploring the neighborhood of current solution (Solver.solutions[i]) */ private void sasatBatch(int maxtries, float decayRate, float tMax, float tMin, boolean noRandom) { startEpoch(); for (int i = 0; i < formulae.size(); ++i) { if (verbose) { System.out.println("Sasat epoch: " + times.size() + " Problem: " + i); } long time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); Solution solution = sasat(formulae.get(i), maxtries, decayRate, tMax, tMin, noRandom ? formulae.get(i).getUniqueLiterals() : null); time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()) - time; float executionTime = (solution != null ? time / 10e6f : Float.NEGATIVE_INFINITY); times.get(times.size() - 1).add(executionTime); solutions.get(solutions.size() - 1).add(solution); if (verbose) { System.out.println("Final solution: " + solution); } try { Thread.sleep(20); } catch (Exception e) { } } } /** * Evolutionary approach, attempts to solve all the Solver.formulae. * Used in conjunction with a local search method in attempt to speed up * the progress once a maximum seems close enough. * @param maxGenerations - number of cross-breeding iterations * @param populationSize - self-explanatory * @param mutationProbability * @param localSearchThreshold - minimum quality required to start a local search * @param offspringOnly - if true, the parent individuals are discarded at each breeding * @param intermediateToParentsRatio - ratio of intermediate offspring individuals number to parents number * iterations and only the offspring can form the successive generation * */ private void evosatBatch(int maxGenerations, int populationSize, float mutationProbability, float localSearchThreshold, boolean offspringOnly, int intermediateToParentsRatio) { startEpoch(); for (int i = 0; i < formulae.size(); ++i) { if (verbose) { System.out.println("Evosat epoch: " + times.size() + " Problem: " + i); } long time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()); Solution solution = evosat(formulae.get(i), maxGenerations, populationSize, localSearchThreshold, offspringOnly, mutationProbability, intermediateToParentsRatio); time = ManagementFactory.getThreadMXBean().getThreadCpuTime(Thread.currentThread().getId()) - time; float executionTime = (solution != null ? time / 10e6f : Float.NEGATIVE_INFINITY); times.get(times.size() - 1).add(executionTime); solutions.get(solutions.size() - 1).add(solution); if (verbose) { System.out.println("Final solution: " + solution); } try { Thread.sleep(20); } catch (Exception e) { } } } /** * Single formula solving function using GSAT algorithm. * @param problem - formula being solved * @param maxtries * @param maxflips * @param distance * @param initial - initial solution; if provided, the exploration of neighborhood will set off from here * @return A - solution if found, null otherwise */ private Solution gsat(FormulaCNF problem, int maxtries, int maxflips, int distance, Solution initial) { for (int attempt = 0; attempt < maxtries; ++attempt) { Solution candidate = (initial == null ? GsatToolkit.randomize(problem.getUniqueLiterals()) : (Solution) initial.clone()); for (int flip = 0; flip < maxflips; ++flip) { if (problem.evaluate(candidate)) { return candidate; } Vector<Solution> area = GsatToolkit.getNeighborhood(candidate, distance); Solution copy = (Solution) candidate.clone(); candidate = GsatToolkit.getBest(problem, candidate, area); if (verbose) { System.out.println("attempt: " + (attempt + 1) + " flips made: " + (flip + 1)); System.out.println((candidate != null ? candidate+ " fitness: "+problem.getTrueClausesPercentage(candidate)+ ", weighed: "+problem.getWeighedTrueClausesPercentage(candidate) : "dead end: " + copy) ); } if (candidate == null) { //dead-end met break; } } } return null; } /** * Single formula solving function using simulated annealing algorithm. * @param maxtries * @param decayRate * @param tMax * @param tMin * @param initial - initial solution; if provided, the exploration of neighborhood will set off from here * @return A solution if found, null otherwise. */ private Solution sasat(FormulaCNF problem, int maxtries, float decayRate, float tMax, float tMin, Solution initial) { for (int attempt = 0; attempt < maxtries; ++attempt) { Solution candidate = initial == null ? GsatToolkit.randomize(problem.getUniqueLiterals()) : (Solution) initial.clone(); float t = tMax; for (int iteration = 0; t > tMin; t = tMax * (float) Math.pow(Math.E, -1 * (iteration++) * decayRate)) { //System.out.println("attempt: "+attempt+". iteration: "+iteration); if (problem.evaluate(candidate)) { return candidate; } if (verbose) { System.out.println("attempt: " + (attempt + 1) + " temperature: " + (t)); System.out.println(candidate); } for (Iterator it = candidate.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); float potentialGain = SasatToolkit.calculatePotentialGain(problem, candidate, key); float probability = (float) Math.pow(1 + (float) Math.pow(Math.E, -1 * potentialGain / t), -1); if ((float) Math.random() <= probability || potentialGain>0) { candidate.put(key, candidate.get(key).booleanValue() ? Boolean.FALSE : Boolean.TRUE); break; } } } } return null; } /** * Single formula solving function using evolutionary approach. * Summary: * 1. Parents for cross-breading are selected in accordance to Monte Carlo rule. * 2. Products of breeding constitute the intermediate offspring * 3. Optionally, parents might be introduced into the intermediate offspring. * 4. Intermediate offspring is subject to mutation. Modified individuals are added, not replaced. * 5. Best individuals form the next generation (quite an exploitive approach) * @param problem - formula being solved * @param problem * @param maxGenerations * @param populationSize * @param localSearchThreshold - fitness level of individual(0-1), * that once crossed triggers a local search with sasat. * @param offspringOnly * @param mutationProbability - the probability of each offspring individual's bit to be flipped during the mutation phase * @param intermediateToParentsRatio - determines the size of intermediate offspring in relation to its parent generation * @return A solution if found, null otherwise. */ private Solution evosat(FormulaCNF problem, int maxGenerations, int populationSize, float localSearchThreshold, boolean offspringOnly, float mutationProbability, int intermediateToParentsRatio) { Population lambda; Population mi = null; lambda = EvosatToolkit.generatePopulation(populationSize, problem.getUniqueLiterals()); for (int generation = 0; generation < maxGenerations; ++generation) { mi = new Population(); //check for a winner Solution candidate = EvosatToolkit.evaluatePopulation(problem, lambda); if (candidate != null) { return candidate; } float minFitness = Float.POSITIVE_INFINITY; float maxFitness = Float.NEGATIVE_INFINITY; float avgFitness = 0; for (Solution s : lambda) { float fitness = problem.getWeighedTrueClausesPercentage(s); minFitness = Math.min(fitness, minFitness); maxFitness = Math.max(fitness, maxFitness); avgFitness += fitness; if (fitness > localSearchThreshold) { //here a local, sasat search is launched Solution localResult = sasat(problem, 1, 0.1f, 100f, 0.01f, s); if (localResult != null) { return localResult; } } } avgFitness /= lambda.size(); if (verbose) { System.out.println("generation: " + generation + ", min fitness: " + minFitness + ", avg fitness: " + avgFitness + ", max fitness: " + maxFitness); } mi = EvosatToolkit.generateOffspring(problem, lambda, intermediateToParentsRatio); if (!offspringOnly) { mi.addAll(lambda); } lambda = EvosatToolkit.applyMutations(mi, mutationProbability); lambda = EvosatToolkit.performSelection(problem, lambda, offspringOnly, populationSize); } return null; } private Vector<Float> getMinAvgMaxCorrect(int problem_index) { float sum = 0; float min = Float.POSITIVE_INFINITY; float max = Float.NEGATIVE_INFINITY; int failures = 0; for (Vector<Float> vt : times) { float time = vt.get(problem_index); if (time < 0f) { failures++; continue; } max = Math.max(max, time); min = Math.min(min, time); sum += time; } Vector<Float> result = new Vector<Float>(); result.add(min); result.add(sum / times.size()); result.add(max); result.add((times.size() - failures) * 100f / (float) times.size()); return result; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat.exceptions; public class ParseException extends Exception{ String description; public ParseException(){ super(); description = "unknown"; } public ParseException(String reason){ description = reason; } public String getError(){ return description; } }
Java
package sat; import sat.exceptions.ParseException; public class StringToolkit { /** * Prosta funkcja wycinająca białe znaki i zdejmująca zewnętrzne nawiasy. * @param meat tekst do przetworzenia * @return tekst przetworzony * @throws ParseException */ public static String strip(String meat) throws ParseException{ meat=meat.replace(" ", ""); meat=meat.replace("\t",""); while(meat.charAt(0)=='('){ if(meat.endsWith(")")){ meat=meat.substring(1, meat.length()-1); }else{ throw new ParseException("Parentheses nesting problem"); } } return meat; } }
Java
package sat; import java.util.HashMap; import java.util.Iterator; import sat.convenience.Solution; /** * Zestaw narzędzi wspierających przeprowadzenie symulowanego wyżarzania. * @author bawey */ public class SasatToolkit { /** * Funkcja oblicza potencjalne poprawy jakości rozwiązania wynikające * z zanegowania każdego pojedynczego przypisania (osobno) * @param solution - obecne podstawienia * @param formula - formuła logiczna poddana rozważaniom * @return HashMap<ZanegowanyLiterał,ZyskZZanegowania> */ public static HashMap<String, Float> calculatePotentialGains(FormulaCNF formula, Solution solution) { HashMap<String, Float> result = new HashMap<String, Float>(); for (Iterator it = solution.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); result.put(key, new Float(calculatePotentialGain(formula, solution, key))); } return result; } /** * Funkcja oblicza zysk na jakości rozwiązania uzyskany poprzez zanegowanie * wartości przypisanej danemu symbolowi * @param formula formuła logiczna * @param solution oryginalne rozwiązanie * @param key rozpatrywany symbol * @return */ public static float calculatePotentialGain(FormulaCNF formula, Solution solution, String key) { solution.put(key, solution.get(key).booleanValue() ? Boolean.FALSE : Boolean.TRUE); float flippedQuality = formula.getWeighedTrueClausesPercentage(solution); //flip back solution.put(key, solution.get(key).booleanValue() ? Boolean.FALSE : Boolean.TRUE); float initialQuality = formula.getWeighedTrueClausesPercentage(solution); return flippedQuality - initialQuality; } }
Java
package sat; import java.util.Vector; import sat.convenience.Solution; import sat.exceptions.ParseException; public class FormulaCNF { private Vector<ClauseCNF> clauses; /** * Konwertuje formułę w postaci CNF z reprezentacji tekstowej na wewnętrzną * @param formula reprezentacja tekstowa * @throws ParseException */ public FormulaCNF(String formula) throws ParseException{ clauses = new Vector<ClauseCNF>(); parseString(formula); } /** * Zwraca zbiór literałów (bez powtórzeń) występujących w formule (zaniedbując * ew. negacje) * @return zbiór literałów wraz z przypisanymi im początkowo wartościami (wszystkie fałsz) */ public Solution getUniqueLiterals(){ Solution resultSet = new Solution(); for(int i=0; i<clauses.size(); ++i){ for(int j=0; j<clauses.get(i).getStringLiterals().size(); ++j){ resultSet.put(clauses.get(i).getStringLiterals().get(j), Boolean.FALSE); } } return resultSet; } /** * Sprawdza, czy podane rozwiązanie spełnia formułę. * @param values * @return */ public boolean evaluate(Solution values){ for(int i=0; i<clauses.size(); ++i){ if(!clauses.get(i).evaluate(values)){ return false; } } return true; } /** * Prywatna metoda realizująca parsowanie tekstu celem konwersji formuły * do reprezentacji wewnętrznej. * @param formula tekstowa postać formuły * @throws ParseException */ private void parseString(String formula) throws ParseException{ String[] tokens = formula.split("&"); for(int i=0; i<tokens.length; ++i){ clauses.add(new ClauseCNF(tokens[i])); } } public String toString(){ StringBuffer sb = new StringBuffer(); for(int i=0; i<clauses.size(); ++i){ if(i!=0){ sb.append(" & "); } sb.append(clauses.get(i).toString()); } return sb.toString(); } /** * Zwraca odsetek klauzul spełnionych danym podstawieniem * @param solution podstawienie * @return odsetek wyrażony jako liczba 0-1 */ public float getTrueClausesPercentage(Solution solution){ int t = 0; for(int i=0; i<clauses.size(); ++i){ t+=(clauses.get(i).evaluate(solution)?1:0); } return t/(float)clauses.size(); } /** * Zwraca odsetek spełnionych klauzul wyrażony jako stosunek łącznej długości * spełnionych klauzul do łącznej długości wszystkich klauzul ("odsetek ważony") * @param solution podstawienie * @return odsetek wyrażony jako liczba 0-1 */ public float getWeighedTrueClausesPercentage(Solution solution){ int t=0, s=0; for(int i=0; i<clauses.size(); ++i){ int literals = clauses.get(i).getLiteralsCount(); s+=literals; t+=(clauses.get(i).evaluate(solution)?literals:0); } return t/(float)s; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat.convenience; import java.util.HashMap; /** * * @author bawey */ public class Solution extends HashMap<String, Boolean> { }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat.convenience; import java.util.HashMap; import java.util.Vector; /** * * @author bawey */ public class VariationMaps extends Vector<VariationMap> { }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat.convenience; import java.util.HashMap; /** * * @author bawey */ public class VariationMap extends HashMap<String,Float>{ }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat.convenience; import java.util.Vector; /** * * @author bawey */ public class Population extends Vector<Solution> { //just a damn convenience }
Java
package sat; /** * @author bawey */ public class LiteralCNF { private boolean negated; private String symbol; /** * Konstruktor klasy reprezentującej literał * @param s symbol literału * @param n true, jeśli literał ma być zanegowany */ public LiteralCNF(String s, boolean n){ negated=n; symbol=s; } public String getSymbol(){ return symbol; } public boolean isNegated(){ return negated; } public String toString(){ return (negated?"~":"")+symbol; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sat; import java.lang.String; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import sat.convenience.Solution; /** * Klasa zawrierająca metody pomocnicze dla algorytmu GSAT * @author bawey */ public class GsatToolkit { /** * Zwraca Vector rozwiązań stanowiących sąsiedztwo zadanego rozwiązania * @param solution rozwiązanie wyjściowe * @param distance dystans Hamminga * @return Vector podstawień */ public static Vector<Solution>getNeighborhood(Solution solution, int distance){ Vector<Solution> result = new Vector<Solution>(); if(distance!=1){ throw new UnsupportedOperationException(); }else{ result.ensureCapacity(solution.keySet().size()); int i=0; for(Iterator it=solution.keySet().iterator(); it.hasNext(); ++i){ result.add((Solution)solution.clone()); String key = (String)it.next(); result.get(i).put(key, (solution.get(key).booleanValue()?Boolean.FALSE:Boolean.TRUE)); // System.out.println(i); // System.out.println(result.get(i)); } } //System.out.println(result); return result; } /** * Inicjalizacja rozwiązania wartościami losowymi * @param solution * @return */ public static Solution randomize(Solution solution){ Solution result = new Solution(); for(Iterator i = solution.keySet().iterator(); i.hasNext(); ){ String key = (String) i.next(); result.put(key, (Math.random()>0.5?Boolean.TRUE:Boolean.FALSE)); } return result; } /** * Zwraca najlepsze rozwiązanie znalezione w otoczeniu rozwiązania candidate. * Jeśli zwraca null - algorytm utknął * @param formula formuła logiczna * @param candidate wyjściowe podstawienia * @param area zbiór rozwiązań przeszukiwanych celem znalezienia lepszego * @return najlepsze z rozpatrywanych rozwiązań */ public static Solution getBest(FormulaCNF formula, Solution candidate, Vector<Solution> area){ //System.out.println(candidate); //System.out.println(area); float initialScore = formula.getTrueClausesPercentage(candidate); //System.out.println("initial score: "+initialScore); float bestScore = Float.NEGATIVE_INFINITY; int leader = -1; for(int i=0; i<area.size(); ++i){ float score = formula.getTrueClausesPercentage(area.get(i))-initialScore; if(score>=bestScore){ bestScore=score; leader=i; } } //System.out.println("best score: "+bestScore); return bestScore>=0f?area.get(leader):null; } }
Java
package sat; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import sat.convenience.Population; import sat.convenience.Solution; import sat.convenience.VariationMap; import sat.convenience.VariationMaps; /** * Klasa zawiera zbiór funkcji wykorzystywanych w implementacji algorytmu evolucyjnego * @author bawey */ public class EvosatToolkit { /** * Funkcja generująca populację rozwiązań * @param size porządana liczność populacji * @param solution rozwiązanie początkowe. Wartości przypisań są ignorowane. * @return uzyskana populacja */ public static Population generatePopulation(int size, Solution solution) { Population population = new Population(); population.ensureCapacity(size); for (int i = 0; i < size; ++i) { population.add(GsatToolkit.randomize(solution)); } return population; } /** * Funkcja przeszukuje populację w nadziei znalezienia podstawienia spełniającego * formułe. * @param formula formuła logiczna * @param population populacja * @return szukane podstawienie lub null */ public static Solution evaluatePopulation(FormulaCNF formula, Population population) { for (int i = 0; i < population.size(); ++i) { if (formula.evaluate(population.get(i))) { return population.get(i); } } return null; } /** * Funkcja generuje populację pośrednią * @param formula formuła logiczna, względem której weryfikowane jest przystosowanie osobników * @param srcPopulation populacja źródłowa * @param intermediateToParentsRatio stosunek liczności populacji macierzystej * do liczności wygenerowanej populacji * @return wygenerowana populacja */ public static Population generateOffspring(FormulaCNF formula, Population srcPopulation, int intermediateToParentsRatio) { intermediateToParentsRatio=Math.max(intermediateToParentsRatio, 1); Population dstPopulation = new Population(); float values[] = new float[srcPopulation.size()]; for (int i = 0; i < srcPopulation.size(); ++i) { values[i] = formula.getTrueClausesPercentage(srcPopulation.get(i)); } float[] distribution = getDistribution(values); //fill the new population for (int i = 0; i < srcPopulation.size()*intermediateToParentsRatio; ++i) { dstPopulation.add(createOneChild(srcPopulation, distribution)); } return dstPopulation; } /** * Funkcja generuje koło ruletki dla populacji. Koło odwzorowane jest na przedział liczbowy 0-1, * a każdemu z odcinków przypisany jest jego podprzedział, proporcjonalny do wartości funkcji * przystosowania danego osobnika. I-ta wartość w zwracanej tablicy odpowiada końcowi przedziału * przydzielonemu itemu osobnikowi. Początek tego porzedziału to koniec poprzedniego lub 0 * (dla pierwszego osobnika). Koło ruletki jest wykorzystywane przy doborze rodziców. * @param values wartości funkcji przystosowania * @return krańce przedziałów przypisanych każdemu z osobników. */ private static float[] getDistribution(float[] values) { float[] result = new float[values.length]; float sum = 0f; for (float value : values) { value = (float) Math.pow(value, 10); sum += value; } //System.out.println(" avg quality: " + sum / values.length); //System.err.println("= "+sum); for (int i = 0; i < values.length; ++i) { float prev = (i == 0 ? 0f : result[i - 1]); result[i] = prev + values[i] / sum; //System.err.println(i+"th value: "+result[i]); } return result; } /** * Na podstawie koła ruletki funkcja dobiera dwa osobniki potomne i tworzy zwraca jeden potomny. * @param srcPopulation populacja źródłowa * @param distribution koło ruletki * @return potomny osobnik */ private static Solution createOneChild(Population srcPopulation, float[] distribution) { float rand1 = (float) Math.random(); float rand2 = (float) Math.random(); int i1 = -1, i2 = -1; for (int i = 0; i < distribution.length; ++i) { float prev = (i == 0 ? 0f : distribution[i - 1]); if (rand1 > prev && rand1 <= distribution[i]) { i1 = i; } if (rand2 > prev && rand2 <= distribution[i]) { i2 = i; } } if (i1 == -1) { i1 = 0; } if (i2 == -1) { i2 = 0; } //so i1 and i2 are the parents chosen for breeding. cool, huh? return crossSolutions(srcPopulation.get(i1), srcPopulation.get(i2)); } /** * Funkcja tworząca rozwiązanie na podstawie losowego krzyżowania dwóch osobników rodzicielskich. * Wartość każdego z podstawień jest losowo dziedziczona po jednym z rodziców. * @param meat1 pierwszy rodzic * @param meat2 drugi rodzic * @return potomek */ private static Solution crossSolutions(Solution meat1, Solution meat2) { Solution child = new Solution(); for (Iterator it = meat1.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); child.put(key, Math.random() > 0.5 ? meat1.get(key) : meat2.get(key)); } return child; } /** * Funkcja wprowadza mutacje poprzez losowe negowanie niektórych przypisań. * @param lambda populacja bez mutacji * @param probability prawdopodobieństwo zajścia mutacji dla każdego z przypisań. * @return populacja zawierająca tak osobniki sprzed, jak i po mutacji */ public static Population applyMutations(Population lambda, float probability) { Population mutants = new Population(); for (Iterator<Solution> it = lambda.iterator(); it.hasNext();) { Solution solution = (Solution) it.next().clone(); mutants.add((Solution)solution.clone()); boolean hasChanged=false; for (Iterator<String> sit = solution.keySet().iterator(); sit.hasNext();) { String key = sit.next(); if (Math.random() < probability) { hasChanged=true; solution.put(key, solution.get(key).booleanValue() ? Boolean.FALSE : Boolean.TRUE); } } if(hasChanged){ mutants.add(solution); } } return mutants; } /** * Funkcja wybiera najlepsze spośród osobników populacji pośredniej, by utworzyły nową populację. * @param problem formuła logiczna stanowiąca rozwiązywany problem * @param mi populacja, wewnątrz której dokonywana jest selekcja * @param offspringOnly prawda, jeśli przekazana funkcji populacja zawiera wyłącznie osobniki potomne * @param limit limit osobników, które mają utworzyć nową populację * @return wynikowa populacja */ public static Population performSelection(FormulaCNF problem, Population mi, boolean offspringOnly, int limit) { final FormulaCNF problem_copy = problem; Collections.sort(mi, new Comparator<Solution>() { @Override public int compare(Solution t, Solution t1) { if (problem_copy.getTrueClausesPercentage(t) > problem_copy.getTrueClausesPercentage(t1)) { return -1; } return 1; } }); Population selection = (Population) mi.clone(); for (int i = limit; i < selection.size(); ++i) { selection.removeElementAt(i); } return selection; } }
Java
package sat; import java.util.HashMap; import java.util.Vector; import sat.exceptions.ParseException; /** * * @author bawey */ public class ClauseCNF { private Vector<LiteralCNF> literals; /** * @param representation formuła logiczna w postaci CNF * @throws ParseException */ public ClauseCNF(String representation) throws ParseException { literals = new Vector<LiteralCNF>(); parseString(representation); } /** * @return liczba literałów w klauzuli */ public int getLiteralsCount() { return literals.size(); } /** * @return Vector literałów występujących w klauzuli, pomija ew. negację */ public Vector<String> getStringLiterals() { Vector<String> temp = new Vector<String>(); for (int i = 0; i < literals.size(); ++i) { temp.add(literals.get(i).getSymbol()); } return temp; } /** * Sprawdza, czy dla danego podstawienia klauzula jest prawdziwa * @param values - podstawienia * @return */ public boolean evaluate(HashMap<String, Boolean> values) { for (int i = 0; i < literals.size(); ++i) { //what will return without entry? if ((values.get(literals.get(i).getSymbol())).booleanValue() ^ literals.get(i).isNegated()) { return true; } } return false; } /** * Funkcja prywatna, konwertuje klauzulę z postaci tekstowej do reprezentacji wewnętrznej * @param c tekst wejściowy * @throws ParseException */ private void parseString(String c) throws ParseException { c = StringToolkit.strip(c); boolean negated = false; StringBuffer literal = new StringBuffer(); for (int i = 0; i < c.length(); ++i) { if (c.charAt(i) == '~') { if (literal.length() == 0) { negated = !negated; } else { throw (new ParseException("unexpected ~")); } } else if (c.charAt(i) == '|') { if (literal.length() > 0) { literals.add(new LiteralCNF(literal.toString(), negated)); literal = new StringBuffer(); negated = false; } else { throw (new ParseException("unexpected |")); } } else { literal.append(c.charAt(i)); } } if (literal.length() > 0) { literals.add(new LiteralCNF(literal.toString(), negated)); } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < literals.size(); ++i) { if (i != 0) { sb.append("|"); } sb.append(literals.get(i).toString()); } sb.append(")"); return sb.toString(); } }
Java
package ru.gelin.android.bells.timers; import java.util.Calendar; import java.util.Date; /** * Timer. */ public class Timer { /** ID of the timer in the collection */ int id; /** Is this timer enabled? */ boolean enabled = true; /** Start time */ Date start = new Date(); /** Period */ Period period = new Period(0, 30); /** Timer message to display */ String message = ""; /** Timer alarm type */ String alarm; public Timer() { } /** * Creates timer with specified ID. */ Timer(int id) { this.id = id; } /** * Returns the ID of the timer. * ID is meaningful only inside the collection of timers. * @return */ public int getId() { return id; } /** * Sets the ID of the timer. */ void setId(int id) { this.id = id; } /** * Returns true if this timer is enabled. */ public boolean isEnabled() { return enabled; } /** * Sets enabled flag for the timer. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Returns the timer message to display to the user. */ public String getMessage() { return message; } /** * Sets the timer message to display to the user. */ public void setMessage(String message) { this.message = message; } /** * Returns the alarm type. */ public String getAlarm() { return alarm; } /** * Sets the alarm type. */ public void setAlarm(String alarm) { this.alarm = alarm; } /** * Gets the start time of the timer. * Each time the alarm happens the start time is shifted to * period. */ public Date getStartTime() { return start; } /** * Sets the start time of the timer. */ public void setStartTime(Date start) { this.start = normalizeDate(start); } /** * Gets the period of the timer. */ public Period getPeriod() { return period; } /** * Sets the period for the timer. */ public void setPeriod(int hours, int minutes) { this.period = new Period(hours, minutes); } /** * Returns the alarm time. * It time in the future when the timer should alarm. * @param now current time * @return some time in future */ public Date getAlarmTime(Date now) { Date nowMinute = normalizeDate(now); Date result = start; while (!result.after(nowMinute)) { result = period.add(result); } return result; } /** * Normalizes the timer, i.e. start time is set to not more than one period * in the past or now or in the future. * @param now time relative to which normalize the timer */ public void normalize(Date now) { Date nowMinute = normalizeDate(now); if (!start.before(nowMinute)) { return; //start is now or in the future } start = period.sub(getAlarmTime(now)); } /** * Normalizes dates, i.e. sets seconds and milliseconds to zero. */ public static Date normalizeDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; if (id > 0) { return result; //just hash code of id } result = prime * result + ((start == null) ? 0 : start.hashCode()); result = prime * result + ((period == null) ? 0 : period.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Timer other = (Timer) obj; if (id != other.id) return false; if (id > 0 && id == other.id) { return true; //equals by ID } if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; if (period == null) { if (other.period != null) return false; } else if (!period.equals(other.period)) return false; return true; } /** * Prints main properties of the timer. */ public String toString() { return "Timer: id = " + id; } /** * Creates new timer equals to this. */ public Timer copy() { Timer result = new Timer(); result.id = id; result.enabled = enabled; result.start = start; result.period = period; result.message = message; result.alarm = alarm; return result; } }
Java
package ru.gelin.android.bells.timers; import java.util.Calendar; import java.util.Date; /** * Period of the timer, in hours and minutes. */ public class Period { /** Hours of the timer period */ int hours; /** Minutes of the timer period */ int minutes; /** * Creates new period. * @param hours 0-24 * @param minutes 0-59 */ public Period(int hours, int minutes) { this.hours = hours; this.minutes = minutes; if (hours * 60 + minutes <= 0) { this.hours = 0; this.minutes = 1; } } public int getHours() { return hours; } public int getMinutes() { return minutes; } /** * Adds the period to the date. */ public Date add(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(date)); calendar.add(Calendar.HOUR_OF_DAY, hours); calendar.add(Calendar.MINUTE, minutes); return calendar.getTime(); } /** * Subtracts the period from the date. */ public Date sub(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(date)); calendar.add(Calendar.HOUR_OF_DAY, -hours); calendar.add(Calendar.MINUTE, -minutes); return calendar.getTime(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hours; result = prime * result + minutes; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Period other = (Period) obj; if (hours != other.hours) return false; if (minutes != other.minutes) return false; return true; } }
Java
package ru.gelin.android.bells.timers; import java.util.Comparator; import java.util.Date; /** * Order timers by the alarm time. * Because of the alarm time depends on the current time * (can be equal to the start time when the start time is in the future), * the constructor of this comparator takes the current time as argument. */ class TimerComparator implements Comparator<Timer> { /** Current time to compare */ Date now = new Date(); /** * Creates new comparator for the current time. * @param current time */ TimerComparator(Date now) { this.now = now; } /** * Order timers by alarm time and ID. * If IDs of both timers are equal, timers are considered equal too. */ @Override public int compare(Timer timer1, Timer timer2) { if (timer1.id > 0 && timer1.id == timer2.id) { return 0; //equals by ID } Date alarm1 = timer1.getAlarmTime(now); Date alarm2 = timer2.getAlarmTime(now); int alarmCompare = alarm1.compareTo(alarm2); if (alarmCompare != 0) { return alarmCompare; } //ordering by ID return timer1.id - timer2.id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((now == null) ? 0 : now.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimerComparator other = (TimerComparator) obj; if (now == null) { if (other.now != null) return false; } else if (!now.equals(other.now)) return false; return true; } }
Java
package ru.gelin.android.bells.timers; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Collections of timers. * Each timer in the collection is identified by the ID. * ID is assigned to the timer during insertion. * ID is used to find timer in the collection during update. */ public class TimerCollection { /** Map of timers by ID */ Map<Integer, Timer> timers = new HashMap<Integer, Timer>(); /** IDs counter */ int idCounter; /** * Inserts new timer to collection. * Sets the ID for the timer. * @param timer ID of this timer is set */ public void insert(Timer timer) { int id = getNextId(); timer.setId(id); timers.put(id, timer.copy()); } /** * Updates timer in the collection. * The timer with specified ID is updated * @param timer timer (ID and values) to update */ public void update(Timer timer) { timers.put(timer.getId(), timer.copy()); } /** * Selects one timer by ID. */ public Timer select(int id) { return timers.get(id).copy(); } /** * Deletes one timer by ID. */ public Timer delete(int id) { return timers.remove(id); } /** * Deletes all timers from the collection. */ public void delete() { timers.clear(); } /** * Returns the list of timers in the collection. * The timers are ordered by the time of the alarm time acceding. * Not the actual, but the deep copy of the original collection * is returned, to modify any element of the collection perform * {@link #update}. * @param now current time, is used to sort the list */ public List<Timer> select(Date now) { List<Timer> result = new ArrayList<Timer>(timers.size()); for (Timer timer : internalList(now)) { result.add(timer.copy()); } return result; } /** * Returns sorted list of actual timers saved in the collection. * @param now current time, is used to sort the list */ protected List<Timer> internalList(Date now) { List<Timer> result = new ArrayList<Timer>(timers.size()); result.addAll(timers.values()); Collections.sort(result, new TimerComparator(now)); return result; } /** * Returns unsorted list of actual timers saved in the collection. */ protected List<Timer> internalList() { List<Timer> result = new ArrayList<Timer>(timers.size()); result.addAll(timers.values()); return result; } /** * Returns the current size of the collection. */ public int size() { return timers.size(); } /** * Selects all timers which alarms have came. * <pre> * now * -------------|--------------- * start alarm * ----------------|------------ * start alarm * ----period---- * </pre> */ public List<Timer> selectAlarms(Date now) { Date nowMinute = Timer.normalizeDate(now); List<Timer> result = new ArrayList<Timer>(); for (Timer timer : internalList(now)) { if (!timer.isEnabled()) { continue; } Date start = timer.getStartTime(); if (!start.before(nowMinute)) { continue; //will start in future } Date startPlusPeriod = timer.getPeriod().add(timer.getStartTime()); if (!startPlusPeriod.after(nowMinute)) { result.add(timer.copy()); } else { break; } } return result; } /** * Normalizes all alarms. I.e. shifts all it's times to make alarm time * in future. * Note that after calling this method {@link #selectAlarms} will * return empty list. */ public void normalize(Date now) { for (Timer timer : internalList(now)) { timer.normalize(now); } } /** * Returns nearest alarm time, i.e. the alarm time of the first * enabled timer in the sorted list. * @return next alarm date or <code>null</code> if there is no enabled timers */ public Date alarmTime(Date now) { for (Timer timer : internalList(now)) { if (timer.isEnabled()) { return timer.getAlarmTime(now); } } return null; } /** * Returns next ID for the inserting Timer */ int getNextId() { return ++idCounter; } }
Java
package ru.gelin.android.bells; import java.util.Date; import android.app.Activity; import android.os.Bundle; /** * Activity which tracks (saves into instance state) the time * when it is started. */ public class NowActivity extends Activity { /** Key in the instance state bundle to save activity start time */ static final String NOW_KEY = "now"; /** Current time (when activity is started) */ Date now; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { //first start now = new Date(); } else { //restart now = new Date( savedInstanceState.getLong(NOW_KEY, System.currentTimeMillis())); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(NOW_KEY, now.getTime()); } }
Java
package ru.gelin.android.bells; import java.util.Date; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class TimersListActivity extends NowActivity implements Constants { /** Storage of the timers */ TimerStorage timers; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timers_list); timers = TimerStorage.getInstance(this); ListView timersList = (ListView)findViewById(R.id.timers_list); registerForContextMenu(timersList); timersList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { editTimer((int)id); } }); setVolumeControlStream(AudioManager.STREAM_ALARM); } @Override public void onResume() { super.onResume(); loadTimers(); if (timers.size() > 0) { findViewById(R.id.add_timer_warn).setVisibility(View.GONE); findViewById(R.id.timers_list).setVisibility(View.VISIBLE); } else { findViewById(R.id.add_timer_warn).setVisibility(View.VISIBLE); findViewById(R.id.timers_list).setVisibility(View.GONE); } } @Override public void onPause() { super.onPause(); timers.save(); timers.scheduleAlarm(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.timers_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_timer: addTimer(); return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.timers_list_item, menu); View itemView = ((AdapterContextMenuInfo)menuInfo).targetView; TextView timerName = (TextView)itemView.findViewById(R.id.timer_name); menu.setHeaderTitle(timerName.getText()); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case R.id.menu_edit_timer: editTimer((int)info.id); return true; case R.id.menu_delete_timer: deleteTimer((int)info.id); return true; case R.id.menu_start_now_timer: startNowTimer((int)info.id); return true; } return super.onContextItemSelected(item); } void loadTimers() { now = new Date(); //we updating and normalizing the timer according actually current time timers.load(); timers.normalize(now); ListView list = (ListView)findViewById(R.id.timers_list); ListAdapter adapter = new TimersListAdapter(this, timers, now); list.setAdapter(adapter); } void addTimer() { Intent intent = new Intent(this, AddTimerActivity.class); startActivity(intent); } void editTimer(int id) { Intent intent = new Intent(this, EditTimerActivity.class); intent.setData(new Uri.Builder().scheme(TIMER_SCHEME). opaquePart(String.valueOf(id)).build()); startActivity(intent); } void deleteTimer(int id) { timers.delete(id); timers.save(); loadTimers(); } void startNowTimer(int id) { Timer timer = timers.select(id); timer.setStartTime(now); timer.normalize(now); timers.update(timer); timers.save(); loadTimers(); } }
Java
package ru.gelin.android.bells; import java.util.Date; import android.content.Context; import android.content.Intent; import android.content.BroadcastReceiver; /** * Broadcast receiver which receives event about boot complete. * Starts AlarmActitity. */ public class BootCompletedReceiver extends BroadcastReceiver implements Constants { public void onReceive (Context context, Intent intent) { Date now = new Date(); TimerStorage timers = TimerStorage.getInstance(context); timers.load(); timers.normalize(now); timers.save(); timers.scheduleAlarm(now); } }
Java
package ru.gelin.android.bells; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class TimerDbOpenHelper extends SQLiteOpenHelper { static final String DATABASE_NAME = "timers"; static final int DATABASE_VERSION = 1; static final String TIMER_TABLE = "timer"; static final String ID = "id"; static final String ENABLED = "enabled"; static final String START = "start"; static final String PERIOD_HOURS = "period_hours"; static final String PERIOD_MINUTES = "period_minutes"; static final String MESSAGE = "message"; static final String ALARM = "alarm"; private static final String TIMER_TABLE_CREATE = "CREATE TABLE " + TIMER_TABLE + " (" + ID + " INTEGER PRIMARY KEY, " + ENABLED + " BOOLEAN, " + START + " DATETIME, " + PERIOD_HOURS + " INTEGER, " + PERIOD_MINUTES + " INTEGER, " + MESSAGE + " TEXT, " + ALARM + " TEXT" + ");"; TimerDbOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TIMER_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //we have only one (first) version of our database //nothing to do here } }
Java
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; /** * Adapter for collection of timers. */ public class TimersListAdapter extends BaseAdapter { /** Application context */ Context context; /** Collection of timers */ TimerStorage timers; /** List of timers (to map positions and IDs) */ List<Timer> timersList = new ArrayList<Timer>(); /** Current time (when the activity starts) */ Date now; public TimersListAdapter(Context context, TimerStorage timers, Date now) { this.context = context; this.timers = timers; this.now = now; timersList = timers.select(now); } @Override public int getCount() { return timers.size(); } @Override public Object getItem(int position) { return timersList.get(position); } @Override public long getItemId(int position) { return timersList.get(position).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.from(context).inflate( R.layout.timers_list_item, parent, false); } final Timer timer = timersList.get(position); Resources resources = context.getResources(); TextView timerName = (TextView)view.findViewById(R.id.timer_name); timerName.setText(getTimerName(resources, timer)); TextView timerPeriod = (TextView)view.findViewById(R.id.timer_period); timerPeriod.setText(resources.getString( R.string.list_timer_period, timer.getPeriod().getHours(), timer.getPeriod().getMinutes())); TextView timerAlarm = (TextView)view.findViewById(R.id.timer_alarm); Date alarmTime = timer.getAlarmTime(now); timerAlarm.setText(resources.getString( isTomorrow(now, alarmTime) ? R.string.timer_alarm_time_tomorrow : R.string.timer_alarm_time, alarmTime)); CheckBox enabledCheckBox = (CheckBox)view.findViewById(R.id.timer_enabled); enabledCheckBox.setChecked(timer.isEnabled()); enabledCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { enableTimer(timer, isChecked); } }); return view; } /** * Makes timer name. It is the message if the message is set, * or the period and next start time if the message is not set. */ String getTimerName(Resources resources, Timer timer) { String name = timer.getMessage(); if (name == null || "".equals(name)) { name = resources.getString( R.string.list_default_timer_name, timer.getPeriod().getHours(), timer.getPeriod().getMinutes(), timer.getStartTime()); } return name; } void enableTimer(Timer timer, boolean isChecked) { timer.setEnabled(isChecked); timers.update(timer); timers.save(); } @Override public boolean hasStableIds() { return true; } }
Java
package ru.gelin.android.bells; import ru.gelin.android.bells.timers.Timer; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TimePicker; /** * Activity to add a timer. */ public class AddTimerActivity extends SaveTimerActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setIs24HourView(true); period.setCurrentHour(0); period.setCurrentMinute(30); View nowButton = findViewById(R.id.timer_start_now); nowButton.setVisibility(View.GONE); final Button button = (Button)findViewById(R.id.submit_button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addTimer(); } }); } void addTimer() { Timer timer = new Timer(); saveTimer(timer); } }
Java
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.Calendar; import java.util.Date; import ru.gelin.android.bells.timers.Timer; import android.database.Cursor; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.TimePicker; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.TimePicker.OnTimeChangedListener; public class SaveTimerActivity extends NowActivity implements Constants { /** Key in the instance state bundle to save selected ringtone */ static final String SELECTED_RINGTONE_KEY = "selectedRingtone"; /** Key in the instance state bundle to save initial timer start time */ static final String INITIAL_START_KEY = "initialStart"; /** Storage of the timers */ protected TimerStorage timers; /** Ringtone manager */ protected RingtoneManager ringtoneManager; /** Previously selected alarm ringtone */ protected int selectedRingtone = 0; //first in the list /** Original start time of the edited timer */ protected Date initialStart; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { initialStart = now; } else { initialStart = new Date( savedInstanceState.getLong(INITIAL_START_KEY, System.currentTimeMillis())); } setContentView(R.layout.timer); timers = TimerStorage.getInstance(this); TimePicker start = (TimePicker)findViewById(R.id.timer_start); start.setIs24HourView(true); start.setOnTimeChangedListener(new OnTimeChangedListener() { public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { updateAlarmTime(); } }); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setIs24HourView(true); period.setOnTimeChangedListener(new OnTimeChangedListener() { public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { updateAlarmTime(); } }); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); ringtoneManager = new RingtoneManager(this); ringtoneManager.setType(RingtoneManager.TYPE_ALARM); ringtoneManager.setStopPreviousRingtone(true); Cursor cursor = ringtoneManager.getCursor(); //DatabaseUtils.dumpCursor(cursor); SpinnerAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {cursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX)}, new int[] {android.R.id.text1}); alarm.setAdapter(adapter); setVolumeControlStream(AudioManager.STREAM_ALARM); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if (savedInstanceState != null) { selectedRingtone = savedInstanceState.getInt(SELECTED_RINGTONE_KEY, selectedRingtone); } Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); alarm.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != selectedRingtone) { //another ringtone is selected ringtoneManager.getRingtone(position).play(); } selectedRingtone = position; } @Override public void onNothingSelected(AdapterView<?> parent) { //nothing to do } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(SELECTED_RINGTONE_KEY, selectedRingtone); outState.putLong(INITIAL_START_KEY, initialStart.getTime()); } @Override public void onPause() { super.onPause(); ringtoneManager.stopPreviousRingtone(); } /** * Converts entered hour and minute to date. * Tries to avoid this situation: * current time is 23:50, entered time is 00:10. * The date should always be in the future * (relative to the startTime of the timer during the activity creation). */ protected Date toDate(int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); Date timer = calendar.getTime(); Date boundary = initialStart.before(now) ? initialStart : now; if (timer.before(boundary)) { calendar.add(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); } else { return timer; } } protected void updateAlarmTime() { Timer timer = new Timer(); TimePicker start = (TimePicker)findViewById(R.id.timer_start); TimePicker period = (TimePicker)findViewById(R.id.timer_period); timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute())); timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute()); timer.normalize(now); TextView nextStart = (TextView)findViewById(R.id.timer_next_start); Date alarmTime = timer.getAlarmTime(now); nextStart.setText(getResources().getString( isTomorrow(now, alarmTime) ? R.string.timer_alarm_time_tomorrow : R.string.timer_alarm_time, alarmTime)); } protected void saveTimer(Timer timer) { CheckBox enabled = (CheckBox)findViewById(R.id.timer_enabled); timer.setEnabled(enabled.isChecked()); TimePicker start = (TimePicker)findViewById(R.id.timer_start); timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute())); TimePicker period = (TimePicker)findViewById(R.id.timer_period); timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute()); TextView message = (TextView)findViewById(R.id.timer_message); timer.setMessage(String.valueOf(message.getText())); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); Uri ringtoneUri = ringtoneManager.getRingtoneUri(alarm.getSelectedItemPosition()); Log.d(TAG, "alarm sound: " + ringtoneUri); timer.setAlarm(String.valueOf(ringtoneUri)); timer.normalize(now); if (timer.getId() == 0) { timers.insert(timer); } else { timers.update(timer); } timers.save(); finish(); } }
Java
package ru.gelin.android.bells; import java.util.Calendar; import java.util.Date; import ru.gelin.android.bells.timers.Timer; /** * Static utility methods. */ public class Utils { /** * Returns true if the specified date is tomorrow date (or after tomorrow...). * @param now current time * @param date time to check */ public static boolean isTomorrow(Date now, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(now)); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); return !Timer.normalizeDate(date).before(calendar.getTime()); } }
Java
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Adapter for collection of alarms (timers). */ public class AlarmsListAdapter extends BaseAdapter { /** Application context */ Context context; /** List of timers (to map positions and IDs) */ List<Timer> alarms = new ArrayList<Timer>(); /** Current time (when Alarm activity is displayed) */ Date now; public AlarmsListAdapter(Context context, List<Timer> alarms, Date now) { this.context = context; this.alarms = alarms; this.now = now; //for (Timer alarm : this.alarms) { // alarm.normalize(now); //to show next alarm time //} } @Override public int getCount() { return alarms.size(); } @Override public Object getItem(int position) { return alarms.get(position); } @Override public long getItemId(int position) { return alarms.get(position).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.from(context).inflate( R.layout.alarms_list_item, parent, false); } final Timer timer = alarms.get(position); Resources resources = context.getResources(); TextView timerName = (TextView)view.findViewById(R.id.timer_name); timerName.setText(getTimerName(resources, timer)); TextView timerAlarm = (TextView)view.findViewById(R.id.timer_alarm); Date alarmTime = timer.getAlarmTime(now); timerAlarm.setText(resources.getString( isTomorrow(now, alarmTime) ? R.string.list_timer_next_alarm_tomorrow : R.string.list_timer_next_alarm, alarmTime)); return view; } /** * Makes timer name. It is the message if the message is set, * or the period and next start time if the message is not set. */ String getTimerName(Resources resources, Timer timer) { String name = timer.getMessage(); if (name == null || "".equals(name)) { name = resources.getString( R.string.list_default_timer_name, timer.getPeriod().getHours(), timer.getPeriod().getMinutes(), timer.getStartTime()); } return name; } @Override public boolean hasStableIds() { return true; } }
Java
package ru.gelin.android.bells; public interface Constants { /** Tag for logs */ String TAG = "ru.gelin.android.bells"; /** Scheme for URIs referencing to timers */ String TIMER_SCHEME = "timer"; }
Java
package ru.gelin.android.bells; import java.util.ArrayList; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.util.Log; /** * The list of ringtones to be played on alarm. * It is populated from the list of alarmed timers. The set of different * alarm ringtones is created. The first ringtone is started by {@link #playNext()} * method call. * The next ringtone is tried to start by {@link #playNext()} call. If the * previous ringtone is playing, nothing is happened. If the previous ringtone * is stopped, the next ringtone is started. * After the last, the first ringtone will be played again. */ public class RingtoneList implements Constants { /** Set of ringtone URIs */ List<Uri> ringtones = new ArrayList<Uri>(); /** Current application context */ Context context; /** Ringtone manager to play a ringtone */ RingtoneManager ringtoneManager; /** Current playing ringtone */ Ringtone ringtone; /** Next ringtone index */ int nextRingtone = 0; /** * Constructs the list * @param context to get ringtone manager * @param list of alarmed timers */ public RingtoneList(Context context, List<Timer> timers) { this.context = context; ringtoneManager = new RingtoneManager(context); ringtoneManager.setType(RingtoneManager.TYPE_ALARM); //ringtoneManager.setStopPreviousRingtone(true); for (Timer timer : timers) { String alarm = timer.getAlarm(); if (!ringtones.contains(alarm)) { try { ringtones.add(Uri.parse(alarm)); } catch (Exception e) { Log.w(TAG, "invalid alarm: " + alarm); } } } if (ringtones.size() == 0) { ringtones.add(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)); } } /** * Starts playing of the next (or the first) ringtone. */ public void playNext() { if (ringtone == null || !ringtone.isPlaying()) { ringtone = getNextRingtone(); ringtone.play(); } } /** * Stops playing of the currect ringtone. */ public void stop() { if (ringtone != null && ringtone.isPlaying()) { ringtone.stop(); } } /** * Returns the next ringtone. */ Ringtone getNextRingtone() { Uri uri = ringtones.get(nextRingtone); int position = ringtoneManager.getRingtonePosition(uri); if (position < 0) { position = 0; } Ringtone ringtone = ringtoneManager.getRingtone(position); Log.d(TAG, "playing " + uri + " - " + ringtone.getTitle(context)); nextRingtone++; if (nextRingtone >= ringtones.size()) { nextRingtone = 0; } return ringtone; } }
Java
package ru.gelin.android.bells; import java.util.Calendar; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; /** * Activity to edit the timer. */ public class EditTimerActivity extends SaveTimerActivity implements Constants { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = intent.getData(); Log.d(TAG, "editing " + uri); final Timer timer = timers.select( Integer.parseInt(uri.getSchemeSpecificPart())); if (savedInstanceState == null) { initialStart = timer.getStartTime(); } loadTimer(timer); final Button nowButton = (Button)findViewById(R.id.timer_start_now); nowButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setStartNow(); } }); final Button submitButton = (Button)findViewById(R.id.submit_button); submitButton.setText(R.string.button_save); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { saveTimer(timer); } }); } void loadTimer(Timer timer) { CheckBox enabled = (CheckBox)findViewById(R.id.timer_enabled); enabled.setChecked(timer.isEnabled()); TimePicker start = (TimePicker)findViewById(R.id.timer_start); Calendar calendar = Calendar.getInstance(); calendar.setTime(timer.getStartTime()); start.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); start.setCurrentMinute(calendar.get(Calendar.MINUTE)); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setCurrentHour(timer.getPeriod().getHours()); period.setCurrentMinute(timer.getPeriod().getMinutes()); TextView message = (TextView)findViewById(R.id.timer_message); message.setText(timer.getMessage()); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); Uri ringtoneUri = Uri.parse(timer.getAlarm()); int ringtonePosition = ringtoneManager.getRingtonePosition(ringtoneUri); if (ringtonePosition >= 0) { selectedRingtone = ringtonePosition; alarm.setSelection(ringtonePosition, false); } } void setStartNow() { Calendar now = Calendar.getInstance(); TimePicker start = (TimePicker)findViewById(R.id.timer_start); start.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); start.setCurrentMinute(now.get(Calendar.MINUTE)); } }
Java
package ru.gelin.android.bells; import static ru.gelin.android.bells.TimerDbOpenHelper.*; import java.util.Date; import java.util.HashMap; import java.util.Map; import ru.gelin.android.bells.timers.Timer; import ru.gelin.android.bells.timers.TimerCollection; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class TimerStorage extends TimerCollection implements Constants { /** Name of the preferences */ static final String PREFERENCES_NAME = "TimerStorage"; /** "enabled" property suffix */ static final String ENABLED_SUFFIX = "_enabled"; /** "start" property suffix */ static final String START_SUFFIX = "_start"; /** "period hours" property suffix */ static final String PERIOD_HOURS_SUFFIX = "_period_hours"; /** "period minutes" property suffix */ static final String PERIOD_MINUTES_SUFFIX = "_period_minutes"; /** "message" property suffix */ static final String MESSAGE_SUFFIX = "_message"; /** "alarm" property suffix */ static final String ALARM_SUFFIX = "_alarm"; /** Storage instance */ static TimerStorage instance; /** Context which uses this storage */ Context context; /** Preferences which saves the timers */ SharedPreferences preferences; /** Database open helper */ SQLiteOpenHelper dbHelper; /** * Private constructor. */ private TimerStorage(Context context) { this.context = context; preferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); dbHelper = new TimerDbOpenHelper(context); } public static TimerStorage getInstance(Context context) { if (instance == null) { instance = new TimerStorage(context); } return instance; } public void load() { delete(); loadFromPreferences(); //backward compatibility SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(TIMER_TABLE, new String[] {ENABLED, START, PERIOD_HOURS, PERIOD_MINUTES, MESSAGE, ALARM}, null, null, null, null, null); int enabledIndex = cursor.getColumnIndex(ENABLED); int startIndex = cursor.getColumnIndex(START); int periodHoursIndex = cursor.getColumnIndex(PERIOD_HOURS); int periodMinutesIndex = cursor.getColumnIndex(PERIOD_MINUTES); int messageIndex = cursor.getColumnIndex(MESSAGE); int alarmIndex = cursor.getColumnIndex(ALARM); if (cursor.moveToFirst()) { do { Timer timer = new Timer(); timer.setEnabled(cursor.getInt(enabledIndex) != 0); timer.setStartTime(new Date(cursor.getLong(startIndex))); timer.setPeriod(cursor.getInt(periodHoursIndex), cursor.getInt(periodMinutesIndex)); timer.setMessage(cursor.getString(messageIndex)); timer.setAlarm(cursor.getString(alarmIndex)); insert(timer); } while (cursor.moveToNext()); } cursor.close(); db.close(); } /** * Saves timers to the persistent storage. */ public void save() { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction(); try { db.delete(TIMER_TABLE, null, null); for (Timer timer : internalList()) { ContentValues values = new ContentValues(); values.put(ID, timer.getId()); values.put(ENABLED, timer.isEnabled()); values.put(START, timer.getStartTime().getTime()); values.put(PERIOD_HOURS, timer.getPeriod().getHours()); values.put(PERIOD_MINUTES, timer.getPeriod().getMinutes()); values.put(MESSAGE, timer.getMessage()); values.put(ALARM, timer.getAlarm()); db.insert(TIMER_TABLE, null, values); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } db.close(); } /** * Schedulers next alarm using AlarmManager. * On alarm AlarmActivity will start. * @param now current time */ public void scheduleAlarm(Date now) { Intent intent = new Intent(context, AlarmActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager)context.getSystemService( Context.ALARM_SERVICE); Date nextAlarm = alarmTime(now); if (nextAlarm == null) { Log.i(TAG, "cancelling alarm scheduler"); alarmManager.cancel(pendingIntent); return; } Log.i(TAG, "scheduling alarm on " + nextAlarm); alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarm.getTime(), pendingIntent); } /** * Schedulers next alarm relative the the current time. */ public void scheduleAlarm() { scheduleAlarm(new Date()); } /** * Loads timers from the persistent storage. */ void loadFromPreferences() { Map<String, ?> values = preferences.getAll(); Map<Integer, Timer> result = new HashMap<Integer, Timer>(); for (Map.Entry<String, ?> entry : values.entrySet()) { String key = entry.getKey(); int id; try { id = Integer.parseInt(key.substring(0, key.indexOf('_'))); } catch (Exception e) { Log.w(TAG, "invalid preferences key: " + key); continue; } Timer timer = result.get(id); if (timer == null) { timer = new Timer(); result.put(id, timer); } try { if (key.endsWith(ENABLED_SUFFIX)) { timer.setEnabled((Boolean)entry.getValue()); } else if (key.endsWith(START_SUFFIX)) { timer.setStartTime(new Date((Long)entry.getValue())); } else if (key.endsWith(PERIOD_HOURS_SUFFIX)) { timer.setPeriod((Integer)entry.getValue(), timer.getPeriod().getMinutes()); } else if (key.endsWith(PERIOD_MINUTES_SUFFIX)) { timer.setPeriod(timer.getPeriod().getHours(), (Integer)entry.getValue()); } else if (key.endsWith(MESSAGE_SUFFIX)) { timer.setMessage((String)entry.getValue()); } else if (key.endsWith(ALARM_SUFFIX)) { timer.setAlarm((String)entry.getValue()); } } catch (Exception e) { Log.w(TAG, "invalid preferences value: " + key + " = " + entry.getValue()); result.remove(id); } } //delete(); for (Timer timer : result.values()) { insert(timer); } } }
Java
package ru.gelin.android.bells; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class AlarmActivity extends NowActivity implements Constants { /** Time (in millis) to show this activity */ static final long SHOW_TIME = 55000; //55 seconds //static final long SHOW_TIME = 10000; //10 seconds /** Period (in millis) to check ringtone */ static final int RINGTONE_TIME = 5000; //5 seconds /** What property of a message to a ring handler */ static final int RING_WHAT = 0; /** Storage of the timers */ TimerStorage timers; /** Ringtones to play */ RingtoneList ringtones; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm); timers = TimerStorage.getInstance(this); Button ok = (Button)findViewById(R.id.ok_button); ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); setVolumeControlStream(AudioManager.STREAM_ALARM); if (savedInstanceState == null) { //first start if (isPlaying() && loadAlarms()) { ringtones.playNext(); ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME); } else { finish(); //immediately close activity Intent intent = new Intent(this, TimersListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); //open timers list } } else { //restart loadAlarms(); } TextView time = (TextView)findViewById(R.id.alarm_time); time.setText(getResources().getString(R.string.alarm_time, now)); } @Override public void onStop() { super.onStop(); if (ringtones != null) { ringtones.stop(); } } /** * Finished the activity. Updates timer's list to the next alarm. */ @Override public void finish() { super.finish(); ringHandler.removeMessages(RING_WHAT); timers.normalize(now); timers.scheduleAlarm(now); timers.save(); } /** * Loads list of alarms. * @return false if there is no alarms */ boolean loadAlarms() { timers.load(); List<Timer> alarms = timers.selectAlarms(now); if (alarms.size() == 0) { return false; } ListView list = (ListView)findViewById(R.id.alarms_list); ListAdapter adapter = new AlarmsListAdapter(this, alarms, now); list.setAdapter(adapter); ringtones = new RingtoneList(this, alarms); return true; } /** * Returns true if we should still play alarm and display timers descriptions. * Returns false if we should not, i.e. 50 seconds came from the * start of the activity. */ boolean isPlaying() { return now != null && System.currentTimeMillis() <= now.getTime() + SHOW_TIME; } /** * Handles ringtone playing. Restarts ringtone if it stops. */ final Handler ringHandler = new Handler() { public void handleMessage(Message msg) { ringtones.playNext(); if (isPlaying()) { ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME); } else { finish(); } }; }; }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; /** * Represents the result of an in-app billing operation. * A result is composed of a response code (an integer) and possibly a * message (String). You can get those by calling * {@link #getResponse} and {@link #getMessage()}, respectively. You * can also inquire whether a result is a success or a failure by * calling {@link #isSuccess()} and {@link #isFailure()}. */ public class IabResult { int mResponse; String mMessage; public IabResult(int response, String message) { mResponse = response; if (message == null || message.trim().length() == 0) { mMessage = IabHelper.getResponseDesc(response); } else { mMessage = message + " (response: " + IabHelper.getResponseDesc(response) + ")"; } } public int getResponse() { return mResponse; } public String getMessage() { return mMessage; } public boolean isSuccess() { return mResponse == IabHelper.BILLING_RESPONSE_RESULT_OK; } public boolean isFailure() { return !isSuccess(); } public String toString() { return "IabResult: " + getMessage(); } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app product's listing details. */ public class SkuDetails { String mItemType; String mSku; String mType; String mPrice; String mTitle; String mDescription; String mJson; public SkuDetails(String jsonSkuDetails) throws JSONException { this(IabHelper.ITEM_TYPE_INAPP, jsonSkuDetails); } public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType; mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mTitle = o.optString("title"); mDescription = o.optString("description"); } public String getSku() { return mSku; } public String getType() { return mType; } public String getPrice() { return mPrice; } public String getTitle() { return mTitle; } public String getDescription() { return mDescription; } @Override public String toString() { return "SkuDetails:" + mJson; } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; /** * Exception thrown when something went wrong with in-app billing. * An IabException has an associated IabResult (an error). * To get the IAB result that caused this exception to be thrown, * call {@link #getResult()}. */ public class IabException extends Exception { IabResult mResult; public IabException(IabResult r) { this(r, null); } public IabException(int response, String message) { this(new IabResult(response, message)); } public IabException(IabResult r, Exception cause) { super(r.getMessage(), cause); mResult = r; } public IabException(int response, String message, Exception cause) { this(new IabResult(response, message), cause); } /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } }
Java
// Copyright 2002, 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.example.android.trivialdrivesample.util; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app billing purchase. */ public class Purchase { String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS String mOrderId; String mPackageName; String mSku; long mPurchaseTime; int mPurchaseState; String mDeveloperPayload; String mToken; String mOriginalJson; String mSignature; public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException { mItemType = itemType; mOriginalJson = jsonPurchaseInfo; JSONObject o = new JSONObject(mOriginalJson); mOrderId = o.optString("orderId"); mPackageName = o.optString("packageName"); mSku = o.optString("productId"); mPurchaseTime = o.optLong("purchaseTime"); mPurchaseState = o.optInt("purchaseState"); mDeveloperPayload = o.optString("developerPayload"); mToken = o.optString("token", o.optString("purchaseToken")); mSignature = signature; } public String getItemType() { return mItemType; } public String getOrderId() { return mOrderId; } public String getPackageName() { return mPackageName; } public String getSku() { return mSku; } public long getPurchaseTime() { return mPurchaseTime; } public int getPurchaseState() { return mPurchaseState; } public String getDeveloperPayload() { return mDeveloperPayload; } public String getToken() { return mToken; } public String getOriginalJson() { return mOriginalJson; } public String getSignature() { return mSignature; } @Override public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; } }
Java
// Portions copyright 2002, 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.example.android.trivialdrivesample.util; // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; import android.text.TextUtils; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "IABUtil/Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; /** * Verifies that the data was signed with the given signature, and returns * the verified purchase. The data is in JSON format and signed * with a private key. The data also contains the {@link PurchaseState} * and product ID of the purchase. * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } boolean verified = false; if (!TextUtils.isEmpty(signature)) { PublicKey key = Security.generatePublicKey(base64PublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return false; } } return true; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import com.android.vending.billing.IInAppBillingService; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * Provides convenience methods for in-app billing. You can create one instance of this * class for your application and use it to process in-app billing operations. * It provides synchronous (blocking) and asynchronous (non-blocking) methods for * many common in-app billing operations, as well as automatic signature * verification. * * After instantiating, you must perform setup in order to start using the object. * To perform setup, call the {@link #startSetup} method and provide a listener; * that listener will be notified when setup is complete, after which (and not before) * you may call other methods. * * After setup is complete, you will typically want to request an inventory of owned * items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} * and related methods. * * When you are done with this object, don't forget to call {@link #dispose} * to ensure proper cleanup. This object holds a binding to the in-app billing * service, which will leak unless you dispose of it correctly. If you created * the object on an Activity's onCreate method, then the recommended * place to dispose of it is the Activity's onDestroy method. * * A note about threading: When using this object from a background thread, you may * call the blocking versions of methods; when using from a UI thread, call * only the asynchronous versions and handle the results via callbacks. * Also, notice that you can only call one asynchronous operation at a time; * attempting to start a second asynchronous operation while the first one * has not yet completed will result in an exception being thrown. * * @author Bruno Oliveira (Google) * */ public class IabHelper { // Is debug logging enabled? boolean mDebugLog = false; String mDebugTag = "IabHelper"; // Is setup done? boolean mSetupDone = false; // Has this object been disposed of? (If so, we should ignore callbacks, etc) boolean mDisposed = false; // Are subscriptions supported? boolean mSubscriptionsSupported = false; // Is an asynchronous operation in progress? // (only one at a time can be in progress) boolean mAsyncInProgress = false; // (for logging/debugging) // if mAsyncInProgress == true, what asynchronous operation is in progress? String mAsyncOperation = ""; // Context we were passed during initialization Context mContext; // Connection to the service IInAppBillingService mService; ServiceConnection mServiceConn; // The request code used to launch purchase flow int mRequestCode; // The item type of the current purchase flow String mPurchasingItemType; // Public key for verifying signature, in base64 encoding String mSignatureBase64 = null; // Billing response codes public static final int BILLING_RESPONSE_RESULT_OK = 0; public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; public static final int BILLING_RESPONSE_RESULT_ERROR = 6; public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; // IAB Helper error codes public static final int IABHELPER_ERROR_BASE = -1000; public static final int IABHELPER_REMOTE_EXCEPTION = -1001; public static final int IABHELPER_BAD_RESPONSE = -1002; public static final int IABHELPER_VERIFICATION_FAILED = -1003; public static final int IABHELPER_SEND_INTENT_FAILED = -1004; public static final int IABHELPER_USER_CANCELLED = -1005; public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006; public static final int IABHELPER_MISSING_TOKEN = -1007; public static final int IABHELPER_UNKNOWN_ERROR = -1008; public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009; public static final int IABHELPER_INVALID_CONSUMPTION = -1010; // Keys for the responses from InAppBillingService public static final String RESPONSE_CODE = "RESPONSE_CODE"; public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; public static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // Item types public static final String ITEM_TYPE_INAPP = "inapp"; public static final String ITEM_TYPE_SUBS = "subs"; // some fields on the getSkuDetails response bundle public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST"; /** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. * This is used for verification of purchase signatures. You can find your app's base64-encoded * public key in your application's page on Google Play Developer Console. Note that this * is NOT your "developer public key". */ public IabHelper(Context ctx, String base64PublicKey) { mContext = ctx.getApplicationContext(); mSignatureBase64 = base64PublicKey; logDebug("IAB helper created."); } /** * Enables or disable debug logging through LogCat. */ public void enableDebugLogging(boolean enable, String tag) { checkNotDisposed(); mDebugLog = enable; mDebugTag = tag; } public void enableDebugLogging(boolean enable) { checkNotDisposed(); mDebugLog = enable; } /** * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called * when the setup process is complete. */ public interface OnIabSetupFinishedListener { /** * Called to notify that setup is complete. * * @param result The result of the setup process. */ public void onIabSetupFinished(IabResult result); } /** * Starts the setup process. This will start up the setup process asynchronously. * You will be notified through the listener when the setup process is complete. * This method is safe to call from a UI thread. * * @param listener The listener to notify when the setup process is complete. */ public void startSetup(final OnIabSetupFinishedListener listener) { // If already set up, can't do it again. checkNotDisposed(); if (mSetupDone) throw new IllegalStateException("IAB helper is already set up."); // Connection to IAB service logDebug("Starting in-app billing setup."); mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { logDebug("Billing service disconnected."); mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (mDisposed) return; logDebug("Billing service connected."); mService = IInAppBillingService.Stub.asInterface(service); String packageName = mContext.getPackageName(); try { logDebug("Checking for in-app billing 3 support."); // check for in-app billing v3 support int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); if (response != BILLING_RESPONSE_RESULT_OK) { if (listener != null) listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support.")); // if in-app purchases aren't supported, neither are subscriptions. mSubscriptionsSupported = false; return; } logDebug("In-app billing version 3 supported for " + packageName); // check for v3 subscriptions support response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Subscriptions AVAILABLE."); mSubscriptionsSupported = true; } else { logDebug("Subscriptions NOT AVAILABLE. Response: " + response); } mSetupDone = true; } catch (RemoteException e) { if (listener != null) { listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing.")); } e.printStackTrace(); return; } if (listener != null) { listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); } } }; Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { // service available to handle that Intent mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } else { // no service available to handle that Intent if (listener != null) { listener.onIabSetupFinished( new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device.")); } } } /** * Dispose of object, releasing resources. It's very important to call this * method when you are done with this object. It will release any resources * used by it such as service connections. Naturally, once the object is * disposed of, it can't be used again. */ public void dispose() { logDebug("Disposing."); mSetupDone = false; if (mServiceConn != null) { logDebug("Unbinding from service."); if (mContext != null) mContext.unbindService(mServiceConn); } mDisposed = true; mContext = null; mServiceConn = null; mService = null; mPurchaseListener = null; } private void checkNotDisposed() { if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used."); } /** Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { checkNotDisposed(); return mSubscriptionsSupported; } /** * Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** * Called to notify that an in-app purchase finished. If the purchase was successful, * then the sku parameter specifies which item was purchased. If the purchase failed, * the sku and extraData parameters may or may not be null, depending on how far the purchase * process went. * * @param result The result of the purchase. * @param info The purchase information (null if purchase failed) */ public void onIabPurchaseFinished(IabResult result, Purchase info); } // The listener registered on launchPurchaseFlow, which we have to call back when // the purchase finishes OnIabPurchaseFinishedListener mPurchaseListener; public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused while * the user interacts with Google Play, and the result will be delivered via the activity's * {@link android.app.Activity#onActivityResult} method, at which point you must call * this object's {@link #handleActivityResult} method to continue the purchase flow. This method * MUST be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) * @param requestCode A request code (to differentiate from other responses -- * as in {@link android.app.Activity#startActivityForResult}). * @param listener The listener to notify when the purchase process finishes * @param extraData Extra data (developer payload), which will be returned with the purchase data * when the purchase completes. This extra data will be permanently bound to that purchase * and will always be returned when the purchase is queried. */ public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { checkNotDisposed(); checkSetupDone("launchPurchaseFlow"); flagStartAsync("launchPurchaseFlow"); IabResult result; if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available."); flagEndAsync(); if (listener != null) listener.onIabPurchaseFinished(r, null); return; } try { logDebug("Constructing buy intent for " + sku + ", item type: " + itemType); Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData); int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { logError("Unable to buy item, Error response: " + getResponseDesc(response)); flagEndAsync(); result = new IabResult(response, "Unable to buy item"); if (listener != null) listener.onIabPurchaseFinished(result, null); return; } PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode); mRequestCode = requestCode; mPurchaseListener = listener; mPurchasingItemType = itemType; act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent."); if (listener != null) listener.onIabPurchaseFinished(result, null); } catch (RemoteException e) { logError("RemoteException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow"); if (listener != null) listener.onIabPurchaseFinished(result, null); } } /** * Handles an activity result that's part of the purchase flow in in-app billing. If you * are calling {@link #launchPurchaseFlow}, then you must call this method from your * Activity's {@link android.app.Activity@onActivityResult} method. This method * MUST be called from the UI thread of the Activity. * * @param requestCode The requestCode as you received it. * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * @return Returns true if the result was related to a purchase flow and was handled; * false if the result was not related to a purchase, in which case you should * handle it normally. */ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) { IabResult result; if (requestCode != mRequestCode) return false; checkNotDisposed(); checkSetupDone("handleActivityResult"); // end of async purchase operation that started on launchPurchaseFlow flagEndAsync(); if (data == null) { logError("Null data in IAB activity result."); result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } int responseCode = getResponseCodeFromIntent(data); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) { logDebug("Successful resultcode from purchase activity."); logDebug("Purchase data: " + purchaseData); logDebug("Data signature: " + dataSignature); logDebug("Extras: " + data.getExtras()); logDebug("Expected item type: " + mPurchasingItemType); if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } Purchase purchase = null; try { purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature); String sku = purchase.getSku(); // Verify signature if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase); return true; } logDebug("Purchase signature successfully verified."); } catch (JSONException e) { logError("Failed to parse purchase data."); e.printStackTrace(); result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); } } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode)); if (mPurchaseListener != null) { result = new IabResult(responseCode, "Problem purchashing item."); mPurchaseListener.onIabPurchaseFinished(result, null); } } else if (resultCode == Activity.RESULT_CANCELED) { logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } else { logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } return true; } public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException { return queryInventory(querySkuDetails, moreSkus, null); } /** * Queries the inventory. This will query all owned items from the server, as well as * information on additional skus, if specified. This method may block or take long to execute. * Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}. * * @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well * as purchase information. * @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @throws IabException if a problem occurs while refreshing the inventory. */ public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException { checkNotDisposed(); checkSetupDone("queryInventory"); try { Inventory inv = new Inventory(); int r = queryPurchases(inv, ITEM_TYPE_INAPP); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned items)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of items)."); } } // if subscriptions are supported, then also query for subscriptions if (mSubscriptionsSupported) { r = queryPurchases(inv, ITEM_TYPE_SUBS); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned subscriptions)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions)."); } } } return inv; } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } } /** * Listener that notifies when an inventory query operation completes. */ public interface QueryInventoryFinishedListener { /** * Called to notify that an inventory query operation completed. * * @param result The result of the operation. * @param inv The inventory. */ public void onQueryInventoryFinished(IabResult result, Inventory inv); } /** * Asynchronous wrapper for inventory query. This will perform an inventory * query as described in {@link #queryInventory}, but will do so asynchronously * and call back the specified listener upon completion. This method is safe to * call from a UI thread. * * @param querySkuDetails as in {@link #queryInventory} * @param moreSkus as in {@link #queryInventory} * @param listener The listener to notify when the refresh operation completes. */ public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final QueryInventoryFinishedListener listener) { final Handler handler = new Handler(); checkNotDisposed(); checkSetupDone("queryInventory"); flagStartAsync("refresh inventory"); (new Thread(new Runnable() { public void run() { IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); Inventory inv = null; try { inv = queryInventory(querySkuDetails, moreSkus); } catch (IabException ex) { result = ex.getResult(); } flagEndAsync(); final IabResult result_f = result; final Inventory inv_f = inv; if (!mDisposed && listener != null) { handler.post(new Runnable() { public void run() { listener.onQueryInventoryFinished(result_f, inv_f); } }); } } })).start(); } public void queryInventoryAsync(QueryInventoryFinishedListener listener) { queryInventoryAsync(true, null, listener); } public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) { queryInventoryAsync(querySkuDetails, null, listener); } /** * Consumes a given in-app product. Consuming can only be done on an item * that's owned, and as a result of consumption, the user will no longer own it. * This method may block or take long to return. Do not call from the UI thread. * For that, see {@link #consumeAsync}. * * @param itemInfo The PurchaseInfo that represents the item to consume. * @throws IabException if there is a problem during consumption. */ void consume(Purchase itemInfo) throws IabException { checkNotDisposed(); checkSetupDone("consume"); if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) { throw new IabException(IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed."); } try { String token = itemInfo.getToken(); String sku = itemInfo.getSku(); if (token == null || token.equals("")) { logError("Can't consume "+ sku + ". No token."); throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo); } logDebug("Consuming sku: " + sku + ", token: " + token); int response = mService.consumePurchase(3, mContext.getPackageName(), token); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Successfully consumed sku: " + sku); } else { logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response)); throw new IabException(response, "Error consuming sku " + sku); } } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e); } } /** * Callback that notifies when a consumption operation finishes. */ public interface OnConsumeFinishedListener { /** * Called to notify that a consumption has finished. * * @param purchase The purchase that was (or was to be) consumed. * @param result The result of the consumption operation. */ public void onConsumeFinished(Purchase purchase, IabResult result); } /** * Callback that notifies when a multi-item consumption operation finishes. */ public interface OnConsumeMultiFinishedListener { /** * Called to notify that a consumption of multiple items has finished. * * @param purchases The purchases that were (or were to be) consumed. * @param results The results of each consumption operation, corresponding to each * sku. */ public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results); } /** * Asynchronous wrapper to item consumption. Works like {@link #consume}, but * performs the consumption in the background and notifies completion through * the provided listener. This method is safe to call from a UI thread. * * @param purchase The purchase to be consumed. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); List<Purchase> purchases = new ArrayList<Purchase>(); purchases.add(purchase); consumeAsyncInternal(purchases, listener, null); } /** * Same as {@link consumeAsync}, but for multiple items at once. * @param purchases The list of PurchaseInfo objects representing the purchases to consume. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); consumeAsyncInternal(purchases, null, listener); } /** * Returns a human-readable description for the given response code. * * @param code The response code * @return A human-readable string explaining the result code. * It also includes the result code numerically. */ public static String getResponseDesc(int code) { String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + "3:Billing Unavailable/4:Item unavailable/" + "5:Developer Error/6:Error/7:Item Already Owned/" + "8:Item not owned").split("/"); String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + "-1002:Bad response received/" + "-1003:Purchase signature verification failed/" + "-1004:Send intent failed/" + "-1005:User cancelled/" + "-1006:Unknown purchase response/" + "-1007:Missing token/" + "-1008:Unknown error/" + "-1009:Subscriptions not available/" + "-1010:Invalid consumption attempt").split("/"); if (code <= IABHELPER_ERROR_BASE) { int index = IABHELPER_ERROR_BASE - code; if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; else return String.valueOf(code) + ":Unknown IAB Helper Error"; } else if (code < 0 || code >= iab_msgs.length) return String.valueOf(code) + ":Unknown"; else return iab_msgs[code]; } // Checks that setup was done; if not, throws an exception. void checkSetupDone(String operation) { if (!mSetupDone) { logError("Illegal state for operation (" + operation + "): IAB helper is not set up."); throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromBundle(Bundle b) { Object o = b.get(RESPONSE_CODE); if (o == null) { logDebug("Bundle with null response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for bundle response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName()); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromIntent(Intent i) { Object o = i.getExtras().get(RESPONSE_CODE); if (o == null) { logError("Intent with no response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for intent response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName()); } } void flagStartAsync(String operation) { if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" + operation + ") because another async operation(" + mAsyncOperation + ") is in progress."); mAsyncOperation = operation; mAsyncInProgress = true; logDebug("Starting async operation: " + operation); } void flagEndAsync() { logDebug("Ending async operation: " + mAsyncOperation); mAsyncOperation = ""; mAsyncInProgress = false; } int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException { // Query purchases logDebug("Querying owned items, item type: " + itemType); logDebug("Package name: " + mContext.getPackageName()); boolean verificationFailed = false; String continueToken = null; do { logDebug("Calling getPurchases with continuation token: " + continueToken); Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken); int response = getResponseCodeFromBundle(ownedItems); logDebug("Owned items response: " + String.valueOf(response)); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getPurchases() failed: " + getResponseDesc(response)); return response; } if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) { logError("Bundle returned from getPurchases() doesn't contain required fields."); return IABHELPER_BAD_RESPONSE; } ArrayList<String> ownedSkus = ownedItems.getStringArrayList( RESPONSE_INAPP_ITEM_LIST); ArrayList<String> purchaseDataList = ownedItems.getStringArrayList( RESPONSE_INAPP_PURCHASE_DATA_LIST); ArrayList<String> signatureList = ownedItems.getStringArrayList( RESPONSE_INAPP_SIGNATURE_LIST); for (int i = 0; i < purchaseDataList.size(); ++i) { String purchaseData = purchaseDataList.get(i); String signature = signatureList.get(i); String sku = ownedSkus.get(i); if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) { logDebug("Sku is owned: " + sku); Purchase purchase = new Purchase(itemType, purchaseData, signature); if (TextUtils.isEmpty(purchase.getToken())) { logWarn("BUG: empty/null token!"); logDebug("Purchase data: " + purchaseData); } // Record ownership and token inv.addPurchase(purchase); } else { logWarn("Purchase signature verification **FAILED**. Not adding item."); logDebug(" Purchase data: " + purchaseData); logDebug(" Signature: " + signature); verificationFailed = true; } } continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN); logDebug("Continuation token: " + continueToken); } while (!TextUtils.isEmpty(continueToken)); return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK; } int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException { logDebug("Querying SKU details."); ArrayList<String> skuList = new ArrayList<String>(); skuList.addAll(inv.getAllOwnedSkus(itemType)); if (moreSkus != null) { for (String sku : moreSkus) { if (!skuList.contains(sku)) { skuList.add(sku); } } } if (skuList.size() == 0) { logDebug("queryPrices: nothing to do because there are no SKUs."); return BILLING_RESPONSE_RESULT_OK; } Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getSkuDetails() failed: " + getResponseDesc(response)); return response; } else { logError("getSkuDetails() returned a bundle with neither an error nor a detail list."); return IABHELPER_BAD_RESPONSE; } } ArrayList<String> responseList = skuDetails.getStringArrayList( RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); logDebug("Got sku details: " + d); inv.addSkuDetails(d); } return BILLING_RESPONSE_RESULT_OK; } void consumeAsyncInternal(final List<Purchase> purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) { final Handler handler = new Handler(); flagStartAsync("consume"); (new Thread(new Runnable() { public void run() { final List<IabResult> results = new ArrayList<IabResult>(); for (Purchase purchase : purchases) { try { consume(purchase); results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku())); } catch (IabException ex) { results.add(ex.getResult()); } } flagEndAsync(); if (!mDisposed && singleListener != null) { handler.post(new Runnable() { public void run() { singleListener.onConsumeFinished(purchases.get(0), results.get(0)); } }); } if (!mDisposed && multiListener != null) { handler.post(new Runnable() { public void run() { multiListener.onConsumeMultiFinished(purchases, results); } }); } } })).start(); } void logDebug(String msg) { if (mDebugLog) Log.d(mDebugTag, msg); } void logError(String msg) { Log.e(mDebugTag, "In-app billing error: " + msg); } void logWarn(String msg) { Log.w(mDebugTag, "In-app billing warning: " + msg); } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a block of information about in-app items. * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. */ public class Inventory { Map<String,SkuDetails> mSkuMap = new HashMap<String,SkuDetails>(); Map<String,Purchase> mPurchaseMap = new HashMap<String,Purchase>(); Inventory() { } /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails(String sku) { return mSkuMap.get(sku); } /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase(String sku) { return mPurchaseMap.get(sku); } /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase(String sku) { return mPurchaseMap.containsKey(sku); } /** Return whether or not details about the given product are available. */ public boolean hasDetails(String sku) { return mSkuMap.containsKey(sku); } /** * Erase a purchase (locally) from the inventory, given its product ID. This just * modifies the Inventory object locally and has no effect on the server! This is * useful when you have an existing Inventory object which you know to be up to date, * and you have just consumed an item successfully, which means that erasing its * purchase data from the Inventory you already have is quicker than querying for * a new Inventory. */ public void erasePurchase(String sku) { if (mPurchaseMap.containsKey(sku)) mPurchaseMap.remove(sku); } /** Returns a list of all owned product IDs. */ List<String> getAllOwnedSkus() { return new ArrayList<String>(mPurchaseMap.keySet()); } /** Returns a list of all owned product IDs of a given type */ List<String> getAllOwnedSkus(String itemType) { List<String> result = new ArrayList<String>(); for (Purchase p : mPurchaseMap.values()) { if (p.getItemType().equals(itemType)) result.add(p.getSku()); } return result; } /** Returns a list of all purchases. */ List<Purchase> getAllPurchases() { return new ArrayList<Purchase>(mPurchaseMap.values()); } void addSkuDetails(SkuDetails d) { mSkuMap.put(d.getSku(), d); } void addPurchase(Purchase p) { mPurchaseMap.put(p.getSku(), p); } }
Java
/* Copyright (c) 2012 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.example.android.trivialdrivesample; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.example.android.trivialdrivesample.util.IabHelper; import com.example.android.trivialdrivesample.util.IabResult; import com.example.android.trivialdrivesample.util.Inventory; import com.example.android.trivialdrivesample.util.Purchase; /** * Example game using in-app billing version 3. * * Before attempting to run this sample, please read the README file. It * contains important information on how to set up this project. * * All the game-specific logic is implemented here in MainActivity, while the * general-purpose boilerplate that can be reused in any app is provided in the * classes in the util/ subdirectory. When implementing your own application, * you can copy over util/*.java to make use of those utility classes. * * This game is a simple "driving" game where the player can buy gas * and drive. The car has a tank which stores gas. When the player purchases * gas, the tank fills up (1/4 tank at a time). When the player drives, the gas * in the tank diminishes (also 1/4 tank at a time). * * The user can also purchase a "premium upgrade" that gives them a red car * instead of the standard blue one (exciting!). * * The user can also purchase a subscription ("infinite gas") that allows them * to drive without using up any gas while that subscription is active. * * It's important to note the consumption mechanics for each item. * * PREMIUM: the item is purchased and NEVER consumed. So, after the original * purchase, the player will always own that item. The application knows to * display the red car instead of the blue one because it queries whether * the premium "item" is owned or not. * * INFINITE GAS: this is a subscription, and subscriptions can't be consumed. * * GAS: when gas is purchased, the "gas" item is then owned. We consume it * when we apply that item's effects to our app's world, which to us means * filling up 1/4 of the tank. This happens immediately after purchase! * It's at this point (and not when the user drives) that the "gas" * item is CONSUMED. Consumption should always happen when your game * world was safely updated to apply the effect of the purchase. So, * in an example scenario: * * BEFORE: tank at 1/2 * ON PURCHASE: tank at 1/2, "gas" item is owned * IMMEDIATELY: "gas" is consumed, tank goes to 3/4 * AFTER: tank at 3/4, "gas" item NOT owned any more * * Another important point to notice is that it may so happen that * the application crashed (or anything else happened) after the user * purchased the "gas" item, but before it was consumed. That's why, * on startup, we check if we own the "gas" item, and, if so, * we have to apply its effects to our world and consume it. This * is also very important! * * @author Bruno Oliveira (Google) */ public class MainActivity extends Activity { // Debug tag, for logging static final String TAG = "TrivialDrive"; // Does the user have the premium upgrade? boolean mIsPremium = false; // Does the user have an active subscription to the infinite gas plan? boolean mSubscribedToInfiniteGas = false; // SKUs for our products: the premium upgrade (non-consumable) and gas (consumable) static final String SKU_PREMIUM = "premium"; static final String SKU_GAS = "gas"; // SKU for our subscription (infinite gas) static final String SKU_INFINITE_GAS = "infinite_gas"; // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 10001; // Graphics for the gas gauge static int[] TANK_RES_IDS = { R.drawable.gas0, R.drawable.gas1, R.drawable.gas2, R.drawable.gas3, R.drawable.gas4 }; // How many units (1/4 tank is our unit) fill in the tank. static final int TANK_MAX = 4; // Current amount of gas in tank, in units int mTank; // The helper object IabHelper mHelper; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // load game data loadData(); /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this sample (don't put these checks on your app!) if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in MainActivity.java. See README."); } if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } // Create the helper, passing it our context and the public key to verify signatures with Log.d(TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set this to false). mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) return; // IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } }); } // Listener that's called when we finish querying the items and subscriptions we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) return; // Is it a failure? if (result.isFailure()) { complain("Failed to query inventory: " + result); return; } Log.d(TAG, "Query inventory was successful."); /* * Check for items we own. Notice that for each purchase, we check * the developer payload to see if it's correct! See * verifyDeveloperPayload(). */ // Do we have the premium upgrade? Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); // Do we have the infinite gas plan? Purchase infiniteGasPurchase = inventory.getPurchase(SKU_INFINITE_GAS); mSubscribedToInfiniteGas = (infiniteGasPurchase != null && verifyDeveloperPayload(infiniteGasPurchase)); Log.d(TAG, "User " + (mSubscribedToInfiniteGas ? "HAS" : "DOES NOT HAVE") + " infinite gas subscription."); if (mSubscribedToInfiniteGas) mTank = TANK_MAX; // Check for gas delivery -- if we own gas, we should fill up the tank immediately Purchase gasPurchase = inventory.getPurchase(SKU_GAS); if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) { Log.d(TAG, "We have gas. Consuming it."); mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), mConsumeFinishedListener); return; } updateUi(); setWaitScreen(false); Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; // User clicked the "Buy Gas" button public void onBuyGasButtonClicked(View arg0) { Log.d(TAG, "Buy gas button clicked."); if (mSubscribedToInfiniteGas) { complain("No need! You're subscribed to infinite gas. Isn't that awesome?"); return; } if (mTank >= TANK_MAX) { complain("Your tank is full. Drive around a bit!"); return; } // launch the gas purchase UI flow. // We will be notified of completion via mPurchaseFinishedListener setWaitScreen(true); Log.d(TAG, "Launching purchase flow for gas."); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_GAS, RC_REQUEST, mPurchaseFinishedListener, payload); } // User clicked the "Upgrade to Premium" button. public void onUpgradeAppButtonClicked(View arg0) { Log.d(TAG, "Upgrade button clicked; launching purchase flow for upgrade."); setWaitScreen(true); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, payload); } // "Subscribe to infinite gas" button clicked. Explain to user, then start purchase // flow for subscription. public void onInfiniteGasButtonClicked(View arg0) { if (!mHelper.subscriptionsSupported()) { complain("Subscriptions not supported on your device yet. Sorry!"); return; } /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; setWaitScreen(true); Log.d(TAG, "Launching purchase flow for infinite gas subscription."); mHelper.launchPurchaseFlow(this, SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS, RC_REQUEST, mPurchaseFinishedListener, payload); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); if (mHelper == null) return; // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Log.d(TAG, "onActivityResult handled by IABUtil."); } } /** Verifies the developer payload of a purchase. */ boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. It will be * the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase and * verifying it here might seem like a good approach, but this will fail in the * case where the user purchases an item on one device and then uses your app on * a different device, because on the other device you will not have access to the * random string you originally generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different between them, * so that one user's purchase can't be replayed to another user. * * 2. The payload must be such that you can verify it even when the app wasn't the * one who initiated the purchase flow (so that items purchased by the user on * one device work on other devices owned by the user). * * Using your own server to store and verify developer payloads across app * installations is recommended. */ return true; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase); // if we were disposed of in the meantime, quit. if (mHelper == null) return; if (result.isFailure()) { complain("Error purchasing: " + result); setWaitScreen(false); return; } if (!verifyDeveloperPayload(purchase)) { complain("Error purchasing. Authenticity verification failed."); setWaitScreen(false); return; } Log.d(TAG, "Purchase successful."); if (purchase.getSku().equals(SKU_GAS)) { // bought 1/4 tank of gas. So consume it. Log.d(TAG, "Purchase is gas. Starting gas consumption."); mHelper.consumeAsync(purchase, mConsumeFinishedListener); } else if (purchase.getSku().equals(SKU_PREMIUM)) { // bought the premium upgrade! Log.d(TAG, "Purchase is premium upgrade. Congratulating user."); alert("Thank you for upgrading to premium!"); mIsPremium = true; updateUi(); setWaitScreen(false); } else if (purchase.getSku().equals(SKU_INFINITE_GAS)) { // bought the infinite gas subscription Log.d(TAG, "Infinite gas subscription purchased."); alert("Thank you for subscribing to infinite gas!"); mSubscribedToInfiniteGas = true; mTank = TANK_MAX; updateUi(); setWaitScreen(false); } } }; // Called when consumption is complete IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result); // if we were disposed of in the meantime, quit. if (mHelper == null) return; // We know this is the "gas" sku because it's the only one we consume, // so we don't check which sku was consumed. If you have more than one // sku, you probably should check... if (result.isSuccess()) { // successfully consumed, so we apply the effects of the item in our // game world's logic, which in our case means filling the gas tank a bit Log.d(TAG, "Consumption successful. Provisioning."); mTank = mTank == TANK_MAX ? TANK_MAX : mTank + 1; saveData(); alert("You filled 1/4 tank. Your tank is now " + String.valueOf(mTank) + "/4 full!"); } else { complain("Error while consuming: " + result); } updateUi(); setWaitScreen(false); Log.d(TAG, "End consumption flow."); } }; // Drive button clicked. Burn gas! public void onDriveButtonClicked(View arg0) { Log.d(TAG, "Drive button clicked."); if (!mSubscribedToInfiniteGas && mTank <= 0) alert("Oh, no! You are out of gas! Try buying some!"); else { if (!mSubscribedToInfiniteGas) --mTank; saveData(); alert("Vroooom, you drove a few miles."); updateUi(); Log.d(TAG, "Vrooom. Tank is now " + mTank); } } // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Log.d(TAG, "Destroying helper."); if (mHelper != null) { mHelper.dispose(); mHelper = null; } } // updates UI to reflect model public void updateUi() { // update the car color to reflect premium status or lack thereof ((ImageView)findViewById(R.id.free_or_premium)).setImageResource(mIsPremium ? R.drawable.premium : R.drawable.free); // "Upgrade" button is only visible if the user is not premium findViewById(R.id.upgrade_button).setVisibility(mIsPremium ? View.GONE : View.VISIBLE); // "Get infinite gas" button is only visible if the user is not subscribed yet findViewById(R.id.infinite_gas_button).setVisibility(mSubscribedToInfiniteGas ? View.GONE : View.VISIBLE); // update gas gauge to reflect tank status if (mSubscribedToInfiniteGas) { ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(R.drawable.gas_inf); } else { int index = mTank >= TANK_RES_IDS.length ? TANK_RES_IDS.length - 1 : mTank; ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(TANK_RES_IDS[index]); } } // Enables or disables the "please wait" screen. void setWaitScreen(boolean set) { findViewById(R.id.screen_main).setVisibility(set ? View.GONE : View.VISIBLE); findViewById(R.id.screen_wait).setVisibility(set ? View.VISIBLE : View.GONE); } void complain(String message) { Log.e(TAG, "**** TrivialDrive Error: " + message); alert("Error: " + message); } void alert(String message) { AlertDialog.Builder bld = new AlertDialog.Builder(this); bld.setMessage(message); bld.setNeutralButton("OK", null); Log.d(TAG, "Showing alert dialog: " + message); bld.create().show(); } void saveData() { /* * WARNING: on a real application, we recommend you save data in a secure way to * prevent tampering. For simplicity in this sample, we simply store the data using a * SharedPreferences. */ SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit(); spe.putInt("tank", mTank); spe.commit(); Log.d(TAG, "Saved data: tank = " + String.valueOf(mTank)); } void loadData() { SharedPreferences sp = getPreferences(MODE_PRIVATE); mTank = sp.getInt("tank", 2); Log.d(TAG, "Loaded data: tank = " + String.valueOf(mTank)); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; /** * This class holds global constants that are used throughout the application * to support in-app billing. */ public class Consts { // The response codes for a request, defined by Android Market. public enum ResponseCode { RESULT_OK, RESULT_USER_CANCELED, RESULT_SERVICE_UNAVAILABLE, RESULT_BILLING_UNAVAILABLE, RESULT_ITEM_UNAVAILABLE, RESULT_DEVELOPER_ERROR, RESULT_ERROR; // Converts from an ordinal value to the ResponseCode public static ResponseCode valueOf(int index) { ResponseCode[] values = ResponseCode.values(); if (index < 0 || index >= values.length) { return RESULT_ERROR; } return values[index]; } } // The possible states of an in-app purchase, as defined by Android Market. public enum PurchaseState { // Responses to requestPurchase or restoreTransactions. PURCHASED, // User was charged for the order. CANCELED, // The charge failed on the server. REFUNDED; // User received a refund for the order. // Converts from an ordinal value to the PurchaseState public static PurchaseState valueOf(int index) { PurchaseState[] values = PurchaseState.values(); if (index < 0 || index >= values.length) { return CANCELED; } return values[index]; } } /** This is the action we use to bind to the MarketBillingService. */ public static final String MARKET_BILLING_SERVICE_ACTION = "com.android.vending.billing.MarketBillingService.BIND"; // Intent actions that we send from the BillingReceiver to the // BillingService. Defined by this application. public static final String ACTION_CONFIRM_NOTIFICATION = "com.example.dungeons.CONFIRM_NOTIFICATION"; public static final String ACTION_GET_PURCHASE_INFORMATION = "com.example.dungeons.GET_PURCHASE_INFORMATION"; public static final String ACTION_RESTORE_TRANSACTIONS = "com.example.dungeons.RESTORE_TRANSACTIONS"; // Intent actions that we receive in the BillingReceiver from Market. // These are defined by Market and cannot be changed. public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY"; public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE"; public static final String ACTION_PURCHASE_STATE_CHANGED = "com.android.vending.billing.PURCHASE_STATE_CHANGED"; // These are the names of the extras that are passed in an intent from // Market to this application and cannot be changed. public static final String NOTIFICATION_ID = "notification_id"; public static final String INAPP_SIGNED_DATA = "inapp_signed_data"; public static final String INAPP_SIGNATURE = "inapp_signature"; public static final String INAPP_REQUEST_ID = "request_id"; public static final String INAPP_RESPONSE_CODE = "response_code"; // These are the names of the fields in the request bundle. public static final String BILLING_REQUEST_METHOD = "BILLING_REQUEST"; public static final String BILLING_REQUEST_API_VERSION = "API_VERSION"; public static final String BILLING_REQUEST_PACKAGE_NAME = "PACKAGE_NAME"; public static final String BILLING_REQUEST_ITEM_ID = "ITEM_ID"; public static final String BILLING_REQUEST_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD"; public static final String BILLING_REQUEST_NOTIFY_IDS = "NOTIFY_IDS"; public static final String BILLING_REQUEST_NONCE = "NONCE"; public static final String BILLING_RESPONSE_RESPONSE_CODE = "RESPONSE_CODE"; public static final String BILLING_RESPONSE_PURCHASE_INTENT = "PURCHASE_INTENT"; public static final String BILLING_RESPONSE_REQUEST_ID = "REQUEST_ID"; public static long BILLING_RESPONSE_INVALID_REQUEST_ID = -1; public static final boolean DEBUG = false; }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; import com.android.vending.billing.IMarketBillingService; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import com.example.dungeons.Security.VerifiedPurchase; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; /** * This class sends messages to Android Market on behalf of the application by * connecting (binding) to the MarketBillingService. The application * creates an instance of this class and invokes billing requests through this service. * * The {@link BillingReceiver} class starts this service to process commands * that it receives from Android Market. * * You should modify and obfuscate this code before using it. */ public class BillingService extends Service implements ServiceConnection { private static final String TAG = "BillingService"; /** The service connection to the remote MarketBillingService. */ private static IMarketBillingService mService; /** * The list of requests that are pending while we are waiting for the * connection to the MarketBillingService to be established. */ private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<BillingRequest>(); /** * The list of requests that we have sent to Android Market but for which we have * not yet received a response code. The HashMap is indexed by the * request Id that each request receives when it executes. */ private static HashMap<Long, BillingRequest> mSentRequests = new HashMap<Long, BillingRequest>(); /** * The base class for all requests that use the MarketBillingService. * Each derived class overrides the run() method to call the appropriate * service interface. If we are already connected to the MarketBillingService, * then we call the run() method directly. Otherwise, we bind * to the service and save the request on a queue to be run later when * the service is connected. */ abstract class BillingRequest { private final int mStartId; protected long mRequestId; public BillingRequest(int startId) { mStartId = startId; } public int getStartId() { return mStartId; } /** * Run the request, starting the connection if necessary. * @return true if the request was executed or queued; false if there * was an error starting the connection */ public boolean runRequest() { if (runIfConnected()) { return true; } if (bindToMarketBillingService()) { // Add a pending request to run when the service is connected. mPendingRequests.add(this); return true; } return false; } /** * Try running the request directly if the service is already connected. * @return true if the request ran successfully; false if the service * is not connected or there was an error when trying to use it */ public boolean runIfConnected() { if (Consts.DEBUG) { Log.d(TAG, getClass().getSimpleName()); } if (mService != null) { try { mRequestId = run(); if (Consts.DEBUG) { Log.d(TAG, "request id: " + mRequestId); } if (mRequestId >= 0) { mSentRequests.put(mRequestId, this); } return true; } catch (RemoteException e) { onRemoteException(e); } } return false; } /** * Called when a remote exception occurs while trying to execute the * {@link #run()} method. The derived class can override this to * execute exception-handling code. * @param e the exception */ protected void onRemoteException(RemoteException e) { Log.w(TAG, "remote billing service crashed"); mService = null; } /** * The derived class must implement this method. * @throws RemoteException */ abstract protected long run() throws RemoteException; /** * This is called when Android Market sends a response code for this * request. * @param responseCode the response code */ protected void responseCodeReceived(ResponseCode responseCode) { } protected Bundle makeRequestBundle(String method) { Bundle request = new Bundle(); request.putString(Consts.BILLING_REQUEST_METHOD, method); request.putInt(Consts.BILLING_REQUEST_API_VERSION, 1); request.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, getPackageName()); return request; } protected void logResponseCode(String method, Bundle response) { ResponseCode responseCode = ResponseCode.valueOf( response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE)); if (Consts.DEBUG) { Log.e(TAG, method + " received " + responseCode.toString()); } } } /** * Wrapper class that checks if in-app billing is supported. */ class CheckBillingSupported extends BillingRequest { public CheckBillingSupported() { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED"); Bundle response = mService.sendBillingRequest(request); int responseCode = response.containsKey(Consts.BILLING_RESPONSE_RESPONSE_CODE) ? response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE) : ResponseCode.RESULT_BILLING_UNAVAILABLE.ordinal(); if (Consts.DEBUG) { Log.i(TAG, "CheckBillingSupported response code: " + ResponseCode.valueOf(responseCode)); } boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal()); ResponseHandler.checkBillingSupportedResponse(billingSupported); return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID; } } /** * Wrapper class that requests a purchase. */ class RequestPurchase extends BillingRequest { public final String mProductId; public final String mDeveloperPayload; public RequestPurchase(String itemId) { this(itemId, null); } public RequestPurchase(String itemId, String developerPayload) { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); mProductId = itemId; mDeveloperPayload = developerPayload; } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("REQUEST_PURCHASE"); request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId); // Note that the developer payload is optional. if (mDeveloperPayload != null) { request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload); } Bundle response = mService.sendBillingRequest(request); PendingIntent pendingIntent = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT); if (pendingIntent == null) { Log.e(TAG, "Error with requestPurchase"); return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID; } Intent intent = new Intent(); ResponseHandler.buyPageIntentResponse(pendingIntent, intent); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void responseCodeReceived(ResponseCode responseCode) { ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode); } } /** * Wrapper class that confirms a list of notifications to the server. */ class ConfirmNotifications extends BillingRequest { final String[] mNotifyIds; public ConfirmNotifications(int startId, String[] notifyIds) { super(startId); mNotifyIds = notifyIds; } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS"); request.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, mNotifyIds); Bundle response = mService.sendBillingRequest(request); logResponseCode("confirmNotifications", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } } /** * Wrapper class that sends a GET_PURCHASE_INFORMATION message to the server. */ class GetPurchaseInformation extends BillingRequest { long mNonce; final String[] mNotifyIds; public GetPurchaseInformation(int startId, String[] notifyIds) { super(startId); mNotifyIds = notifyIds; } @Override protected long run() throws RemoteException { mNonce = Security.generateNonce(); Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION"); request.putLong(Consts.BILLING_REQUEST_NONCE, mNonce); request.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, mNotifyIds); Bundle response = mService.sendBillingRequest(request); logResponseCode("getPurchaseInformation", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void onRemoteException(RemoteException e) { super.onRemoteException(e); Security.removeNonce(mNonce); } } /** * Wrapper class that sends a RESTORE_TRANSACTIONS message to the server. */ class RestoreTransactions extends BillingRequest { long mNonce; public RestoreTransactions() { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); } @Override protected long run() throws RemoteException { mNonce = Security.generateNonce(); Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS"); request.putLong(Consts.BILLING_REQUEST_NONCE, mNonce); Bundle response = mService.sendBillingRequest(request); logResponseCode("restoreTransactions", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void onRemoteException(RemoteException e) { super.onRemoteException(e); Security.removeNonce(mNonce); } @Override protected void responseCodeReceived(ResponseCode responseCode) { ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode); } } public BillingService() { super(); } public void setContext(Context context) { attachBaseContext(context); } /** * We don't support binding to this service, only starting the service. */ @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { handleCommand(intent, startId); } // Overrides onStartCommand for people who build on SDK versions > 4. // Override annotation is commented out as the method does not always exist. // @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { stopSelfResult(startId); return; } handleCommand(intent, startId); return 0; // Service.START_STICKY_COMPATIBILITY } /** * The {@link BillingReceiver} sends messages to this service using intents. * Each intent has an action and some extra arguments specific to that action. * @param intent the intent containing one of the supported actions * @param startId an identifier for the invocation instance of this service */ public void handleCommand(Intent intent, int startId) { String action = intent.getAction(); if (Consts.DEBUG) { Log.i(TAG, "handleCommand() action: " + action); } if (Consts.ACTION_CONFIRM_NOTIFICATION.equals(action)) { String[] notifyIds = intent.getStringArrayExtra(Consts.NOTIFICATION_ID); confirmNotifications(startId, notifyIds); } else if (Consts.ACTION_GET_PURCHASE_INFORMATION.equals(action)) { String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID); getPurchaseInformation(startId, new String[] { notifyId }); } else if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) { String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA); String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE); purchaseStateChanged(startId, signedData, signature); } else if (Consts.ACTION_RESPONSE_CODE.equals(action)) { long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1); int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, ResponseCode.RESULT_ERROR.ordinal()); ResponseCode responseCode = ResponseCode.valueOf(responseCodeIndex); checkResponseCode(requestId, responseCode); } } /** * Binds to the MarketBillingService and returns true if the bind * succeeded. * @return true if the bind succeeded; false otherwise */ private boolean bindToMarketBillingService() { try { if (Consts.DEBUG) { Log.i(TAG, "binding to Market billing service"); } boolean bindResult = bindService( new Intent(Consts.MARKET_BILLING_SERVICE_ACTION), this, // ServiceConnection. Context.BIND_AUTO_CREATE); if (bindResult) { return true; } else { Log.e(TAG, "Could not bind to service."); } } catch (SecurityException e) { Log.e(TAG, "Security exception: " + e); } return false; } /** * Checks if in-app billing is supported. The result is asynchronously returned to the * application via ResponseHandler.checkBillingSupported. * @return false if there was an error connecting to Android Market */ public boolean checkBillingSupported() { return new CheckBillingSupported().runRequest(); } /** * Requests that the given item be offered to the user for purchase. When * the purchase succeeds (or is canceled) the {@link BillingReceiver} * receives an intent with the action {@link Consts#ACTION_NOTIFY}. * Returns false if there was an error trying to connect to Android Market. * @param productId an identifier for the item being offered for purchase * @param developerPayload a payload that is associated with a given * purchase, if null, no payload is sent * @return false if there was an error connecting to Android Market */ public boolean requestPurchase(String productId, String developerPayload) { return new RequestPurchase(productId, developerPayload).runRequest(); } /** * Requests transaction information for all managed items. Call this only when the * application is first installed or after a database wipe. Do NOT call this * every time the application starts up. * @return false if there was an error connecting to Android Market */ public boolean restoreTransactions() { return new RestoreTransactions().runRequest(); } /** * Confirms receipt of a purchase state change. Each {@code notifyId} is * an opaque identifier that came from the server. This method sends those * identifiers back to the MarketBillingService, which ACKs them to the * server. Returns false if there was an error trying to connect to the * MarketBillingService. * @param startId an identifier for the invocation instance of this service * @param notifyIds a list of opaque identifiers associated with purchase * state changes. * @return false if there was an error connecting to Market */ private boolean confirmNotifications(int startId, String[] notifyIds) { return new ConfirmNotifications(startId, notifyIds).runRequest(); } /** * Gets the purchase information. This message includes a list of * notification IDs sent to us by Android Market, which we include in * our request. The server responds with the purchase information, * encoded as a JSON string, and sends that to the {@link BillingReceiver} * in an intent with the action {@link Consts#ACTION_PURCHASE_STATE_CHANGED}. * Returns false if there was an error trying to connect to the MarketBillingService. * * @param startId an identifier for the invocation instance of this service * @param notifyIds a list of opaque identifiers associated with purchase * state changes * @return false if there was an error connecting to Android Market */ private boolean getPurchaseInformation(int startId, String[] notifyIds) { return new GetPurchaseInformation(startId, notifyIds).runRequest(); } /** * Verifies that the data was signed with the given signature, and calls * {@link ResponseHandler#purchaseResponse(Context, PurchaseState, String, String, long)} * for each verified purchase. * @param startId an identifier for the invocation instance of this service * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ private void purchaseStateChanged(int startId, String signedData, String signature) { ArrayList<Security.VerifiedPurchase> purchases; purchases = Security.verifyPurchase(signedData, signature); if (purchases == null) { return; } ArrayList<String> notifyList = new ArrayList<String>(); for (VerifiedPurchase vp : purchases) { if (vp.notificationId != null) { notifyList.add(vp.notificationId); } ResponseHandler.purchaseResponse(this, vp.purchaseState, vp.productId, vp.orderId, vp.purchaseTime, vp.developerPayload); } if (!notifyList.isEmpty()) { String[] notifyIds = notifyList.toArray(new String[notifyList.size()]); confirmNotifications(startId, notifyIds); } } /** * This is called when we receive a response code from Android Market for a request * that we made. This is used for reporting various errors and for * acknowledging that an order was sent to the server. This is NOT used * for any purchase state changes. All purchase state changes are received * in the {@link BillingReceiver} and passed to this service, where they are * handled in {@link #purchaseStateChanged(int, String, String)}. * @param requestId a number that identifies a request, assigned at the * time the request was made to Android Market * @param responseCode a response code from Android Market to indicate the state * of the request */ private void checkResponseCode(long requestId, ResponseCode responseCode) { BillingRequest request = mSentRequests.get(requestId); if (request != null) { if (Consts.DEBUG) { Log.d(TAG, request.getClass().getSimpleName() + ": " + responseCode); } request.responseCodeReceived(responseCode); } mSentRequests.remove(requestId); } /** * Runs any pending requests that are waiting for a connection to the * service to be established. This runs in the main UI thread. */ private void runPendingRequests() { int maxStartId = -1; BillingRequest request; while ((request = mPendingRequests.peek()) != null) { if (request.runIfConnected()) { // Remove the request mPendingRequests.remove(); // Remember the largest startId, which is the most recent // request to start this service. if (maxStartId < request.getStartId()) { maxStartId = request.getStartId(); } } else { // The service crashed, so restart it. Note that this leaves // the current request on the queue. bindToMarketBillingService(); return; } } // If we get here then all the requests ran successfully. If maxStartId // is not -1, then one of the requests started the service, so we can // stop it now. if (maxStartId >= 0) { if (Consts.DEBUG) { Log.i(TAG, "stopping service, startId: " + maxStartId); } stopSelf(maxStartId); } } /** * This is called when we are connected to the MarketBillingService. * This runs in the main UI thread. */ public void onServiceConnected(ComponentName name, IBinder service) { if (Consts.DEBUG) { Log.d(TAG, "Billing service connected"); } mService = IMarketBillingService.Stub.asInterface(service); runPendingRequests(); } /** * This is called when we are disconnected from the MarketBillingService. */ public void onServiceDisconnected(ComponentName name) { Log.w(TAG, "Billing service disconnected"); mService = null; } /** * Unbinds from the MarketBillingService. Call this when the application * terminates to avoid leaking a ServiceConnection. */ public void unbind() { try { unbindService(this); } catch (IllegalArgumentException e) { // This might happen if the service was disconnected } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.Consts.PurchaseState; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * An example database that records the state of each purchase. You should use * an obfuscator before storing any information to persistent storage. The * obfuscator should use a key that is specific to the device and/or user. * Otherwise an attacker could copy a database full of valid purchases and * distribute it to others. */ public class PurchaseDatabase { private static final String TAG = "PurchaseDatabase"; private static final String DATABASE_NAME = "purchase.db"; private static final int DATABASE_VERSION = 1; private static final String PURCHASE_HISTORY_TABLE_NAME = "history"; private static final String PURCHASED_ITEMS_TABLE_NAME = "purchased"; // These are the column names for the purchase history table. We need a // column named "_id" if we want to use a CursorAdapter. The primary key is // the orderId so that we can be robust against getting multiple messages // from the server for the same purchase. static final String HISTORY_ORDER_ID_COL = "_id"; static final String HISTORY_STATE_COL = "state"; static final String HISTORY_PRODUCT_ID_COL = "productId"; static final String HISTORY_PURCHASE_TIME_COL = "purchaseTime"; static final String HISTORY_DEVELOPER_PAYLOAD_COL = "developerPayload"; private static final String[] HISTORY_COLUMNS = { HISTORY_ORDER_ID_COL, HISTORY_PRODUCT_ID_COL, HISTORY_STATE_COL, HISTORY_PURCHASE_TIME_COL, HISTORY_DEVELOPER_PAYLOAD_COL }; // These are the column names for the "purchased items" table. static final String PURCHASED_PRODUCT_ID_COL = "_id"; static final String PURCHASED_QUANTITY_COL = "quantity"; private static final String[] PURCHASED_COLUMNS = { PURCHASED_PRODUCT_ID_COL, PURCHASED_QUANTITY_COL }; private SQLiteDatabase mDb; private DatabaseHelper mDatabaseHelper; public PurchaseDatabase(Context context) { mDatabaseHelper = new DatabaseHelper(context); mDb = mDatabaseHelper.getWritableDatabase(); } public void close() { mDatabaseHelper.close(); } /** * Inserts a purchased product into the database. There may be multiple * rows in the table for the same product if it was purchased multiple times * or if it was refunded. * @param orderId the order ID (matches the value in the product list) * @param productId the product ID (sku) * @param state the state of the purchase * @param purchaseTime the purchase time (in milliseconds since the epoch) * @param developerPayload the developer provided "payload" associated with * the order. */ private void insertOrder(String orderId, String productId, PurchaseState state, long purchaseTime, String developerPayload) { ContentValues values = new ContentValues(); values.put(HISTORY_ORDER_ID_COL, orderId); values.put(HISTORY_PRODUCT_ID_COL, productId); values.put(HISTORY_STATE_COL, state.ordinal()); values.put(HISTORY_PURCHASE_TIME_COL, purchaseTime); values.put(HISTORY_DEVELOPER_PAYLOAD_COL, developerPayload); mDb.replace(PURCHASE_HISTORY_TABLE_NAME, null /* nullColumnHack */, values); } /** * Updates the quantity of the given product to the given value. If the * given value is zero, then the product is removed from the table. * @param productId the product to update * @param quantity the number of times the product has been purchased */ private void updatePurchasedItem(String productId, int quantity) { if (quantity == 0) { mDb.delete(PURCHASED_ITEMS_TABLE_NAME, PURCHASED_PRODUCT_ID_COL + "=?", new String[] { productId }); return; } ContentValues values = new ContentValues(); values.put(PURCHASED_PRODUCT_ID_COL, productId); values.put(PURCHASED_QUANTITY_COL, quantity); mDb.replace(PURCHASED_ITEMS_TABLE_NAME, null /* nullColumnHack */, values); } /** * Adds the given purchase information to the database and returns the total * number of times that the given product has been purchased. * @param orderId a string identifying the order * @param productId the product ID (sku) * @param purchaseState the purchase state of the product * @param purchaseTime the time the product was purchased, in milliseconds * since the epoch (Jan 1, 1970) * @param developerPayload the developer provided "payload" associated with * the order * @return the number of times the given product has been purchased. */ public synchronized int updatePurchase(String orderId, String productId, PurchaseState purchaseState, long purchaseTime, String developerPayload) { insertOrder(orderId, productId, purchaseState, purchaseTime, developerPayload); Cursor cursor = mDb.query(PURCHASE_HISTORY_TABLE_NAME, HISTORY_COLUMNS, HISTORY_PRODUCT_ID_COL + "=?", new String[] { productId }, null, null, null, null); if (cursor == null) { return 0; } int quantity = 0; try { // Count the number of times the product was purchased while (cursor.moveToNext()) { int stateIndex = cursor.getInt(2); PurchaseState state = PurchaseState.valueOf(stateIndex); // Note that a refunded purchase is treated as a purchase. Such // a friendly refund policy is nice for the user. if (state == PurchaseState.PURCHASED || state == PurchaseState.REFUNDED) { quantity += 1; } } // Update the "purchased items" table updatePurchasedItem(productId, quantity); } finally { if (cursor != null) { cursor.close(); } } return quantity; } /** * Returns a cursor that can be used to read all the rows and columns of * the "purchased items" table. */ public Cursor queryAllPurchasedItems() { return mDb.query(PURCHASED_ITEMS_TABLE_NAME, PURCHASED_COLUMNS, null, null, null, null, null); } /** * This is a standard helper class for constructing the database. */ private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { createPurchaseTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Production-quality upgrade code should modify the tables when // the database version changes instead of dropping the tables and // re-creating them. if (newVersion != DATABASE_VERSION) { Log.w(TAG, "Database upgrade from old: " + oldVersion + " to: " + newVersion); db.execSQL("DROP TABLE IF EXISTS " + PURCHASE_HISTORY_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + PURCHASED_ITEMS_TABLE_NAME); createPurchaseTable(db); return; } } private void createPurchaseTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + PURCHASE_HISTORY_TABLE_NAME + "(" + HISTORY_ORDER_ID_COL + " TEXT PRIMARY KEY, " + HISTORY_STATE_COL + " INTEGER, " + HISTORY_PRODUCT_ID_COL + " TEXT, " + HISTORY_DEVELOPER_PAYLOAD_COL + " TEXT, " + HISTORY_PURCHASE_TIME_COL + " INTEGER)"); db.execSQL("CREATE TABLE " + PURCHASED_ITEMS_TABLE_NAME + "(" + PURCHASED_PRODUCT_ID_COL + " TEXT PRIMARY KEY, " + PURCHASED_QUANTITY_COL + " INTEGER)"); } } }
Java
// Copyright 2002, 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.example.dungeons.util; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
Java
// Portions copyright 2002, 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.example.dungeons.util; // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class contains the methods that handle responses from Android Market. The * implementation of these methods is specific to a particular application. * The methods in this example update the database and, if the main application * has registered a {@llink PurchaseObserver}, will also update the UI. An * application might also want to forward some responses on to its own server, * and that could be done here (in a background thread) but this example does * not do that. * * You should modify and obfuscate this code before using it. */ public class ResponseHandler { private static final String TAG = "ResponseHandler"; /** * This is a static instance of {@link PurchaseObserver} that the * application creates and registers with this class. The PurchaseObserver * is used for updating the UI if the UI is visible. */ private static PurchaseObserver sPurchaseObserver; /** * Registers an observer that updates the UI. * @param observer the observer to register */ public static synchronized void register(PurchaseObserver observer) { sPurchaseObserver = observer; } /** * Unregisters a previously registered observer. * @param observer the previously registered observer. */ public static synchronized void unregister(PurchaseObserver observer) { sPurchaseObserver = null; } /** * Notifies the application of the availability of the MarketBillingService. * This method is called in response to the application calling * {@link BillingService#checkBillingSupported()}. * @param supported true if in-app billing is supported. */ public static void checkBillingSupportedResponse(boolean supported) { if (sPurchaseObserver != null) { sPurchaseObserver.onBillingSupported(supported); } } /** * Starts a new activity for the user to buy an item for sale. This method * forwards the intent on to the PurchaseObserver (if it exists) because * we need to start the activity on the activity stack of the application. * * @param pendingIntent a PendingIntent that we received from Android Market that * will create the new buy page activity * @param intent an intent containing a request id in an extra field that * will be passed to the buy page activity when it is created */ public static void buyPageIntentResponse(PendingIntent pendingIntent, Intent intent) { if (sPurchaseObserver == null) { if (Consts.DEBUG) { Log.d(TAG, "UI is not running"); } return; } sPurchaseObserver.startBuyPageActivity(pendingIntent, intent); } /** * Notifies the application of purchase state changes. The application * can offer an item for sale to the user via * {@link BillingService#requestPurchase(String)}. The BillingService * calls this method after it gets the response. Another way this method * can be called is if the user bought something on another device running * this same app. Then Android Market notifies the other devices that * the user has purchased an item, in which case the BillingService will * also call this method. Finally, this method can be called if the item * was refunded. * @param purchaseState the state of the purchase request (PURCHASED, * CANCELED, or REFUNDED) * @param productId a string identifying a product for sale * @param orderId a string identifying the order * @param purchaseTime the time the product was purchased, in milliseconds * since the epoch (Jan 1, 1970) * @param developerPayload the developer provided "payload" associated with * the order */ public static void purchaseResponse( final Context context, final PurchaseState purchaseState, final String productId, final String orderId, final long purchaseTime, final String developerPayload) { // Update the database with the purchase state. We shouldn't do that // from the main thread so we do the work in a background thread. // We don't update the UI here. We will update the UI after we update // the database because we need to read and update the current quantity // first. new Thread(new Runnable() { public void run() { PurchaseDatabase db = new PurchaseDatabase(context); int quantity = db.updatePurchase( orderId, productId, purchaseState, purchaseTime, developerPayload); db.close(); // This needs to be synchronized because the UI thread can change the // value of sPurchaseObserver. synchronized(ResponseHandler.class) { if (sPurchaseObserver != null) { sPurchaseObserver.postPurchaseStateChange( purchaseState, productId, quantity, purchaseTime, developerPayload); } } } }).start(); } /** * This is called when we receive a response code from Android Market for a * RequestPurchase request that we made. This is used for reporting various * errors and also for acknowledging that an order was sent successfully to * the server. This is NOT used for any purchase state changes. All * purchase state changes are received in the {@link BillingReceiver} and * are handled in {@link Security#verifyPurchase(String, String)}. * @param context the context * @param request the RequestPurchase request for which we received a * response code * @param responseCode a response code from Market to indicate the state * of the request */ public static void responseCodeReceived(Context context, RequestPurchase request, ResponseCode responseCode) { if (sPurchaseObserver != null) { sPurchaseObserver.onRequestPurchaseResponse(request, responseCode); } } /** * This is called when we receive a response code from Android Market for a * RestoreTransactions request. * @param context the context * @param request the RestoreTransactions request for which we received a * response code * @param responseCode a response code from Market to indicate the state * of the request */ public static void responseCodeReceived(Context context, RestoreTransactions request, ResponseCode responseCode) { if (sPurchaseObserver != null) { sPurchaseObserver.onRestoreTransactionsResponse(request, responseCode); } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.util.Base64; import com.example.dungeons.util.Base64DecoderException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.text.TextUtils; import android.util.Log; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.HashSet; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; private static final SecureRandom RANDOM = new SecureRandom(); /** * This keeps track of the nonces that we generated and sent to the * server. We need to keep track of these until we get back the purchase * state and send a confirmation message back to Android Market. If we are * killed and lose this list of nonces, it is not fatal. Android Market will * send us a new "notify" message and we will re-generate a new nonce. * This has to be "static" so that the {@link BillingReceiver} can * check if a nonce exists. */ private static HashSet<Long> sKnownNonces = new HashSet<Long>(); /** * A class to hold the verified purchase information. */ public static class VerifiedPurchase { public PurchaseState purchaseState; public String notificationId; public String productId; public String orderId; public long purchaseTime; public String developerPayload; public VerifiedPurchase(PurchaseState purchaseState, String notificationId, String productId, String orderId, long purchaseTime, String developerPayload) { this.purchaseState = purchaseState; this.notificationId = notificationId; this.productId = productId; this.orderId = orderId; this.purchaseTime = purchaseTime; this.developerPayload = developerPayload; } } /** Generates a nonce (a random number used once). */ public static long generateNonce() { long nonce = RANDOM.nextLong(); sKnownNonces.add(nonce); return nonce; } public static void removeNonce(long nonce) { sKnownNonces.remove(nonce); } public static boolean isNonceKnown(long nonce) { return sKnownNonces.contains(nonce); } /** * Verifies that the data was signed with the given signature, and returns * the list of verified purchases. The data is in JSON format and contains * a nonce (number used once) that we generated and that was signed * (as part of the whole data string) with a private key. The data also * contains the {@link PurchaseState} and product ID of the purchase. * In the general case, there can be an array of purchase transactions * because there may be delays in processing the purchase on the backend * and then several purchases can be batched together. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return null; } if (Consts.DEBUG) { Log.i(TAG, "signedData: " + signedData); } boolean verified = false; if (!TextUtils.isEmpty(signature)) { /** * Compute your public key (that you got from the Android Market publisher site). * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an adversary to replace the public key with one * of their own and then fake messages from the server. * * Generally, encryption keys / passwords should only be kept in memory * long enough to perform the operation they need to perform. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; PublicKey key = Security.generatePublicKey(base64EncodedPublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject(signedData); // The nonce might be null if the user backed out of the buy page. nonce = jObject.optLong("nonce"); jTransactionsArray = jObject.optJSONArray("orders"); if (jTransactionsArray != null) { numTransactions = jTransactionsArray.length(); } } catch (JSONException e) { return null; } if (!Security.isNonceKnown(nonce)) { Log.w(TAG, "Nonce not found: " + nonce); return null; } ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>(); try { for (int i = 0; i < numTransactions; i++) { JSONObject jElement = jTransactionsArray.getJSONObject(i); int response = jElement.getInt("purchaseState"); PurchaseState purchaseState = PurchaseState.valueOf(response); String productId = jElement.getString("productId"); String packageName = jElement.getString("packageName"); long purchaseTime = jElement.getLong("purchaseTime"); String orderId = jElement.optString("orderId", ""); String notifyId = null; if (jElement.has("notificationId")) { notifyId = jElement.getString("notificationId"); } String developerPayload = jElement.optString("developerPayload", null); // If the purchase state is PURCHASED, then we require a // verified nonce. if (purchaseState == PurchaseState.PURCHASED && !verified) { continue; } purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload)); } } catch (JSONException e) { Log.e(TAG, "JSON exception: ", e); return null; } removeNonce(nonce); return purchases; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { if (Consts.DEBUG) { Log.i(TAG, "signature: " + signature); } Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.Html; import android.text.Spanned; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.HashSet; import java.util.Locale; import java.util.Set; /** * A sample application that demonstrates in-app billing. */ public class Dungeons extends Activity implements OnClickListener, OnItemSelectedListener { private static final String TAG = "Dungeons"; /** * Used for storing the log text. */ private static final String LOG_TEXT_KEY = "DUNGEONS_LOG_TEXT"; /** * The SharedPreferences key for recording whether we initialized the * database. If false, then we perform a RestoreTransactions request * to get all the purchases for this user. */ private static final String DB_INITIALIZED = "db_initialized"; private DungeonsPurchaseObserver mDungeonsPurchaseObserver; private Handler mHandler; private BillingService mBillingService; private Button mBuyButton; private Button mEditPayloadButton; private TextView mLogTextView; private Spinner mSelectItemSpinner; private ListView mOwnedItemsTable; private SimpleCursorAdapter mOwnedItemsAdapter; private PurchaseDatabase mPurchaseDatabase; private Cursor mOwnedItemsCursor; private Set<String> mOwnedItems = new HashSet<String>(); /** * The developer payload that is sent with subsequent * purchase requests. */ private String mPayloadContents = null; private static final int DIALOG_CANNOT_CONNECT_ID = 1; private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2; /** * Each product in the catalog is either MANAGED or UNMANAGED. MANAGED * means that the product can be purchased only once per user (such as a new * level in a game). The purchase is remembered by Android Market and * can be restored if this application is uninstalled and then * re-installed. UNMANAGED is used for products that can be used up and * purchased multiple times (such as poker chips). It is up to the * application to keep track of UNMANAGED products for the user. */ private enum Managed { MANAGED, UNMANAGED } /** * A {@link PurchaseObserver} is used to get callbacks when Android Market sends * messages to this application so that we can update the UI. */ private class DungeonsPurchaseObserver extends PurchaseObserver { public DungeonsPurchaseObserver(Handler handler) { super(Dungeons.this, handler); } @Override public void onBillingSupported(boolean supported) { if (Consts.DEBUG) { Log.i(TAG, "supported: " + supported); } if (supported) { restoreDatabase(); mBuyButton.setEnabled(true); mEditPayloadButton.setEnabled(true); } else { showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID); } } @Override public void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity, long purchaseTime, String developerPayload) { if (Consts.DEBUG) { Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState); } if (developerPayload == null) { logProductActivity(itemId, purchaseState.toString()); } else { logProductActivity(itemId, purchaseState + "\n\t" + developerPayload); } if (purchaseState == PurchaseState.PURCHASED) { mOwnedItems.add(itemId); } mCatalogAdapter.setOwnedItems(mOwnedItems); mOwnedItemsCursor.requery(); } @Override public void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode) { if (Consts.DEBUG) { Log.d(TAG, request.mProductId + ": " + responseCode); } if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.i(TAG, "purchase was successfully sent to server"); } logProductActivity(request.mProductId, "sending purchase request"); } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) { if (Consts.DEBUG) { Log.i(TAG, "user canceled purchase"); } logProductActivity(request.mProductId, "dismissed purchase dialog"); } else { if (Consts.DEBUG) { Log.i(TAG, "purchase failed"); } logProductActivity(request.mProductId, "request purchase returned " + responseCode); } } @Override public void onRestoreTransactionsResponse(RestoreTransactions request, ResponseCode responseCode) { if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.d(TAG, "completed RestoreTransactions request"); } // Update the shared preferences so that we don't perform // a RestoreTransactions again. SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(DB_INITIALIZED, true); edit.commit(); } else { if (Consts.DEBUG) { Log.d(TAG, "RestoreTransactions error: " + responseCode); } } } } private static class CatalogEntry { public String sku; public int nameId; public Managed managed; public CatalogEntry(String sku, int nameId, Managed managed) { this.sku = sku; this.nameId = nameId; this.managed = managed; } } /** An array of product list entries for the products that can be purchased. */ private static final CatalogEntry[] CATALOG = new CatalogEntry[] { new CatalogEntry("sword_001", R.string.two_handed_sword, Managed.MANAGED), new CatalogEntry("potion_001", R.string.potions, Managed.UNMANAGED), new CatalogEntry("android.test.purchased", R.string.android_test_purchased, Managed.UNMANAGED), new CatalogEntry("android.test.canceled", R.string.android_test_canceled, Managed.UNMANAGED), new CatalogEntry("android.test.refunded", R.string.android_test_refunded, Managed.UNMANAGED), new CatalogEntry("android.test.item_unavailable", R.string.android_test_item_unavailable, Managed.UNMANAGED), }; private String mItemName; private String mSku; private CatalogAdapter mCatalogAdapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); mDungeonsPurchaseObserver = new DungeonsPurchaseObserver(mHandler); mBillingService = new BillingService(); mBillingService.setContext(this); mPurchaseDatabase = new PurchaseDatabase(this); setupWidgets(); // Check if billing is supported. ResponseHandler.register(mDungeonsPurchaseObserver); if (!mBillingService.checkBillingSupported()) { showDialog(DIALOG_CANNOT_CONNECT_ID); } } /** * Called when this activity becomes visible. */ @Override protected void onStart() { super.onStart(); ResponseHandler.register(mDungeonsPurchaseObserver); initializeOwnedItems(); } /** * Called when this activity is no longer visible. */ @Override protected void onStop() { super.onStop(); ResponseHandler.unregister(mDungeonsPurchaseObserver); } @Override protected void onDestroy() { super.onDestroy(); mPurchaseDatabase.close(); mBillingService.unbind(); } /** * Save the context of the log so simple things like rotation will not * result in the log being cleared. */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(LOG_TEXT_KEY, Html.toHtml((Spanned) mLogTextView.getText())); } /** * Restore the contents of the log if it has previously been saved. */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { mLogTextView.setText(Html.fromHtml(savedInstanceState.getString(LOG_TEXT_KEY))); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CANNOT_CONNECT_ID: return createDialog(R.string.cannot_connect_title, R.string.cannot_connect_message); case DIALOG_BILLING_NOT_SUPPORTED_ID: return createDialog(R.string.billing_not_supported_title, R.string.billing_not_supported_message); default: return null; } } private Dialog createDialog(int titleId, int messageId) { String helpUrl = replaceLanguageAndRegion(getString(R.string.help_url)); if (Consts.DEBUG) { Log.i(TAG, helpUrl); } final Uri helpUri = Uri.parse(helpUrl); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(titleId) .setIcon(android.R.drawable.stat_sys_warning) .setMessage(messageId) .setCancelable(false) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(R.string.learn_more, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_VIEW, helpUri); startActivity(intent); } }); return builder.create(); } /** * Replaces the language and/or country of the device into the given string. * The pattern "%lang%" will be replaced by the device's language code and * the pattern "%region%" will be replaced with the device's country code. * * @param str the string to replace the language/country within * @return a string containing the local language and region codes */ private String replaceLanguageAndRegion(String str) { // Substitute language and or region if present in string if (str.contains("%lang%") || str.contains("%region%")) { Locale locale = Locale.getDefault(); str = str.replace("%lang%", locale.getLanguage().toLowerCase()); str = str.replace("%region%", locale.getCountry().toLowerCase()); } return str; } /** * Sets up the UI. */ private void setupWidgets() { mLogTextView = (TextView) findViewById(R.id.log); mBuyButton = (Button) findViewById(R.id.buy_button); mBuyButton.setEnabled(false); mBuyButton.setOnClickListener(this); mEditPayloadButton = (Button) findViewById(R.id.payload_edit_button); mEditPayloadButton.setEnabled(false); mEditPayloadButton.setOnClickListener(this); mSelectItemSpinner = (Spinner) findViewById(R.id.item_choices); mCatalogAdapter = new CatalogAdapter(this, CATALOG); mSelectItemSpinner.setAdapter(mCatalogAdapter); mSelectItemSpinner.setOnItemSelectedListener(this); mOwnedItemsCursor = mPurchaseDatabase.queryAllPurchasedItems(); startManagingCursor(mOwnedItemsCursor); String[] from = new String[] { PurchaseDatabase.PURCHASED_PRODUCT_ID_COL, PurchaseDatabase.PURCHASED_QUANTITY_COL }; int[] to = new int[] { R.id.item_name, R.id.item_quantity }; mOwnedItemsAdapter = new SimpleCursorAdapter(this, R.layout.item_row, mOwnedItemsCursor, from, to); mOwnedItemsTable = (ListView) findViewById(R.id.owned_items); mOwnedItemsTable.setAdapter(mOwnedItemsAdapter); } private void prependLogEntry(CharSequence cs) { SpannableStringBuilder contents = new SpannableStringBuilder(cs); contents.append('\n'); contents.append(mLogTextView.getText()); mLogTextView.setText(contents); } private void logProductActivity(String product, String activity) { SpannableStringBuilder contents = new SpannableStringBuilder(); contents.append(Html.fromHtml("<b>" + product + "</b>: ")); contents.append(activity); prependLogEntry(contents); } /** * If the database has not been initialized, we send a * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items * for this user. This happens if the application has just been installed * or the user wiped data. We do not want to do this on every startup, rather, we want to do * only when the database needs to be initialized. */ private void restoreDatabase() { SharedPreferences prefs = getPreferences(MODE_PRIVATE); boolean initialized = prefs.getBoolean(DB_INITIALIZED, false); if (!initialized) { mBillingService.restoreTransactions(); Toast.makeText(this, R.string.restoring_transactions, Toast.LENGTH_LONG).show(); } } /** * Creates a background thread that reads the database and initializes the * set of owned items. */ private void initializeOwnedItems() { new Thread(new Runnable() { public void run() { doInitializeOwnedItems(); } }).start(); } /** * Reads the set of purchased items from the database in a background thread * and then adds those items to the set of owned items in the main UI * thread. */ private void doInitializeOwnedItems() { Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems(); if (cursor == null) { return; } final Set<String> ownedItems = new HashSet<String>(); try { int productIdCol = cursor.getColumnIndexOrThrow( PurchaseDatabase.PURCHASED_PRODUCT_ID_COL); while (cursor.moveToNext()) { String productId = cursor.getString(productIdCol); ownedItems.add(productId); } } finally { cursor.close(); } // We will add the set of owned items in a new Runnable that runs on // the UI thread so that we don't need to synchronize access to // mOwnedItems. mHandler.post(new Runnable() { public void run() { mOwnedItems.addAll(ownedItems); mCatalogAdapter.setOwnedItems(mOwnedItems); } }); } /** * Called when a button is pressed. */ public void onClick(View v) { if (v == mBuyButton) { if (Consts.DEBUG) { Log.d(TAG, "buying: " + mItemName + " sku: " + mSku); } if (!mBillingService.requestPurchase(mSku, mPayloadContents)) { showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID); } } else if (v == mEditPayloadButton) { showPayloadEditDialog(); } } /** * Displays the dialog used to edit the payload dialog. */ private void showPayloadEditDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); final View view = View.inflate(this, R.layout.edit_payload, null); final TextView payloadText = (TextView) view.findViewById(R.id.payload_text); if (mPayloadContents != null) { payloadText.setText(mPayloadContents); } dialog.setView(view); dialog.setPositiveButton( R.string.edit_payload_accept, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mPayloadContents = payloadText.getText().toString(); } }); dialog.setNegativeButton( R.string.edit_payload_clear, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (dialog != null) { mPayloadContents = null; dialog.cancel(); } } }); dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { if (dialog != null) { dialog.cancel(); } } }); dialog.show(); } /** * Called when an item in the spinner is selected. */ public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mItemName = getString(CATALOG[position].nameId); mSku = CATALOG[position].sku; } public void onNothingSelected(AdapterView<?> arg0) { } /** * An adapter used for displaying a catalog of products. If a product is * managed by Android Market and already purchased, then it will be "grayed-out" in * the list and not selectable. */ private static class CatalogAdapter extends ArrayAdapter<String> { private CatalogEntry[] mCatalog; private Set<String> mOwnedItems = new HashSet<String>(); public CatalogAdapter(Context context, CatalogEntry[] catalog) { super(context, android.R.layout.simple_spinner_item); mCatalog = catalog; for (CatalogEntry element : catalog) { add(context.getString(element.nameId)); } setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } public void setOwnedItems(Set<String> ownedItems) { mOwnedItems = ownedItems; notifyDataSetChanged(); } @Override public boolean areAllItemsEnabled() { // Return false to have the adapter call isEnabled() return false; } @Override public boolean isEnabled(int position) { // If the item at the given list position is not purchasable, // then prevent the list item from being selected. CatalogEntry entry = mCatalog[position]; if (entry.managed == Managed.MANAGED && mOwnedItems.contains(entry.sku)) { return false; } return true; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { // If the item at the given list position is not purchasable, then // "gray out" the list item. View view = super.getDropDownView(position, convertView, parent); view.setEnabled(isEnabled(position)); return view; } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.Consts.ResponseCode; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class implements the broadcast receiver for in-app billing. All asynchronous messages from * Android Market come to this app through this receiver. This class forwards all * messages to the {@link BillingService}, which can start background threads, * if necessary, to process the messages. This class runs on the UI thread and must not do any * network I/O, database updates, or any tasks that might take a long time to complete. * It also must not start a background thread because that may be killed as soon as * {@link #onReceive(Context, Intent)} returns. * * You should modify and obfuscate this code before using it. */ public class BillingReceiver extends BroadcastReceiver { private static final String TAG = "BillingReceiver"; /** * This is the entry point for all asynchronous messages sent from Android Market to * the application. This method forwards the messages on to the * {@link BillingService}, which handles the communication back to Android Market. * The {@link BillingService} also reports state changes back to the application through * the {@link ResponseHandler}. */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) { String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA); String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE); purchaseStateChanged(context, signedData, signature); } else if (Consts.ACTION_NOTIFY.equals(action)) { String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID); if (Consts.DEBUG) { Log.i(TAG, "notifyId: " + notifyId); } notify(context, notifyId); } else if (Consts.ACTION_RESPONSE_CODE.equals(action)) { long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1); int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, ResponseCode.RESULT_ERROR.ordinal()); checkResponseCode(context, requestId, responseCodeIndex); } else { Log.w(TAG, "unexpected action: " + action); } } /** * This is called when Android Market sends information about a purchase state * change. The signedData parameter is a plaintext JSON string that is * signed by the server with the developer's private key. The signature * for the signed data is passed in the signature parameter. * @param context the context * @param signedData the (unencrypted) JSON string * @param signature the signature for the signedData */ private void purchaseStateChanged(Context context, String signedData, String signature) { Intent intent = new Intent(Consts.ACTION_PURCHASE_STATE_CHANGED); intent.setClass(context, BillingService.class); intent.putExtra(Consts.INAPP_SIGNED_DATA, signedData); intent.putExtra(Consts.INAPP_SIGNATURE, signature); context.startService(intent); } /** * This is called when Android Market sends a "notify" message indicating that transaction * information is available. The request includes a nonce (random number used once) that * we generate and Android Market signs and sends back to us with the purchase state and * other transaction details. This BroadcastReceiver cannot bind to the * MarketBillingService directly so it starts the {@link BillingService}, which does the * actual work of sending the message. * * @param context the context * @param notifyId the notification ID */ private void notify(Context context, String notifyId) { Intent intent = new Intent(Consts.ACTION_GET_PURCHASE_INFORMATION); intent.setClass(context, BillingService.class); intent.putExtra(Consts.NOTIFICATION_ID, notifyId); context.startService(intent); } /** * This is called when Android Market sends a server response code. The BillingService can * then report the status of the response if desired. * * @param context the context * @param requestId the request ID that corresponds to a previous request * @param responseCodeIndex the ResponseCode ordinal value for the request */ private void checkResponseCode(Context context, long requestId, int responseCodeIndex) { Intent intent = new Intent(Consts.ACTION_RESPONSE_CODE); intent.setClass(context, BillingService.class); intent.putExtra(Consts.INAPP_REQUEST_ID, requestId); intent.putExtra(Consts.INAPP_RESPONSE_CODE, responseCodeIndex); context.startService(intent); } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.Activity; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.Intent; import android.content.IntentSender; import android.os.Handler; import android.util.Log; import java.lang.reflect.Method; /** * An interface for observing changes related to purchases. The main application * extends this class and registers an instance of that derived class with * {@link ResponseHandler}. The main application implements the callbacks * {@link #onBillingSupported(boolean)} and * {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. These methods * are used to update the UI. */ public abstract class PurchaseObserver { private static final String TAG = "PurchaseObserver"; private final Activity mActivity; private final Handler mHandler; private Method mStartIntentSender; private Object[] mStartIntentSenderArgs = new Object[5]; private static final Class[] START_INTENT_SENDER_SIG = new Class[] { IntentSender.class, Intent.class, int.class, int.class, int.class }; public PurchaseObserver(Activity activity, Handler handler) { mActivity = activity; mHandler = handler; initCompatibilityLayer(); } /** * This is the callback that is invoked when Android Market responds to the * {@link BillingService#checkBillingSupported()} request. * @param supported true if in-app billing is supported. */ public abstract void onBillingSupported(boolean supported); /** * This is the callback that is invoked when an item is purchased, * refunded, or canceled. It is the callback invoked in response to * calling {@link BillingService#requestPurchase(String)}. It may also * be invoked asynchronously when a purchase is made on another device * (if the purchase was for a Market-managed item), or if the purchase * was refunded, or the charge was canceled. This handles the UI * update. The database update is handled in * {@link ResponseHandler#purchaseResponse(Context, PurchaseState, * String, String, long)}. * @param purchaseState the purchase state of the item * @param itemId a string identifying the item (the "SKU") * @param quantity the current quantity of this item after the purchase * @param purchaseTime the time the product was purchased, in * milliseconds since the epoch (Jan 1, 1970) */ public abstract void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity, long purchaseTime, String developerPayload); /** * This is called when we receive a response code from Market for a * RequestPurchase request that we made. This is NOT used for any * purchase state changes. All purchase state changes are received in * {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. * This is used for reporting various errors, or if the user backed out * and didn't purchase the item. The possible response codes are: * RESULT_OK means that the order was sent successfully to the server. * The onPurchaseStateChange() will be invoked later (with a * purchase state of PURCHASED or CANCELED) when the order is * charged or canceled. This response code can also happen if an * order for a Market-managed item was already sent to the server. * RESULT_USER_CANCELED means that the user didn't buy the item. * RESULT_SERVICE_UNAVAILABLE means that we couldn't connect to the * Android Market server (for example if the data connection is down). * RESULT_BILLING_UNAVAILABLE means that in-app billing is not * supported yet. * RESULT_ITEM_UNAVAILABLE means that the item this app offered for * sale does not exist (or is not published) in the server-side * catalog. * RESULT_ERROR is used for any other errors (such as a server error). */ public abstract void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode); /** * This is called when we receive a response code from Android Market for a * RestoreTransactions request that we made. A response code of * RESULT_OK means that the request was successfully sent to the server. */ public abstract void onRestoreTransactionsResponse(RestoreTransactions request, ResponseCode responseCode); private void initCompatibilityLayer() { try { mStartIntentSender = mActivity.getClass().getMethod("startIntentSender", START_INTENT_SENDER_SIG); } catch (SecurityException e) { mStartIntentSender = null; } catch (NoSuchMethodException e) { mStartIntentSender = null; } } void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) { if (mStartIntentSender != null) { // This is on Android 2.0 and beyond. The in-app buy page activity // must be on the activity stack of the application. try { // This implements the method call: // mActivity.startIntentSender(pendingIntent.getIntentSender(), // intent, 0, 0, 0); mStartIntentSenderArgs[0] = pendingIntent.getIntentSender(); mStartIntentSenderArgs[1] = intent; mStartIntentSenderArgs[2] = Integer.valueOf(0); mStartIntentSenderArgs[3] = Integer.valueOf(0); mStartIntentSenderArgs[4] = Integer.valueOf(0); mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs); } catch (Exception e) { Log.e(TAG, "error starting activity", e); } } else { // This is on Android version 1.6. The in-app buy page activity must be on its // own separate activity stack instead of on the activity stack of // the application. try { pendingIntent.send(mActivity, 0 /* code */, intent); } catch (CanceledException e) { Log.e(TAG, "error starting activity", e); } } } /** * Updates the UI after the database has been updated. This method runs * in a background thread so it has to post a Runnable to run on the UI * thread. * @param purchaseState the purchase state of the item * @param itemId a string identifying the item * @param quantity the quantity of items in this purchase */ void postPurchaseStateChange(final PurchaseState purchaseState, final String itemId, final int quantity, final long purchaseTime, final String developerPayload) { mHandler.post(new Runnable() { public void run() { onPurchaseStateChange( purchaseState, itemId, quantity, purchaseTime, developerPayload); } }); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.tech; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.NfcF; import com.sinpo.xnfc.Util; public class FeliCa { public static final byte[] EMPTY = {}; protected byte[] data; protected FeliCa() { } protected FeliCa(byte[] bytes) { data = (bytes == null) ? FeliCa.EMPTY : bytes; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class IDm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public IDm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes); } public final String getManufactureCode() { return Util.toHexString(data, 0, 2); } public final String getCardIdentification() { return Util.toHexString(data, 2, 6); } public boolean isEmpty() { final byte[] d = data; for (final byte v : d) { if (v != 0) return false; } return true; } } public final static class PMm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public PMm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes); } public final String getIcCode() { return Util.toHexString(data, 0, 2); } public final String getMaximumResponseTime() { return Util.toHexString(data, 2, 6); } } public final static class SystemCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public SystemCode(byte[] sc) { super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc); } public int toInt() { return toInt(data); } public static int toInt(byte[] data) { return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1])); } } public final static class ServiceCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public static final int T_UNKNOWN = 0; public static final int T_RANDOM = 1; public static final int T_CYCLIC = 2; public static final int T_PURSE = 3; public ServiceCode(byte[] sc) { super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc); } public ServiceCode(int code) { this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) }); } public boolean isEncrypt() { return (data[0] & 0x1) == 0; } public boolean isWritable() { final int f = data[0] & 0x3F; return (f & 0x2) == 0 || f == 0x13 || f == 0x12; } public int getAccessAttr() { return data[0] & 0x3F; } public int getDataType() { final int f = data[0] & 0x3F; if ((f & 0x10) == 0) return T_PURSE; return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC; } } public final static class Block extends FeliCa { public Block() { data = new byte[16]; } public Block(byte[] bytes) { super((bytes == null || bytes.length < 16) ? new byte[16] : bytes); } } public final static class BlockListElement extends FeliCa { private static final byte LENGTH_2_BYTE = (byte) 0x80; private static final byte LENGTH_3_BYTE = (byte) 0x00; // private static final byte ACCESSMODE_DECREMENT = (byte) 0x00; // private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01; private final byte lengthAndaccessMode; private final byte serviceCodeListOrder; public BlockListElement(byte mode, byte order, byte... blockNumber) { if (blockNumber.length > 1) { lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF); } else { lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF); } serviceCodeListOrder = (byte) (order & 0x0F); data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber; } @Override public byte[] getBytes() { if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) { ByteBuffer buff = ByteBuffer.allocate(2); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[0]); return buff.array(); } else { ByteBuffer buff = ByteBuffer.allocate(3); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[1]).put(data[0]); return buff.array(); } } } public final static class MemoryConfigurationBlock extends FeliCa { public MemoryConfigurationBlock(byte[] bytes) { super((bytes == null || bytes.length < 4) ? new byte[4] : bytes); } public boolean isNdefSupport() { return (data == null) ? false : (data[3] & (byte) 0xff) == 1; } public void setNdefSupport(boolean ndefSupport) { data[3] = (byte) (ndefSupport ? 1 : 0); } public boolean isWritable(int... addrs) { if (data == null) return false; boolean result = true; for (int a : addrs) { byte b = (byte) ((a & 0xff) + 1); if (a < 8) { result &= (data[0] & b) == b; continue; } else if (a < 16) { result &= (data[1] & b) == b; continue; } else result &= (data[2] & b) == b; } return result; } } public final static class Service extends FeliCa { private final ServiceCode[] serviceCodes; private final BlockListElement[] blockListElements; public Service(ServiceCode[] codes, BlockListElement... blocks) { serviceCodes = (codes == null) ? new ServiceCode[0] : codes; blockListElements = (blocks == null) ? new BlockListElement[0] : blocks; } @Override public byte[] getBytes() { int length = 0; for (ServiceCode s : this.serviceCodes) { length += s.getBytes().length; } for (BlockListElement b : blockListElements) { length += b.getBytes().length; } ByteBuffer buff = ByteBuffer.allocate(length); for (ServiceCode s : this.serviceCodes) { buff.put(s.getBytes()); } for (BlockListElement b : blockListElements) { buff.put(b.getBytes()); } return buff.array(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (ServiceCode s : serviceCodes) { sb.append(s.toString()); } for (BlockListElement b : blockListElements) { sb.append(b.toString()); } return sb.toString(); } } public final static class Command extends FeliCa { private final int length; private final byte code; private final IDm idm; public Command(final byte[] bytes) { this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length)); } public Command(byte code, final byte... bytes) { this.code = code; if (bytes.length >= 8) { idm = new IDm(Arrays.copyOfRange(bytes, 0, 8)); data = Arrays.copyOfRange(bytes, 8, bytes.length); } else { idm = null; data = bytes; } length = bytes.length + 2; } public Command(byte code, IDm idm, final byte... bytes) { this.code = code; this.idm = idm; this.data = bytes; this.length = idm.getBytes().length + data.length + 2; } public Command(byte code, byte[] idm, final byte... bytes) { this.code = code; this.idm = new IDm(idm); this.data = bytes; this.length = idm.length + data.length + 2; } @Override public byte[] getBytes() { ByteBuffer buff = ByteBuffer.allocate(length); byte length = (byte) this.length; if (idm != null) { buff.put(length).put(code).put(idm.getBytes()).put(data); } else { buff.put(length).put(code).put(data); } return buff.array(); } } public static class Response extends FeliCa { protected final int length; protected final byte code; protected final IDm idm; public Response(byte[] bytes) { if (bytes != null && bytes.length >= 10) { length = bytes[0] & 0xff; code = bytes[1]; idm = new IDm(Arrays.copyOfRange(bytes, 2, 10)); data = bytes; } else { length = 0; code = 0; idm = new IDm(null); data = FeliCa.EMPTY; } } public IDm getIDm() { return idm; } } public final static class PollingResponse extends Response { private final PMm pmm; public PollingResponse(byte[] bytes) { super(bytes); if (size() >= 18) { pmm = new PMm(Arrays.copyOfRange(data, 10, 18)); } else { pmm = new PMm(null); } } public PMm getPMm() { return pmm; } } public final static class ReadResponse extends Response { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF }; private final byte[] blockData; public ReadResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) { blockData = Arrays.copyOfRange(data, 13, data.length); } else { blockData = FeliCa.EMPTY; } } public int getStatusFlag1() { return data[10]; } public int getStatusFlag2() { return data[11]; } public int getBlockCount() { return (data.length > 12) ? (0xFF & data[12]) : 0; } public byte[] getBlockData() { return blockData; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class WriteResponse extends Response { public WriteResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); } public int getStatusFlag1() { return data[0]; } public int getStatusFlag2() { return data[1]; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class Tag { private final NfcF nfcTag; private boolean isFeliCaLite; private int sys; private IDm idm; private PMm pmm; public Tag(NfcF tag) { nfcTag = tag; sys = SystemCode.toInt(tag.getSystemCode()); idm = new IDm(tag.getTag().getId()); pmm = new PMm(tag.getManufacturer()); } public int getSystemCode() { return sys; } public IDm getIDm() { return idm; } public PMm getPMm() { return pmm; } public boolean checkFeliCaLite() { isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty(); return isFeliCaLite; } public boolean isFeliCaLite() { return isFeliCaLite; } public PollingResponse polling(int systemCode) { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (systemCode >> 8), (byte) (systemCode & 0xff), (byte) 0x01, (byte) 0x00 }); PollingResponse r = new PollingResponse(transceive(cmd)); idm = r.getIDm(); pmm = r.getPMm(); return r; } public PollingResponse polling() { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (SYS_FELICA_LITE >> 8), (byte) (SYS_FELICA_LITE & 0xff), (byte) 0x01, (byte) 0x00 }); PollingResponse r = new PollingResponse(transceive(cmd)); idm = r.getIDm(); pmm = r.getPMm(); return r; } public final SystemCode[] getSystemCodeList() { final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm); final byte[] bytes = transceive(cmd); final int num = (int) bytes[10]; final SystemCode ret[] = new SystemCode[num]; for (int i = 0; i < num; ++i) { ret[i] = new SystemCode(Arrays.copyOfRange(bytes, 11 + i * 2, 13 + i * 2)); } return ret; } public ServiceCode[] getServiceCodeList() { ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>(); int index = 1; while (true) { byte[] bytes = searchServiceCode(index); if (bytes.length != 2 && bytes.length != 4) break; if (bytes.length == 2) { if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff) break; ret.add(new ServiceCode(bytes)); } ++index; } return ret.toArray(new ServiceCode[ret.size()]); } private byte[] searchServiceCode(int index) { Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] { (byte) (index & 0xff), (byte) (index >> 8) }); byte[] bytes = transceive(cmd); if (bytes == null || bytes.length < 12 || bytes[1] != (byte) 0x0b) { return FeliCa.EMPTY; } return Arrays.copyOfRange(bytes, 10, bytes.length); } public ReadResponse readWithoutEncryption(ServiceCode code, byte addr) { byte[] bytes = code.getBytes(); Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, addr }); return new ReadResponse(transceive(cmd)); } public ReadResponse readWithoutEncryption(byte addr) { Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READONLY >> 8), (byte) (SRV_FELICA_LITE_READONLY & 0xff), (byte) 0x01, (byte) 0x80, addr }); return new ReadResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(ServiceCode code, byte addr, byte[] buff) { byte[] bytes = code.getBytes(); ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, (byte) addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(byte addr, byte[] buff) { ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READWRITE >> 8), (byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01, (byte) 0x80, addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public MemoryConfigurationBlock getMemoryConfigBlock() { ReadResponse r = readWithoutEncryption((byte) 0x88); return (r != null) ? new MemoryConfigurationBlock(r.getBlockData()) : null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (idm != null) { sb.append(idm.toString()); if (pmm != null) sb.append(pmm.toString()); } return sb.toString(); } public void connect() { try { nfcTag.connect(); } catch (Exception e) { } } public void close() { try { nfcTag.close(); } catch (Exception e) { } } public byte[] transceive(Command cmd) { try { return nfcTag.transceive(cmd.getBytes()); } catch (Exception e) { return Response.EMPTY; } } } // polling public static final byte CMD_POLLING = 0x00; public static final byte RSP_POLLING = 0x01; // request service public static final byte CMD_REQUEST_SERVICE = 0x02; public static final byte RSP_REQUEST_SERVICE = 0x03; // request RESPONSE public static final byte CMD_REQUEST_RESPONSE = 0x04; public static final byte RSP_REQUEST_RESPONSE = 0x05; // read without encryption public static final byte CMD_READ_WO_ENCRYPTION = 0x06; public static final byte RSP_READ_WO_ENCRYPTION = 0x07; // write without encryption public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08; public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09; // search service code public static final byte CMD_SEARCH_SERVICECODE = 0x0a; public static final byte RSP_SEARCH_SERVICECODE = 0x0b; // request system code public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c; public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d; // authentication 1 public static final byte CMD_AUTHENTICATION1 = 0x10; public static final byte RSP_AUTHENTICATION1 = 0x11; // authentication 2 public static final byte CMD_AUTHENTICATION2 = 0x12; public static final byte RSP_AUTHENTICATION2 = 0x13; // read public static final byte CMD_READ = 0x14; public static final byte RSP_READ = 0x15; // write public static final byte CMD_WRITE = 0x16; public static final byte RSP_WRITE = 0x17; public static final int SYS_ANY = 0xffff; public static final int SYS_FELICA_LITE = 0x88b4; public static final int SYS_COMMON = 0xfe00; public static final int SRV_FELICA_LITE_READONLY = 0x0b00; public static final int SRV_FELICA_LITE_READWRITE = 0x0900; public static final int STA1_NORMAL = 0x00; public static final int STA1_ERROR = 0xff; public static final int STA2_NORMAL = 0x00; public static final int STA2_ERROR_LENGTH = 0x01; public static final int STA2_ERROR_FLOWN = 0x02; public static final int STA2_ERROR_MEMORY = 0x70; public static final int STA2_ERROR_WRITELIMIT = 0x71; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.tech; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.IsoDep; import com.sinpo.xnfc.Util; public class Iso7816 { public static final byte[] EMPTY = { 0 }; protected byte[] data; protected Iso7816() { data = Iso7816.EMPTY; } protected Iso7816(byte[] bytes) { data = (bytes == null) ? Iso7816.EMPTY : bytes; } public boolean match(byte[] bytes) { return match(bytes, 0); } public boolean match(byte[] bytes, int start) { final byte[] data = this.data; if (data.length <= bytes.length - start) { for (final byte v : data) { if (v != bytes[start++]) return false; } } return true; } public boolean match(byte tag) { return (data.length == 1 && data[0] == tag); } public boolean match(short tag) { final byte[] data = this.data; if (data.length == 2) { final byte d0 = (byte) (0x000000FF & tag); final byte d1 = (byte) (0x000000FF & (tag >> 8)); return (data[0] == d0 && data[1] == d1); } return false; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class ID extends Iso7816 { public ID(byte[] bytes) { super(bytes); } } public final static class Response extends Iso7816 { public static final byte[] EMPTY = {}; public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN public Response(byte[] bytes) { super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes); } public byte getSw1() { return data[data.length - 2]; } public byte getSw2() { return data[data.length - 1]; } public short getSw12() { final byte[] d = this.data; int n = d.length; return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1])); } public boolean isOkey() { return equalsSw12(SW_NO_ERROR); } public boolean equalsSw12(short val) { return getSw12() == val; } public int size() { return data.length - 2; } public byte[] getBytes() { return isOkey() ? Arrays.copyOfRange(data, 0, size()) : Response.EMPTY; } } public final static class BerT extends Iso7816 { // tag template public static final byte TMPL_FCP = 0x62; // File Control Parameters public static final byte TMPL_FMD = 0x64; // File Management Data public static final byte TMPL_FCI = 0x6F; // FCP and FMD // proprietary information public final static BerT CLASS_PRI = new BerT((byte) 0xA5); // short EF identifier public final static BerT CLASS_SFI = new BerT((byte) 0x88); // dedicated file name public final static BerT CLASS_DFN = new BerT((byte) 0x84); // application data object public final static BerT CLASS_ADO = new BerT((byte) 0x61); // application id public final static BerT CLASS_AID = new BerT((byte) 0x4F); public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x1F) == 0x1F) { while ((bytes[start + len] & 0x80) == 0x80) ++len; ++len; } return len; } public static BerT read(byte[] bytes, int start) { return new BerT(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerT(byte tag) { this(new byte[] { tag }); } public BerT(short tag) { this(new byte[] { (byte) (0x000000FF & (tag >> 8)), (byte) (0x000000FF & tag) }); } public BerT(byte[] bytes) { super(bytes); } public boolean hasChild() { return ((data[0] & 0x20) == 0x20); } } public final static class BerL extends Iso7816 { private final int val; public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x80) == 0x80) { len += bytes[start] & 0x07; } return len; } public static int calc(byte[] bytes, int start) { if ((bytes[start] & 0x80) == 0x80) { int v = 0; int e = start + bytes[start] & 0x07; while (++start <= e) { v <<= 8; v |= bytes[start] & 0xFF; } return v; } return bytes[start]; } public static BerL read(byte[] bytes, int start) { return new BerL(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerL(byte[] bytes) { super(bytes); val = calc(bytes, 0); } public int toInt() { return val; } } public final static class BerV extends Iso7816 { public static BerV read(byte[] bytes, int start, int len) { return new BerV(Arrays.copyOfRange(bytes, start, start + len)); } public BerV(byte[] bytes) { super(bytes); } } public final static class BerTLV extends Iso7816 { public static int test(byte[] bytes, int start) { final int lt = BerT.test(bytes, start); final int ll = BerL.test(bytes, start + lt); final int lv = BerL.calc(bytes, start + lt); return lt + ll + lv; } public static BerTLV read(Iso7816 obj) { return read(obj.getBytes(), 0); } public static BerTLV read(byte[] bytes, int start) { int s = start; final BerT t = BerT.read(bytes, s); s += t.size(); final BerL l = BerL.read(bytes, s); s += l.size(); final BerV v = BerV.read(bytes, s, l.toInt()); s += v.size(); final BerTLV tlv = new BerTLV(t, l, v); tlv.data = Arrays.copyOfRange(bytes, start, s); return tlv; } public static ArrayList<BerTLV> readList(Iso7816 obj) { return readList(obj.getBytes()); } public static ArrayList<BerTLV> readList(final byte[] data) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); int start = 0; int end = data.length - 3; while (start < end) { final BerTLV tlv = read(data, start); ret.add(tlv); start += tlv.size(); } return ret; } public final BerT t; public final BerL l; public final BerV v; public BerTLV(BerT t, BerL l, BerV v) { this.t = t; this.l = l; this.v = v; } public BerTLV getChildByTag(BerT tag) { if (t.hasChild()) { final byte[] raw = v.getBytes(); int start = 0; int end = raw.length; while (start < end) { if (tag.match(raw, start)) return read(raw, start); start += test(raw, start); } } return null; } public BerTLV getChild(int index) { if (t.hasChild()) { final byte[] raw = v.getBytes(); int start = 0; int end = raw.length; int i = 0; while (start < end) { if (i++ == index) return read(raw, start); start += test(raw, start); } } return null; } } public final static class Tag { private final IsoDep nfcTag; private ID id; public Tag(IsoDep tag) { nfcTag = tag; id = new ID(tag.getTag().getId()); } public ID getID() { return id; } public Response verify() { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0x20, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x02, // Lc (byte) 0x12, (byte) 0x34, }; return new Response(transceive(cmd)); } public Response initPurchase(boolean isEP) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x50, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x0B, // Lc (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x0F, // Le }; return new Response(transceive(cmd)); } public Response getBalance(boolean isEP) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x5C, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x04, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi, int index) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) index, // P1 Parameter 1 (byte) ((sfi << 3) | 0x04), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) ((sfi << 3) | 0x05), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readBinary(int sfi) { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB0, // INS Instruction (byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(int sfi) { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (sfi & 0x1F), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response selectByID(byte... name) { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response selectByName(byte... name) { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x04) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public void connect() { try { nfcTag.connect(); } catch (Exception e) { } } public void close() { try { nfcTag.close(); } catch (Exception e) { } } public byte[] transceive(final byte[] cmd) { try { return nfcTag.transceive(cmd); } catch (Exception e) { return Response.ERROR; } } } public static final short SW_NO_ERROR = (short) 0x9000; public static final short SW_BYTES_REMAINING_00 = 0x6100; public static final short SW_WRONG_LENGTH = 0x6700; public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982; public static final short SW_FILE_INVALID = 0x6983; public static final short SW_DATA_INVALID = 0x6984; public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985; public static final short SW_COMMAND_NOT_ALLOWED = 0x6986; public static final short SW_APPLET_SELECT_FAILED = 0x6999; public static final short SW_WRONG_DATA = 0x6A80; public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81; public static final short SW_FILE_NOT_FOUND = 0x6A82; public static final short SW_RECORD_NOT_FOUND = 0x6A83; public static final short SW_INCORRECT_P1P2 = 0x6A86; public static final short SW_WRONG_P1P2 = 0x6B00; public static final short SW_CORRECT_LENGTH_00 = 0x6C00; public static final short SW_INS_NOT_SUPPORTED = 0x6D00; public static final short SW_CLA_NOT_SUPPORTED = 0x6E00; public static final short SW_UNKNOWN = 0x6F00; public static final short SW_FILE_FULL = 0x6A84; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; public final class Util { private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private Util() { } public static byte[] toBytes(int a) { return new byte[] { (byte) (0x000000ff & (a >>> 24)), (byte) (0x000000ff & (a >>> 16)), (byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) }; } public static int toInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toIntR(byte[] b, int s, int n) { int ret = 0; for (int i = s; (i >= 0 && n > 0); --i, --n) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toInt(byte... b) { int ret = 0; for (final byte a : b) { ret <<= 8; ret |= a & 0xFF; } return ret; } public static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String toHexStringR(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; int x = 0; for (int i = s + n - 1; i >= s; --i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static int parseInt(String txt, int radix, int def) { int ret; try { ret = Integer.valueOf(txt, radix); } catch (Exception e) { ret = def; } return ret; } public static String toAmountString(float value) { return String.format("%.2f", value); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card; import android.content.res.Resources; import android.nfc.tech.NfcV; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; final class VicinityCard { private static final int SYS_UNKNOWN = 0x00000000; private static final int SYS_SZLIB = 0x00010000; private static final int DEP_SZLIB_CENTER = 0x0100; private static final int DEP_SZLIB_NANSHAN = 0x0200; private static final int SRV_USER = 0x0001; private static final int SRV_BOOK = 0x0002; public static final int SW1_OK = 0x00; static String load(NfcV tech, Resources res) { String data = null; try { tech.connect(); int pos, BLKSIZE, BLKCNT; byte cmd[], rsp[], ID[], RAW[], STA[], flag, DSFID; ID = tech.getTag().getId(); if (ID == null || ID.length != 8) throw new Exception(); /*--------------------------------------------------------------*/ // get system information /*--------------------------------------------------------------*/ cmd = new byte[10]; cmd[0] = (byte) 0x22; // flag cmd[1] = (byte) 0x2B; // command System.arraycopy(ID, 0, cmd, 2, ID.length); // UID rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); pos = 10; flag = rsp[1]; DSFID = ((flag & 0x01) == 0x01) ? rsp[pos++] : 0; if ((flag & 0x02) == 0x02) pos++; if ((flag & 0x04) == 0x04) { BLKCNT = rsp[pos++] + 1; BLKSIZE = (rsp[pos++] & 0xF) + 1; } else { BLKCNT = BLKSIZE = 0; } /*--------------------------------------------------------------*/ // read first 8 block /*--------------------------------------------------------------*/ cmd = new byte[12]; cmd[0] = (byte) 0x22; // flag cmd[1] = (byte) 0x23; // command System.arraycopy(ID, 0, cmd, 2, ID.length); // UID cmd[10] = (byte) 0x00; // index of first block to get cmd[11] = (byte) 0x07; // block count, one less! (see ISO15693-3) rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); RAW = rsp; /*--------------------------------------------------------------*/ // read last block /*--------------------------------------------------------------*/ cmd[10] = (byte) (BLKCNT - 1); // index of first block to get cmd[11] = (byte) 0x00; // block count, one less! (see ISO15693-3) rsp = tech.transceive(cmd); if (rsp[0] != SW1_OK) throw new Exception(); STA = rsp; data = Util.toHexString(rsp, 0, rsp.length); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final int type = parseType(DSFID, RAW, BLKSIZE); final String name = parseName(type, res); final String info = parseInfo(ID, res); final String extra = parseData(type, RAW, STA, BLKSIZE, res); data = CardManager.buildResult(name, info, extra, null); } catch (Exception e) { data = null; // data = e.getMessage(); } try { tech.close(); } catch (Exception e) { } return data; } private static int parseType(byte dsfid, byte[] raw, int blkSize) { int ret = SYS_UNKNOWN; if (blkSize == 4 && (raw[4] & 0x10) == 0x10 && (raw[14] & 0xAB) == 0xAB && (raw[13] & 0xE0) == 0xE0) { ret = SYS_SZLIB; if ((raw[13] & 0x0F) == 0x05) ret |= DEP_SZLIB_CENTER; else ret |= DEP_SZLIB_NANSHAN; if (raw[4] == 0x12) ret |= SRV_USER; else ret |= SRV_BOOK; } return ret; } private static String parseName(int type, Resources res) { if ((type & SYS_SZLIB) == SYS_SZLIB) { final String dep; if ((type & DEP_SZLIB_CENTER) == DEP_SZLIB_CENTER) dep = res.getString(R.string.name_szlib_center); else if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN) dep = res.getString(R.string.name_szlib_nanshan); else dep = null; final String srv; if ((type & SRV_BOOK) == SRV_BOOK) srv = res.getString(R.string.name_lib_booktag); else if ((type & SRV_USER) == SRV_USER) srv = res.getString(R.string.name_lib_readercard); else srv = null; if (dep != null && srv != null) return dep + " " + srv; } return res.getString(R.string.name_unknowntag); } private static String parseInfo(byte[] id, Resources res) { final StringBuilder r = new StringBuilder(); final String i = res.getString(R.string.lab_id); r.append("<b>").append(i).append("</b> ") .append(Util.toHexStringR(id, 0, id.length)); return r.toString(); } private static String parseData(int type, byte[] raw, byte[] sta, int blkSize, Resources res) { if ((type & SYS_SZLIB) == SYS_SZLIB) { return parseSzlibData(type, raw, sta, blkSize, res); } return null; } private static String parseSzlibData(int type, byte[] raw, byte[] sta, int blkSize, Resources res) { long id = 0; for (int i = 3; i > 0; --i) id = (id <<= 8) | (0x000000FF & raw[i]); for (int i = 8; i > 4; --i) id = (id <<= 8) | (0x000000FF & raw[i]); final String sid; if ((type & SRV_USER) == SRV_USER) sid = res.getString(R.string.lab_user_id); else sid = res.getString(R.string.lab_bktg_sn); final StringBuilder r = new StringBuilder(); r.append("<b>").append(sid).append(" <font color=\"teal\">"); r.append(String.format("%013d", id)).append("</font></b><br />"); final String scat; if ((type & SRV_BOOK) == SRV_BOOK) { final byte cat = raw[12]; if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN) { if (cat == 0x10) scat = res.getString(R.string.name_bkcat_soc); else if (cat == 0x20) { if (raw[11] == (byte) 0x84) scat = res.getString(R.string.name_bkcat_ltr); else scat = res.getString(R.string.name_bkcat_sci); } else scat = null; } else { scat = null; } if (scat != null) { final String scl = res.getString(R.string.lab_bkcat); r.append("<b>").append(scl).append("</b> ").append(scat) .append("<br />"); } } // final int len = raw.length; // for (int i = 1, n = 0; i < len; i += blkSize) { // final String blk = Util.toHexString(raw, i, blkSize); // r.append("<br />").append(n++).append(": ").append(blk); // } // final String blk = Util.toHexString(sta, 0, blkSize); // r.append("<br />S: ").append(blk); return r.toString(); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card; import com.sinpo.xnfc.card.pboc.PbocCard; import android.content.IntentFilter; import android.content.res.Resources; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import android.nfc.tech.NfcV; import android.os.Parcelable; public final class CardManager { private static final String SP = "<br/><img src=\"spliter\"/><br/>"; public static String[][] TECHLISTS; public static IntentFilter[] FILTERS; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() }, { NfcV.class.getName() }, { NfcF.class.getName() }, }; FILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } public static String buildResult(String n, String i, String d, String x) { if (n == null) return null; final StringBuilder s = new StringBuilder(); s.append("<br/><b>").append(n).append("</b>"); if (i != null) s.append(SP).append(i); if (d != null) s.append(SP).append(d); if (x != null) s.append(SP).append(x); return s.append("<br/><br/>").toString(); } public static String load(Parcelable parcelable, Resources res) { final Tag tag = (Tag) parcelable; final IsoDep isodep = IsoDep.get(tag); if (isodep != null) { return PbocCard.load(isodep, res); } final NfcV nfcv = NfcV.get(tag); if (nfcv != null) { return VicinityCard.load(nfcv, res); } final NfcF nfcf = NfcF.get(tag); if (nfcf != null) { return OctopusCard.load(nfcf, res); } return null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.tech.Iso7816; final class ChanganTong extends PbocCard { private final static byte[] DFN_SRV = { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x86, (byte) 0x98, (byte) 0x07, (byte) 0x01, }; private ChanganTong(Iso7816.Tag tag, Resources res) { super(tag); name = res.getString(R.string.name_cac); } @SuppressWarnings("unchecked") final static ChanganTong load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_PSE).isOkey()) { Iso7816.Response INFO, CASH; /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_SRV).isOkey()) { /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final ChanganTong ret = new ChanganTong(tag, res); ret.parseBalance(CASH); ret.parseInfo(INFO, 4, false); ret.parseLog(LOG); return ret; } } return null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.tech.Iso7816; final class WuhanTong extends PbocCard { private final static int SFI_INFO = 5; private final static int SFI_SERL = 10; private final static byte[] DFN_SRV = { (byte) 0x41, (byte) 0x50, (byte) 0x31, (byte) 0x2E, (byte) 0x57, (byte) 0x48, (byte) 0x43, (byte) 0x54, (byte) 0x43, }; private WuhanTong(Iso7816.Tag tag, Resources res) { super(tag); name = res.getString(R.string.name_wht); } @SuppressWarnings("unchecked") final static WuhanTong load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_PSE).isOkey()) { Iso7816.Response SERL, INFO, CASH; /*--------------------------------------------------------------*/ // read card info file, binary (5, 10) /*--------------------------------------------------------------*/ if (!(SERL = tag.readBinary(SFI_SERL)).isOkey()) return null; if (!(INFO = tag.readBinary(SFI_INFO)).isOkey()) return null; CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_SRV).isOkey()) { /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ if (!CASH.isOkey()) CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final WuhanTong ret = new WuhanTong(tag, res); ret.parseBalance(CASH); ret.parseInfo(SERL, INFO); ret.parseLog(LOG); return ret; } } return null; } private void parseInfo(Iso7816.Response sn, Iso7816.Response info) { if (sn.size() < 27 || info.size() < 27) { serl = version = date = count = null; return; } final byte[] d = info.getBytes(); serl = Util.toHexString(sn.getBytes(), 0, 5); version = String.format("%02d", d[24]); date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[16], d[17], d[18], d[19]); count = null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.tech.Iso7816; final class ShenzhenTong extends PbocCard { private final static byte[] DFN_SRV = { (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Z', (byte) 'T' }; private ShenzhenTong(Iso7816.Tag tag, Resources res) { super(tag); name = res.getString(R.string.name_szt); } @SuppressWarnings("unchecked") final static ShenzhenTong load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_PSE).isOkey()) { Iso7816.Response INFO, CASH; /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_SRV).isOkey()) { /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final ShenzhenTong ret = new ShenzhenTong(tag, res); ret.parseBalance(CASH); ret.parseInfo(INFO, 4, true); ret.parseLog(LOG); return ret; } } return null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import java.util.Arrays; import android.content.res.Resources; import android.nfc.tech.IsoDep; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.card.CardManager; import com.sinpo.xnfc.tech.Iso7816; public class PbocCard { protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 }; protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 }; protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] DFN_PXX = { (byte) 'P' }; protected final static int MAX_LOG = 10; protected final static int SFI_EXTRA = 21; protected final static int SFI_LOG = 24; protected final static byte TRANS_CSU = 6; protected final static byte TRANS_CSU_CPX = 9; protected String name; protected String id; protected String serl; protected String version; protected String date; protected String count; protected String cash; protected String log; public static String load(IsoDep tech, Resources res) { final Iso7816.Tag tag = new Iso7816.Tag(tech); tag.connect(); PbocCard card = null; do { if ((card = ShenzhenTong.load(tag, res)) != null) break; if ((card = BeijingMunicipal.load(tag, res)) != null) break; if ((card = ChanganTong.load(tag, res)) != null) break; if ((card = WuhanTong.load(tag, res)) != null) break; if ((card = YangchengTong.load(tag, res)) != null) break; if ((card = HardReader.load(tag, res)) != null) break; } while (false); tag.close(); return (card != null) ? card.toString(res) : null; } protected PbocCard(Iso7816.Tag tag) { id = tag.getID().toString(); } protected void parseInfo(Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { serl = version = date = count = null; return; } final byte[] d = data.getBytes(); if (dec < 1 || dec > 10) { serl = Util.toHexString(d, 10, 10); } else { final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d, 20 - dec, dec); serl = String.format("%d", 0xFFFFFFFFL & sn); } version = (d[9] != 0) ? String.valueOf(d[9]) : null; date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27]); count = null; } protected static boolean addLog(final Iso7816.Response r, ArrayList<byte[]> l) { if (!r.isOkey()) return false; final byte[] raw = r.getBytes(); final int N = raw.length - 23; if (N < 0) return false; for (int s = 0, e = 0; s <= N; s = e) { l.add(Arrays.copyOfRange(raw, s, (e = s + 23))); } return true; } protected static ArrayList<byte[]> readLog(Iso7816.Tag tag, int sfi) { final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG); final Iso7816.Response rsp = tag.readRecord(sfi); if (rsp.isOkey()) { addLog(rsp, ret); } else { for (int i = 1; i <= MAX_LOG; ++i) { if (!addLog(tag.readRecord(sfi, i), ret)) break; } } return ret; } protected void parseLog(ArrayList<byte[]>... logs) { final StringBuilder r = new StringBuilder(); for (final ArrayList<byte[]> log : logs) { if (log == null) continue; if (r.length() > 0) r.append("<br />--------------"); for (final byte[] v : log) { final int cash = Util.toInt(v, 5, 4); if (cash > 0) { r.append("<br />").append( String.format("%02X%02X.%02X.%02X %02X:%02X ", v[16], v[17], v[18], v[19], v[20], v[21], v[22])); final char t = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-' : '+'; r.append(t).append(Util.toAmountString(cash / 100.0f)); final int over = Util.toInt(v, 2, 3); if (over > 0) r.append(" [o:") .append(Util.toAmountString(over / 100.0f)) .append(']'); r.append(" [").append(Util.toHexString(v, 10, 6)) .append(']'); } } } this.log = r.toString(); } protected void parseBalance(Iso7816.Response data) { if (!data.isOkey() || data.size() < 4) { cash = null; return; } int n = Util.toInt(data.getBytes(), 0, 4); if (n > 100000 || n < -100000) n -= 0x80000000; cash = Util.toAmountString(n / 100.0f); } protected String formatInfo(Resources res) { if (serl == null) return null; final StringBuilder r = new StringBuilder(); r.append(res.getString(R.string.lab_serl)).append(' ').append(serl); if (version != null) { final String sv = res.getString(R.string.lab_ver); r.append("<br />").append(sv).append(' ').append(version); } if (date != null) { final String sd = res.getString(R.string.lab_date); r.append("<br />").append(sd).append(' ').append(date); } if (count != null) { final String so = res.getString(R.string.lab_op); final String st = res.getString(R.string.lab_op_time); r.append("<br />").append(so).append(' ').append(count).append(st); } return r.toString(); } protected String formatLog(Resources res) { if (log == null || log.length() < 1) return null; final StringBuilder ret = new StringBuilder(); final String sl = res.getString(R.string.lab_log); ret.append("<b>").append(sl).append("</b><small>"); ret.append(log).append("</small>"); return ret.toString(); } protected String formatBalance(Resources res) { if (cash == null || cash.length() < 1) return null; final String s = res.getString(R.string.lab_balance); final String c = res.getString(R.string.lab_cur_cny); return new StringBuilder("<b>").append(s) .append("<font color=\"teal\"> ").append(cash).append(' ') .append(c).append("</font></b>").toString(); } protected String toString(Resources res) { final String info = formatInfo(res); final String hist = formatLog(res); final String cash = formatBalance(res); return CardManager.buildResult(name, info, cash, hist); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.tech.Iso7816; final class YangchengTong extends PbocCard { private final static byte[] DFN_SRV = { (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'A', (byte) 'P', (byte) 'P', (byte) 'Y', }; private final static byte[] DFN_SRV_S1 = { (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'P', (byte) 'A', (byte) 'S', (byte) 'D', }; private final static byte[] DFN_SRV_S2 = { (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'T', (byte) 'I', (byte) 'C', (byte) 'L', }; private YangchengTong(Iso7816.Tag tag, Resources res) { super(tag); name = res.getString(R.string.name_lnt); } @SuppressWarnings("unchecked") final static YangchengTong load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_PSE).isOkey()) { Iso7816.Response INFO, CASH; /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_SRV).isOkey()) { /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG1 = (tag.selectByName(DFN_SRV_S1).isOkey()) ? readLog( tag, SFI_LOG) : null; ArrayList<byte[]> LOG2 = (tag.selectByName(DFN_SRV_S2).isOkey()) ? readLog( tag, SFI_LOG) : null; /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final YangchengTong ret = new YangchengTong(tag, res); ret.parseBalance(CASH); ret.parseInfo(INFO); ret.parseLog(LOG1, LOG2); return ret; } } return null; } private void parseInfo(Iso7816.Response info) { if (!info.isOkey() || info.size() < 50) { serl = version = date = count = null; return; } final byte[] d = info.getBytes(); serl = Util.toHexString(d, 11, 5); version = String.format("%02X.%02X", d[44], d[45]); date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[23], d[24], d[25], d[26], d[27], d[28], d[29], d[30]); count = null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.tech.Iso7816; final class BeijingMunicipal extends PbocCard { private final static int SFI_EXTRA_LOG = 4; private final static int SFI_EXTRA_CNT = 5; private BeijingMunicipal(Iso7816.Tag tag, Resources res) { super(tag); name = res.getString(R.string.name_bj); } @SuppressWarnings("unchecked") final static BeijingMunicipal load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (tag.selectByName(DFN_PSE).isOkey()) { Iso7816.Response INFO, CNT, CASH; /*--------------------------------------------------------------*/ // read card info file, binary (4) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA_LOG); if (INFO.isOkey()) { /*--------------------------------------------------------------*/ // read card operation file, binary (5) /*--------------------------------------------------------------*/ CNT = tag.readBinary(SFI_EXTRA_CNT); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (tag.selectByID(DFI_EP).isOkey()) { /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ CASH = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final BeijingMunicipal ret = new BeijingMunicipal(tag, res); ret.parseBalance(CASH); ret.parseInfo(INFO, CNT); ret.parseLog(LOG); return ret; } } } return null; } private void parseInfo(Iso7816.Response info, Iso7816.Response cnt) { if (!info.isOkey() || info.size() < 32) { serl = version = date = count = null; return; } final byte[] d = info.getBytes(); serl = Util.toHexString(d, 0, 8); version = String.format("%02X.%02X%02X", d[8], d[9], d[10]); date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24], d[25], d[26], d[27], d[28], d[29], d[30], d[31]); count = null; if (cnt != null && cnt.isOkey() && cnt.size() > 4) { byte[] e = cnt.getBytes(); final int n = Util.toInt(e, 1, 4); if (e[0] == 0) count = String.format("%d ", n); else count = String.format("%d* ", n); } } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card.pboc; import java.util.ArrayList; import android.content.res.Resources; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.tech.Iso7816; import com.sinpo.xnfc.tech.Iso7816.BerT; final class HardReader extends PbocCard { public static final byte TMPL_PDR = 0x70; // Payment Directory Entry Record public static final byte TMPL_PDE = 0x61; // Payment Directory Entry private HardReader(Iso7816.Tag tag, byte[] name, Resources res) { super(tag); this.name = (name != null) ? Util.toHexString(name, 0, name.length) : res.getString(R.string.name_unknowntag); } @SuppressWarnings("unchecked") final static HardReader load(Iso7816.Tag tag, Resources res) { /*--------------------------------------------------------------*/ // select PSF (1PAY.SYS.DDF01) /*--------------------------------------------------------------*/ if (!tag.selectByName(DFN_PSE).isOkey() && !tag.selectByID(DFI_MF).isOkey()) return null; /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ Iso7816.Response CASH = getBalance(tag); Iso7816.Response INFO = null; ArrayList<byte[]> LOG = new ArrayList<byte[]>(); byte[] name = null; /*--------------------------------------------------------------*/ // try to find AID list /*--------------------------------------------------------------*/ ArrayList<byte[]> AIDs = findAIDs(tag); for (final byte[] aid : AIDs) { /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if ((name = selectAID(tag, aid)) != null) { /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ if (!CASH.isOkey()) CASH = getBalance(tag); /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ if (INFO == null || !INFO.isOkey()) INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ LOG.addAll(readLog(tag, SFI_LOG)); } } /*--------------------------------------------------------------*/ // try to PXX AID /*--------------------------------------------------------------*/ if ((INFO == null || !INFO.isOkey()) && ((name = selectAID(tag, DFN_PXX)) != null)) { if (!CASH.isOkey()) CASH = getBalance(tag); INFO = tag.readBinary(SFI_EXTRA); LOG.addAll(readLog(tag, SFI_LOG)); } /*--------------------------------------------------------------*/ // try to 0x1001 AID /*--------------------------------------------------------------*/ if ((INFO == null || !INFO.isOkey()) && tag.selectByID(DFI_EP).isOkey()) { name = DFI_EP; if (!CASH.isOkey()) CASH = getBalance(tag); INFO = tag.readBinary(SFI_EXTRA); LOG.addAll(readLog(tag, SFI_LOG)); } if (!CASH.isOkey() && INFO == null && LOG.isEmpty() && name == null) return null; /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final HardReader ret = new HardReader(tag, name, res); ret.parseBalance(CASH); if (INFO != null) ret.parseInfo(INFO, 0, false); ret.parseLog(LOG); return ret; } private static byte[] selectAID(Iso7816.Tag tag, byte[] aid) { if (!tag.selectByName(DFN_PSE).isOkey() && !tag.selectByID(DFI_MF).isOkey()) return null; final Iso7816.Response rsp = tag.selectByName(aid); if (!rsp.isOkey()) return null; Iso7816.BerTLV tlv = Iso7816.BerTLV.read(rsp); if (tlv.t.match(Iso7816.BerT.TMPL_FCI)) { tlv = tlv.getChildByTag(Iso7816.BerT.CLASS_DFN); if (tlv != null) return tlv.v.getBytes(); } return aid; } private static ArrayList<byte[]> findAIDs(Iso7816.Tag tag) { ArrayList<byte[]> ret = new ArrayList<byte[]>(); for (int i = 1; i <= 31; ++i) { Iso7816.Response r = tag.readRecord(i, 1); for (int p = 2; r.isOkey(); ++p) { byte[] aid = findAID(r); if (aid == null) break; ret.add(aid); r = tag.readRecord(i, p); } } return ret; } private static byte[] findAID(Iso7816.Response record) { Iso7816.BerTLV tlv = Iso7816.BerTLV.read(record); if (tlv.t.match(TMPL_PDR)) { tlv = tlv.getChildByTag(BerT.CLASS_ADO); if (tlv != null) { tlv = tlv.getChildByTag(BerT.CLASS_AID); return (tlv != null) ? tlv.v.getBytes() : null; } } return null; } private static Iso7816.Response getBalance(Iso7816.Tag tag) { final Iso7816.Response rsp = tag.getBalance(true); return rsp.isOkey() ? rsp : tag.getBalance(false); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.card; import android.content.res.Resources; import android.nfc.tech.NfcF; import com.sinpo.xnfc.R; import com.sinpo.xnfc.Util; import com.sinpo.xnfc.tech.FeliCa; final class OctopusCard { private static final int SYS_SZT = 0x8005; private static final int SRV_SZT = 0x0118; private static final int SYS_OCTOPUS = 0x8008; private static final int SRV_OCTOPUS = 0x0117; static String load(NfcF tech, Resources res) { final FeliCa.Tag tag = new FeliCa.Tag(tech); /*--------------------------------------------------------------*/ // check card system /*--------------------------------------------------------------*/ final int system = tag.getSystemCode(); final FeliCa.ServiceCode service; if (system == SYS_OCTOPUS) service = new FeliCa.ServiceCode(SRV_OCTOPUS); else if (system == SYS_SZT) service = new FeliCa.ServiceCode(SRV_SZT); else return null; tag.connect(); /*--------------------------------------------------------------*/ // read service data without encryption /*--------------------------------------------------------------*/ final float[] data = new float[] { 0, 0, 0 }; final int N = data.length; int p = 0; for (byte i = 0; p < N; ++i) { final FeliCa.ReadResponse r = tag.readWithoutEncryption(service, i); if (!r.isOkey()) break; data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f; } tag.close(); /*--------------------------------------------------------------*/ // build result string /*--------------------------------------------------------------*/ final String name = parseName(system, res); final String info = parseInfo(tag, res); final String hist = parseLog(null, res); final String cash = parseBalance(data, p, res); return CardManager.buildResult(name, info, cash, hist); } private static String parseName(int system, Resources res) { if (system == SYS_OCTOPUS) return res.getString(R.string.name_octopuscard); if (system == SYS_SZT) return res.getString(R.string.name_szt_f); return null; } private static String parseInfo(FeliCa.Tag tag, Resources res) { final StringBuilder r = new StringBuilder(); final String i = res.getString(R.string.lab_id); final String p = res.getString(R.string.lab_pmm); r.append("<b>").append(i).append("</b> ") .append(tag.getIDm().toString()); r.append("<br />").append(p).append(' ') .append(tag.getPMm().toString()); return r.toString(); } private static String parseBalance(float[] value, int count, Resources res) { if (count < 1) return null; final StringBuilder r = new StringBuilder(); final String s = res.getString(R.string.lab_balance); final String c = res.getString(R.string.lab_cur_hkd); r.append("<b>").append(s).append(" <font color=\"teal\">"); for (int i = 0; i < count; ++i) r.append(Util.toAmountString(value[i])).append(' '); return r.append(c).append("</font></b>").toString(); } private static String parseLog(byte[] data, Resources res) { return null; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import java.util.Arrays; import org.xml.sax.XMLReader; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.nfc.NfcAdapter; import android.os.Bundle; import android.os.Parcelable; import android.text.ClipboardManager; import android.text.Editable; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.Toast; import com.sinpo.xnfc.card.CardManager; public final class NFCard extends Activity implements OnClickListener, Html.ImageGetter, Html.TagHandler { private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private Resources res; private TextView board; private enum ContentType { HINT, DATA, MSG } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.nfcard); final Resources res = getResources(); this.res = res; final View decor = getWindow().getDecorView(); final TextView board = (TextView) decor.findViewById(R.id.board); this.board = board; decor.findViewById(R.id.btnCopy).setOnClickListener(this); decor.findViewById(R.id.btnNfc).setOnClickListener(this); decor.findViewById(R.id.btnExit).setOnClickListener(this); board.setMovementMethod(LinkMovementMethod.getInstance()); board.setFocusable(false); board.setClickable(false); board.setLongClickable(false); nfcAdapter = NfcAdapter.getDefaultAdapter(this); pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); onNewIntent(getIntent()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.clear: showData(null); return true; case R.id.help: showHelp(R.string.info_help); return true; case R.id.about: showHelp(R.string.info_about); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onPause() { super.onPause(); if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(this); } @Override protected void onResume() { super.onResume(); if (nfcAdapter != null) nfcAdapter.enableForegroundDispatch(this, pendingIntent, CardManager.FILTERS, CardManager.TECHLISTS); refreshStatus(); } @Override protected void onNewIntent(Intent intent) { final Parcelable p = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); showData((p != null) ? CardManager.load(p, res) : null); } @Override public void onClick(final View v) { switch (v.getId()) { case R.id.btnCopy: { copyData(); break; } case R.id.btnNfc: { startActivityForResult(new Intent( android.provider.Settings.ACTION_WIRELESS_SETTINGS), 0); break; } case R.id.btnExit: { finish(); break; } default: break; } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { refreshStatus(); } private void refreshStatus() { final Resources r = this.res; final String tip; if (nfcAdapter == null) tip = r.getString(R.string.tip_nfc_notfound); else if (nfcAdapter.isEnabled()) tip = r.getString(R.string.tip_nfc_enabled); else tip = r.getString(R.string.tip_nfc_disabled); final StringBuilder s = new StringBuilder( r.getString(R.string.app_name)); s.append(" -- ").append(tip); setTitle(s); final CharSequence text = board.getText(); if (text == null || board.getTag() == ContentType.HINT) showHint(); } private void copyData() { final CharSequence text = board.getText(); if (text == null || board.getTag() != ContentType.DATA) return; ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)) .setText(text); final String msg = res.getString(R.string.msg_copied); final Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } private void showData(String data) { if (data == null || data.length() == 0) { showHint(); return; } final TextView board = this.board; final Resources res = this.res; final int padding = res.getDimensionPixelSize(R.dimen.pnl_margin); board.setPadding(padding, padding, padding, padding); board.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); board.setTextSize(res.getDimension(R.dimen.text_small)); board.setTextColor(res.getColor(R.color.text_default)); board.setGravity(Gravity.NO_GRAVITY); board.setTag(ContentType.DATA); board.setText(Html.fromHtml(data, this, null)); } private void showHelp(int id) { final TextView board = this.board; final Resources res = this.res; final int padding = res.getDimensionPixelSize(R.dimen.pnl_margin); board.setPadding(padding, padding, padding, padding); board.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); board.setTextSize(res.getDimension(R.dimen.text_small)); board.setTextColor(res.getColor(R.color.text_default)); board.setGravity(Gravity.NO_GRAVITY); board.setTag(ContentType.MSG); board.setText(Html.fromHtml(res.getString(id), this, this)); } private void showHint() { final TextView board = this.board; final Resources res = this.res; final String hint; if (nfcAdapter == null) hint = res.getString(R.string.msg_nonfc); else if (nfcAdapter.isEnabled()) hint = res.getString(R.string.msg_nocard); else hint = res.getString(R.string.msg_nfcdisabled); final int padding = res.getDimensionPixelSize(R.dimen.text_middle); board.setPadding(padding, padding, padding, padding); board.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC)); board.setTextSize(res.getDimension(R.dimen.text_middle)); board.setTextColor(res.getColor(R.color.text_tip)); board.setGravity(Gravity.CENTER_VERTICAL); board.setTag(ContentType.HINT); board.setText(Html.fromHtml(hint)); } @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { if (!opening && "version".equals(tag)) { try { output.append(getPackageManager().getPackageInfo( getPackageName(), 0).versionName); } catch (NameNotFoundException e) { } } } private Drawable spliter; @Override public Drawable getDrawable(String source) { final Resources res = this.res; final Drawable ret; if (source.startsWith("spliter")) { if (spliter == null) { final int w = res.getDisplayMetrics().widthPixels; final int h = (int) (res.getDisplayMetrics().densityDpi / 72f + 0.5f); final int[] pix = new int[w * h]; Arrays.fill(pix, res.getColor(R.color.bg_default)); spliter = new BitmapDrawable(Bitmap.createBitmap(pix, w, h, Bitmap.Config.ARGB_8888)); spliter.setBounds(0, 3 * h, w, 4 * h); } ret = spliter; } else if (source.startsWith("icon_main")) { ret = res.getDrawable(R.drawable.ic_app_main); final String[] params = source.split(","); final float f = res.getDisplayMetrics().densityDpi / 72f; final float w = Util.parseInt(params[1], 10, 16) * f + 0.5f; final float h = Util.parseInt(params[2], 10, 16) * f + 0.5f; ret.setBounds(0, 0, (int) w, (int) h); } else { ret = null; } return ret; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pojo; import java.util.Date; import java.util.List; import org.apache.cassandra.thrift.Column; /** * * @author tipuder */ public class Tag { public static String name_col_cdate = "create_date"; public static String name_col_mdate = "modify_date"; public static String name_col_state = "state"; public static String name_scol_lstatus = "list_status_ID"; public static String name_scol_info = "info_tag"; public static String col_parent = "Tag"; private String name_tag; private List<String> list_status_ID; private String create_date; private String modify_date; private String state; public static String getCol_parent() { return col_parent; } public static void setCol_parent(String col_parent) { Tag.col_parent = col_parent; } public Tag() { } public String getCreate_date() { return create_date; } public void setCreate_date(String create_date) { this.create_date = create_date; } public List<String> getList_status_ID() { return list_status_ID; } public void setList_status_ID(List<String> list_status_ID) { this.list_status_ID = list_status_ID; } public String getModify_date() { return modify_date; } public void setModify_date(String modify_date) { this.modify_date = modify_date; } public static String getName_col_cdate() { return name_col_cdate; } public static void setName_col_cdate(String name_col_cdate) { Tag.name_col_cdate = name_col_cdate; } public static String getName_col_mdate() { return name_col_mdate; } public static void setName_col_mdate(String name_col_mdate) { Tag.name_col_mdate = name_col_mdate; } public static String getName_col_state() { return name_col_state; } public static void setName_col_state(String name_col_state) { Tag.name_col_state = name_col_state; } public String getName_tag() { return name_tag; } public void setName_tag(String name_tag) { this.name_tag = name_tag; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Tag(String name_tag, List<String> list_status_ID, String create_date, String modify_date, String state) { this.name_tag = name_tag; this.list_status_ID = list_status_ID; this.create_date = create_date; this.modify_date = modify_date; this.state = state; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pojo; import java.util.List; /** * * @author tipuder */ public class User { public static String col_favorite = "list_status_ID"; public static String col_parent = "FavoriteStatus"; private String user_ID; private List<String> list_status_ID; public User() { } public User(String user_ID, List<String> list_status_ID) { this.user_ID = user_ID; this.list_status_ID = list_status_ID; } public static String getCol_favorite() { return col_favorite; } public static void setCol_favorite(String col_favorite) { User.col_favorite = col_favorite; } public List<String> getList_status_ID() { return list_status_ID; } public void setList_status_ID(List<String> list_status_ID) { this.list_status_ID = list_status_ID; } public String getUser_ID() { return user_ID; } public void setUser_ID(String user_ID) { this.user_ID = user_ID; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pojo; /** * * @author tipuder */ public class Status { public static String colname_content = "content"; public static String colname_tags = "tags"; public static String colname_likecount = "like_count"; public static String colname_dislikecount = "dislike_count"; public static String colname_createdate = "create_date"; public static String colname_modifydate = "modify_date"; public static String colname_state = "state"; public static String col_parent = "Status"; private String status_ID; private String content; private String create_date; private String dislike_count; private String like_count; private String modify_date; private String state; private String tags; public Status() { } public Status(String status_ID, String content, String create_date, String dislike_count, String like_count, String modify_date, String state, String tags) { this.status_ID = status_ID; this.content = content; this.create_date = create_date; this.dislike_count = dislike_count; this.like_count = like_count; this.modify_date = modify_date; this.state = state; this.tags = tags; } public String getContent() { return content; } public String getCreate_date() { return create_date; } public String getDislike_count() { return dislike_count; } public String getLike_count() { return like_count; } public String getModify_date() { return modify_date; } public String getState() { return state; } public String getStatus_ID() { return status_ID; } public String getTags() { return tags; } public void setContent(String content) { this.content = content; } public void setCreate_date(String create_date) { this.create_date = create_date; } public void setDislike_count(String dislike_count) { this.dislike_count = dislike_count; } public void setLike_count(String like_count) { this.like_count = like_count; } public void setModify_date(String modify_date) { this.modify_date = modify_date; } public void setState(String state) { this.state = state; } public void setStatus_ID(String status_ID) { this.status_ID = status_ID; } public void setTags(String tags) { this.tags = tags; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import static common.Constants.*; import org.apache.cassandra.thrift.Cassandra; import org.apache.cassandra.thrift.InvalidRequestException; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; /** * * @author tipuder */ public class CassandraDataAccessHelper { TTransport tr = new TSocket(HOST, PORT); // returns a new connection to our keyspace public Cassandra.Client connect() throws TTransportException, TException, InvalidRequestException { TFramedTransport tf = new TFramedTransport(tr); TProtocol proto = new TBinaryProtocol(tf); Cassandra.Client client = new Cassandra.Client(proto); tr.open(); client.set_keyspace(KEYSPACE); return client; } public void close() { tr.close(); } }
Java
package DAO; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cassandra.thrift.*; import org.apache.thrift.TException; import pojo.Tag; import pojo.User; public class UserDAO { private static Cassandra.Client client; private static UserDAO instance; public static UserDAO getInstance(Cassandra.Client _client) { if (instance != null) return instance; instance = new UserDAO(); client = _client; return instance; } /* public boolean savefavoriteStatus_T(String UserID,String StatusID) { boolean result = false; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID); ColumnPath path = new ColumnPath(User.col_parent); path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite); //Kiểm tra xem UserID đã được insert chưa bằng cách lấy hết UserID lên so sánh. ColumnParent parent = new ColumnParent(User.col_parent); SlicePredicate predicate = new SlicePredicate(); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(User.col_favorite)); KeyRange range = new KeyRange(); range.start_key = common.GeneralHandling.toByteBuffer(""); range.end_key = common.GeneralHandling.toByteBuffer(""); List<KeySlice> list = client.get_range_slices(parent, predicate, range, common.Constants.CL); SuperColumn supercol = new SuperColumn(); supercol.setName(common.GeneralHandling.toByteBuffer(User.col_favorite)); for (KeySlice keySlice : list) { if (keySlice.key == common.GeneralHandling.toByteBuffer(UserID)) { supercol = (client.get(rowkey, path, common.Constants.CL)).super_column; break; } } supercol.addToColumns(common.GeneralHandling.createCol(StatusID, "")); Addsupercolumn(rowkey, supercol); result = true; } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (NotFoundException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String selectfavoriteStatus_T(String UserID) { String result = ""; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID); ColumnPath path = new ColumnPath(User.col_parent); path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite); SuperColumn supercol = (client.get(rowkey, path, common.Constants.CL)).getSuper_column(); result = ParseToJSON(supercol); } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (NotFoundException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public boolean deletefavoriteStatus_T(String UserID, String statusID) { boolean result = false; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID); ColumnPath path = new ColumnPath(User.col_parent); path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite); SuperColumn supercol = (client.get(rowkey, path, common.Constants.CL)).super_column; SuperColumn newsupercol = new SuperColumn(); newsupercol.setName(supercol.name); for (Column col : supercol.getColumns()) { if (common.GeneralHandling.toString(col.name).equals(statusID)) { col.value = common.GeneralHandling.toByteBuffer(" 1"); newsupercol.addToColumns(col); } else newsupercol.addToColumns(col); } client.remove(rowkey, path, System.currentTimeMillis(), common.Constants.CL); Addsupercolumn(rowkey, newsupercol); result = true; } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (NotFoundException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public void Addsupercolumn(ByteBuffer rowkey, SuperColumn supercol) { try { List<Mutation> mutations = new ArrayList<Mutation>(); ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn(); Mutation m = new Mutation(); colorsupcol.setSuper_column(supercol); m.setColumn_or_supercolumn(colorsupcol); mutations.add(m); Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>(); keyMutations.put(User.col_parent, mutations); Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>(); mutationsMap.put(rowkey, keyMutations); client.batch_mutate(mutationsMap, common.Constants.CL); } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } */ public boolean savefavoriteStatus(String UserID,String statusID) { boolean result = update(UserID,statusID,"0"); return result; } public boolean deletefavoriteStatus(String UserID, String statusID) { boolean result = update(UserID,statusID,"1"); return result; } public boolean update(String UserID, String statusID,String state) { boolean result = false; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID); ColumnParent parent = new ColumnParent(User.col_parent); Column col = common.GeneralHandling.createCol(statusID, state); client.insert(rowkey, parent, col, common.Constants.CL); result = true; } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String selectfavoriteStatus(String UserID) { String result=""; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID); ColumnParent parent = new ColumnParent(User.col_parent); SlicePredicate predicate = new SlicePredicate(); SliceRange range = new SliceRange(); range.start = common.GeneralHandling.toByteBuffer(""); range.finish = common.GeneralHandling.toByteBuffer(""); predicate.slice_range = range; List<ColumnOrSuperColumn> listcol = client.get_slice(rowkey, parent, predicate, common.Constants.CL); List<ByteBuffer> liststatusID = new ArrayList<ByteBuffer>(); for (ColumnOrSuperColumn columnOrSuperColumn : listcol) { Column col = columnOrSuperColumn.getColumn(); String x = common.GeneralHandling.toString(col.value); if (x.equals("0")) liststatusID.add(col.name); } StatusDAO status_DAO = StatusDAO.getInstance(client); result = status_DAO.Getliststatus(liststatusID); } catch (InvalidRequestException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String ParseToJSON(SuperColumn supercol) throws UnsupportedEncodingException { List<ByteBuffer> liststatusID = new ArrayList<ByteBuffer>(); for (Column col : supercol.getColumns()) { if (!"1".equals(common.GeneralHandling.toString(col.value))) liststatusID.add(col.name); } StatusDAO status_DAO = StatusDAO.getInstance(client); String result = status_DAO.Getliststatus(liststatusID); return result; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import common.GeneralHandling; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import pojo.Tag; import org.apache.cassandra.thrift.*; import org.apache.thrift.TException; /** * * @author tipuder */ public class TagDAO { private static Cassandra.Client client; private static TagDAO instance; public static TagDAO getInstance(Cassandra.Client _client) { if (instance != null) return instance; instance = new TagDAO(); client = _client; return instance; } public boolean InsertTag(Tag newTag) { boolean result = false; try { //Tạo supercolumn list_status_ID // SuperColumn liststatus = new SuperColumn(); // liststatus.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus); // List<String> lstatus = newTag.getList_status_ID(); // for (int i = 0; i < newTag.getList_status_ID().size(); i++) // { // String colname = lstatus.get(i); // liststatus.addToColumns(common.GeneralHandling.createCol(colname, "")); // } //Tạo supercolumn info_tag SuperColumn info_tag = new SuperColumn(); info_tag.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_info); //String createD = Long.toString((new Date()).getTime()); info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_cdate, "")); String modifyD = ""; info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_mdate, modifyD)); String state = "public"; info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_state, state)); //Insert supercolunm bằng batch_mutate ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(newTag.getName_tag()); List<Mutation> mutations = new ArrayList<Mutation>(); ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn(); Mutation m = new Mutation(); colorsupcol.setSuper_column(info_tag); m.setColumn_or_supercolumn(colorsupcol); mutations.add(m); // colorsupcol = new ColumnOrSuperColumn(); // m = new Mutation(); // colorsupcol.setSuper_column(liststatus); // m.setColumn_or_supercolumn(colorsupcol); // mutations.add(m); Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>(); keyMutations.put(Tag.col_parent, mutations); Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>(); mutationsMap.put(rowkey, keyMutations); client.batch_mutate(mutationsMap, common.Constants.CL); result = true; } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public boolean InsertStatusIDtoTag(String StatusID,String nameTag) { boolean result = false; try { Tag updateTag = selectTagFromID(nameTag); SuperColumn liststatus = new SuperColumn(); liststatus.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus); List<String> lstatus = updateTag.getList_status_ID(); if (lstatus == null) lstatus = new ArrayList<String>(); lstatus.add(StatusID); for (int i = 0; i < lstatus.size(); i++) { String colname = lstatus.get(i); liststatus.addToColumns(common.GeneralHandling.createCol(colname, "")); } ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(updateTag.getName_tag()); List<Mutation> mutations = new ArrayList<Mutation>(); ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn(); Mutation m = new Mutation(); colorsupcol.setSuper_column(liststatus); m.setColumn_or_supercolumn(colorsupcol); mutations.add(m); Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>(); keyMutations.put(Tag.col_parent, mutations); Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>(); mutationsMap.put(rowkey, keyMutations); client.batch_mutate(mutationsMap, common.Constants.CL); result = true; } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public Tag selectTagFromID(String nameTag) { Tag result = new Tag(); try { SlicePredicate predicate = new SlicePredicate(); SliceRange range = new SliceRange(GeneralHandling.toByteBuffer(""), GeneralHandling.toByteBuffer(""), false, 10); predicate.setSlice_range(range); ColumnParent parent = new ColumnParent(Tag.col_parent); List<ColumnOrSuperColumn> results = client.get_slice(GeneralHandling.toByteBuffer(nameTag), parent, predicate, common.Constants.CL); if (!results.isEmpty()) { result.setName_tag(nameTag); for (ColumnOrSuperColumn temp : results) { SuperColumn sc = temp.super_column; String colname = common.GeneralHandling.toString(sc.name); if (Tag.name_scol_lstatus.equals(colname)) { List<String> list_status_ID = new ArrayList<String>(); for (Column col : sc.columns) list_status_ID.add(common.GeneralHandling.toString(col.name)); result.setList_status_ID(list_status_ID); } else for (Column col : sc.columns) { String name = common.GeneralHandling.toString(col.name); switch (name.charAt(0)) { case 'c': { result.setCreate_date(common.GeneralHandling.toString(col.value)); } case 'm': { result.setModify_date(common.GeneralHandling.toString(col.value)); } case 's': { result.setState("public"); } } } } } } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public boolean RemoveTag(String rowkey) { boolean result = false; try { long time = System.currentTimeMillis(); ColumnPath path = new ColumnPath(); path.column_family = Tag.col_parent; path.super_column = common.GeneralHandling.toByteBuffer(Tag.name_scol_info); client.remove(common.GeneralHandling.toByteBuffer(rowkey),path,time,common.Constants.CL); path = new ColumnPath(); path.column_family = Tag.col_parent; path.super_column = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus); client.remove(common.GeneralHandling.toByteBuffer(rowkey),path,time,common.Constants.CL); result = true; } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public void PrintALLTag() { try { List<ByteBuffer> colNames = new ArrayList<ByteBuffer>(); colNames.add(common.GeneralHandling.toByteBuffer(Tag.name_scol_info)); SlicePredicate predicate = new SlicePredicate(); predicate.column_names = colNames; ColumnParent parent = new ColumnParent(Tag.col_parent); KeyRange range = new KeyRange(); range.start_key = common.GeneralHandling.toByteBuffer(""); range.end_key = common.GeneralHandling.toByteBuffer(""); List<KeySlice> results = client.get_range_slices(parent, predicate, range, common.Constants.CL); for (KeySlice row : results) { Tag temp = selectTagFromID(common.GeneralHandling.toString(row.key)); if (temp.getName_tag() != null) PrintTag(temp); } } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } } private void PrintTag(Tag temp) { System.out.println("Key : " + temp.getName_tag()); System.out.println("List status ID : "); List<String> list = temp.getList_status_ID(); for (int i = 0; i < list.size(); i++) { String x = list.get(i) + ", "; System.out.print(x); } System.out.println(); System.out.println("Create Date : " + temp.getCreate_date()); System.out.println("Modify Date : " + temp.getModify_date()); System.out.println("State : " + temp.getState()); System.out.println("-----------------------------------------"); } public String PrintALLTag_S() { String result = "{\"result\":["; try { List<ByteBuffer> colNames = new ArrayList<ByteBuffer>(); colNames.add(common.GeneralHandling.toByteBuffer(Tag.name_scol_info)); SlicePredicate predicate = new SlicePredicate(); predicate.column_names = colNames; ColumnParent parent = new ColumnParent(Tag.col_parent); KeyRange range = new KeyRange(); range.start_key = common.GeneralHandling.toByteBuffer(""); range.end_key = common.GeneralHandling.toByteBuffer(""); List<KeySlice> results = client.get_range_slices(parent, predicate, range, common.Constants.CL); for (KeySlice row : results) { Tag temp = selectTagFromID(common.GeneralHandling.toString(row.key)); if (temp.getName_tag() != null && temp.getList_status_ID() != null) result += PrintTag_S(temp); } result = result.substring(0, result.length()-1); result += "]}"; } catch (TException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidRequestException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } private String PrintTag_S(Tag temp) { String result = ""; result += "{\"Key\":\"" + temp.getName_tag() + "\","; result += "\"List status ID\":\""; List<String> list = temp.getList_status_ID(); for (int i = 0; i < list.size(); i++) { String x = list.get(i) + ","; result += x; } result = result.substring(0, result.length()-1); result += "\","; result += "\"Create Date\":\"" + temp.getCreate_date() + "\","; result += "\"Modify Date\":\"" + temp.getModify_date() + "\","; result += "\"State\":\"" + temp.getState() + "\"},"; return result; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DAO; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cassandra.thrift.*; import org.apache.thrift.TException; import pojo.Status; import common.GeneralHandling; import java.util.*; import pojo.Tag; /** * * @author huy */ public class StatusDAO { private static Cassandra.Client client; private static StatusDAO instance; public static StatusDAO getInstance(Cassandra.Client _client) { if (instance != null) return instance; instance = new StatusDAO(); client = _client; return instance; } public boolean InsertStatus(Status newstatus) { boolean result = false; try { ColumnParent parent = new ColumnParent(Status.col_parent); ByteBuffer status_ID = common.GeneralHandling.toByteBuffer(UUID.randomUUID().toString()); //Add các column vào CF. client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_content, newstatus.getContent()),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_tags, newstatus.getTags()),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_likecount, newstatus.getLike_count()),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_dislikecount, newstatus.getDislike_count()),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_createdate, ""),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_modifydate, ""),common.Constants.CL); client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_state, "public"),common.Constants.CL); //Cập nhật list_status_ID cho tag tương ứng. String[] tags = newstatus.getTags().split(","); TagDAO tag_DAO = TagDAO.getInstance(client); String x = GeneralHandling.toString(status_ID); for (int i = 0; i < tags.length; i++) { if (!tag_DAO.InsertStatusIDtoTag(x, tags[i])) return result; } result = true; } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String SelectRandom() { String result = ""; try { ColumnParent parent = new ColumnParent(Status.col_parent); SlicePredicate predicate = new SlicePredicate(); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content)); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_tags)); KeyRange range = new KeyRange(); range.start_key = common.GeneralHandling.toByteBuffer(""); range.end_key = common.GeneralHandling.toByteBuffer(""); List<KeySlice> p_listkey = client.get_range_slices(parent, predicate, range, common.Constants.CL); int keystart = (new Random()).nextInt(/*common.Constants.countStatus*/70); int count = (new Random()).nextInt(5) + 6; List<KeySlice> listkey = p_listkey.subList(keystart, keystart + count); result = ParseToJSON(listkey); } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String SelectRandomtoTag(String Tagname) { String result = ""; try { ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(Tagname); ColumnParent parent = new ColumnParent(Tag.col_parent); SlicePredicate predicate = new SlicePredicate(); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus)); List<ColumnOrSuperColumn> result_key = client.get_slice(rowkey, parent, predicate, common.Constants.CL); List<ByteBuffer> listStatusID = new ArrayList<ByteBuffer>(); for (ColumnOrSuperColumn col : result_key) { for (Column c : col.getSuper_column().columns) listStatusID.add(c.name); } //Xáo trôn list statusID Random rd = new Random(); for (int i = 0; i < listStatusID.size() - 1; i++) { for (int j = i + 1; j < listStatusID.size(); j++) { if (rd.nextInt(1) < rd.nextInt(3)) { ByteBuffer temp = listStatusID.get(i); listStatusID.set(i, listStatusID.get(j)); listStatusID.set(j, temp); } } } int length = rd.nextInt(5) + 6; if (listStatusID.size() > length) listStatusID = listStatusID.subList(0, length); result = Getliststatus(listStatusID); } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String Getliststatus(List<ByteBuffer> listStatusID) { String result = ""; try { ColumnParent parent = new ColumnParent(Status.col_parent); SlicePredicate predicate = new SlicePredicate(); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content)); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_tags)); Map<ByteBuffer, List<ColumnOrSuperColumn>> mapstatus = client.multiget_slice(listStatusID, parent, predicate, common.Constants.CL); List<KeySlice> liststatus = new ArrayList<KeySlice>(); for (int i = 0; i < mapstatus.size(); i++) { liststatus.add(new KeySlice(listStatusID.get(i), mapstatus.get(listStatusID.get(i)))); } result = ParseToJSON(liststatus); } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } //Lấy danh sách 20 câu status nổi bật nhất public String listOutstandingStatus() { String result = ""; try { ColumnParent parent = new ColumnParent(Status.col_parent); SlicePredicate predicate = new SlicePredicate(); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content)); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_likecount)); predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_dislikecount)); KeyRange keyrange = new KeyRange(); keyrange.start_key = common.GeneralHandling.toByteBuffer(""); keyrange.end_key = common.GeneralHandling.toByteBuffer(""); List<KeySlice> liststatus = client.get_range_slices(parent, predicate, keyrange, common.Constants.CL); liststatus = Sort(liststatus); result = ParseToJSON(liststatus); } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } private List<KeySlice> Sort(List<KeySlice> list) throws UnsupportedEncodingException { for (int i=0; i<list.size()-1; i++) for (int j=i+1; j<list.size(); j++) { if (OutstandingPoint(list.get(i)) < OutstandingPoint(list.get(j))) { KeySlice temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); } } List<KeySlice> result = list.subList(0, 19); return result; } //Tính điểm nổi bật của từng status like * 8 + dislike * 2 private int OutstandingPoint(KeySlice x) throws UnsupportedEncodingException { int like = 0,dislike = 0; for (ColumnOrSuperColumn columnOrSuperColumn : x.getColumns()) { if(columnOrSuperColumn.column.name == common.GeneralHandling.toByteBuffer(Status.colname_likecount)) like = Integer.parseInt(common.GeneralHandling.toString(columnOrSuperColumn.column.value)); if(columnOrSuperColumn.column.name == common.GeneralHandling.toByteBuffer(Status.colname_dislikecount)) dislike = Integer.parseInt(common.GeneralHandling.toString(columnOrSuperColumn.column.value)); } return like * 8 + dislike * 2; } //Tăng số like lên 1 public boolean increaseLikecount(String status_ID) { boolean result = Inscrease(status_ID,Status.colname_likecount); return result; } //Tăng số dislike lên 1 public boolean increaseDislikecount(String status_ID) { boolean result = Inscrease(status_ID,Status.colname_dislikecount); return result; } private boolean Inscrease(String status_ID,String typecol) { boolean result = false; try { ByteBuffer id = common.GeneralHandling.toByteBuffer(status_ID); ColumnParent parent = new ColumnParent(Status.col_parent); ColumnPath path = new ColumnPath(Status.col_parent); path.column = common.GeneralHandling.toByteBuffer(typecol); ColumnOrSuperColumn status = client.get(id, path, common.Constants.CL); int likecount_curr = Integer.parseInt(common.GeneralHandling.toString(status.column.value)); Column newcol = common.GeneralHandling.createCol(typecol, Integer.toString(likecount_curr + 1)); client.insert(id, parent, newcol, common.Constants.CL); result = true; } catch (NotFoundException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidRequestException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnavailableException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TimedOutException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } return result; } public String ParseToJSON(List<KeySlice> list) { String result = "{\"result\":["; for (KeySlice keySlice : list) { if (keySlice.columns.size() < 2) continue; try { result += "{\"status_ID\":\"" + common.GeneralHandling.toString(keySlice.key) + "\""; for (ColumnOrSuperColumn col : keySlice.columns) { Column c = col.column; String colname = common.GeneralHandling.toString(c.name); if (colname.equals(Status.colname_content)) result += ",\"" + Status.colname_content + "\":\"" + common.GeneralHandling.toString(c.value) + "\""; else if(colname.equals(Status.colname_tags)) result += ",\"" + Status.colname_tags + "\":\"" + common.GeneralHandling.toString(c.value) + "\"},"; } } catch (UnsupportedEncodingException ex) { Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex); } } int x = result.length(); result = result.substring(0, x - 1); result += "]}"; return result; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import server.User; /** * * @author huy */ public class NonblockingClient { private void invoke() { TTransport transport; try { transport = new TFramedTransport(new TSocket("localhost", 7911)); TProtocol protocol = new TBinaryProtocol(transport); User.Client client = new User.Client(protocol); transport.open(); /*Gọi các phương thức trong service tại đây*/ System.out.println(client.listTag()); transport.close(); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } } public static void main(String[] args) { NonblockingClient c = new NonblockingClient(); c.invoke(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import org.apache.thrift.server.TNonblockingServer; import org.apache.thrift.server.TServer; import org.apache.thrift.transport.TNonblockingServerSocket; import org.apache.thrift.transport.TNonblockingServerTransport; import org.apache.thrift.transport.TTransportException; /** * * @author huy */ public class NonblockingServer { private void start() { try { TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911); User.Processor processor = new User.Processor(new UserImpl()); TServer server = new TNonblockingServer(new TNonblockingServer.Args(serverTransport). processor(processor)); System.out.println("Starting server on port 7911 ..."); server.serve(); } catch (TTransportException e) { e.printStackTrace(); } } public static void main(String[] args) { NonblockingServer srv = new NonblockingServer(); srv.start(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package server; import DAO.StatusDAO; import DAO.TagDAO; import DAO.UserDAO; import Testing.app; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cassandra.thrift.*; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import pojo.Tag; /** * * @author huy */ public class UserImpl implements User.Iface{ private TTransport tr; private Cassandra.Client client; public UserImpl() { try { tr = new TFramedTransport(new TSocket(common.Constants.HOST, common.Constants.PORT)); TProtocol proto = new TBinaryProtocol(tr); client = new Cassandra.Client(proto); tr.open(); client.set_keyspace(common.Constants.KEYSPACE); } catch (InvalidRequestException ex) { Logger.getLogger(UserImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(UserImpl.class.getName()).log(Level.SEVERE, null, ex); } } @Override public String selectRandom(){ StatusDAO status_DAO = StatusDAO.getInstance(client); String result = status_DAO.SelectRandom(); //tr.close(); return result; } @Override public String selectRandomtoTag(String NameTag){ StatusDAO status_DAO = StatusDAO.getInstance(client); String result = status_DAO.SelectRandomtoTag(NameTag); //tr.close(); return result; } @Override public boolean savefavoriteStatus(String UseriD, String StatusID){ UserDAO user_DAO = UserDAO.getInstance(client); boolean result = user_DAO.savefavoriteStatus(UseriD, StatusID); //tr.close(); return result; } @Override public String selectfavoriteStatus(String UserID){ UserDAO user_DAO = UserDAO.getInstance(client); String result = user_DAO.selectfavoriteStatus(UserID); //tr.close(); return result; } @Override public boolean deletefavoriteStatus(String UserID, String StatusID){ UserDAO user_DAO = UserDAO.getInstance(client); boolean result = user_DAO.deletefavoriteStatus(UserID, StatusID); //tr.close(); return result; } @Override public String listOutstandingStatus(){ StatusDAO status_DAO = StatusDAO.getInstance(client); String result = status_DAO.listOutstandingStatus(); //tr.close(); return result; } @Override public boolean inscreaseLikecount(String StatusID){ StatusDAO status_DAO = StatusDAO.getInstance(client); boolean result = status_DAO.increaseLikecount(StatusID); //tr.close(); return result; } @Override public boolean inscreaseDislikecount(String StatusID){ StatusDAO status_DAO = StatusDAO.getInstance(client); boolean result = status_DAO.increaseDislikecount(StatusID); //tr.close(); return result; } @Override public String listTag(){ TagDAO tag_DAO = TagDAO.getInstance(client); String result = tag_DAO.PrintALLTag_S(); //tr.close(); return result; } }
Java
package Testing; import DAO.StatusDAO; import DAO.TagDAO; import DAO.UserDAO; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import pojo.Status; /** * * @author ngochuy */ import org.apache.cassandra.thrift.*; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import pojo.Tag; public class app { public static void main(String[] args) { try { TTransport tr = new TFramedTransport(new TSocket(common.Constants.HOST, common.Constants.PORT)); TProtocol proto = new TBinaryProtocol(tr); Cassandra.Client client = new Cassandra.Client(proto); tr.open(); client.set_keyspace(common.Constants.KEYSPACE); TagDAO tag_DAO = TagDAO.getInstance(client); // String[] listname = {"chúc tết","tiền","break up","châm biếm", // "châm ngôn sống","cuộc sống","failure", // "gia đình","heart","hài hước","hôn nhân", // "life","love","lời hay ý đẹp","mới nhất", // "phụ nữ","thành công","tình bạn","tình cảm", // "tình yêu","vui vẻ","đàn ông"}; // for (int j=0; j<listname.length;j++) // { // Tag newTag = new Tag(); // //// List<String> liststatusID = new ArrayList<String>(); //// Random rd = new Random(); //// for (int i = 0; i < rd.nextInt(4) + 3; i++) //// liststatusID.add(Integer.toString(rd.nextInt(20)+2)); // newTag.setName_tag(listname[j]); // //newTag.setList_status_ID(liststatusID); // // if (tag_DAO.InsertTag(newTag)) // System.out.println("Insert thành công"); // } //// if (tag_DAO.RemoveTag("Tình yêu")); //// System.out.println("Remove thành công"); // StatusDAO sta_DAO = StatusDAO.getInstance(client); // Status newstatus = new Status(); // newstatus.setContent("Người ta có thể quên đi điều bạn nói, nhưng những gì bạn để lại trong lòng họ thì không bao giờ nhạt phai." ); // newstatus.setTags("tình bạn"); // Random rd = new Random(); // // newstatus.setLike_count(Integer.toString(rd.nextInt(30))); // newstatus.setDislike_count(Integer.toString(rd.nextInt(30))); // if (sta_DAO.InsertStatus(newstatus)) // System.out.println("Insert thành công"); // UserDAO user_DAO = UserDAO.getInstance(client); String result = user_DAO.selectfavoriteStatus("2"); System.out.println(result); tr.close(); } catch (InvalidRequestException ex) { Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex); } catch (TException ex) { Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ServicesAccessData; /** * * @author tipuder */ public class Server { }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package common; import static common.Constants.UTF8; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cassandra.thrift.Column; import pojo.Status; import pojo.Tag; /** * * @author tipuder */ public class GeneralHandling { public static Column createCol(String name, String value) { Column result = new Column(); long time = System.currentTimeMillis(); try { result = new Column(toByteBuffer(name)); if (name.equals(Status.colname_createdate) || name.equals(Tag.name_col_cdate)) { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); result.setValue(toByteBuffer(sdf.format(cal.getTime()))); } else result.setValue(toByteBuffer(value)); result.setTimestamp(time); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GeneralHandling.class.getName()).log(Level.SEVERE, null, ex); } return result; } public static ByteBuffer toByteBuffer(String value) throws UnsupportedEncodingException { return ByteBuffer.wrap(value.getBytes(UTF8)); } public static String toString(ByteBuffer buffer) throws UnsupportedEncodingException { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); return new String(bytes, UTF8); } public static int toInt(ByteBuffer buffer) throws UnsupportedEncodingException { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String temp = new String(bytes, UTF8); return Integer.parseInt(temp); } public static java.util.UUID getTimeUUID() { return java.util.UUID.fromString(new com.eaio.uuid.UUID().toString()); } /** * Returns an instance of uuid. * * @param uuid the uuid * @return the java.util. uuid */ public static java.util.UUID toUUID( byte[] uuid ) { long msb = 0; long lsb = 0; assert uuid.length == 16; for (int i=0; i<8; i++) msb = (msb << 8) | (uuid[i] & 0xff); for (int i=8; i<16; i++) lsb = (lsb << 8) | (uuid[i] & 0xff); long mostSigBits = msb; long leastSigBits = lsb; com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(msb,lsb); return java.util.UUID.fromString(u.toString()); } /** * As byte array. * * @param uuid the uuid * * @return the byte[] */ public static byte[] asByteArray(java.util.UUID uuid) { long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); byte[] buffer = new byte[16]; for (int i = 0; i < 8; i++) { buffer[i] = (byte) (msb >>> 8 * (7 - i)); } for (int i = 8; i < 16; i++) { buffer[i] = (byte) (lsb >>> 8 * (7 - i)); } return buffer; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package common; import org.apache.cassandra.thrift.ConsistencyLevel; /** * * @author tipuder */ public class Constants { public static final String UTF8 = "UTF8"; public static final String KEYSPACE = "NghiNhanh2"; public static final ConsistencyLevel CL = ConsistencyLevel.ONE; public static final String HOST = "localhost"; public static final int PORT = 9160; public static int countStatus; }
Java
import java.io.*; import java.net.*; public class socket { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("10.16.150.233", 4567); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
Java
import java.io.*; import java.net.*; public class socketserver { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(4567); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } }
Java
import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SocketController implements ISocketController { private String host; private int port; public SocketController(String host, int port) { super(); this.host = host; this.port = port; } public void send(String s) throws IOException { Socket socket = new Socket(host, port); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); out.writeBytes(s); out.close(); socket.close(); } public String receive() { return null; } }
Java
import java.util.Scanner; // Testing 01 public class A { private static String host; private static int port; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter port number (xxxx): "); port = sc.nextInt(); System.out.println("Enter IP address (Ex 192.168.0.1): "); host = sc.next(); } ISocketController socketCtrl = new SocketController(host, port); socketController.send(String); } }
Java
import java.io.IOException; public interface ISocketController { void send(String s) throws IOException; String receive(); }
Java
package yuku.filechooser.demo; import android.app.*; import android.content.*; import android.os.*; import android.view.*; import android.widget.*; import java.util.*; import yuku.filechooser.*; import yuku.filechooser.FileChooserConfig.Mode; public class FileChooserDemoActivity extends Activity { private static final int REQCODE_showFileChooser = 1; private static final int REQCODE_showFolderChooser = 2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void bShowFileChooser_click(View v) { EditText tInitialDir = (EditText) findViewById(R.id.tInitialDir); EditText tTitle = (EditText) findViewById(R.id.tTitle); EditText tPattern = (EditText) findViewById(R.id.tPattern); FileChooserConfig config = new FileChooserConfig(); config.mode = Mode.Open; config.initialDir = tInitialDir.length() == 0 ? null : tInitialDir.getText().toString(); config.title = tTitle.length() == 0 ? null : tTitle.getText().toString(); config.pattern = tPattern.length() == 0 ? null : tPattern.getText().toString(); startActivityForResult(FileChooserActivity.createIntent(getApplicationContext(), config), REQCODE_showFileChooser); } public void bShowFolderChooser_click(View v) { EditText tInitialDir = (EditText) findViewById(R.id.tInitialDir); EditText tTitle = (EditText) findViewById(R.id.tTitle); CheckBox cShowHidden = (CheckBox) findViewById(R.id.cShowHidden); FolderChooserConfig config = new FolderChooserConfig(); config.roots = Arrays.asList(Environment.getExternalStorageDirectory().toString(), tInitialDir.getText().toString()); config.showHidden = cShowHidden.isChecked(); config.title = tTitle.length() == 0 ? null : tTitle.getText().toString(); startActivityForResult(FolderChooserActivity.createIntent(getApplicationContext(), config), REQCODE_showFolderChooser); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQCODE_showFileChooser) { } if (requestCode == REQCODE_showFolderChooser) { if (resultCode == RESULT_OK) { FolderChooserResult result = FolderChooserActivity.obtainResult(data); new AlertDialog.Builder(this) .setTitle("Result") .setMessage(result.selectedFolder) .show(); } } } }
Java
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type long and long. * * <p>The iterator semantics for Trove's primitive maps is slightly different * from those defined in <tt>java.util.Iterator</tt>, but still well within * the scope of the pattern, as defined by Gamma, et al.</p> * * <p>This iterator does <b>not</b> implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>, * the <tt>value()</tt> or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time.</p> * * <p>In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger.</p> * * <p>Here are some sample scenarios for this class of iterator:</p> * * <pre> * // accessing keys/values through an iterator: * for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * doSomethingWithValue( it.value() ); * } * } * </pre> * * <pre> * // modifying values in-place through iteration: * for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * it.setValue( newValueForKey( it.key() ) ); * } * } * </pre> * * <pre> * // deleting entries during iteration: * for ( TLongLongIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * it.remove(); * } * } * </pre> * * <pre> * // faster iteration by avoiding hasNext(): * TLongLongIterator iterator = map.iterator(); * for ( int i = map.size(); i-- > 0; ) { * iterator.advance(); * doSomethingWithKeyAndValue( iterator.key(), iterator.value() ); * } * </pre> */ public interface TLongLongIterator extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public long key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public long value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must <tt>advance()</tt> the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public long setValue( long val ); }
Java
// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; /** * Common interface for iterators that operate via the "advance" method for moving the * cursor to the next element. */ public interface TAdvancingIterator extends TIterator { /** * Moves the iterator forward to the next entry. * * @throws java.util.NoSuchElementException if the iterator is already exhausted */ public void advance(); }
Java
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type int and Object. * <p/> * The iterator semantics for Trove's primitive maps is slightly different * from those defined in <tt>java.util.Iterator</tt>, but still well within * the scope of the pattern, as defined by Gamma, et al. * <p/> * This iterator does <b>not</b> implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>, * the <tt>value()</tt> or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time. * <p/> * In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger. * <p/> * Here are some sample scenarios for this class of iterator: * <p/> * <pre> * // accessing keys/values through an iterator: * for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) ) { * doSomethingWithValue( it.value() ); * } * } * </pre> * <p/> * <pre> * // modifying values in-place through iteration: * for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) ) { * it.setValue( newValueForKey( it.key() ) ); * } * } * </pre> * <p/> * <pre> * // deleting entries during iteration: * for ( TIntObjectIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) ) { * it.remove(); * } * } * </pre> * <p/> * <pre> * // faster iteration by avoiding hasNext(): * TIntObjectIterator iterator = map.iterator(); * for ( int i = map.size(); i-- > 0; ) { * iterator.advance(); * doSomethingWithKeyAndValue( iterator.key(), iterator.value() ); * } * </pre> * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $ */ public interface TIntObjectIterator<V> extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public int key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public V value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must <tt>advance()</tt> the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public V setValue( V val ); }
Java
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type long and int. * * <p>The iterator semantics for Trove's primitive maps is slightly different * from those defined in <tt>java.util.Iterator</tt>, but still well within * the scope of the pattern, as defined by Gamma, et al.</p> * * <p>This iterator does <b>not</b> implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>, * the <tt>value()</tt> or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time.</p> * * <p>In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger.</p> * * <p>Here are some sample scenarios for this class of iterator:</p> * * <pre> * // accessing keys/values through an iterator: * for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * doSomethingWithValue( it.value() ); * } * } * </pre> * * <pre> * // modifying values in-place through iteration: * for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * it.setValue( newValueForKey( it.key() ) ); * } * } * </pre> * * <pre> * // deleting entries during iteration: * for ( TLongIntIterator it = map.iterator(); it.hasNext(); ) { * it.advance(); * if ( satisfiesCondition( it.key() ) { * it.remove(); * } * } * </pre> * * <pre> * // faster iteration by avoiding hasNext(): * TLongIntIterator iterator = map.iterator(); * for ( int i = map.size(); i-- > 0; ) { * iterator.advance(); * doSomethingWithKeyAndValue( iterator.key(), iterator.value() ); * } * </pre> */ public interface TLongIntIterator extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public long key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public int value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must <tt>advance()</tt> the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public int setValue( int val ); }
Java